-
-
Save paydro/2927159 to your computer and use it in GitHub Desktop.
Sends an Apple Push Notification with Ruby
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 "rubygems" | |
require "yajl" | |
require "openssl" | |
require "socket" | |
device_token = '39cac56f 986a0e66 3c4fd4f4 68df5598 024d2ca3 8b9f307c 741c180e 9fc30c62' | |
device_token = device_token.gsub(" ", "") | |
the_byte_token = [device_token].pack("H*") | |
file = File.open("ruby_the_byte_token", "wb") | |
file.print(the_byte_token) | |
file.close | |
the_beginning = [0, 0, 32].pack("ccc") | |
file = File.open("ruby_the_beginning", "wb") | |
file.print(the_beginning) | |
file.close | |
def the_payload | |
payload = Hash.new | |
payload['aps'] = Hash.new | |
payload['aps']['alert'] = "Ruby - Oh no! Server\'s Down!" | |
payload['aps']['sound'] = 'k1DiveAlarm.caf' | |
payload['aps']['badge'] = 42 | |
payload['test_data'] = {'foo' => 'bar'} | |
Yajl::Encoder.encode(payload) | |
end | |
the_notification = [0, 0, 32, the_byte_token, 0, the_payload.length, the_payload].pack("ccca*cca*") | |
file = File.open("ruby_the_notification", "wb") | |
file.print(the_notification) | |
file.close | |
def connect | |
cert = File.read('cert_ios_production.pem') | |
ctx = OpenSSL::SSL::SSLContext.new | |
ctx.key = OpenSSL::PKey::RSA.new(cert, nil) | |
ctx.cert = OpenSSL::X509::Certificate.new(cert) | |
sock = TCPSocket.new('gateway.push.apple.com', 2195) | |
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx) | |
ssl.connect | |
return ssl, sock | |
end | |
def write(ssl, sock, the_notification) | |
ssl.write(the_notification) | |
ssl.flush | |
if IO.select([ssl], nil, nil, 1) | |
error = ssl.read(6) | |
if error | |
error = error.unpack("ccN") | |
puts "ERROR: #{error}" | |
else | |
puts "NO ERROR" | |
end | |
end | |
end | |
def close(ssl, sock) | |
ssl.close | |
sock.close | |
end | |
ssl, sock = connect | |
write(ssl, sock, the_notification) | |
close(ssl, sock) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment