discourse/lib/bookmark_reminder_notification_handler.rb
Martin Brennan 222c8d9b6a
FEATURE: Polymorphic bookmarks pt. 3 (reminders, imports, exports, refactors) (#16591)
A bit of a mixed bag, this addresses several edge areas of bookmarks and makes them compatible with polymorphic bookmarks (hidden behind the `use_polymorphic_bookmarks` site setting). The main ones are:

* ExportUserArchive compatibility
* SyncTopicUserBookmarked job compatibility
* Sending different notifications for the bookmark reminders based on the bookmarkable type
* Import scripts compatibility
* BookmarkReminderNotificationHandler compatibility

This PR also refactors the `register_bookmarkable` API so it accepts a class descended from a `BaseBookmarkable` class instead. This was done because we kept having to add more and more lambdas/properties inline and it was very messy, so a factory pattern is cleaner. The classes can be tested independently as well.

Some later PRs will address some other areas like the discourse narrative bot, advanced search, reports, and the .ics endpoint for bookmarks.
2022-05-09 09:37:23 +10:00

69 lines
1.7 KiB
Ruby

# frozen_string_literal: true
class BookmarkReminderNotificationHandler
attr_reader :bookmark
def initialize(bookmark)
@bookmark = bookmark
end
def send_notification
return if bookmark.blank?
Bookmark.transaction do
# TODO (martin) [POLYBOOK] Can probably change this to call the
# can_send_reminder? on the registered bookmarkable directly instead
# of having can_send_reminder?
if !can_send_reminder?
clear_reminder
else
create_notification
if bookmark.auto_delete_when_reminder_sent?
BookmarkManager.new(bookmark.user).destroy(bookmark.id)
end
clear_reminder
end
end
end
private
def clear_reminder
Rails.logger.debug(
"Clearing bookmark reminder for bookmark_id #{bookmark.id}. reminder at: #{bookmark.reminder_at}"
)
if bookmark.auto_clear_reminder_when_reminder_sent?
bookmark.reminder_at = nil
end
bookmark.clear_reminder!
end
def can_send_reminder?
if SiteSetting.use_polymorphic_bookmarks
bookmark.registered_bookmarkable.can_send_reminder?(bookmark)
else
bookmark.post.present? && bookmark.topic.present?
end
end
def create_notification
if SiteSetting.use_polymorphic_bookmarks
bookmark.registered_bookmarkable.send_reminder_notification(bookmark)
else
bookmark.user.notifications.create!(
notification_type: Notification.types[:bookmark_reminder],
topic_id: bookmark.topic_id,
post_number: bookmark.post.post_number,
data: {
topic_title: bookmark.topic.title,
display_username: bookmark.user.username,
bookmark_name: bookmark.name
}.to_json
)
end
end
end