Skip to content

Commit 221c6c7

Browse files
committed
Comment Mentions: Added core back-end logic
- Added new user notification preference, opt-in by default - Added parser to extract mentions from comment HTML, with tests to cover. - Added notification and notification handling Not yet tested, needs testing coverage.
1 parent e2f91c2 commit 221c6c7

File tree

13 files changed

+260
-1
lines changed

13 files changed

+260
-1
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace BookStack\Activity\Models;
4+
5+
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Support\Carbon;
7+
8+
/**
9+
* @property int $id
10+
* @property string $mentionable_type
11+
* @property int $mentionable_id
12+
* @property int $from_user_id
13+
* @property int $to_user_id
14+
* @property Carbon $created_at
15+
* @property Carbon $updated_at
16+
*/
17+
class MentionHistory extends Model
18+
{
19+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
<?php
2+
3+
namespace BookStack\Activity\Notifications\Handlers;
4+
5+
use BookStack\Activity\ActivityType;
6+
use BookStack\Activity\Models\Activity;
7+
use BookStack\Activity\Models\Comment;
8+
use BookStack\Activity\Models\Loggable;
9+
use BookStack\Activity\Models\MentionHistory;
10+
use BookStack\Activity\Notifications\Messages\CommentMentionNotification;
11+
use BookStack\Activity\Tools\MentionParser;
12+
use BookStack\Entities\Models\Page;
13+
use BookStack\Settings\UserNotificationPreferences;
14+
use BookStack\Users\Models\User;
15+
use Illuminate\Database\Eloquent\Collection;
16+
use Illuminate\Support\Carbon;
17+
18+
class CommentMentionNotificationHandler extends BaseNotificationHandler
19+
{
20+
public function handle(Activity $activity, Loggable|string $detail, User $user): void
21+
{
22+
$page = $detail->entity;
23+
if (!($detail instanceof Comment) || !($page instanceof Page)) {
24+
throw new \InvalidArgumentException("Detail for comment mention notifications must be a comment on a page");
25+
}
26+
27+
$parser = new MentionParser();
28+
$mentionedUserIds = $parser->parseUserIdsFromHtml($detail->html);
29+
$realMentionedUsers = User::whereIn('id', $mentionedUserIds)->get();
30+
31+
$receivingNotifications = $realMentionedUsers->filter(function (User $user) {
32+
$prefs = new UserNotificationPreferences($user);
33+
return $prefs->notifyOnCommentMentions();
34+
});
35+
$receivingNotificationsUserIds = $receivingNotifications->pluck('id')->toArray();
36+
37+
$userMentionsToLog = $realMentionedUsers;
38+
39+
// When an edit, we check our history to see if we've already notified the user about this comment before
40+
// so that we can filter them out to avoid double notifications.
41+
if ($activity->type === ActivityType::COMMENT_UPDATE) {
42+
$previouslyNotifiedUserIds = $this->getPreviouslyNotifiedUserIds($detail);
43+
$receivingNotificationsUserIds = array_values(array_diff($receivingNotificationsUserIds, $previouslyNotifiedUserIds));
44+
$userMentionsToLog = $userMentionsToLog->filter(function (User $user) use ($previouslyNotifiedUserIds) {
45+
return !in_array($user->id, $previouslyNotifiedUserIds);
46+
});
47+
}
48+
49+
$this->logMentions($userMentionsToLog, $detail, $user);
50+
$this->sendNotificationToUserIds(CommentMentionNotification::class, $receivingNotificationsUserIds, $user, $detail, $page);
51+
}
52+
53+
protected function logMentions(Collection $mentionedUsers, Comment $comment, User $fromUser): void
54+
{
55+
$mentions = [];
56+
$now = Carbon::now();
57+
58+
foreach ($mentionedUsers as $mentionedUser) {
59+
$mentions[] = [
60+
'mentionable_type' => $comment->getMorphClass(),
61+
'mentionable_id' => $comment->id,
62+
'from_user_id' => $fromUser->id,
63+
'to_user_id' => $mentionedUser->id,
64+
'created_at' => $now,
65+
'updated_at' => $now,
66+
];
67+
}
68+
69+
MentionHistory::query()->insert($mentions);
70+
}
71+
72+
protected function getPreviouslyNotifiedUserIds(Comment $comment): array
73+
{
74+
return MentionHistory::query()
75+
->where('mentionable_id', $comment->id)
76+
->where('mentionable_type', $comment->getMorphClass())
77+
->pluck('to_user_id')
78+
->toArray();
79+
}
80+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
namespace BookStack\Activity\Notifications\Messages;
4+
5+
use BookStack\Activity\Models\Comment;
6+
use BookStack\Activity\Notifications\MessageParts\EntityLinkMessageLine;
7+
use BookStack\Activity\Notifications\MessageParts\ListMessageLine;
8+
use BookStack\Entities\Models\Page;
9+
use BookStack\Users\Models\User;
10+
use Illuminate\Notifications\Messages\MailMessage;
11+
12+
class CommentMentionNotification extends BaseActivityNotification
13+
{
14+
public function toMail(User $notifiable): MailMessage
15+
{
16+
/** @var Comment $comment */
17+
$comment = $this->detail;
18+
/** @var Page $page */
19+
$page = $comment->entity;
20+
21+
$locale = $notifiable->getLocale();
22+
23+
$listLines = array_filter([
24+
$locale->trans('notifications.detail_page_name') => new EntityLinkMessageLine($page),
25+
$locale->trans('notifications.detail_page_path') => $this->buildPagePathLine($page, $notifiable),
26+
$locale->trans('notifications.detail_commenter') => $this->user->name,
27+
$locale->trans('notifications.detail_comment') => strip_tags($comment->html),
28+
]);
29+
30+
return $this->newMailMessage($locale)
31+
->subject($locale->trans('notifications.comment_mention_subject', ['pageName' => $page->getShortName()]))
32+
->line($locale->trans('notifications.comment_mention_intro', ['appName' => setting('app-name')]))
33+
->line(new ListMessageLine($listLines))
34+
->action($locale->trans('notifications.action_view_comment'), $page->getUrl('#comment' . $comment->local_id))
35+
->line($this->buildReasonFooterLine($locale));
36+
}
37+
}

app/Activity/Notifications/NotificationManager.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use BookStack\Activity\Models\Activity;
77
use BookStack\Activity\Models\Loggable;
88
use BookStack\Activity\Notifications\Handlers\CommentCreationNotificationHandler;
9+
use BookStack\Activity\Notifications\Handlers\CommentMentionNotificationHandler;
910
use BookStack\Activity\Notifications\Handlers\NotificationHandler;
1011
use BookStack\Activity\Notifications\Handlers\PageCreationNotificationHandler;
1112
use BookStack\Activity\Notifications\Handlers\PageUpdateNotificationHandler;
@@ -48,5 +49,7 @@ public function loadDefaultHandlers(): void
4849
$this->registerHandler(ActivityType::PAGE_CREATE, PageCreationNotificationHandler::class);
4950
$this->registerHandler(ActivityType::PAGE_UPDATE, PageUpdateNotificationHandler::class);
5051
$this->registerHandler(ActivityType::COMMENT_CREATE, CommentCreationNotificationHandler::class);
52+
$this->registerHandler(ActivityType::COMMENT_CREATE, CommentMentionNotificationHandler::class);
53+
$this->registerHandler(ActivityType::COMMENT_UPDATE, CommentMentionNotificationHandler::class);
5154
}
5255
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
namespace BookStack\Activity\Tools;
4+
5+
use BookStack\Util\HtmlDocument;
6+
use DOMElement;
7+
8+
class MentionParser
9+
{
10+
public function parseUserIdsFromHtml(string $html): array
11+
{
12+
$doc = new HtmlDocument($html);
13+
14+
$ids = [];
15+
$mentionLinks = $doc->queryXPath('//a[@data-mention-user-id]');
16+
17+
foreach ($mentionLinks as $link) {
18+
if ($link instanceof DOMElement) {
19+
$id = intval($link->getAttribute('data-mention-user-id'));
20+
if ($id > 0) {
21+
$ids[] = $id;
22+
}
23+
}
24+
}
25+
26+
return array_values(array_unique($ids));
27+
}
28+
}

app/App/Providers/AppServiceProvider.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace BookStack\App\Providers;
44

55
use BookStack\Access\SocialDriverManager;
6+
use BookStack\Activity\Models\Comment;
67
use BookStack\Activity\Tools\ActivityLogger;
78
use BookStack\Entities\Models\Book;
89
use BookStack\Entities\Models\Bookshelf;
@@ -73,6 +74,7 @@ public function boot(): void
7374
'book' => Book::class,
7475
'chapter' => Chapter::class,
7576
'page' => Page::class,
77+
'comment' => Comment::class,
7678
]);
7779
}
7880
}

app/Config/setting-defaults.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
'bookshelves_view_type' => env('APP_VIEWS_BOOKSHELVES', 'grid'),
4242
'bookshelf_view_type' => env('APP_VIEWS_BOOKSHELF', 'grid'),
4343
'books_view_type' => env('APP_VIEWS_BOOKS', 'grid'),
44+
'notifications#comment-mentions' => true,
4445
],
4546

4647
];

app/Settings/UserNotificationPreferences.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,14 @@ public function notifyOnCommentReplies(): bool
2626
return $this->getNotificationSetting('comment-replies');
2727
}
2828

29+
public function notifyOnCommentMentions(): bool
30+
{
31+
return $this->getNotificationSetting('comment-mentions');
32+
}
33+
2934
public function updateFromSettingsArray(array $settings)
3035
{
31-
$allowList = ['own-page-changes', 'own-page-comments', 'comment-replies'];
36+
$allowList = ['own-page-changes', 'own-page-comments', 'comment-replies', 'comment-mentions'];
3237
foreach ($settings as $setting => $status) {
3338
if (!in_array($setting, $allowList)) {
3439
continue;
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
use Illuminate\Database\Migrations\Migration;
4+
use Illuminate\Database\Schema\Blueprint;
5+
use Illuminate\Support\Facades\Schema;
6+
7+
return new class extends Migration
8+
{
9+
/**
10+
* Run the migrations.
11+
*/
12+
public function up(): void
13+
{
14+
Schema::create('mention_history', function (Blueprint $table) {
15+
$table->increments('id');
16+
$table->string('mentionable_type', 50)->index();
17+
$table->unsignedBigInteger('mentionable_id')->index();
18+
$table->unsignedInteger('from_user_id')->index();
19+
$table->unsignedInteger('to_user_id');
20+
$table->timestamps();
21+
});
22+
}
23+
24+
/**
25+
* Reverse the migrations.
26+
*/
27+
public function down(): void
28+
{
29+
Schema::dropIfExists('mention_history');
30+
}
31+
};

lang/en/notifications.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
'updated_page_subject' => 'Updated page: :pageName',
1212
'updated_page_intro' => 'A page has been updated in :appName:',
1313
'updated_page_debounce' => 'To prevent a mass of notifications, for a while you won\'t be sent notifications for further edits to this page by the same editor.',
14+
'comment_mention_subject' => 'You were mentioned in a comment on :pageName',
15+
'comment_mention_intro' => 'You were mentioned in a comment on :appName:',
1416

1517
'detail_page_name' => 'Page Name:',
1618
'detail_page_path' => 'Page Path:',

0 commit comments

Comments
 (0)