Created
November 17, 2011 18:09
-
-
Save rafmagana/1373956 to your computer and use it in GitHub Desktop.
Ruby script to send Apple push notifications
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
#! /usr/bin/env ruby | |
# Rafael Magana (rafmagana@gmail.com) | |
# chmod +x ios_push.rb (make the script executable) | |
# Usage: ./ios_push 'message to alert' | |
%w/logger socket openssl json/.each { |lib| require lib } | |
SSL = OpenSSL::SSL | |
SSLContext = SSL::SSLContext | |
SSLSocket = SSL::SSLSocket | |
Certificate = OpenSSL::X509::Certificate | |
RSA = OpenSSL::PKey::RSA | |
class Notifier | |
def initialize(device_token) | |
@device_token, @server, @port = device_token, 'gateway.sandbox.push.apple.com', 2195 | |
@logger = Logger.new 'notifications.log' | |
@ssl, @tcp = connect | |
end | |
def connect | |
cert = File.read 'your_certificate_here.pem' | |
ssl_context = SSLContext.new | |
ssl_context.cert = Certificate.new cert | |
ssl_context.key = RSA.new cert, '1234' | |
tcp_socket = TCPSocket.new @server, @port | |
ssl_socket = SSLSocket.new tcp_socket, ssl_context | |
ssl_socket.connect | |
[ssl_socket, tcp_socket] | |
end | |
def send(message) | |
@ssl.write payload message | |
@logger.info "Sent '#{message}' to device '#{@device_token[0..5]}...'" | |
@ssl.close | |
@tcp.close | |
end | |
def payload(m) | |
aps = {} | |
aps[:alert] = { :body => m, "action-loc-key" => "_button's text_" } | |
aps[:badge] = 10 | |
aps[:sound] = 'default' | |
@logger.info "Payload: #{aps}" | |
binarize :aps => aps | |
end | |
def binarize(aps) | |
j = JSON.dump aps | |
"\0\0 #{[@device_token].pack('H*')}\0#{j.length.chr}#{j}" | |
end | |
end | |
devices = %w/ | |
device_token_1 | |
device_token_2 | |
device_token_n/ | |
devices.each do |token| | |
Notifier.new(token).send ARGV.first | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment