44
55import base64
66import os
7-
7+ import json
88import http_ece
99import pyelliptic
1010import requests
@@ -151,10 +151,14 @@ def encode(self, data):
151151 'body' : encrypted ,
152152 })
153153
154- def send (self , data , headers = {}, ttl = 0 ):
154+ def send (self , data , gcm_key = None , reg_id = None , headers = {}, ttl = 0 ):
155155 """Encode and send the data to the Push Service.
156156
157157 :param data: A serialized block of data (see encode() ).
158+ :param gcm_key: API key obtained from the Google Developer Console.
159+ Needed if endpoint is https://android.googleapis.com/gcm/send
160+ :param reg_id: registration id of the recipient. If not provided,
161+ it will be extracted from the endpoint.
158162 :param headers: A dictionary containing any additional HTTP headers.
159163 :param ttl: The Time To Live in seconds for this message if the
160164 recipient is not online. (Defaults to "0", which discards the
@@ -175,10 +179,32 @@ def send(self, data, headers={}, ttl=0):
175179 'encryption' : "keyid=p256dh;salt=" +
176180 encoded ['salt' ].decode ('utf8' ),
177181 })
182+
183+ if self .subscription_info ['endpoint' ].startswith ('https://android.googleapis.com/gcm/send' ):
184+
185+ if not gcm_key :
186+ raise WebPushException ("API key not provided for google gcm endpoint" )
187+ endpoint = 'https://android.googleapis.com/gcm/send'
188+ reg_ids = []
189+ if not reg_id :
190+ reg_id = self .subscription_info ['endpoint' ].rsplit ('/' , 1 )[- 1 ]
191+ reg_ids .append (reg_id )
192+ data = {}
193+ data ['registration_ids' ] = reg_ids
194+ data ['raw_data' ] = base64 .b64encode (encoded .get ('body' ))
195+ encoded_data = json .dumps (data )
196+ headers .update ({
197+ 'Authorization' : 'key=' + gcm_key ,
198+ 'Content-Type' : 'application/json' ,
199+ })
200+ else :
201+ encoded_data = encoded .get ('body' )
202+ endpoint = self .subscription_info ['endpoint' ]
203+
178204 if 'ttl' not in headers or ttl :
179205 headers ['ttl' ] = ttl
180206 # Additionally useful headers:
181207 # Authorization / Crypto-Key (VAPID headers)
182- return requests .post (self . subscription_info [ ' endpoint' ] ,
183- data = encoded . get ( 'body' ) ,
208+ return requests .post (endpoint ,
209+ data = encoded_data ,
184210 headers = headers )
0 commit comments