55import base64
66import os
77
8+ import json
89import http_ece
910import pyelliptic
1011import requests
@@ -143,10 +144,14 @@ def encode(self, data):
143144 'body' : encrypted ,
144145 })
145146
146- def send (self , data , headers = {}, ttl = 0 ):
147+ def send (self , data , headers = {}, ttl = 0 , gcm_key = None , reg_id = None ):
147148 """Encode and send the data to the Push Service.
148149
149150 :param data: A serialized block of data (see encode() ).
151+ :param gcm_key: API key obtained from the Google Developer Console.
152+ Needed if endpoint is https://android.googleapis.com/gcm/send
153+ :param reg_id: registration id of the recipient. If not provided,
154+ it will be extracted from the endpoint.
150155 :param headers: A dictionary containing any additional HTTP headers.
151156 :param ttl: The Time To Live in seconds for this message if the
152157 recipient is not online. (Defaults to "0", which discards the
@@ -166,10 +171,32 @@ def send(self, data, headers={}, ttl=0):
166171 'content-encoding' : 'aesgcm' ,
167172 'encryption' : "keyid=p256dh;salt=" + encoded ['salt' ],
168173 })
174+ gcm_endpoint = 'https://android.googleapis.com/gcm/send'
175+ if self .subscription_info ['endpoint' ].startswith (gcm_endpoint ):
176+
177+ if not gcm_key :
178+ raise WebPushException ("API key not provided for gcm endpoint" )
179+ endpoint = gcm_endpoint
180+ reg_ids = []
181+ if not reg_id :
182+ reg_id = self .subscription_info ['endpoint' ].rsplit ('/' , 1 )[- 1 ]
183+ reg_ids .append (reg_id )
184+ data = {}
185+ data ['registration_ids' ] = reg_ids
186+ data ['raw_data' ] = base64 .b64encode (encoded .get ('body' ))
187+ encoded_data = json .dumps (data )
188+ headers .update ({
189+ 'Authorization' : 'key=' + gcm_key ,
190+ 'Content-Type' : 'application/json' ,
191+ })
192+ else :
193+ encoded_data = encoded .get ('body' )
194+ endpoint = self .subscription_info ['endpoint' ]
195+
169196 if 'ttl' not in headers or ttl :
170197 headers ['ttl' ] = ttl
171198 # Additionally useful headers:
172199 # Authorization / Crypto-Key (VAPID headers)
173- return requests .post (self . subscription_info [ ' endpoint' ] ,
174- data = encoded . get ( 'body' ) ,
200+ return requests .post (endpoint ,
201+ data = encoded_data ,
175202 headers = headers )
0 commit comments