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



114
115
116
117
118
119
120
121
122
123
124
# File 'app/models/endpoints/push_subscriber.rb', line 114

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.as_json(PushMessage.json_attrs), 200]
rescue ActiveRecord::RecordInvalid => e
  [{ error: e.message }, 422]
end

#broadcast_push(params) ⇒ Object



94
95
96
97
98
99
100
101
# File 'app/models/endpoints/push_subscriber.rb', line 94

def broadcast_push(params)
  return [{ error: 'title is required' }, 422] if params[:title].blank?
  return [{ error: 'body is required' }, 422] if params[:body].blank?

  broadcast_push_all(params)
rescue => e
  [{ error: e.message }, 500]
end

#send_push(params) ⇒ Object



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

def send_push(params)
  return [{ error: 'title is required' }, 422] if params[:title].blank?
  return [{ error: 'body is required' }, 422] if params[:body].blank?

  if params[:push_subscriber_ids].present?
    send_push_bulk(params)
  else
    send_push_single(params)
  end
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