[PLUGIN][AttachmentCollections] Add Attachment Collection plugin which allow users to save attachments in collections

This commit is contained in:
Phablulo Joel 2021-12-23 21:38:06 -03:00
parent 63f9c6341e
commit 82e6e95b6a
10 changed files with 707 additions and 0 deletions

View File

@ -0,0 +1,214 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* Attachments Albums for GNU social
*
* @package GNUsocial
* @category Plugin
* @author Phablulo <phablulo@gmail.com>
* @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\AttachmentCollections;
use App\Core\Form;
use App\Core\Event;
use App\Core\DB\DB;
use App\Util\Common;
use App\Entity\Feed;
use App\Util\Nickname;
use App\Util\Formatting;
use App\Entity\LocalUser;
use App\Core\Router\Router;
use App\Core\Modules\Plugin;
use function App\Core\I18n\_m;
use App\Core\Router\RouteLoader;
use Symfony\Component\HttpFoundation\Request;
use Plugin\AttachmentCollections\Controller as C;
use Plugin\AttachmentCollections\Entity\Collection;
use Plugin\AttachmentCollections\Entity\CollectionEntry;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class AttachmentCollections extends Plugin
{
public function onAddRoute(RouteLoader $r): bool
{
// View all collections by actor id and nickname
$r->connect(
id: 'collections_view_by_actor_id', uri_path: '/actor/{id<\d+>}/collections',
target: [C\Controller::class, 'collectionsViewByActorId']
);
$r->connect(
id: 'collections_view_by_nickname', uri_path: '/@{nickname<' . Nickname::DISPLAY_FMT . '>}/collections',
target: [C\Controller::class, 'collectionsByActorNickname']
);
// View notes from a collection by actor id and nickname
$r->connect(
id: 'collection_notes_view_by_actor_id', uri_path: '/actor/{id<\d+>}/collections/{cid<\d+>}',
target: [C\Controller::class, 'collectionNotesViewByActorId']
);
$r->connect(
id: 'collection_notes_view_by_nickname', uri_path: '/@{nickname<' . Nickname::DISPLAY_FMT . '>}/collections/{cid<\d+>}',
target: [C\Controller::class, 'collectionNotesByNickname']
);
return Event::next;
}
public function onCreateDefaultFeeds(int $actor_id, LocalUser $user, int &$ordering)
{
DB::persist(Feed::create([
'actor_id' => $actor_id,
'url' => Router::url($route = 'collections_view_by_nickname', ['nickname' => $user->getNickname()]),
'route' => $route,
'title' => _m('Attachment Collections'),
'ordering' => $ordering++,
]));
return Event::next;
}
public function onAppendRightPanelBlock($vars, Request $request, &$res): bool
{
if ($vars['path'] !== 'attachment_show') return Event::next;
$user = Common::user();
if (\is_null($user)) return Event::next;
$colls = DB::dql(
'select coll from Plugin\AttachmentCollections\Entity\Collection coll where coll.actor_id = :id',
['id' => $user->getId()]
);
// add to collection form
$attachment_id = $vars['vars']['attachment_id'];
$choices = [];
foreach ($colls as $col) {
$choices[$col->getName()] = $col->getId();
}
$already_selected = DB::dql(
'select entry.collection_id from attachment_album_entry entry '
. 'inner join attachment_collection collection '
. 'with collection.id = entry.collection_id '
. 'where entry.attachment_id = :aid and collection.actor_id = :id',
['aid' => $attachment_id, 'id' => $user->getId()]
);
$already_selected = \array_map(fn ($x) => $x['collection_id'], $already_selected);
$add_form = Form::create([
['collections', ChoiceType::class, [
'choices' => $choices,
'multiple' => true,
'required' => false,
'choice_attr' => function ($id) use ($already_selected) {
if (\in_array($id, $already_selected)) {
return ['selected' => 'selected'];
}
return [];
}
]],
['add', SubmitType::class, [
'label' => _m('Add to collections'),
'attr' => [
'title' => _m('Add to collection'),
],
]],
]);
$add_form->handleRequest($request);
if ($add_form->isSubmitted() && $add_form->isValid()) {
$collections = $add_form->getData()['collections'];
$removed = \array_filter($already_selected, fn ($x) => !\in_array($x, $collections));
$added = \array_filter($collections, fn ($x) => !\in_array($x, $already_selected));
if (\count($removed)) {
DB::dql(
'delete from Plugin\AttachmentCollections\Entity\CollectionEntry entry '
. 'where entry.attachment_id = :aid and entry.collection_id in ('
. 'select collection.id from Plugin\AttachmentCollections\Entity\Collection collection '
. 'where collection.id in (:ids) '
// prevent user from deleting something he doesn't own:
. 'and collection.actor_id = :id'
. ')',
['aid' => $attachment_id, 'id' => $user->getId(), 'ids' => $removed]
);
}
foreach ($added as $cid) {
DB::persist(CollectionEntry::create([
'attachment_id' => $attachment_id,
'collection_id' => $cid,
]));
}
DB::flush();
}
// add to new collection form
$create_form = Form::create([
['name', TextType::class, [
'label' => _m('Collection name'),
'attr' => [
'placeholder' => _m('Name'),
'required' => 'required'
],
'data' => '',
]],
['create', SubmitType::class, [
'label' => _m('Create a new collection'),
'attr' => [
'title' => _m('Create a new collection'),
],
]],
]);
$create_form->handleRequest($request);
if ($create_form->isSubmitted() && $create_form->isValid()) {
$name = $create_form->getData()['name'];
$coll = Collection::create([
'name' => $name,
'actor_id' => $user->getId(),
]);
DB::persist($coll);
DB::flush();
DB::persist(CollectionEntry::create([
'attachment_id' => $attachment_id,
'collection_id' => $coll->getId(),
]));
DB::flush();
}
$res[] = Formatting::twigRenderFile(
'AttachmentCollections/widget.html.twig',
[
'colls' => $colls,
'add_form' => $add_form->createView(),
'create_form' => $create_form->createView(),
]
);
return Event::next;
}
/**
* Output our dedicated stylesheet
*
* @param array $styles stylesheets path
*
* @return bool hook value; true means continue processing, false means stop
*/
public function onEndShowStyles(array &$styles, string $route): bool
{
$styles[] = 'plugins/AttachmentCollections/assets/css/widget.css';
$styles[] = 'plugins/AttachmentCollections/assets/css/pages.css';
return Event::next;
}
}

View File

@ -0,0 +1,182 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Plugin\AttachmentCollections\Controller;
use App\Core\Form;
use App\Core\DB\DB;
use App\Util\Common;
use App\Core\Router\Router;
use function App\Core\I18n\_m;
use Component\Feed\Util\FeedController;
use Symfony\Component\HttpFoundation\Request;
use Plugin\AttachmentCollections\Entity\Collection;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class Controller extends FeedController
{
public function collectionsByActorNickname(Request $request, string $nickname): array
{
$user = DB::findOneBy('local_user', ['nickname' => $nickname]);
return self::collectionsView($request, $user->getId(), $nickname);
}
public function collectionsViewByActorId(Request $request, int $id): array
{
return self::collectionsView($request, $id, null);
}
public function collectionsView(Request $request, int $id, ?string $nickname): array
{
$collections = DB::dql(
'select collection from Plugin\AttachmentCollections\Entity\Collection collection '
. 'where collection.actor_id = :id',
['id' => $id]
);
$create = null;
if (Common::user()?->getId() === $id) {
$create = Form::create([
['name', TextType::class, [
'label' => _m('Create collection'),
'attr' => [
'placeholder' => _m('Name'),
'required' => 'required'
],
'data' => '',
]],
['add_collection', SubmitType::class, [
'label' => _m('Create collection'),
'attr' => [
'title' => _m('Create collection'),
],
]],
]);
$create->handleRequest($request);
if ($create->isSubmitted() && $create->isValid()) {
DB::persist(Collection::create([
'name' => $create->getData()['name'],
'actor_id' => $id,
]));
DB::flush();
}
}
$fn = new class ($id, $nickname, $request)
{
private $id;
private $nick;
private $request;
public function __construct($id, $nickname, $request)
{
$this->id = $id;
$this->nick = $nickname;
$this->request = $request;
}
public function getUrl($cid)
{
if (\is_null($this->nick)) {
return Router::url(
'collection_notes_view_by_actor_id',
['id' => $this->id, 'cid' => $cid]
);
}
return Router::url(
'collection_notes_view_by_nickname',
['nickname' => $this->nick, 'cid' => $cid]
);
}
public function editForm($collection)
{
$edit = Form::create([
['name', TextType::class, [
'attr' => [
'placeholder' => 'New name',
'required' => 'required'
],
'data' => '',
]],
['update_'.$collection->getId(), SubmitType::class, [
'label' => _m('Save'),
'attr' => [
'title' => _m('Save'),
],
]],
]);
$edit->handleRequest($this->request);
if ($edit->isSubmitted() && $edit->isValid()) {
$collection->setName($edit->getData()['name']);
DB::persist($collection);
DB::flush();
}
return $edit->createView();
}
public function rmForm($collection)
{
$rm = Form::create([
['remove_'.$collection->getId(), SubmitType::class, [
'label' => _m('Delete collection'),
'attr' => [
'title' => _m('Delete collection'),
'class' => 'danger',
],
]],
]);
$rm->handleRequest($this->request);
if ($rm->isSubmitted()) {
DB::remove($collection);
DB::flush();
}
return $rm->createView();
}
};
return [
'_template' => 'AttachmentCollections/collections.html.twig',
'page_title' => 'Attachment Collections list',
'add_collection' => $create?->createView(),
'fn' => $fn,
'collections' => $collections,
];
}
public function collectionNotesByNickname(Request $request, string $nickname, int $cid): array
{
$user = DB::findOneBy('local_user', ['nickname' => $nickname]);
return self::collectionNotesByActorId($request, $user->getId(), $cid);
}
public function collectionNotesByActorId(Request $request, int $id, int $cid): array
{
$collection = DB::findOneBy('attachment_collection', ['id' => $cid]);
$attchs = DB::dql(
'select attch from attachment_album_entry entry '
. 'left join Component\Attachment\Entity\Attachment attch '
. 'with entry.attachment_id = attch.id '
. 'where entry.collection_id = :cid',
['cid' => $cid]
);
return [
'_template' => 'AttachmentCollections/collection.html.twig',
'page_title' => $collection->getName(),
'attachments' => $attchs,
];
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace Plugin\AttachmentCollections\Entity;
use App\Core\Entity;
class Collection extends Entity
{
// These tags are meant to be literally included and will be populated with the appropriate fields, setters and getters by `bin/generate_entity_fields`
// {{{ Autocode
// @codeCoverageIgnoreStart
private int $id;
private ?string $name;
private int $actor_id;
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
public function getId(): int
{
return $this->id;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setActorId(int $actor_id): self
{
$this->actor_id = $actor_id;
return $this;
}
public function getActorId(): int
{
return $this->actor_id;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
public static function schemaDef()
{
return [
'name' => 'attachment_collection',
'fields' => [
'id' => ['type' => 'serial', 'not null' => true, 'description' => 'unique identifier'],
'name' => ['type' => 'varchar', 'length' => 255, 'description' => 'collection\'s name'],
'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to many', 'not null' => true, 'description' => 'foreign key to actor table'],
],
'primary key' => ['id'],
];
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace Plugin\AttachmentCollections\Entity;
use App\Core\Entity;
class CollectionEntry extends Entity
{
// These tags are meant to be literally included and will be populated with the appropriate fields, setters and getters by `bin/generate_entity_fields`
// {{{ Autocode
// @codeCoverageIgnoreStart
private int $id;
private int $attachment_id;
private int $collection_id;
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
public function getId(): int
{
return $this->id;
}
public function setAttachmentId(int $attachment_id): self
{
$this->attachment_id = $attachment_id;
return $this;
}
public function getAttachmentId(): int
{
return $this->attachment_id;
}
public function setCollectionId(int $collection_id): self
{
$this->collection_id = $collection_id;
return $this;
}
public function getCollectionId(): int
{
return $this->collection_id;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
public static function schemaDef()
{
return [
'name' => 'attachment_album_entry',
'fields' => [
'id' => ['type' => 'serial', 'not null' => true, 'description' => 'unique identifier'],
'attachment_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Attachment.id', 'multiplicity' => 'one to one', 'not null' => true, 'description' => 'foreign key to attachment table'],
'collection_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'AttachmentCollection.id', 'multiplicity' => 'one to one', 'not null' => true, 'description' => 'foreign key to attachment_collection table'],
],
'primary key' => ['id'],
];
}
}

View File

@ -0,0 +1,26 @@
{% extends 'stdgrid.html.twig' %}
{% import '/cards/note/view.html.twig' as noteView %}
{% block title %}{{ page_title | trans }}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('assets/default_theme/css/pages/feeds.css') }}" type="text/css">
{% endblock stylesheets %}
{% block body %}
<h1>{{ page_title | trans }}</h1>
{# Backwards compatibility with hAtom 0.1 #}
<main class="feed" tabindex="0" role="feed">
<div class="h-feed hfeed notes">
{% for attachment in attachments %}
<section class="section-widget section-padding">
{% include '/cards/attachments/view.html.twig' with {'attachment': attachment, 'note': null} only%}
<a class="section-widget-button-like" href="{{ path('attachment_download', {'id': attachment.id}) }}"> {{ 'Download link' | trans }}</a>
</section>
{% else %}
<div id="empty-notes"><h1>{% trans %}No attachments here.{% endtrans %}</h1></div>
{% endfor %}
</div>
</main>
{% endblock body %}

View File

@ -0,0 +1,43 @@
{% extends 'stdgrid.html.twig' %}
{% import '/cards/note/view.html.twig' as noteView %}
{% block title %}{{ page_title | trans }}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('assets/default_theme/css/pages/feeds.css') }}" type="text/css">
{% endblock stylesheets %}
{% block body %}
<h1>{{ 'Attachment Collections' | trans }}</h1>
{# Backwards compatibility with hAtom 0.1 #}
<main class="feed" tabindex="0" role="feed">
<div class="h-feed hfeed notes">
{% if add_collection %}
<div class="h-entry hentry note attachment-collection-add">
{{ form(add_collection) }}
</div>
{% endif %}
<div class="h-entry hentry note attachment-collections-list">
<h3>{{ 'Your collections' | trans }}</h3>
{% for col in collections %}
<div class="attachment-collection-item">
<a class="name" href="{{ fn.getUrl(col.id) }}">{{ col.name }}</a>
<details title="Expand if you want to edit the collection's name">
<summary>
<div class="collection-action">{{ icon('edit') | raw }}</div>
</summary>
{{ form(fn.editForm(col)) }}
</details>
<details title="Expand if you want to delete the collection">
<summary>
<div class="collection-action">{{ icon('delete') | raw }}</div>
</summary>
{{ form(fn.rmForm(col)) }}
</details>
</div>
{% endfor %}
</div>
</div>
</main>
{% endblock body %}

View File

@ -0,0 +1,18 @@
<section class="section-widget section-widget-padded attachment-collections">
<details class="section-widget-title-details" title="Expand if you want to access more options.">
<summary class="section-title-summary">
<h2>{% trans %}Add to collection{% endtrans %}</h2>
{{ icon('arrow-down', 'icon icon-details-open') | raw }}
</summary>
{{ form(add_form) }}
<br/>
<details class="section-widget-subtitle-details" title="Expand if you want to access more options.">
<summary class="section-subtitle-summary">
<h3>{% trans %}More options{% endtrans %}</h3>
{{ icon('arrow-down', 'icon icon-details-close') | raw }}
</summary>
{{ form(create_form) }}
</details>
</details>
</section>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- https://github.com/primer/octicons -->
<!-- MIT License -->
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" class="{{ iconClass|default('') }}">
<title>Delete</title>
<path fill-rule="evenodd" d="M2.343 13.657A8 8 0 1113.657 2.343 8 8 0 012.343 13.657zM6.03 4.97a.75.75 0 00-1.06 1.06L6.94 8 4.97 9.97a.75.75 0 101.06 1.06L8 9.06l1.97 1.97a.75.75 0 101.06-1.06L9.06 8l1.97-1.97a.75.75 0 10-1.06-1.06L8 6.94 6.03 4.97z"></path>
</svg>

After

Width:  |  Height:  |  Size: 535 B

View File

@ -0,0 +1,73 @@
.attachment-collection-add, .attachment-collections-list {
padding: 10px 12px;
}
.attachment-collection-add > form > div {
display: flex;
align-items: flex-end;
}
.attachment-collection-add > form > div .mb-6 {
margin-right: 12px;
}
.attachment-collection-add > form > div button {
margin-top: 0px;
margin-bottom: var(--s);
}
@media only screen and (max-width:465px) {
.attachment-collection-add > form, .attachment-collection-add > form > div .mb-6 {
width: 100%;
margin: 0px;
}
.attachment-collection-add > form > div {
flex-direction: column;
}
.attachment-collection-add > form > div button {
margin-top: var(--s);;
margin-bottom: 0px;
}
}
:root {
--collections-list-quantity: 3;
}
.attachment-collections-list {
display: grid !important;
grid-gap: 12px;
grid-template-columns: repeat(var(--collections-list-quantity), 1fr);
}
.attachment-collections-list h3, .attachment-collections-list h2, .attachment-collections-list h1 {
grid-column-start: 1;
grid-column-end: calc(var(--collections-list-quantity) + 1);
}
.attachment-collections-list .attachment-collection-item {
border: 2px solid var(--border);
border-radius: var(--s);
padding: 10px 20px;
display: flex;
flex-direction: column;
position: relative;
}
.attachment-collections-list .attachment-collection-item .name {
margin-right: auto;
flex-grow: 1;
flex-shrink: 1;
word-break: break-word;
margin-right: 60px;
}
.attachment-collections-list .attachment-collection-item summary {
position: absolute;
top: 10px;
right: 50px;
width: 16px;
}
.attachment-collections-list .attachment-collection-item details + details > summary {
right: 20px;
}
.attachment-collections-list .attachment-collection-item details {
margin-top: 12px;
}
.attachment-collections-list .attachment-collection-item details label {
display: none;
}
.attachment-collections-list .attachment-collection-item details .danger {
color: #cb2d2d;
}

View File

@ -0,0 +1,12 @@
.attachment-collections {
background-color: red;
}
.attachment-collections .attachment-collections-selections-options {
display: flex;
margin-top: 12px;
align-items: center;
justify-content: space-between;
}
.attachment-collections .attachment-collections-selections-options button {
margin: 0 !important;
}