Skip to content

Instantly share code, notes, and snippets.

@fermion
Forked from scotttam/apns.rb
Created March 2, 2012 12:35
Show Gist options
  • Save fermion/1958138 to your computer and use it in GitHub Desktop.
Save fermion/1958138 to your computer and use it in GitHub Desktop.
Sends an Apple Push Notification with Ruby
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*")
the_byte_token = "\xBA\xFE\xD9\v \xD9\xC5\xAE\xCED\xD0-\xF2\x87\xAA\bkn\x9F\xC4aY\xD1v_|6\x97\xF8g\xAB\x17"
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('config/certs/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
begin
write(ssl, sock, the_notification)
ensure
close(ssl, sock)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment