forked from discourse/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbookmark_manager.rb
72 lines (55 loc) · 1.92 KB
/
bookmark_manager.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# frozen_string_literal: true
class BookmarkManager
include HasErrors
def initialize(user)
@user = user
end
def create(post_id:, name: nil, reminder_type: nil, reminder_at: nil)
post = Post.unscoped.includes(:topic).find(post_id)
reminder_type = Bookmark.reminder_types[reminder_type.to_sym] if reminder_type.present?
raise Discourse::InvalidAccess.new if !Guardian.new(@user).can_see_post?(post)
bookmark = Bookmark.create(
user_id: @user.id,
topic: post.topic,
post: post,
name: name,
reminder_type: reminder_type,
reminder_at: reminder_at,
reminder_set_at: Time.zone.now
)
if bookmark.errors.any?
return add_errors_from(bookmark)
end
BookmarkReminderNotificationHandler.cache_pending_at_desktop_reminder(@user)
bookmark
end
def destroy(bookmark_id)
bookmark = Bookmark.find_by(id: bookmark_id)
raise Discourse::NotFound if bookmark.blank?
raise Discourse::InvalidAccess.new if !Guardian.new(@user).can_delete?(bookmark)
bookmark.destroy
clear_at_desktop_cache_if_required
end
def destroy_for_topic(topic)
topic_bookmarks = Bookmark.where(user_id: @user.id, topic_id: topic.id)
Bookmark.transaction do
topic_bookmarks.each do |bookmark|
raise Discourse::InvalidAccess.new if !Guardian.new(@user).can_delete?(bookmark)
bookmark.destroy
end
end
clear_at_desktop_cache_if_required
end
def self.send_reminder_notification(id)
bookmark = Bookmark.find_by(id: id)
BookmarkReminderNotificationHandler.send_notification(bookmark)
end
private
def clear_at_desktop_cache_if_required
return if user_has_any_pending_at_desktop_reminders?
Discourse.redis.del(BookmarkReminderNotificationHandler::PENDING_AT_DESKTOP_KEY_PREFIX + @user.id.to_s)
end
def user_has_any_pending_at_desktop_reminders?
Bookmark.at_desktop_reminders_for_user(@user).any?
end
end