Class: Endpoints::PushSubscriber

Inherits:
NonCrudEndpoints
  • Object
show all
Defined in:
app/models/endpoints/push_subscriber.rb

Instance Method Summary collapse

Instance Method Details

#acknowledge(params) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
# File 'app/models/endpoints/push_subscriber.rb', line 99

def acknowledge(params)
  message = PushMessage.find_by(id: params[:push_message_id])
  return [{ error: 'Message not found' }, 404] unless message

  now = Time.current
  message.update!(received_at: now) if params[:received] && message.received_at.nil?
  message.update!(read_at: now) if params[:read] && message.read_at.nil?
  [message, 200]
rescue ActiveRecord::RecordInvalid => e
  [{ error: e.message }, 422]
end

#send_push(params) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'app/models/endpoints/push_subscriber.rb', line 70

def send_push(params)
  subscriber = PushSubscriber.active.find_by(id: params[:push_subscriber_id])
  return [{ error: 'Subscriber not found' }, 404] unless subscriber
  message = subscriber.push_messages.build(
    title: params[:title],
    body: params[:body],
    url: params[:url],
    icon: params[:icon]
  )
  unless message.save
    return [{ error: message.errors.full_messages.join(', ') }, 422]
  end
  ThecoreBackendCommons::PushNotificationService.dispatch(subscriber, message)
  [message, 201]
rescue => e
  [{ error: e.message }, 500]
end

#subscribe(params) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/endpoints/push_subscriber.rb', line 43

def subscribe(params)
  user = User.find(params[:current_user_id])
  subscriber = PushSubscriber.subscribe_for(
    user,
    endpoint: params[:endpoint],
    p256dh: params[:p256dh],
    auth: params[:auth],
    user_agent: params[:user_agent]
  )
  status = subscriber.previously_new_record? ? 201 : 200
  [subscriber, status]
rescue ActiveRecord::RecordInvalid => e
  [{ error: e.message }, 422]
end

#vapid_public_key(params) ⇒ Object



27
28
29
30
# File 'app/models/endpoints/push_subscriber.rb', line 27

def vapid_public_key(params)
  key = ThecoreSettings::Setting.where(ns: :vapid, key: :public_key).pluck(:raw).first
  [{ vapid_public_key: key }, 200]
end