Class: Simplepush

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/simplepush.rb,
lib/simplepush/version.rb

Constant Summary collapse

VERSION =
"0.7.6"

Instance Method Summary collapse

Constructor Details

#initialize(key, password = nil, salt = '1789F0B8C4A051E5') ⇒ Simplepush

If password and salt are provided, then message and title will be encrypted.



22
23
24
25
26
# File 'lib/simplepush.rb', line 22

def initialize(key, password = nil, salt = '1789F0B8C4A051E5')
  raise "Key must be set" unless key
  @key = key
  @cipher_key = [Digest::SHA1.hexdigest(password + salt)[0,32]].pack "H*" if password
end

Instance Method Details

#send(title, message, event = nil) ⇒ Object

Send the given title/message.

This method is blocking.

Returns the response object from Httparty.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/simplepush.rb', line 35

def send(title, message, event = nil)
  raise "Key and message argument must be set" unless message

  payload = {}
  payload[:key] = @key
  payload[:msg] = message.to_s
  payload[:event] = event.to_s if event
  payload[:title] = title.to_s if title

  if @cipher_key
    require 'openssl'
    payload[:encrypted] = true

    cipher = OpenSSL::Cipher::AES.new(128, :CBC)
    cipher.encrypt
    cipher.key = @cipher_key

    # Set random_iv and store as payload
    payload[:iv] = cipher.random_iv.unpack("H*").first.upcase

    # Automatically uses PKCS7
    payload[:msg] = Base64.urlsafe_encode64(cipher.update(payload[:msg]) + cipher.final)

    if title
      cipher.encrypt # Restart cipher
      cipher.key = @cipher_key
      payload[:title] = Base64.urlsafe_encode64(cipher.update(payload[:title]) + cipher.final)
    end
  end

  return self.class.post('/send', body: payload)
end