44
55import base64
66import os
7-
7+ import json
88import http_ece
99import pyelliptic
1010import requests
@@ -143,10 +143,14 @@ def encode(self, data):
143143 'body' : encrypted ,
144144 })
145145
146- def send (self , data , headers = {}, ttl = 0 ):
146+ def send (self , data , gcm_key = None , reg_id = None , headers = {}, ttl = 0 ):
147147 """Encode and send the data to the Push Service.
148148
149149 :param data: A serialized block of data (see encode() ).
150+ :param gcm_key: API key obtained from the Google Developer Console.
151+ Needed if endpoint is https://android.googleapis.com/gcm/send
152+ :param reg_id: registration id of the recipient. If not provided,
153+ it will be extracted from the endpoint.
150154 :param headers: A dictionary containing any additional HTTP headers.
151155 :param ttl: The Time To Live in seconds for this message if the
152156 recipient is not online. (Defaults to "0", which discards the
@@ -166,10 +170,32 @@ def send(self, data, headers={}, ttl=0):
166170 'content-encoding' : 'aesgcm' ,
167171 'encryption' : "keyid=p256dh;salt=" + encoded ['salt' ],
168172 })
173+
174+ if self .subscription_info ['endpoint' ].startswith ('https://android.googleapis.com/gcm/send' ):
175+
176+ if not gcm_key :
177+ raise WebPushException ("API key not provided for google gcm endpoint" )
178+ endpoint = 'https://android.googleapis.com/gcm/send'
179+ reg_ids = []
180+ if not reg_id :
181+ reg_id = self .subscription_info ['endpoint' ].rsplit ('/' , 1 )[- 1 ]
182+ reg_ids .append (reg_id )
183+ data = {}
184+ data ['registration_ids' ] = reg_ids
185+ data ['raw_data' ] = base64 .b64encode (encoded .get ('body' ))
186+ encoded_data = json .dumps (data )
187+ headers .update ({
188+ 'Authorization' : 'key=' + gcm_key ,
189+ 'Content-Type' : 'application/json' ,
190+ })
191+ else :
192+ encoded_data = encoded .get ('body' )
193+ endpoint = self .subscription_info ['endpoint' ]
194+
169195 if 'ttl' not in headers or ttl :
170196 headers ['ttl' ] = ttl
171197 # Additionally useful headers:
172198 # Authorization / Crypto-Key (VAPID headers)
173- return requests .post (self . subscription_info [ ' endpoint' ] ,
174- data = encoded . get ( 'body' ) ,
199+ return requests .post (endpoint ,
200+ data = encoded_data ,
175201 headers = headers )
0 commit comments