Skip to content

Instantly share code, notes, and snippets.

@Artur-Sulej
Created May 11, 2016 09:38
Show Gist options
  • Save Artur-Sulej/4a102256200ad79fb8afe17cc1e80c63 to your computer and use it in GitHub Desktop.
Save Artur-Sulej/4a102256200ad79fb8afe17cc1e80c63 to your computer and use it in GitHub Desktop.
PushTokensHelper module - utility for storing data for sending mobile pushes and for sending push notifications. Sending them should be performed on a separate thread.
require 'net/http'
module PushTokensHelper
def send_pushes(user, data)
PushToken.where(user: user).to_a.each do |push_token|
send_push_to_device(push_token, data)
end
end
private
def send_push_to_device(push_token, data)
case push_token.platform.downcase
when 'android'
send_push_android(push_token.push_token, data)
when 'ios'
# Not implemented yet
when 'windowsphone'
# Not implemented yet
end
end
def send_push_android(gcm_token, data)
params = create_data_android(gcm_token, data)
uri = URI.parse('https://gcm-http.googleapis.com/gcm/send')
json_headers = {'Authorization' => "key=#{ENV['ANDROID_PUSH_SECRET']}",
'Content-Type' => 'application/json'}
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.post(uri.path, params.to_json, json_headers)
end
def store_push_token(params, user_id)
if params[:push_token] && params[:platform] && user_id
PushToken.store_token(push_token: params[:push_token], platform: params[:platform], user_id: user_id)
end
end
private
def create_data_android(gcm_token, data)
{to: gcm_token, data: data}
end
end
class PushToken < ActiveRecord::Base
belongs_to :user
def self.store_token(push_token:, platform:, user_id:)
PushToken.find_or_initialize_by(
platform: platform,
push_token: push_token
)
.update(
user_id: user_id
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment