Class: Pushkin::Fcm::SendFcmPushService

Inherits:
Object
  • Object
show all
Defined in:
app/services/pushkin/fcm/send_fcm_push_service.rb

Constant Summary collapse

FCM_API_DOMAIN =
"https://fcm.googleapis.com"
FCM_API_URL =
"/fcm/send"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tokens, payload) ⇒ SendFcmPushService

Returns a new instance of SendFcmPushService.



13
14
15
16
17
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 13

def initialize(tokens, payload)
  @tokens = tokens
  @payload = payload
  @server_key = Pushkin.config.fcm_server_key
end

Instance Attribute Details

#payloadObject

Returns the value of attribute payload.



10
11
12
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 10

def payload
  @payload
end

#server_keyObject

Returns the value of attribute server_key.



11
12
13
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 11

def server_key
  @server_key
end

#tokensObject

Returns the value of attribute tokens.



10
11
12
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 10

def tokens
  @tokens
end

Instance Method Details

#callObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 19

def call
  # Сохранение в БД информации по отправке
  @push_sending_result = PushSendingResult.create(started_at: DateTime.now, platform: self.get_platform)

  # Выполнение HTTP запроса по отправке уведомлений
  conn = Faraday.new(:url => FCM_API_DOMAIN)
  response = conn.post do |req|
    req.url FCM_API_URL
    req.headers['Content-Type'] = 'application/json'
    req.headers['Authorization'] = "key=#{self.server_key}"
    req.body = self.get_request_body.to_json
  end

  # Сохранение результатов отправки в БД
  self.process_response(response)
  @push_sending_result
end

#get_data_hashObject



102
103
104
105
106
107
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 102

def get_data_hash
  (self.payload.data || {}).merge({
    notification_type: self.payload.notification.notification_type,
    notification_id: self.payload.notification.id
  })
end

#get_notification_hashObject



94
95
96
97
98
99
100
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 94

def get_notification_hash
  return {
    title: self.payload.title,
    body: self.payload.body,
    tag: self.payload.notification.id.to_s
  }
end

#get_platformObject

Raises:

  • (Exception)


109
110
111
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 109

def get_platform
  raise Exception.new("You must implement 'get_platform' method in child class")
end

#get_request_bodyObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 74

def get_request_body
  body = {
    registration_ids: self.tokens.map { |token_object| token_object.token },
    content_available: self.is_data_message
  }

  notification_hash = self.get_notification_hash
  data_hash = self.get_data_hash

  if self.is_data_message
    data_hash = data_hash.merge(notification_hash)
    notification_hash = nil
  end

  body[:notification] = notification_hash if notification_hash.present?
  body[:data] = data_hash if data_hash.present?

  body
end

#is_data_messageObject

Raises:

  • (Exception)


113
114
115
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 113

def is_data_message
  raise Exception.new("You must implement 'is_data_message' method in child class")
end

#parse_token_result(result, token) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 58

def parse_token_result(result, token)
  error = result[:error]
  token_result = TokenResult.new(token_id: token.id)

  if error.blank?
    token_result.set_success
  elsif error == "NotRegistered" || error == "InvalidRegistration"
    token_result.set_invalid
  else
    token_result.set_error(error)
  end

  token_result.save
  token_result
end

#process_response(response) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/services/pushkin/fcm/send_fcm_push_service.rb', line 37

def process_response(response)
  @push_sending_result.finished_at = DateTime.now

  if response.status == 200
    @push_sending_result.success = true

    # Обработка ответа с сохранением в БД
    response_body = JSON.parse(response.body, symbolize_names: true)
    response_body[:results].each_with_index.map do |result, index|
      token_result = self.parse_token_result(result, self.tokens[index])
      token_result.push_sending_result_id = @push_sending_result.id
      token_result.save
    end
  else
    @push_sending_result.success = false
    @push_sending_result.error = response.body
  end

  @push_sending_result.save
end