hackedunit-apn_sender 1.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 Kali Donovan
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,131 @@
1
+ == Synopsis
2
+
3
+ Need to send background notifications to an iPhone application over a <em>persistent</em> connection in Ruby? Keep reading...
4
+
5
+ == The Story
6
+
7
+ So you're building the server component of an iPhone application in Ruby. And you want to send background notifications through the Apple Push Notification servers, which doesn't seem too bad at first. But then you read in the {Apple Documentation}[https://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/WhatAreRemoteNotif/WhatAreRemoteNotif.html#//apple_ref/doc/uid/TP40008194-CH102-SW7] that Apple's servers may treat non-persistent connections as a Denial of Service attack, and you realize that Rails has no easy way to maintain a persistent connection internally, and things started looking more complicated.
8
+
9
+ The apn_sender gem includes a background daemon which processes background messages from your application and sends them along to Apple <em>over a single, persistent socket</em>. It also includes the ability to query the Feedback service, helper methods for enqueueing your jobs, and a sample monit config to make sure the background worker is around when you need it.
10
+
11
+ == Yet another ApplePushNotification interface?
12
+
13
+ Yup. There's some great code out there already, but we didn't like the idea of getting banned from the APN gateway for establishing a new connection each time we needed to send a batch of messages, and none of the libraries I found handled maintaining a persistent connection.
14
+
15
+ == Current Status
16
+
17
+ This gem has been in production use since early May, 2010. There are no guarantees of complete functionality, of course, but it's working for us. :)
18
+
19
+
20
+ == Usage
21
+
22
+ === 1. Queueing Messages From Your Application
23
+
24
+ To queue a message for sending through Apple's Push Notification service from your Rails application:
25
+
26
+ APN.notify(token, opts_hash)
27
+
28
+ where +token+ is the unique identifier of the iPhone to receive the notification and +opts_hash+ can have any of the following keys:
29
+
30
+ # :alert #=> The alert to send
31
+ # :badge #=> The badge number to send
32
+ # :sound #=> The sound file to play on receipt, or true to play the default sound installed with your app
33
+
34
+ If any other keys are present they'll be be passed along as custom data to your application.
35
+
36
+ === 2. Sending Queued Messages
37
+
38
+ Put your <code>apn_development.pem</code> and <code>apn_production.pem</code> certificates from Apple in your <code>RAILS_ROOT/config/certs</code> directory.
39
+
40
+ Once this is done, you can fire off a background worker with
41
+
42
+ $ rake apn:sender
43
+
44
+ For production, you're probably better off running a dedicated daemon and setting up monit to watch over it for you. Luckily, that's pretty easy:
45
+
46
+ # To generate daemon
47
+ ./script/generate apn_sender
48
+
49
+ # To run daemon. Pass --help to print all options
50
+ ./script/apn_sender --environment=production --verbose start
51
+
52
+ Note the --environment must be explicitly set (separately from your <code>RAILS_ENV</code>) to production in order to send messages via the production APN servers. Any other environment sends messages through Apple's sandbox servers at <code>gateway.sandbox.push.apple.com</code>.
53
+
54
+ Check <code>RAILS_ROOT/logs/apn_sender.log</code> for debugging output. In addition to logging any major errors there, apn_sender hooks into the Resque::Worker logging to display any verbose or very_verbose worker output in apn_sender.log file as well.
55
+
56
+
57
+ === 3. Checking Apple's Feedback Service
58
+
59
+ Since push notifications are a fire-and-forget sorta deal, where you get no indication if your message was received (or if the specified recipient even exists), Apple needed to come up with some other way to ensure their network isn't clogged with thousands of bogus messages (e.g. from developers sending messages to phones where their application <em>used</em> to be installed, but where the user has since removed it). Hence, the Feedback Service.
60
+
61
+ It's actually really simple - you connect to them periodically and they give you a big dump of tokens you shouldn't send to anymore. The gem wraps this up nicely -- just call:
62
+
63
+ # APN::Feedback accepts the same optional :environment and :cert_path options as APN::Sender
64
+ feedback = APN::Feedback.new()
65
+
66
+ tokens = feedback.tokens # => Array of device tokens
67
+ tokens.each do |token|
68
+ # ... custom logic here to stop you app from
69
+ # sending further notifications to this token
70
+ end
71
+
72
+ If you're interested in knowing exactly <em>when</em> Apple determined each token was expired (which can be useful in determining if the application re-registered with your service since it first appeared in the expired queue):
73
+
74
+ items = feedback.data # => Array of APN::FeedbackItem elements
75
+ items.each do |item|
76
+ item.token
77
+ item.timestamp
78
+ # ... custom logic here
79
+ end
80
+
81
+ The Feedback Service works as a big queue. When you connect it pops off all its data and sends it over the wire at once, which means connecting a second time will return an empty array, so for ease of use a call to either +tokens+ or +data+ will connect once and cache the data. If you call either one again it'll continue to use its cached version (rather than connecting to Apple a second time to retrieve an empty array, which is probably not what you want).
82
+
83
+ Forcing a reconnect is as easy as calling either method with the single parameter +true+, but be sure you've already used the existing data because you'll never get it back.
84
+
85
+
86
+ ==== Warning: No really, check Apple's Feedback Service occasionally
87
+
88
+ If you're sending notifications, you should definitely call one of the <code>receive</code> methods periodically, as Apple's policies require it and they apparently monitors providers for compliance. I'd definitely recommend throwing together a quick rake task to take care of this for you (the {whenever library}[http://github.com/javan/whenever] provides a nice wrapper around scheduling tasks to run at certain times (for systems with cron enabled)).
89
+
90
+ Just for the record, this is essentially what you want to have whenever run periodically for you:
91
+
92
+ def self.clear_uninstalled_applications
93
+ feedback_data = APN::Feedback.new(:environment => :production).data
94
+
95
+ feedback_data.each do |item|
96
+ user = User.find_by_iphone_token( item.token )
97
+
98
+ if user.iphone_token_updated_at && user.iphone_token_updated_at > item.timestamp
99
+ return true # App has been reregistered since Apple determined it'd been uninstalled
100
+ else
101
+ user.update_attributes(:iphone_token => nil, :iphone_token_updated_at => Time.now)
102
+ end
103
+ end
104
+ end
105
+
106
+
107
+
108
+
109
+ === Keeping Your Workers Working
110
+
111
+ There's also an included sample <code>apn_sender.monitrc</code> file in the <code>contrib/</code> folder to help monit handle server restarts and unexpected disasters.
112
+
113
+
114
+ == Installation
115
+
116
+ APN is built on top of {Resque}[http://github.com/defunkt/resque] (an awesome {Redis}[http://code.google.com/p/redis/]-based background runner similar to {delayed_job}[http://github.com/collectiveidea/delayed_job]). Read through the {Resque README}[http://github.com/defunkt/resque#readme] to get a feel for what's going on, follow the installation instructions there, and then run:
117
+
118
+ $ sudo gem install apn_sender
119
+
120
+ In your Rails app, add
121
+
122
+ config.gem 'apn_sender', :lib => 'apn'
123
+
124
+ To add a few useful rake tasks for running workers, add the following line to your Rakefile:
125
+
126
+ require 'apn/tasks'
127
+
128
+
129
+ == Copyright
130
+
131
+ Copyright (c) 2010 Kali Donovan. See LICENSE for details.
@@ -0,0 +1,56 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ load 'lib/apn/tasks.rb'
5
+
6
+ begin
7
+ require 'jeweler'
8
+ Jeweler::Tasks.new do |gem|
9
+ gem.name = "hackedunit-apn_sender"
10
+ gem.summary = %Q{Resque-based background worker to send Apple Push Notifications over a persistent TCP socket.}
11
+ gem.description = %Q{Resque-based background worker to send Apple Push Notifications over a persistent TCP socket. Includes Resque tweaks to allow persistent sockets between jobs, helper methods for enqueueing APN notifications, and a background daemon to send them.}
12
+ gem.email = "kali.donovan@gmail.com"
13
+ gem.homepage = "http://github.com/hackedunit/apn_sender"
14
+ gem.authors = ["Kali Donovan", "Tinu Cleatus"]
15
+ gem.add_dependency 'resque'
16
+ gem.add_dependency 'resque-access_worker_from_job'
17
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
18
+ end
19
+ Jeweler::GemcutterTasks.new
20
+ rescue LoadError
21
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
22
+ end
23
+
24
+ require 'rake/testtask'
25
+ Rake::TestTask.new(:test) do |test|
26
+ test.libs << 'lib' << 'test'
27
+ test.pattern = 'test/**/test_*.rb'
28
+ test.verbose = true
29
+ end
30
+
31
+ begin
32
+ require 'rcov/rcovtask'
33
+ Rcov::RcovTask.new do |test|
34
+ test.libs << 'test'
35
+ test.pattern = 'test/**/test_*.rb'
36
+ test.verbose = true
37
+ end
38
+ rescue LoadError
39
+ task :rcov do
40
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
41
+ end
42
+ end
43
+
44
+ task :test => :check_dependencies
45
+
46
+ task :default => :test
47
+
48
+ require 'rake/rdoctask'
49
+ Rake::RDocTask.new do |rdoc|
50
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
51
+
52
+ rdoc.rdoc_dir = 'rdoc'
53
+ rdoc.title = "apple_push_notification #{version}"
54
+ rdoc.rdoc_files.include('README*')
55
+ rdoc.rdoc_files.include('lib/**/*.rb')
56
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.1.0
@@ -0,0 +1,22 @@
1
+ # An example Monit configuration file for running the apn_sender background daemon
2
+ #
3
+ # 1. Replace #{app_name} with your application name
4
+ # 2. Add any arguments between apn_sender the and start/stop command
5
+ # 3. Install as a monitrc file (paste to bottom of /etc/monit/monitrc, or save as a .monitrc file and include in the main config)
6
+
7
+ check process redis
8
+ with pidfile /var/run/redis.pid
9
+ group apn_sender
10
+ start program = "/usr/bin/redis-server /etc/redis/redis.conf"
11
+ stop program = "/bin/echo SHUTDOWN | nc localhost 6379"
12
+ if failed host 127.0.0.1 port 6379 then restart
13
+ if 5 restarts within 5 cycles then timeout
14
+
15
+
16
+ check process apn_sender
17
+ with pidfile /var/www/#{app_name}/shared/pids/apn_sender.pid
18
+ group apn_sender
19
+ start program = "/var/www/#{app_name}/current/script/apn_sender --environment=production --verbose start"
20
+ stop program = "/var/www/{#app_name}/current/script/apn_sender --environment=production --verbose stop"
21
+ if 2 restarts within 3 cycles then timeout
22
+ depends_on redis
@@ -0,0 +1,9 @@
1
+ class ApnSenderGenerator < Rails::Generator::Base
2
+
3
+ def manifest
4
+ record do |m|
5
+ m.template 'script', 'script/apn_sender', :chmod => 0755
6
+ end
7
+ end
8
+
9
+ end
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # Daemons sets pwd to /, so we have to explicitly set RAILS_ROOT
4
+ RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
5
+
6
+ require 'rubygems'
7
+ require 'apn'
8
+ require 'apn/sender_daemon'
9
+
10
+ APN::SenderDaemon.new(ARGV).daemonize
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.dirname(__FILE__) + "/rails/init.rb"
@@ -0,0 +1,13 @@
1
+ require 'resque'
2
+ require 'resque/plugins/access_worker_from_job'
3
+ require 'resque/hooks/before_unregister_worker'
4
+ require 'json'
5
+ require 'active_support'
6
+
7
+ require 'apn/queue_name'
8
+ require 'apn/queue_manager'
9
+ require 'apn/notification'
10
+ require 'apn/notification_job'
11
+ require 'apn/connection/base'
12
+ require 'apn/sender'
13
+ require 'apn/feedback'
@@ -0,0 +1,117 @@
1
+ require 'socket'
2
+ require 'openssl'
3
+ require 'resque'
4
+
5
+ module APN
6
+ module Connection
7
+ # APN::Connection::Base takes care of all the boring certificate loading, socket creating, and logging
8
+ # responsibilities so APN::Sender and APN::Feedback and focus on their respective specialties.
9
+ module Base
10
+ attr_accessor :opts, :logger
11
+
12
+ def initialize(opts = {})
13
+ @opts = opts
14
+
15
+ setup_logger
16
+ log(:info, "APN::Sender initializing. Establishing connections first...") if @opts[:verbose]
17
+ setup_paths
18
+
19
+ super( APN::QUEUE_NAME ) if self.class.ancestors.include?(Resque::Worker)
20
+ end
21
+
22
+ # Lazy-connect the socket once we try to access it in some way
23
+ def socket
24
+ setup_connection unless @socket
25
+ return @socket
26
+ end
27
+
28
+ protected
29
+
30
+ # Default to Rails or Merg logger, if available
31
+ def setup_logger
32
+ @logger = if defined?(Merb::Logger)
33
+ Merb.logger
34
+ elsif defined?(RAILS_DEFAULT_LOGGER)
35
+ RAILS_DEFAULT_LOGGER
36
+ end
37
+ end
38
+
39
+ # Log message to any logger provided by the user (e.g. the Rails logger).
40
+ # Accepts +log_level+, +message+, since that seems to make the most sense,
41
+ # and just +message+, to be compatible with Resque's log method and to enable
42
+ # sending verbose and very_verbose worker messages to e.g. the rails logger.#
43
+ #
44
+ # Perhaps a method definition of +message, +level+ would make more sense, but
45
+ # that's also the complete opposite of what anyone comming from rails would expect.
46
+ alias_method(:resque_log, :log) if defined?(log)
47
+ def log(level, message = nil)
48
+ level, message = 'info', level if message.nil? # Handle only one argument if called from Resque, which expects only message
49
+
50
+ resque_log(message) if defined?(resque_log)
51
+ return false unless self.logger && self.logger.respond_to?(level)
52
+ self.logger.send(level, "#{Time.now}: #{message}")
53
+ end
54
+
55
+ # Log the message first, to ensure it reports what went wrong if in daemon mode. Then die, because something went horribly wrong.
56
+ def log_and_die(msg)
57
+ log(:fatal, msg)
58
+ raise msg
59
+ end
60
+
61
+ def apn_production?
62
+ @opts[:environment] && @opts[:environment] != '' && :production == @opts[:environment].to_sym
63
+ end
64
+
65
+ # Get a fix on the .pem certificate we'll be using for SSL
66
+ def setup_paths
67
+ # Set option defaults
68
+ @opts[:cert_path] ||= File.join(File.expand_path(RAILS_ROOT), "config", "certs") if defined?(RAILS_ROOT)
69
+ @opts[:environment] ||= RAILS_ENV if defined?(RAILS_ENV)
70
+
71
+ log_and_die("Missing certificate path. Please specify :cert_path when initializing class.") unless @opts[:cert_path]
72
+
73
+ cert_name = apn_production? ? "apn_production.pem" : "apn_development.pem"
74
+ cert_path = File.join(@opts[:cert_path], cert_name)
75
+
76
+ @apn_cert = File.exists?(cert_path) ? File.read(cert_path) : nil
77
+ log_and_die("Missing apple push notification certificate in #{cert_path}") unless @apn_cert
78
+ end
79
+
80
+ # Open socket to Apple's servers
81
+ def setup_connection
82
+ log_and_die("Missing apple push notification certificate") unless @apn_cert
83
+ return true if @socket && @socket_tcp
84
+ log_and_die("Trying to open half-open connection") if @socket || @socket_tcp
85
+
86
+ ctx = OpenSSL::SSL::SSLContext.new
87
+ ctx.cert = OpenSSL::X509::Certificate.new(@apn_cert)
88
+ ctx.key = OpenSSL::PKey::RSA.new(@apn_cert)
89
+
90
+ @socket_tcp = TCPSocket.new(apn_host, apn_port)
91
+ @socket = OpenSSL::SSL::SSLSocket.new(@socket_tcp, ctx)
92
+ @socket.sync = true
93
+ @socket.connect
94
+ rescue SocketError => error
95
+ log_and_die("Error with connection to #{apn_host}: #{error}")
96
+ end
97
+
98
+ # Close open sockets
99
+ def teardown_connection
100
+ log(:info, "Closing connections...") if @opts[:verbose]
101
+
102
+ begin
103
+ @socket.close if @socket
104
+ rescue Exception => e
105
+ log(:error, "Error closing SSL Socket: #{e}")
106
+ end
107
+
108
+ begin
109
+ @socket_tcp.close if @socket_tcp
110
+ rescue Exception => e
111
+ log(:error, "Error closing TCP Socket: #{e}")
112
+ end
113
+ end
114
+
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,92 @@
1
+ require 'apn/connection/base'
2
+
3
+ module APN
4
+ # Encapsulates data returned from the {APN Feedback Service}[http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3].
5
+ # Possesses +timestamp+ and +token+ attributes.
6
+ class FeedbackItem
7
+ attr_accessor :timestamp, :token
8
+
9
+ def initialize(time, token)
10
+ @timestamp = time
11
+ @token = token
12
+ end
13
+
14
+ # For convenience, return the token on to_s
15
+ def to_s
16
+ token
17
+ end
18
+ end
19
+
20
+ # When supplied with the certificate path and the desired environment, connects to the {APN Feedback Service}[http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3]
21
+ # and returns any response as an array of APN::FeedbackItem elements.
22
+ #
23
+ # See README for usage and details.
24
+ class Feedback
25
+ include APN::Connection::Base
26
+
27
+ # Returns array of APN::FeedbackItem elements read from Apple. Connects to Apple once and caches the
28
+ # data, continues to returns cached data unless called with <code>data(true)</code>, which clears the
29
+ # existing feedback array. Note that once you force resetting the cache you loose all previous feedback,
30
+ # so be sure you've already processed it.
31
+ def data(force = nil)
32
+ @feedback = nil if force
33
+ @feedback ||= receive
34
+ end
35
+
36
+ # Wrapper around +data+ returning just an array of token strings.
37
+ def tokens(force = nil)
38
+ data(force).map(&:token)
39
+ end
40
+
41
+ # Prettify to return meaningful status information when printed. Can't add these directly to connection/base, because Resque depends on decoding to_s
42
+ def inspect
43
+ "#<#{self.class.name}: #{to_s}>"
44
+ end
45
+
46
+ # Prettify to return meaningful status information when printed. Can't add these directly to connection/base, because Resque depends on decoding to_s
47
+ def to_s
48
+ "#{@socket ? 'Connected' : 'Connection not currently established'} to #{apn_host} on #{apn_port}"
49
+ end
50
+
51
+ protected
52
+
53
+ # Connects to Apple's Feedback Service and checks if there's anything there for us.
54
+ # Returns an array of APN::FeedbackItem pairs
55
+ def receive
56
+ feedback = []
57
+
58
+ # Hi Apple
59
+ setup_connection
60
+
61
+ # Unpacking code borrowed from http://github.com/jpoz/APNS/blob/master/lib/apns/core.rb
62
+ while line = socket.gets # Read lines from the socket
63
+ line.strip!
64
+ f = line.unpack('N1n1H140')
65
+ feedback << APN::FeedbackItem.new(Time.at(f[0]), f[2])
66
+ end
67
+
68
+ # Bye Apple
69
+ teardown_connection
70
+
71
+ return feedback
72
+ end
73
+
74
+
75
+ def apn_host
76
+ @apn_host ||= apn_production? ? "feedback.push.apple.com" : "feedback.sandbox.push.apple.com"
77
+ end
78
+
79
+ def apn_port
80
+ 2196
81
+ end
82
+
83
+ end
84
+ end
85
+
86
+
87
+
88
+ __END__
89
+ # Testing from irb
90
+ irb -r 'lib/apn/feedback'
91
+
92
+ a=APN::Feedback.new(:cert_path => '/Users/kali/Code/insurrection/certs/', :environment => :production)
@@ -0,0 +1,86 @@
1
+ module APN
2
+ # Encapsulates the logic necessary to convert an iPhone token and an array of options into a string of the format required
3
+ # by Apple's servers to send the notification. Much of the processing code here copied with many thanks from
4
+ # http://github.com/samsoffes/apple_push_notification/blob/master/lib/apple_push_notification.rb
5
+ #
6
+ # APN::Notification.new's first argument is the token of the iPhone which should receive the notification. The second argument
7
+ # is a hash with any of :alert, :badge, and :sound keys. All three accept string arguments, while :sound can also be set to +true+
8
+ # to play the default sound installed with the application. At least one of these keys must exist. Any other keys are merged into
9
+ # the root of the hash payload ultimately sent to the iPhone:
10
+ #
11
+ # APN::Notification.new(token, {:alert => 'Stuff', :custom => {:code => 23}})
12
+ # # Writes this JSON to servers: {"aps" => {"alert" => "Stuff"}, "custom" => {"code" => 23}}
13
+ #
14
+ # As a shortcut, APN::Notification.new also accepts a string as the second argument, which it converts into the alert to send. The
15
+ # following two lines are equivalent:
16
+ #
17
+ # APN::Notification.new(token, 'Some Alert')
18
+ # APN::Notification.new(token, {:alert => 'Some Alert'})
19
+ #
20
+ class Notification
21
+ # Available to help clients determine before they create the notification if their message will be too large.
22
+ # Each iPhone Notification payload must be 256 or fewer characters. Encoding a null message has a 57
23
+ # character overhead, so there are 199 characters available for the alert string.
24
+ MAX_ALERT_LENGTH = 199
25
+
26
+ attr_accessor :options, :token
27
+ def initialize(token, opts)
28
+ @options = hash_as_symbols(opts.is_a?(Hash) ? opts : {:alert => opts})
29
+ @token = token
30
+
31
+ raise "The maximum size allowed for a notification payload is 256 bytes." if packaged_notification.size.to_i > 256
32
+ end
33
+
34
+ def to_s
35
+ packaged_notification
36
+ end
37
+
38
+ # Ensures at least one of <code>%w(alert badge sound)</code> is present
39
+ def valid?
40
+ return true if %w(alert badge sound).any?{|key| options.keys.include?(key.to_sym) }
41
+ false
42
+ end
43
+
44
+ protected
45
+
46
+ # Completed encoded notification, ready to send down the wire to Apple
47
+ def packaged_notification
48
+ pt = packaged_token
49
+ pm = packaged_message
50
+ [0, 0, 32, pt, 0, pm.size, pm].pack("ccca*cca*")
51
+ end
52
+
53
+ # Device token, compressed and hex-ified
54
+ def packaged_token
55
+ [@token.gsub(/[\s|<|>]/,'')].pack('H*')
56
+ end
57
+
58
+ # Converts the supplied options into the JSON needed for Apple's push notification servers.
59
+ # Extracts :alert, :badge, and :sound keys into the 'aps' hash, merges any other hash data
60
+ # into the root of the hash to encode and send to apple.
61
+ def packaged_message
62
+ opts = @options.clone # Don't destroy our pristine copy
63
+ hsh = {'aps' => {}}
64
+ hsh['aps']['alert'] = opts.delete(:alert).to_s if opts[:alert]
65
+ hsh['aps']['badge'] = opts.delete(:badge).to_i if opts[:badge]
66
+ if sound = opts.delete(:sound)
67
+ hsh['aps']['sound'] = sound.is_a?(TrueClass) ? 'default' : sound.to_s
68
+ end
69
+ hsh.merge!(opts)
70
+ ActiveSupport::JSON::encode(hsh)
71
+ end
72
+
73
+ # Symbolize keys, using ActiveSupport if available
74
+ def hash_as_symbols(hash)
75
+ if hash.respond_to?(:symbolize_keys)
76
+ return hash.symbolize_keys
77
+ else
78
+ hash.inject({}) do |opt, (key, value)|
79
+ opt[(key.to_sym rescue key) || key] = value
80
+ opt
81
+ end
82
+ end
83
+ end
84
+
85
+ end
86
+ end
@@ -0,0 +1,23 @@
1
+ module APN
2
+ # This is the class that's actually enqueued via Resque when user calls +APN.notify+.
3
+ # It gets added to the +apple_server_notifications+ Resque queue, which should only be operated on by
4
+ # workers of the +APN::Sender+ class.
5
+ class NotificationJob
6
+ # Behind the scenes, this is the name of our Resque queue
7
+ @queue = APN::QUEUE_NAME
8
+
9
+ # Build a notification from arguments and send to Apple
10
+ def self.perform(token, opts)
11
+ msg = APN::Notification.new(token, opts)
12
+ raise "Invalid notification options (did you provide :alert, :badge, or :sound?): #{opts.inspect}" unless msg.valid?
13
+
14
+ worker.send_to_apple( msg )
15
+ end
16
+
17
+
18
+ # Only execute this job in specialized APN::Sender workers, since
19
+ # standard Resque workers don't maintain the persistent TCP connection.
20
+ extend Resque::Plugins::AccessWorkerFromJob
21
+ self.required_worker_class = 'APN::Sender'
22
+ end
23
+ end
@@ -0,0 +1,57 @@
1
+ # Extending Resque to respond to the +before_unregister_worker+ hook. Note this requires a matching
2
+ # monkeypatch in the Resque::Worker class. See +resque/hooks/before_unregister_worker.rb+ for an
3
+ # example implementation
4
+
5
+ module APN
6
+ # Enqueues a notification to be sent in the background via the persistent TCP socket, assuming apn_sender is running (or will be soon)
7
+ def self.notify(token, opts = {})
8
+ token = token.to_s.gsub(/\W/, '')
9
+ APN::QueueManager.enqueue(APN::NotificationJob, token, opts)
10
+ end
11
+
12
+ # Extends Resque, allowing us to add all the callbacks to Resque we desire without affecting the expected
13
+ # functionality in the parent app, if we're included in e.g. a Rails application.
14
+ class QueueManager
15
+ extend Resque
16
+
17
+ def self.before_unregister_worker(&block)
18
+ block ? (@before_unregister_worker = block) : @before_unregister_worker
19
+ end
20
+
21
+ def self.before_unregister_worker=(before_unregister_worker)
22
+ @before_unregister_worker = before_unregister_worker
23
+ end
24
+
25
+ def self.to_s
26
+ "APN::QueueManager (Resque Client) connected to #{redis.server}"
27
+ end
28
+ end
29
+
30
+ end
31
+
32
+ # Ensures we close any open sockets when the worker exits
33
+ APN::QueueManager.before_unregister_worker do |worker|
34
+ worker.send(:teardown_connection) if worker.respond_to?(:teardown_connection)
35
+ end
36
+
37
+
38
+ # # Run N jobs per fork, rather than creating a new fork for each notification
39
+ # # By defunkt - http://gist.github.com/349376
40
+ # APN::QueueManager.after_fork do |job|
41
+ # # How many jobs should we process in each fork?
42
+ # jobs_per_fork = 10
43
+ #
44
+ # # Set hook to nil to prevent running this hook over
45
+ # # and over while processing more jobs in this fork.
46
+ # Resque.after_fork = nil
47
+ #
48
+ # # Make sure we process jobs in the right order.
49
+ # job.worker.process(job)
50
+ #
51
+ # # One less than specified because the child will run a
52
+ # # final job after exiting this hook.
53
+ # (jobs_per_fork.to_i - 1).times do
54
+ # job.worker.process
55
+ # end
56
+ # end
57
+
@@ -0,0 +1,4 @@
1
+ module APN
2
+ # Change this to modify the queue from which notification jobs are pushed and pulled
3
+ QUEUE_NAME = :apple_push_notifications
4
+ end
@@ -0,0 +1,47 @@
1
+ module APN
2
+ # Subclass of Resque::Worker which initializes a single TCP socket on creation to communicate with Apple's Push Notification servers.
3
+ # Shares this socket with each child process forked off by Resque to complete a job. Socket is closed in the before_unregister_worker
4
+ # callback, which gets called on normal or exceptional exits.
5
+ #
6
+ # End result: single persistent TCP connection to Apple, so they don't ban you for frequently opening and closing connections,
7
+ # which they apparently view as a DOS attack.
8
+ #
9
+ # Accepts <code>:environment</code> (production vs anything else) and <code>:cert_path</code> options on initialization. If called in a
10
+ # Rails context, will default to RAILS_ENV and RAILS_ROOT/config/certs. :environment will default to development.
11
+ # APN::Sender expects two files to exist in the specified <code>:cert_path</code> directory:
12
+ # <code>apn_production.pem</code> and <code>apn_development.pem</code>.
13
+ #
14
+ # If a socket error is encountered, will teardown the connection and retry again twice before admitting defeat.
15
+ class Sender < ::Resque::Worker
16
+ include APN::Connection::Base
17
+ TIMES_TO_RETRY_SOCKET_ERROR = 2
18
+
19
+ # Send a raw string over the socket to Apple's servers (presumably already formatted by APN::Notification)
20
+ def send_to_apple( notification, attempt = 0 )
21
+ if attempt > TIMES_TO_RETRY_SOCKET_ERROR
22
+ log_and_die("Error with connection to #{apn_host} (retried #{TIMES_TO_RETRY_SOCKET_ERROR} times): #{error}")
23
+ end
24
+
25
+ self.socket.write( notification.to_s )
26
+ rescue SocketError => error
27
+ log(:error, "Error with connection to #{apn_host} (attempt #{attempt}): #{error}")
28
+
29
+ # Try reestablishing the connection
30
+ teardown_connection
31
+ setup_connection
32
+ send_to_apple(notification, attempt + 1)
33
+ end
34
+
35
+ protected
36
+
37
+ def apn_host
38
+ @apn_host ||= apn_production? ? "gateway.push.apple.com" : "gateway.sandbox.push.apple.com"
39
+ end
40
+
41
+ def apn_port
42
+ 2195
43
+ end
44
+
45
+ end
46
+
47
+ end
@@ -0,0 +1,75 @@
1
+ # Based roughly on delayed_job's delayed/command.rb
2
+ require 'rubygems'
3
+ require 'daemons'
4
+ require 'optparse'
5
+ require 'logger'
6
+
7
+ module APN
8
+ # A wrapper designed to daemonize an APN::Sender instance to keep in running in the background.
9
+ # Connects worker's output to a custom logger, if available. Creates a pid file suitable for
10
+ # monitoring with {monit}[http://mmonit.com/monit/].
11
+ #
12
+ # Based off delayed_job's great example, except we can be much lighter by not loading the entire
13
+ # Rails environment. To use in a Rails app, <code>script/generate apn_sender</code>.
14
+ class SenderDaemon
15
+
16
+ def initialize(args)
17
+ @options = {:worker_count => 1, :environment => :development, :delay => 5}
18
+
19
+ optparse = OptionParser.new do |opts|
20
+ opts.banner = "Usage: #{File.basename($0)} [options] start|stop|restart|run"
21
+
22
+ opts.on('-h', '--help', 'Show this message') do
23
+ puts opts
24
+ exit 1
25
+ end
26
+ opts.on('-e', '--environment=NAME', 'Specifies the environment to run this apn_sender under ([development]/production).') do |e|
27
+ @options[:environment] = e
28
+ end
29
+ opts.on('--cert-path=NAME', 'Path to directory containing apn .pem certificates.') do |path|
30
+ @options[:cert_path] = path
31
+ end
32
+ opts.on('-n', '--number-of-workers=WORKERS', "Number of unique workers to spawn") do |worker_count|
33
+ @options[:worker_count] = worker_count.to_i rescue 1
34
+ end
35
+ opts.on('-v', '--verbose', "Turn on verbose mode") do
36
+ @options[:verbose] = true
37
+ end
38
+ opts.on('-V', '--very-verbose', "Turn on very verbose mode") do
39
+ @options[:very_verbose] = true
40
+ end
41
+ opts.on('-d', '--delay=D', "Delay between rounds of work (seconds)") do |d|
42
+ @options[:delay] = d
43
+ end
44
+ end
45
+
46
+ # If no arguments, give help screen
47
+ @args = optparse.parse!(args.empty? ? ['-h'] : args)
48
+ @options[:verbose] = true if @options[:very_verbose]
49
+ end
50
+
51
+ def daemonize
52
+ @options[:worker_count].times do |worker_index|
53
+ process_name = @options[:worker_count] == 1 ? "apn_sender" : "apn_sender.#{worker_index}"
54
+ Daemons.run_proc(process_name, :dir => "#{::RAILS_ROOT}/tmp/pids", :dir_mode => :normal, :ARGV => @args) do |*args|
55
+ run process_name
56
+ end
57
+ end
58
+ end
59
+
60
+ def run(worker_name = nil)
61
+ logger = Logger.new(File.join(::RAILS_ROOT, 'log', 'apn_sender.log'))
62
+
63
+ worker = APN::Sender.new(@options)
64
+ worker.logger = logger
65
+ worker.verbose = @options[:verbose]
66
+ worker.very_verbose = @options[:very_verbose]
67
+ worker.work(@options[:delay])
68
+ rescue => e
69
+ STDERR.puts e.message
70
+ logger.fatal(e) if logger && logger.respond_to?(:fatal)
71
+ exit 1
72
+ end
73
+
74
+ end
75
+ end
@@ -0,0 +1,39 @@
1
+ # Slight modifications from the default Resque tasks
2
+ namespace :apn do
3
+ task :setup
4
+ task :work => :sender
5
+ task :workers => :senders
6
+
7
+ desc "Start an APN worker"
8
+ task :sender => :setup do
9
+ require 'apn'
10
+
11
+ worker = nil
12
+
13
+ begin
14
+ worker = APN::Sender.new(:cert_path => ENV['CERT_PATH'], :environment => ENV['ENVIRONMENT'])
15
+ worker.verbose = ENV['LOGGING'] || ENV['VERBOSE']
16
+ worker.very_verbose = ENV['VVERBOSE']
17
+ rescue Exception => e
18
+ raise e
19
+ # abort "set QUEUE env var, e.g. $ QUEUE=critical,high rake resque:work"
20
+ end
21
+
22
+ puts "*** Starting worker to send apple notifications in the background from #{worker}"
23
+
24
+ worker.work(ENV['INTERVAL'] || 5) # interval, will block
25
+ end
26
+
27
+ desc "Start multiple APN workers. Should only be used in dev mode."
28
+ task :senders do
29
+ threads = []
30
+
31
+ ENV['COUNT'].to_i.times do
32
+ threads << Thread.new do
33
+ system "rake apn:work"
34
+ end
35
+ end
36
+
37
+ threads.each { |thread| thread.join }
38
+ end
39
+ end
@@ -0,0 +1,30 @@
1
+ # Adding a +before_unregister_worker+ hook Resque::Worker. To be used, must be matched by a similar monkeypatch
2
+ # for Resque class itself, or else a class that extends Resque. See apple_push_notification/queue_manager.rb for
3
+ # an implementation.
4
+ module Resque
5
+ class Worker
6
+ alias_method :unregister_worker_without_before_hook, :unregister_worker
7
+
8
+ # Wrapper for original unregister_worker method which adds a before hook +before_unregister_worker+
9
+ # to be executed if present.
10
+ def unregister_worker
11
+ run_hook(:before_unregister_worker, self)
12
+ unregister_worker_without_before_hook
13
+ end
14
+
15
+
16
+ # Unforunately have to override Resque::Worker's +run_hook+ method to call hook on
17
+ # APN::QueueManager rather on Resque directly. Any suggestions on
18
+ # how to make this more flexible are more than welcome.
19
+ def run_hook(name, *args)
20
+ # return unless hook = Resque.send(name)
21
+ return unless hook = APN::QueueManager.send(name)
22
+ msg = "Running #{name} hook"
23
+ msg << " with #{args.inspect}" if args.any?
24
+ log msg
25
+
26
+ args.any? ? hook.call(*args) : hook.call
27
+ end
28
+
29
+ end
30
+ end
@@ -0,0 +1 @@
1
+ require "apn"
@@ -0,0 +1,10 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+ require 'shoulda'
4
+
5
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
6
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
7
+ require 'apple_push_notification'
8
+
9
+ class Test::Unit::TestCase
10
+ end
@@ -0,0 +1,7 @@
1
+ require 'helper'
2
+
3
+ class TestAPN < Test::Unit::TestCase
4
+ should "probably rename this file and start testing for real" do
5
+ flunk "hey buddy, you should probably rename this file and start testing for real"
6
+ end
7
+ end
metadata ADDED
@@ -0,0 +1,102 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hackedunit-apn_sender
3
+ version: !ruby/object:Gem::Version
4
+ prerelease:
5
+ version: 1.1.0
6
+ platform: ruby
7
+ authors:
8
+ - Kali Donovan
9
+ - Tinu Cleatus
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+
14
+ date: 2011-03-26 00:00:00 +05:30
15
+ default_executable:
16
+ dependencies:
17
+ - !ruby/object:Gem::Dependency
18
+ name: resque
19
+ prerelease: false
20
+ requirement: &id001 !ruby/object:Gem::Requirement
21
+ none: false
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: "0"
26
+ type: :runtime
27
+ version_requirements: *id001
28
+ - !ruby/object:Gem::Dependency
29
+ name: resque-access_worker_from_job
30
+ prerelease: false
31
+ requirement: &id002 !ruby/object:Gem::Requirement
32
+ none: false
33
+ requirements:
34
+ - - ">="
35
+ - !ruby/object:Gem::Version
36
+ version: "0"
37
+ type: :runtime
38
+ version_requirements: *id002
39
+ description: Resque-based background worker to send Apple Push Notifications over a persistent TCP socket. Includes Resque tweaks to allow persistent sockets between jobs, helper methods for enqueueing APN notifications, and a background daemon to send them.
40
+ email: kali.donovan@gmail.com
41
+ executables: []
42
+
43
+ extensions: []
44
+
45
+ extra_rdoc_files:
46
+ - LICENSE
47
+ - README.rdoc
48
+ files:
49
+ - .document
50
+ - LICENSE
51
+ - README.rdoc
52
+ - Rakefile
53
+ - VERSION
54
+ - contrib/apn_sender.monitrc
55
+ - generators/apn_sender_generator.rb
56
+ - generators/templates/script
57
+ - init.rb
58
+ - lib/apn.rb
59
+ - lib/apn/connection/base.rb
60
+ - lib/apn/feedback.rb
61
+ - lib/apn/notification.rb
62
+ - lib/apn/notification_job.rb
63
+ - lib/apn/queue_manager.rb
64
+ - lib/apn/queue_name.rb
65
+ - lib/apn/sender.rb
66
+ - lib/apn/sender_daemon.rb
67
+ - lib/apn/tasks.rb
68
+ - lib/resque/hooks/before_unregister_worker.rb
69
+ - rails/init.rb
70
+ - test/helper.rb
71
+ - test/test_apple_push_notification.rb
72
+ has_rdoc: true
73
+ homepage: http://github.com/hackedunit/apn_sender
74
+ licenses: []
75
+
76
+ post_install_message:
77
+ rdoc_options: []
78
+
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ none: false
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: "0"
87
+ required_rubygems_version: !ruby/object:Gem::Requirement
88
+ none: false
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: "0"
93
+ requirements: []
94
+
95
+ rubyforge_project:
96
+ rubygems_version: 1.5.0
97
+ signing_key:
98
+ specification_version: 3
99
+ summary: Resque-based background worker to send Apple Push Notifications over a persistent TCP socket.
100
+ test_files:
101
+ - test/helper.rb
102
+ - test/test_apple_push_notification.rb