Last active
June 24, 2016 04:26
-
-
Save Passerby/fddaccce3d97038ff2ac2b51cdab3e32 to your computer and use it in GitHub Desktop.
Azure Notification Hub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'multi_json' | |
require 'uri' | |
require 'base64' | |
require 'openssl' | |
require 'cgi' | |
require 'net/http' | |
require 'time' | |
module AzureNotificationHub | |
ENDPOINT = '' | |
SHAREDACCESSKEYNAME = '' | |
SHAREDACCESSKEY = '' | |
def self.send_apple body, device_id, &block | |
uri = URI "#{ENDPOINT}idt-notification/messages/?api-version=2015-04" | |
request_header = { | |
'Authorization' => generate_sas_token(uri), | |
'Content-Type' => 'application/json;charset=utf-8', | |
'Accept' => 'application/json;charset=utf-8', | |
'ServiceBusNotification-Format' => 'apple', | |
'ServiceBusNotification-Apns-Expiry' => (Time.now + 300).utc.iso8601 | |
} | |
request_header['ServiceBusNotification-Tags'] = device_id unless device_id.nil? | |
self.send_notification(uri, request_header, { aps: { alert: body }}, device_id, &block) | |
end | |
def self.send_gcm body, device_id, title, &block | |
title = body if title.nil? | |
uri = URI "#{ENDPOINT}idt-notification/messages/?api-version=2015-04" | |
request_header = { | |
'Authorization' => generate_sas_token(uri), | |
'Content-Type' => 'application/json;charset=utf-8', | |
'Accept' => 'application/json;charset=utf-8', | |
'ServiceBusNotification-Format' => 'gcm', | |
} | |
request_header['ServiceBusNotification-Tags'] = device_id unless device_id.nil? | |
# self.send_notification(uri, request_header, { notification: { body: body, title: title }}, device_id, &block) | |
self.send_notification(uri, request_header, {"data":{"message":"Notification Hub test notification"}}, device_id, &block) | |
end | |
def self.send_notification uri, request_header, body, device_id, &block | |
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| | |
req = Net::HTTP::Post.new(uri, request_header) | |
req.body = MultiJson.dump(body) | |
response = http.request req # Net::HTTPResponse object | |
unless block.nil? | |
block.call(response.body, response) | |
else | |
response | |
end | |
end | |
end | |
def self.generate_sas_token uri | |
target_uri = CGI.escape(uri.to_s.downcase).downcase | |
expires = Time.now.to_i + 600 | |
sign = CGI.escape(Base64.encode64(OpenSSL::HMAC.digest('sha256', SHAREDACCESSKEY, "#{target_uri}\n#{expires}")).strip) | |
"SharedAccessSignature sr=#{target_uri}&sig=#{sign}&se=#{expires}&skn=#{SHAREDACCESSKEYNAME}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment