jera_push 1.2.3 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (69) hide show
  1. checksums.yaml +4 -4
  2. data/Rakefile +12 -18
  3. data/app/controllers/jera_push/admin/messages_controller.rb +23 -10
  4. data/app/presenters/jera_push/message_presenter.rb +22 -18
  5. data/app/views/jera_push/admin/messages/show.html.erb +7 -4
  6. data/config/locale/jera_push.pt-BR.yml +7 -0
  7. data/config/routes.rb +1 -0
  8. data/lib/generators/active_record/templates/create_jera_push_devices.rb +2 -1
  9. data/lib/generators/active_record/templates/create_jera_push_messages.rb +6 -3
  10. data/lib/generators/active_record/templates/create_jera_push_messages_devices.rb +3 -3
  11. data/lib/generators/jera_push/templates/jera_push.rb +2 -1
  12. data/lib/jera_push/firebase/client.rb +56 -59
  13. data/lib/jera_push/models/device.rb +3 -31
  14. data/lib/jera_push/models/message.rb +2 -142
  15. data/lib/jera_push/models/message_device.rb +1 -0
  16. data/lib/jera_push/services/base_service.rb +23 -0
  17. data/lib/jera_push/services/send_message.rb +23 -8
  18. data/lib/jera_push/services/send_push_service.rb +99 -0
  19. data/lib/jera_push/services/send_to_device_service.rb +52 -0
  20. data/lib/jera_push/services/send_to_devices_service.rb +54 -0
  21. data/lib/jera_push/services/send_to_everyone_service.rb +40 -0
  22. data/lib/jera_push/services/send_to_topic_service.rb +37 -0
  23. data/lib/jera_push/services/topic_service.rb +18 -0
  24. data/lib/jera_push/version.rb +1 -1
  25. data/lib/jera_push.rb +19 -5
  26. metadata +71 -116
  27. data/test/dummy/README.rdoc +0 -28
  28. data/test/dummy/Rakefile +0 -6
  29. data/test/dummy/app/assets/javascripts/application.js +0 -13
  30. data/test/dummy/app/assets/stylesheets/application.css +0 -15
  31. data/test/dummy/app/controllers/application_controller.rb +0 -5
  32. data/test/dummy/app/helpers/application_helper.rb +0 -2
  33. data/test/dummy/app/models/user.rb +0 -3
  34. data/test/dummy/app/views/layouts/application.html.erb +0 -14
  35. data/test/dummy/bin/bundle +0 -3
  36. data/test/dummy/bin/rails +0 -4
  37. data/test/dummy/bin/rake +0 -4
  38. data/test/dummy/bin/setup +0 -29
  39. data/test/dummy/config/application.rb +0 -25
  40. data/test/dummy/config/boot.rb +0 -5
  41. data/test/dummy/config/database.yml +0 -16
  42. data/test/dummy/config/environment.rb +0 -5
  43. data/test/dummy/config/environments/development.rb +0 -41
  44. data/test/dummy/config/environments/production.rb +0 -79
  45. data/test/dummy/config/environments/test.rb +0 -42
  46. data/test/dummy/config/initializers/assets.rb +0 -12
  47. data/test/dummy/config/initializers/backtrace_silencers.rb +0 -7
  48. data/test/dummy/config/initializers/cookies_serializer.rb +0 -3
  49. data/test/dummy/config/initializers/filter_parameter_logging.rb +0 -4
  50. data/test/dummy/config/initializers/inflections.rb +0 -16
  51. data/test/dummy/config/initializers/mime_types.rb +0 -4
  52. data/test/dummy/config/initializers/session_store.rb +0 -3
  53. data/test/dummy/config/initializers/wrap_parameters.rb +0 -14
  54. data/test/dummy/config/locales/en.yml +0 -23
  55. data/test/dummy/config/locales/pt-BR.yml +0 -23
  56. data/test/dummy/config/routes.rb +0 -57
  57. data/test/dummy/config/secrets.yml +0 -22
  58. data/test/dummy/config.ru +0 -4
  59. data/test/dummy/db/migrate/20161005121035_create_users.rb +0 -10
  60. data/test/dummy/db/schema.rb +0 -61
  61. data/test/dummy/db/seeds.rb +0 -70
  62. data/test/dummy/public/404.html +0 -67
  63. data/test/dummy/public/422.html +0 -67
  64. data/test/dummy/public/500.html +0 -66
  65. data/test/dummy/public/favicon.ico +0 -0
  66. data/test/dummy/test/fixtures/users.yml +0 -7
  67. data/test/dummy/test/models/user_test.rb +0 -7
  68. data/test/jera_push_test.rb +0 -7
  69. data/test/test_helper.rb +0 -20
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 94afb52f8fb32e6554bdb73f7b03ba48a1ea0cc57cd1789df19f914593739b45
4
- data.tar.gz: 7586cb6aebe1df7119a2bd9a87ec1cb9de37ac8343c8488477cc5cc99dfc234c
3
+ metadata.gz: f808be96eee74520b6a4907d7147a1cc4881cacb9a01a2d12a08ad81a2003d8f
4
+ data.tar.gz: 301f267535f6edc5f5f614f829c11e5fcbeb49e6541ac9a23e6ec5c230c4778b
5
5
  SHA512:
6
- metadata.gz: 9d917503e6bc9904fab6e3c309856491f2c1230baa7b8cd8e946c9560c9aa938a0be3fc40dbb9e9329869cad622cbf49bf9e88701204b383a94f11e871f7858b
7
- data.tar.gz: b2147d84acdead00ff1351f65e5da1e2ff1061c397b5a754a870f4c112f7bb9c84b57849653fd8bef7adadb0d9207a070755f91a35ad1e1942ea3311114273b0
6
+ metadata.gz: d5494f51637a7f208dd28e7bbad74937b9ce9ccbea88c7f75264a9e1eda79bd3b69197daf5be9f12f5259f0a5582b5a28eb62efbccda64071004aee63602ebe2
7
+ data.tar.gz: 82a894de332a1d3d6af5c95c388a74cf0f937c087d79a2df507322afbb5ea0ed96116ab93f86e4737229d4229595041eca99093ee5283b683f03bd760b40873c
data/Rakefile CHANGED
@@ -1,10 +1,16 @@
1
+ require 'rake'
2
+
1
3
  begin
2
4
  require 'bundler/setup'
5
+
6
+ Bundler::GemHelper.install_tasks
3
7
  rescue LoadError
4
- puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
8
+ puts 'although not required, bundler is recommended for running the tests'
5
9
  end
6
10
 
7
- require 'rdoc/task'
11
+ task default: :spec
12
+
13
+ require 'rspec/core/rake_task'
8
14
 
9
15
  RDoc::Task.new(:rdoc) do |rdoc|
10
16
  rdoc.rdoc_dir = 'rdoc'
@@ -14,21 +20,9 @@ RDoc::Task.new(:rdoc) do |rdoc|
14
20
  rdoc.rdoc_files.include('lib/**/*.rb')
15
21
  end
16
22
 
23
+ require 'rubocop/rake_task'
17
24
 
18
-
19
-
20
-
21
-
22
- Bundler::GemHelper.install_tasks
23
-
24
- require 'rake/testtask'
25
-
26
- Rake::TestTask.new(:test) do |t|
27
- t.libs << 'lib'
28
- t.libs << 'test'
29
- t.pattern = 'test/**/*_test.rb'
30
- t.verbose = false
25
+ RuboCop::RakeTask.new do |task|
26
+ task.requires << 'rubocop-performance'
27
+ task.requires << 'rubocop-rspec'
31
28
  end
32
-
33
-
34
- task default: :test
@@ -28,7 +28,7 @@ module JeraPush
28
28
  end
29
29
 
30
30
  def create
31
- push_message = JeraPush::Service::SendMessage.new(params).call
31
+ push_message = JeraPush::Services::SendMessage.new(params).call
32
32
 
33
33
  if push_message
34
34
  flash[:notice] = t('jera_push.admin.messages.new.toast.success')
@@ -40,16 +40,29 @@ module JeraPush
40
40
  end
41
41
  end
42
42
 
43
+ def resend_push
44
+ message = JeraPush::Message.find(params[:id])
45
+ message.devices.find_each do |device|
46
+ JeraPush::Services::SendPushService.new(device: device,
47
+ message: message,
48
+ message_device: message.message_devices.where(device: device).last
49
+ ).call
50
+ end
51
+ flash[:notice] = t('jera_push.admin.messages.new.toast.success')
52
+ redirect_to jera_push_admin_message_path(message)
53
+ end
54
+
43
55
  private
44
56
 
45
- def apply_filter
46
- @filter = JeraPush::DeviceFilter.new device_filter_params
47
- @devices = @filter.search.limit(params[:limit]).order(created_at: :desc)
48
- @message_devices = JeraPush::MessageDevice.includes(:device).where('message_id = :id and device_id in (:device_ids)', id: params[:id], device_ids: @devices.pluck(:id))
49
- end
57
+ def apply_filter
58
+ @filter = JeraPush::DeviceFilter.new device_filter_params
59
+ @devices = @filter.search.limit(params[:limit]).order(created_at: :desc)
60
+ @message_devices = JeraPush::MessageDevice.includes(:device).where(message_id: params[:id], device_id: @devices.pluck(:id))
61
+ end
62
+
63
+ def device_filter_params
64
+ params.permit(:value, :field, platform: []).merge({ message_id: params[:id] })
65
+ end
50
66
 
51
- def device_filter_params
52
- params.permit(:value, :field, :resource_name, platform: []).merge({ message_id: params[:id] })
53
- end
54
67
  end
55
- end
68
+ end
@@ -1,25 +1,29 @@
1
1
  class JeraPush::MessagePresenter < BasePresenter
2
2
 
3
- def list_content
4
- JSON.pretty_generate({
5
- title: item.content["title"],
6
- body: item.content["body"]
7
- })
8
- end
3
+ def list_content
4
+ JSON.pretty_generate({
5
+ title: item.title,
6
+ body: item.body
7
+ })
8
+ end
9
9
 
10
- def display_content
11
- JSON.pretty_generate(item.content)
12
- end
10
+ def display_content
11
+ JSON.pretty_generate({
12
+ title: item.title,
13
+ body: item.body,
14
+ data: item.data
15
+ })
16
+ end
13
17
 
14
- def display_created_at
15
- item.created_at.strftime('%d/%m/%Y %H:%M')
16
- end
18
+ def display_created_at
19
+ item.created_at.strftime('%d/%m/%Y %H:%M')
20
+ end
17
21
 
18
- def show_link
19
- helpers.link_to(
20
- helpers.t('jera_push.admin.buttons.details'),
21
- Rails.application.routes.url_helpers.jera_push_admin_message_path(item), class: 'waves-effect waves-light btn'
22
- )
23
- end
22
+ def show_link
23
+ helpers.link_to(
24
+ helpers.t('jera_push.admin.buttons.details'),
25
+ Rails.application.routes.url_helpers.jera_push_admin_message_path(item), class: 'waves-effect waves-light btn'
26
+ )
27
+ end
24
28
 
25
29
  end
@@ -2,7 +2,10 @@
2
2
 
3
3
  <div class="details">
4
4
  <h3><%= t('jera_push.active_record.model.message.one') %></h3>
5
-
5
+ <%= form_tag resend_push_jera_push_admin_message_path(@message), method: :get, class: 'col s12', remote: true do |f| %>
6
+ <%= submit_tag t('jera_push.admin.messages.resend'), class: 'btn' %>
7
+ <% end %>
8
+ <br>
6
9
  <span class="field">
7
10
  <%= t('jera_push.active_record.messages.attributes.id') %>
8
11
  </span>
@@ -13,7 +16,7 @@
13
16
  </span>
14
17
  <blockquote class="json-message"><%= @message.display_content %></blockquote>
15
18
 
16
- <% unless @message.kind.broadcast? %>
19
+ <% unless @message.kind.everyone? %>
17
20
  <span class="field">
18
21
  <%= t('jera_push.active_record.messages.attributes.status') %>
19
22
  </span>
@@ -25,8 +28,8 @@
25
28
  <% end %>
26
29
  </div>
27
30
 
28
- <% if @message.kind.broadcast? %>
29
- <h3><%= JeraPush::Message.kind.broadcast.text %></h3>
31
+ <% if @message.kind.everyone? %>
32
+ <h3><%= JeraPush::Message.kind.everyone.text %></h3>
30
33
 
31
34
  <div class="message-info">
32
35
  <%= render partial: 'jera_push/admin/messages/broadcast_message', message: @message %>
@@ -29,6 +29,7 @@ pt-BR:
29
29
  admin:
30
30
  attributes:
31
31
  id: Identificador
32
+ token: Token
32
33
  name: Nome
33
34
  email: Email
34
35
  navbar:
@@ -62,6 +63,7 @@ pt-BR:
62
63
  messages:
63
64
  failures: "Falhas: %{value}"
64
65
  success: "Sucessos: %{value}"
66
+ resend: Reenviar a push
65
67
  show:
66
68
  broadcast:
67
69
  platform: Plataforma
@@ -76,3 +78,8 @@ pt-BR:
76
78
  new_attribute: Novo Atributo
77
79
  specific: Específico
78
80
  broadcast: Broadcast
81
+ services:
82
+ errors:
83
+ not_found:
84
+ device: Dispositivo não pode ficar em branco
85
+
data/config/routes.rb CHANGED
@@ -10,6 +10,7 @@ Rails.application.routes.draw do
10
10
  end
11
11
  member do
12
12
  get :message_devices_filter, format: :js
13
+ get :resend_push, format: :js
13
14
  end
14
15
  end
15
16
  resources :devices, only: [:index]
@@ -5,8 +5,9 @@ class CreateJeraPushDevices < ActiveRecord::Migration<%= migration_version %>
5
5
  t.string :platform, index: true
6
6
  t.references :pushable, polymorphic: true, index: true
7
7
 
8
- t.timestamps null: false
8
+ t.timestamps
9
9
  end
10
+
10
11
  add_index :jera_push_devices, [:token, :platform], unique: true
11
12
  end
12
13
  end
@@ -1,17 +1,20 @@
1
1
  class CreateJeraPushMessages < ActiveRecord::Migration<%= migration_version %>
2
2
  def change
3
3
  create_table :jera_push_messages do |t|
4
- t.text :content
4
+ t.string :title
5
+ t.text :body
6
+ t.json :data
7
+ t.string :multicast_id
5
8
  t.text :broadcast_result
6
9
  t.string :status
7
10
  t.string :kind
8
11
  t.string :topic
9
12
  t.string :firebase_id
10
- t.string :error_message
13
+ t.json :error_message
11
14
  t.integer :failure_count, default: 0
12
15
  t.integer :success_count, default: 0
13
16
 
14
- t.timestamps null: false
17
+ t.timestamps
15
18
  end
16
19
  end
17
20
  end
@@ -1,13 +1,13 @@
1
1
  class CreateJeraPushMessagesDevices < ActiveRecord::Migration<%= migration_version %>
2
2
  def change
3
3
  create_table :jera_push_messages_devices do |t|
4
- t.integer :device_id, index: true, foreign_key: true
5
- t.integer :message_id, index: true, foreign_key: true
4
+ t.integer :device_id, index: true
5
+ t.integer :message_id, index: true
6
6
  t.string :status
7
7
  t.string :error_message
8
8
  t.string :firebase_id
9
9
 
10
- t.timestamps null: false
10
+ t.timestamps
11
11
  end
12
12
 
13
13
  add_index :jera_push_messages_devices, [:device_id, :message_id], unique: true, name: :jera_push_index_messages_id_devices_id
@@ -4,7 +4,8 @@ JeraPush.setup do |config|
4
4
  config.firebase_api_key = "YOUR_API_KEY"
5
5
  # Change this for every new model
6
6
  config.resources_name = ["<%= file_name.classify %>"]
7
-
7
+ config.project_name = "YOUR_PROJECT_NAME"
8
+ config.credentials_path = "YOUR_CREDENTIALS_PATH" #https://firebase.google.com/docs/cloud-messaging/migrate-v1?hl=pt-br#provide-credentials-manually
8
9
  ######################################################
9
10
  # Resource attribute showed in views #
10
11
  # IMPORTANT: All models need to have this attributes #
@@ -1,69 +1,66 @@
1
- module JeraPush
2
- module Firebase
3
- class Client
4
-
5
- cattr_accessor :client
6
-
7
- FIREBASE_URL = "https://fcm.googleapis.com/fcm/send"
8
- FIREBASE_INSTANCE_ID_URL = "https://iid.googleapis.com/iid"
9
-
10
- def default_headers
11
- return {
12
- "Authorization" => "key=#{::JeraPush.firebase_api_key}",
13
- "Content-Type" => "application/json"
14
- }
15
- end
1
+ module JeraPush::Firebase
2
+ class Client
3
+ FIREBASE_API_VERSION = 'v1'.freeze
4
+ FIREBASE_INSTANCE_ID_URL = 'https://iid.googleapis.com/iid'.freeze
5
+ SCOPE = 'https://www.googleapis.com/auth/firebase.messaging'.freeze
6
+
7
+ def initialize
8
+ @client = Google::Apis::FcmV1::FirebaseCloudMessagingService.new
9
+ @authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
10
+ json_key_io: File.open(::JeraPush::credentials_path),
11
+ scope: SCOPE
12
+ )
13
+ @client.authorization = fetch_access_token
14
+ end
15
+
16
+ def send_to_device(message:)
17
+ @client.send_message("projects/#{::JeraPush.project_name}", message, options: { retries: 3, multiplier: 1, max_interval: 2 })
18
+ end
16
19
 
17
- def self.instance
18
- @@client ||= JeraPush::Firebase::Client.new
19
- end
20
+ def add_device_to_topic(topic:, device:)
21
+ send(url: "#{FIREBASE_INSTANCE_ID_URL}/v1/#{device.token}/rel/topics/#{topic}")
22
+ end
20
23
 
21
- def send_message(message:, devices: [])
22
- registration_ids = devices.map(&:token)
23
- body = { registration_ids: registration_ids, priority: 'high' }
24
- response = HTTParty.post(FIREBASE_URL, { body: body.merge!(message).to_json, headers: default_headers })
25
- puts response
26
- ApiResult.new(response, registration_ids: registration_ids)
27
- end
24
+ def remove_device_from_topic(topic:, devices: [])
25
+ send(
26
+ url: "#{FIREBASE_INSTANCE_ID_URL}/v1:batchRemove",
27
+ body: {
28
+ to: "/topics/#{topic}",
29
+ registration_tokens: devices.pluck(:token)
30
+ }.to_json
31
+ )
32
+ end
28
33
 
29
- def send_message_to_topic(message:, topic:)
30
- body = { to: "/topics/#{topic}", priority: 'high' }
31
- response = HTTParty.post(FIREBASE_URL, { body: body.merge!(message).to_json, headers: default_headers })
32
- puts response
33
- ApiResult.new(response, topic: topic)
34
- end
34
+ def send_message_to_topic(message:, topic:)
35
+ send(
36
+ url: FIREBASE_URL,
37
+ body: {
38
+ title: message.title,
39
+ body: message.body,
40
+ to: "/topics/#{topic}",
41
+ priority: 'high'
42
+ }.to_json
43
+ )
44
+ end
35
45
 
36
- def device_details(device:)
37
- url = "#{FIREBASE_INSTANCE_ID_URL}/info/#{device.token}/"
38
- response = HTTParty.post(url, { body: Hash.new.to_json, headers: default_headers })
39
- ApiResult.new(response)
40
- end
46
+ private
41
47
 
42
- def add_device_to_topic(topic:, device:)
43
- url = "#{FIREBASE_INSTANCE_ID_URL}/v1/#{device.token}/rel/topics/#{topic}"
44
- response = HTTParty.post(url, { body: Hash.new.to_json, headers: default_headers })
45
- ApiResult.new(response)
46
- end
48
+ def send(url:, body: {})
49
+ response = HTTParty.post(url, { body: body, headers: default_headers })
50
+ JSON.parse(response)
51
+ end
47
52
 
48
- def add_devices_to_topic(topic:, devices: [])
49
- url = "#{FIREBASE_INSTANCE_ID_URL}/v1:batchAdd"
50
- body = {
51
- "to": "/topics/#{topic}",
52
- "registration_tokens": devices.map(&:token),
53
- }
54
- response = HTTParty.post(url, { body: body.to_json, headers: default_headers })
55
- ApiResult.new(response)
56
- end
53
+ def fetch_access_token
54
+ @authorizer.fetch_access_token! if @authorizer.needs_access_token?
55
+
56
+ @authorizer
57
+ end
57
58
 
58
- def remove_device_from_topic(topic:, devices: [])
59
- url = "#{FIREBASE_INSTANCE_ID_URL}/v1:batchRemove"
60
- body = {
61
- "to": "/topics/#{topic}",
62
- "registration_tokens": devices.map(&:token),
63
- }
64
- response = HTTParty.post(url, { body: body.to_json, headers: default_headers })
65
- ApiResult.new(response)
66
- end
59
+ def default_headers
60
+ {
61
+ "Authorization" => "key=#{::JeraPush.firebase_api_key}",
62
+ "Content-Type" => "application/json"
63
+ }
67
64
  end
68
65
  end
69
66
  end
@@ -3,21 +3,16 @@ require 'enumerize'
3
3
  class JeraPush::Device < ActiveRecord::Base
4
4
  extend Enumerize
5
5
 
6
- DEFAULT_TOPIC = 'general'
7
-
8
6
  self.table_name = "jera_push_devices"
9
7
 
10
- has_many :message_devices, table_name: "jera_push_message_devices"
11
- has_many :messages, through: :message_devices, table_name: "jera_push_messages"
12
-
13
8
  belongs_to :pushable, polymorphic: true
14
9
 
10
+ has_many :message_devices, class_name: "JeraPush::MessageDevice"
11
+ has_many :messages, through: :message_devices, class_name: "JeraPush::Message"
12
+
15
13
  validates :token, :platform, presence: true
16
14
  validates :token, uniqueness: { scope: :platform }
17
15
 
18
- after_create :register_to_current_topic
19
- before_destroy :unregister_from_current_topic
20
-
21
16
  enumerize :platform, in: [:android, :ios, :chrome], predicate: true
22
17
 
23
18
  scope :ios, -> { where(platform: :ios) }
@@ -25,27 +20,4 @@ class JeraPush::Device < ActiveRecord::Base
25
20
  scope :chrome, -> { where(platform: :chrome) }
26
21
  scope :with_joins, -> (resource_type) { joins("INNER JOIN #{resource_type.downcase.pluralize} ON jera_push_devices.pushable_id = #{resource_type.downcase.pluralize}.id AND jera_push_devices.pushable_type = '#{resource_type}'") }
27
22
 
28
- def send_message(message)
29
- JeraPush::Message.send_to self, content: message
30
- end
31
-
32
- def subscribe(topic)
33
- client = JeraPush::Firebase::Client.instance
34
- client.add_device_to_topic(topic: topic, device: self)
35
- end
36
-
37
- def unsubscribe(topic)
38
- client = JeraPush::Firebase::Client.instance
39
- client.remove_device_from_topic(topic: topic, devices: [self])
40
- end
41
-
42
- private
43
-
44
- def register_to_current_topic
45
- subscribe(JeraPush.send("topic_#{self.platform}"))
46
- end
47
-
48
- def unregister_from_current_topic
49
- unsubscribe(JeraPush.send("topic_#{self.platform}"))
50
- end
51
23
  end
@@ -2,152 +2,12 @@ require 'enumerize'
2
2
 
3
3
  class JeraPush::Message < ActiveRecord::Base
4
4
  extend Enumerize
5
+
5
6
  self.table_name = "jera_push_messages"
6
7
 
7
8
  has_many :message_devices
8
9
  has_many :devices, through: :message_devices
9
10
 
10
- serialize :broadcast_result
11
-
12
- enumerize :kind, in: [:broadcast, :specific], predicate: true, default: :specific
13
-
14
- def self.send_to(target, content: {})
15
- return nil if target.blank? || content.blank?
16
-
17
- push_message = JeraPush::Message.create content: content
18
- push_message.devices << target
19
-
20
- if push_message && target.is_a?(JeraPush::Device)
21
- push_message.send_to_device device: target
22
- else
23
- push_message.send_to_devices devices: target
24
- end
25
- push_message
26
- end
27
-
28
- def self.send_broadcast(content:)
29
- return nil if content.blank?
30
-
31
- push_message = JeraPush::Message.create content: content, kind: :broadcast
32
- @@client ||= JeraPush::Firebase::Client.instance
33
-
34
- results = []
35
- results << push_message.to_android_topic
36
- results << push_message.to_ios_topic
37
- results << push_message.to_chrome_topic
38
-
39
- JeraPush::Firebase::ApiResult.broadcast_result(message: push_message, results: results)
40
- push_message
41
- end
42
-
43
- def self.send_to_topic(topic: , content: {})
44
- return nil if topic.blank? || content.blank?
45
-
46
- push_message = JeraPush::Message.create content: content, topic: topic
47
- client = JeraPush::Firebase::Client.instance
48
- response = client.send_message_to_topic(message: { data: content }, topic: topic)
49
- response.topic_result(message: push_message)
50
- push_message
51
- end
52
-
53
- def self.format_hash(messages = [])
54
- return false if messages.blank?
55
- messages.collect do |obj|
56
- hash = { obj[:key].to_sym => obj[:value] }
57
- hash.delete_if { |key, value| key.blank? || value.blank? }
58
- end.reduce(:merge)
59
- end
60
-
61
- def content=(content)
62
- raise 'Invalid message format. Hash format expected' unless content.is_a? Hash
63
-
64
- super(content.to_json)
65
- end
66
-
67
- def content
68
- if super()
69
- JSON.parse(super())
70
- else
71
- return {}
72
- end
73
- end
74
-
75
- def send_to_devices(devices: [])
76
- return nil if devices.empty?
77
- platform_devices = devices.group_by { |device| device.platform }
78
- client = JeraPush::Firebase::Client.instance
79
-
80
- platform_devices.keys.each do |platform|
81
- payload = self.send("body_#{platform.to_s}", self.content)
82
- response = client.send_message(message: payload, devices: platform_devices[platform])
83
- if response
84
- response.result_to(message: self)
85
- end
86
- end
87
- end
88
-
89
- def send_to_device(device: nil)
90
- return nil if device.nil?
91
-
92
- payload = {}
93
- if device.platform.ios?
94
- payload = body_ios(self.content)
95
- elsif device.platform.android?
96
- payload = body_android(self.content)
97
- elsif device.platform.chrome?
98
- payload = body_chrome(self.content)
99
- end
100
- client = JeraPush::Firebase::Client.instance
101
- response = client.send_message(message: payload, devices: [device])
102
- if response
103
- response.result_to(message: self)
104
- end
105
- end
106
-
107
- def to_android_topic
108
- @@client.send_message_to_topic(
109
- message: body_android(content),
110
- topic: JeraPush.topic_android
111
- )
112
- end
113
-
114
- def to_ios_topic
115
- @@client.send_message_to_topic(
116
- message: body_ios(content),
117
- topic: JeraPush.topic_ios
118
- )
119
- end
120
-
121
- def to_chrome_topic
122
- @@client.send_message_to_topic(
123
- message: body_chrome(content),
124
- topic: JeraPush.topic_chrome
125
- )
126
- end
127
-
128
- private
129
-
130
- def body_ios(content)
131
- params = [:title, :body, :'content-available', :sound, :badge, :click_action, :body_loc_key, :body_loc_args, :title_loc_key, :title_loc_args]
132
-
133
- content.symbolize_keys!
134
- content[:sound] = 'default' unless content.has_key?(:sound)
135
-
136
- return {
137
- notification: content.select { |key, value| params.include?(key) },
138
- data: content.reject { |key, value| params.include?(key) }
139
- }
140
- end
141
-
142
- def body_android(content)
143
- return {
144
- data: content
145
- }
146
- end
11
+ enumerize :kind, in: [:specific, :everyone, :topic], predicate: true, default: :specific
147
12
 
148
- def body_chrome(content)
149
- return {
150
- data: content
151
- }
152
- end
153
13
  end
@@ -1,6 +1,7 @@
1
1
  require 'enumerize'
2
2
  class JeraPush::MessageDevice < ActiveRecord::Base
3
3
  extend Enumerize
4
+
4
5
  self.table_name = "jera_push_messages_devices"
5
6
 
6
7
  belongs_to :device
@@ -0,0 +1,23 @@
1
+ module JeraPush::Services
2
+ class BaseService
3
+ extend ActiveModel::Naming
4
+
5
+ def initialize(*)
6
+ @errors = ActiveModel::Errors.new(self)
7
+ @firebase = JeraPush::Firebase::Client.new
8
+ end
9
+
10
+ def read_attribute_for_validation(attr)
11
+ send(attr)
12
+ end
13
+
14
+ def self.human_attribute_name(attr, options = {})
15
+ attr
16
+ end
17
+
18
+ def self.lookup_ancestors
19
+ [self]
20
+ end
21
+
22
+ end
23
+ end