Skip to content

Instantly share code, notes, and snippets.

@ydaniju
Last active June 10, 2018 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ydaniju/feebe10f4cd2630c00b8030ea793e889 to your computer and use it in GitHub Desktop.
Save ydaniju/feebe10f4cd2630c00b8030ea793e889 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "httparty"
class FirebaseMessaging
include HTTParty
default_timeout 30
format :json
base_uri "https://fcm.googleapis.com/fcm"
def create_device_group(name:, ids: [])
group_operation(key_name: name, ids: ids, type: "create")
end
def add_devices(key:, key_name:, ids:)
group_operation(key: key, key_name: key_name, ids: ids, type: "add")
end
def remove_devices(key:, key_name:, ids:)
group_operation(key: key, key_name: key_name, ids: ids, type: "remove")
end
def retrieve_notification_key(key_name:)
params = { headers: build_header }
self.class.get("/notification?notification_key_name=#{key_name}", params)
end
def send_group_notification(key:, title:, body:, data: {})
params = {
body: notification_body(key, title, body, data).to_json,
headers: build_header
}
self.class.post("/send", params)
end
private
def notification_body(key, title, body, data)
{
to: key,
notification: { title: title, body: body },
data: data,
android: { notification: { sound: "default" } }
}
end
def group_operation(**kwargs)
body = {
"operation": kwargs[:type],
notification_key_name: kwargs[:key_name],
registration_ids: kwargs[:ids]
}.tap { |h| h.merge(notification_key: kwargs[:key]) if kwargs[:key] }
params = { body: body.to_json, headers: build_header }
self.class.post("/notification", params)
end
def build_header(extras = {})
{
"Authorization" => "key=#{ENV['FIREBASE_SERVER_KEY']}",
"project_id" => ENV["FIREBASE_PROJECT_ID"],
"Content-Type" => "application/json"
}.merge(extras)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment