fix(notifications): notify actors after activities insert / update using model callback methods

--> Remove sql triggers because most shared hosting plans prevent using them
This commit is contained in:
Yassine Doghri 2022-09-08 11:50:23 +00:00
parent 460f52f70e
commit e08555a4e9
10 changed files with 98 additions and 126 deletions

View File

@ -1,50 +0,0 @@
<?php
declare(strict_types=1);
/**
* Class AddActivitiesTriggerAfterInsert Creates activities trigger in database
*
* @copyright 2020 Ad Aures
* @license https://www.gnu.org/licenses/agpl-3.0.en.html AGPL3
* @link https://castopod.org/
*/
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddActivitiesTriggerAfterInsert extends Migration
{
public function up(): void
{
$activitiesTable = $this->db->prefixTable(config('Fediverse')->tablesPrefix . 'activities');
$notificationsTable = $this->db->prefixTable('notifications');
$createQuery = <<<CODE_SAMPLE
CREATE TRIGGER `{$activitiesTable}_after_insert`
AFTER INSERT ON `{$activitiesTable}`
FOR EACH ROW
BEGIN
-- only create notification if new incoming activity with NULL status is created
IF NEW.target_actor_id AND NEW.target_actor_id != NEW.actor_id AND NEW.status IS NULL THEN
IF NEW.type = 'Follow' THEN
INSERT INTO `{$notificationsTable}` (`actor_id`, `target_actor_id`, `activity_id`, `type`, `created_at`, `updated_at`)
VALUES (NEW.actor_id, NEW.target_actor_id, NEW.id, 'follow', NEW.created_at, NEW.created_at);
ELSEIF NEW.type = 'Undo_Follow' THEN
DELETE FROM `{$notificationsTable}`
WHERE `actor_id` = NEW.actor_id
AND `target_actor_id` = NEW.target_actor_id
AND `type` = 'follow';
END IF;
END IF;
END
CODE_SAMPLE;
$this->db->query($createQuery);
}
public function down(): void
{
$activitiesTable = $this->db->prefixTable(config('Fediverse')->tablesPrefix . 'activities');
$this->db->query("DROP TRIGGER IF EXISTS `{$activitiesTable}_after_insert`");
}
}

View File

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
/**
* Class AddActivitiesTriggerAfterUpdate Creates activities trigger in database
*
* @copyright 2020 Ad Aures
* @license https://www.gnu.org/licenses/agpl-3.0.en.html AGPL3
* @link https://castopod.org/
*/
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddActivitiesTriggerAfterUpdate extends Migration
{
public function up(): void
{
$activitiesTable = $this->db->prefixTable(config('Fediverse')->tablesPrefix . 'activities');
$notificationsTable = $this->db->prefixTable('notifications');
$createQuery = <<<CODE_SAMPLE
CREATE TRIGGER `{$activitiesTable}_after_update`
AFTER UPDATE ON `{$activitiesTable}`
FOR EACH ROW
BEGIN
-- only create notification if new incoming activity with NULL status is created
IF NEW.target_actor_id AND NEW.target_actor_id != NEW.actor_id AND NEW.status IS NULL THEN
IF NEW.type IN ('Create', 'Like', 'Announce') AND OLD.post_id IS NULL AND NEW.post_id IS NOT NULL THEN
SET @type = (CASE
WHEN NEW.type = 'Create' THEN 'reply'
WHEN NEW.type = 'Like' THEN 'like'
WHEN NEW.type = 'Announce' THEN 'share'
END);
INSERT INTO `{$notificationsTable}` (`actor_id`, `target_actor_id`,`post_id`, `activity_id`, `type`, `created_at`, `updated_at`)
VALUES (NEW.actor_id, NEW.target_actor_id,NEW.post_id, NEW.id, @type, NEW.created_at, NEW.created_at);
ELSEIF NEW.type IN ('Undo_Like', 'Undo_Announce') THEN
DELETE FROM `{$notificationsTable}`
WHERE `actor_id` = NEW.actor_id
AND `target_actor_id` = NEW.target_actor_id
AND `type` = (CASE
WHEN NEW.type = 'Undo_Like' THEN 'like'
WHEN NEW.type = 'Undo_Announce' THEN 'share'
END)
AND `post_id` = NEW.post_id;
END IF;
END IF;
END
CODE_SAMPLE;
$this->db->query($createQuery);
}
public function down(): void
{
$activitiesTable = $this->db->prefixTable(config('Fediverse')->tablesPrefix . 'activities');
$this->db->query("DROP TRIGGER IF EXISTS `{$activitiesTable}_after_update`");
}
}

View File

@ -10,13 +10,13 @@ declare(strict_types=1);
namespace Modules\Admin\Controllers;
use App\Entities\Notification;
use App\Entities\Podcast;
use App\Models\NotificationModel;
use App\Models\PodcastModel;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\I18n\Time;
use Modules\Fediverse\Entities\Notification;
use Modules\Fediverse\Models\NotificationModel;
use Modules\Fediverse\Models\PostModel;
class NotificationController extends BaseController

View File

@ -13,7 +13,7 @@ return [
'reply' => '{actor_username} replied to your post',
'favourite' => '{actor_username} favourited your post',
'reblog' => '{actor_username} shared your post',
'follow' => '{actor_username} started following {target_actor_username}',
'follow' => '{actor_username} started following you',
'no_notifications' => 'No notifications',
'mark_all_as_read' => 'Mark all as read',
];

View File

@ -11,9 +11,9 @@ declare(strict_types=1);
namespace Modules\Auth\Entities;
use App\Entities\Podcast;
use App\Models\NotificationModel;
use App\Models\PodcastModel;
use App\Models\UserModel;
use Modules\Fediverse\Models\NotificationModel;
use Myth\Auth\Entities\User as MythAuthUser;
use RuntimeException;

View File

@ -65,11 +65,11 @@ class AddNotifications extends Migration
$this->forge->addForeignKey('target_actor_id', $tablesPrefix . 'actors', 'id', '', 'CASCADE');
$this->forge->addForeignKey('post_id', $tablesPrefix . 'posts', 'id', '', 'CASCADE');
$this->forge->addForeignKey('activity_id', $tablesPrefix . 'activities', 'id', '', 'CASCADE');
$this->forge->createTable('notifications');
$this->forge->createTable($tablesPrefix . 'notifications');
}
public function down(): void
{
$this->forge->dropTable('notifications');
$this->forge->dropTable(config('Fediverse')->tablesPrefix . 'notifications');
}
}

View File

@ -8,12 +8,9 @@ declare(strict_types=1);
* @link https://castopod.org/
*/
namespace App\Entities;
namespace Modules\Fediverse\Entities;
use Michalsn\Uuid\UuidEntity;
use Modules\Fediverse\Entities\Activity;
use Modules\Fediverse\Entities\Actor;
use Modules\Fediverse\Entities\Post;
use Modules\Fediverse\Models\ActorModel;
use Modules\Fediverse\Models\PostModel;
use RuntimeException;

View File

@ -32,6 +32,16 @@ class ActivityModel extends BaseUuidModel
*/
protected $uuidFields = ['id', 'post_id'];
/**
* @var string[]
*/
protected $afterInsert = ['notify'];
/**
* @var string[]
*/
protected $afterUpdate = ['notify'];
/**
* @var string[]
*/
@ -116,4 +126,71 @@ class ActivityModel extends BaseUuidModel
->orderBy('scheduled_at', 'ASC')
->findAll();
}
/**
* @param array<string, array<string|int, mixed>> $data
* @return array<string, array<string|int, mixed>>
*/
protected function notify(array $data): array
{
$activity = (new self())->getActivityById(is_array($data['id']) ? $data['id'][0] : $data['id']);
if (! $activity instanceof Activity) {
return $data;
}
if ($activity->target_actor_id === $activity->actor_id) {
return $data;
}
// notify only if incoming activity (with status set to NULL) is created
if ($activity->status !== null) {
return $data;
}
if ($activity->type === 'Follow') {
(new NotificationModel())->insert([
'actor_id' => $activity->actor_id,
'target_actor_id' => $activity->target_actor_id,
'activity_id' => $activity->id,
'type' => 'follow',
'created_at' => $activity->created_at,
]);
} elseif ($activity->type === 'Undo_Follow') {
(new NotificationModel())->builder()
->delete([
'actor_id' => $activity->actor_id,
'target_actor_id' => $activity->target_actor_id,
'type' => 'follow',
]);
} elseif (in_array($activity->type, ['Create', 'Like', 'Announce'], true) && $activity->post_id !== null) {
(new NotificationModel())->insert([
'actor_id' => $activity->actor_id,
'target_actor_id' => $activity->target_actor_id,
'post_id' => $activity->post_id,
'activity_id' => $activity->id,
'type' => match ($activity->type) {
'Create' => 'reply',
'Like' => 'like',
'Announce' => 'share',
},
'created_at' => $activity->created_at,
]);
} elseif (in_array($activity->type, ['Undo_Like', 'Undo_Announce'], true) && $activity->post_id !== null) {
(new NotificationModel())->builder()
->delete([
'actor_id' => $activity->actor_id,
'target_actor_id' => $activity->target_actor_id,
'post_id' => service('uuid')
->fromString($activity->post_id)
->getBytes(),
'type' => match ($activity->type) {
'Undo_Like' => 'like',
'Undo_Announce' => 'share',
},
]);
}
return $data;
}
}

View File

@ -3,17 +3,16 @@
declare(strict_types=1);
/**
* @copyright 2021 Ad Aures
* @copyright 2022 Ad Aures
* @license https://www.gnu.org/licenses/agpl-3.0.en.html AGPL3
* @link https://castopod.org/
*/
namespace App\Models;
namespace Modules\Fediverse\Models;
use App\Entities\Notification;
use Michalsn\Uuid\UuidModel;
use Modules\Fediverse\Entities\Notification;
class NotificationModel extends UuidModel
class NotificationModel extends BaseUuidModel
{
/**
* @var string
@ -43,5 +42,14 @@ class NotificationModel extends UuidModel
/**
* @var string[]
*/
protected $allowedFields = ['read_at'];
protected $allowedFields = [
'actor_id',
'target_actor_id',
'post_id',
'activity_id',
'type',
'read_at',
'created_at',
'updated_at',
];
}

View File

@ -53,7 +53,6 @@
], null, false),
'follow' => lang('Notifications.follow', [
'actor_username' => $actorUsernameHtml,
'target_actor_username' => $targetActorUsernameHtml,
], null, false),
default => '',
};