5
5
import base64
6
6
import os
7
7
8
+ import json
8
9
import http_ece
9
10
import pyelliptic
10
11
import requests
@@ -143,10 +144,14 @@ def encode(self, data):
143
144
'body' : encrypted ,
144
145
})
145
146
146
- def send (self , data , headers = {}, ttl = 0 ):
147
+ def send (self , data , headers = {}, ttl = 0 , gcm_key = None , reg_id = None ):
147
148
"""Encode and send the data to the Push Service.
148
149
149
150
: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.
150
155
:param headers: A dictionary containing any additional HTTP headers.
151
156
:param ttl: The Time To Live in seconds for this message if the
152
157
recipient is not online. (Defaults to "0", which discards the
@@ -166,10 +171,32 @@ def send(self, data, headers={}, ttl=0):
166
171
'content-encoding' : 'aesgcm' ,
167
172
'encryption' : "keyid=p256dh;salt=" + encoded ['salt' ],
168
173
})
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
+
169
196
if 'ttl' not in headers or ttl :
170
197
headers ['ttl' ] = ttl
171
198
# Additionally useful headers:
172
199
# 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 ,
175
202
headers = headers )
0 commit comments