-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
1947 lines (1602 loc) · 71.9 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
import webapp2
from google.appengine.ext.webapp import util
from google.appengine.ext import db
import json as simplejson
import unicodedata
import time
from google.appengine.api import users
import logging
import email
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
import urllib
import urllib2
from google.appengine.api import xmpp
from google.appengine.api import mail
from google.appengine.api.mail import EncodedPayload
import re
from google.appengine.api import oauth
import traceback
from google.appengine.ext.db import Property
from google.appengine.api import memcache
from userobject import UserObject
from userobject import UserObjectHandler
import random
import base64
import hashlib
from handlers import APIHandler
from google.appengine.api import urlfetch
class User(db.Model):
registration_id = db.StringProperty(indexed = False)
forward_xmpp = db.BooleanProperty(indexed = False)
forward_email = db.BooleanProperty(indexed = False)
forward_web = db.BooleanProperty(indexed = False)
version_code = db.IntegerProperty()
subscription_expiration = db.IntegerProperty(indexed = False)
registration_date = db.IntegerProperty()
promotion = db.StringProperty(indexed = False)
promotion_date = db.IntegerProperty(indexed = False)
class UserContact(db.Model):
number = db.StringProperty(indexed = False)
class UserContactSubscribed(db.Model):
pass
class UserContactLastMessage(object):
# is this stuff necessary? I guess so if sync is off.
last_message = None
last_message_name = None
last_message_number = None
class Sms(UserObject):
message = db.StringProperty(multiline = True, indexed = False)
#seen = db.IntegerProperty()
type = db.IntegerProperty(indexed = False)
date = db.IntegerProperty()
#id = db.IntegerProperty()
number = db.StringProperty(indexed = False)
image = db.BlobProperty(default = None)
#read = db.BooleanProperty()
#thread_id = db.IntegerProperty()
name = db.StringProperty(indexed = False)
type.json_serialize = False
image.json_serialize = False
def json_serialize(self, data):
UserObject.json_serialize(self, data)
if self.type == 2:
data['type'] = 'outgoing'
elif self.type == 1:
data['type'] = 'incoming'
elif self.type == 3:
data['type'] = 'pending'
if self.image:
data['image'] = True
def json_deserialize(self, data):
type = data.get('type', None)
if type == 'incoming':
self.type = 1
elif type == 'outgoing':
self.type = 2
elif type == 'pending':
self.type = 3
elif type == None:
# HACK: I had a bug in the original client that never set
# a type on proxied/outgoing messages
self.type = 2
image = data.get('image', None)
if image:
self.image = base64.decodestring(image)
class OutboxSms(UserObject):
# need to ensure this is multiline
message = db.StringProperty(multiline = True, indexed = False)
date = db.IntegerProperty()
number = db.StringProperty(indexed = False)
class Call(UserObject):
#id = db.IntegerProperty()
number = db.StringProperty(indexed = False)
date = db.IntegerProperty()
duration = db.IntegerProperty(indexed = False)
type = db.IntegerProperty(indexed = False)
name = db.StringProperty(indexed = False)
type.json_serialize = False
def json_serialize(self, data):
UserObject.json_serialize(self, data)
if self.type == 2:
data['type'] = 'outgoing'
elif self.type == 1:
data['type'] = 'incoming'
elif self.type == 3:
data['type'] = 'missed'
def json_deserialize(self, data):
type = data.get('type', None)
if type == 'incoming':
self.type = 1
elif type == 'outgoing':
self.type = 2
elif type == 'missed':
self.type = 3
else:
# HACK: I had a bug in the original client that never set
# a type on proxied/outgoing messages
self.type = 2
class LoginHandler(APIHandler):
def get(self):
email = self.check_authorization(False)
continue_url = self.request.get('continue', '/')
continue_url = str(continue_url)
logging.info('continue')
logging.info(continue_url)
if email:
logging.info(email)
logging.info(email)
logging.info('redirecting')
self.redirect(continue_url)
return
logging.info(self.request.query)
self.redirect(users.create_login_url(self.request.path + '?continue=' + continue_url))
class LogoutHandler(APIHandler):
def get(self):
continue_url = self.request.get('continue', '/')
self.redirect(users.create_logout_url(continue_url))
class WhoamiHandler(APIHandler):
@staticmethod
def get_buyer_id(email):
return hashlib.sha256('asdkoiajsdoijasdojasdasdoijasod' + email).hexdigest()
def get(self):
email = self.check_authorization()
if not email:
self.dumps({'error': 'not logged in'})
return
key_string = 'Whoami/' + email
ret = memcache.get(key_string)
sandbox = SandboxHelper.is_sandbox(self)
if not ret or ret.get('version', None) != 4 or sandbox:
logging.info('grabbing fresh registration')
ret = {'email': email, 'buyer_id': WhoamiHandler.get_buyer_id(email) }
key = db.Key.from_path('User', email)
registration = db.get(key)
if registration is not None:
ret['subscription_expiration'] = registration.subscription_expiration
ret['registration_id'] = registration.registration_id
ret['version_code'] = registration.version_code
ret['version'] = 4
current_user = users.get_current_user()
if self.user:
ret['nickname'] = self.user.nickname()
if not sandbox:
memcache.set(key_string, ret)
#del ret['version']
self.dumps(ret)
class BadgeHandler(APIHandler):
def get(self):
email = self.check_authorization()
if email is None:
return
now = int(time.time() * 1000)
# if no start is provided, return a default and the current time
# do the same for an invalid after_date
after_date = self.get_request_int_argument('after_date')
if after_date is None or after_date > now:
self.dumps({'email': email, 'badge': 0, 'date': now})
return
# see if we have the last incoming sms is before the provided after_date
# and we can short circuit
cur_last_incoming_sms = memcache.get('LastIncomingSms/' + email)
if cur_last_incoming_sms is not None and cur_last_incoming_sms <= after_date:
logging.info('memcache hit')
self.dumps({'email': email, 'badge': 0, 'date': after_date, 'cur_last_incoming_sms': cur_last_incoming_sms})
return
logging.info('memcache miss')
data = db.GqlQuery("SELECT * FROM Sms WHERE email=:1 and date > :2 order by date ASC", email, after_date)
count = 0
data = list(data)
logging.info(data)
logging.info('count: ' + str(count))
last_incoming_sms = after_date
# we can count on this to be returned in ascending order
for sms in data:
# badge for incoming only
if sms.type == 1:
count = count + 1
last_incoming_sms = sms.date
logging.info(last_incoming_sms)
logging.info(cur_last_incoming_sms)
if last_incoming_sms > cur_last_incoming_sms:
logging.info('last_incoming_sms > cur_last_incoming_sms')
memcache.set('LastIncomingSms/' + email, last_incoming_sms)
else:
logging.info('last_incoming_sms < cur_last_incoming_sms')
self.dumps({'email': email, 'badge': count, 'date': now})
class DialHandler(APIHandler):
def get(self):
email = self.check_authorization()
if email is None:
return
number = self.request.get('number', None)
if number is None:
self.dumps({'error': 'no number provided'})
return
PushHelper.push(email, { 'type': 'dial', 'email': email, 'number': number })
self.dumps({'success': True})
class PhoneEventHandler(UserObjectHandler):
registration = None
expired = False
def where(self):
query = ''
values = ()
after_date = self.get_request_int_argument('after_date')
before_date = self.get_request_int_argument('before_date')
min_date = self.get_request_int_argument('min_date')
max_date = self.get_request_int_argument('max_date')
date = self.request.get('date', None)
if min_date is not None:
query += "AND date >= :%d " % (len(values) + 2)
values += min_date,
if max_date is not None:
query += "AND date <= :%d " % (len(values) + 2)
values += max_date,
if after_date is not None:
query += "AND date > :%d " % (len(values) + 2)
values += after_date,
if before_date is not None:
query += "AND date < :%d " % (len(values) + 2)
values += before_date,
return (query, values)
def should_put(self, email, envelope, put):
sync = envelope.get('sync', None)
if sync is None:
# if we do not have a forward_web property set, that's just weird.
# I just have this here, just in case, so shit works rather than doesn't work.
return self.registration.forward_web is None or self.registration.forward_web == True
else:
return sync
def should_process(self, email, envelope):
key = db.Key.from_path('User', email)
self.registration = db.get(key)
if self.registration is None:
logging.info('not registered')
self.dumps_raw({ 'error': 'not registered', 'registered': False })
return False
registration = self.registration
logging.info(registration.subscription_expiration)
logging.info(time.time() * 1000)
now = time.time() * 1000
# valid expiration time
if registration.subscription_expiration > now:
return True
# iOS users beta ends on ~feb 1, regardless if account was opened a while ago
if registration.registration_id.startswith("ios:"):
if registration.subscription_expiration < 1327109062435:
registration.subscription_expiration = 1327109062435
db.put(registration)
if registration.subscription_expiration < now - 2 * 7 * 24 * 60 * 60 * 1000:
self.dumps_raw({ 'error': 'expired' })
return False
# expired account, let's jack up the messages
self.expired = True
for event in envelope['data']:
type = event.get('type', None)
if not type:
logging.info('no type provided?')
logging.error(event)
continue
if type != self.get_notify_type() or event['number'] == 'DeskSMS' or not event.get('message', None):
continue
logging.info(event)
event['message'] = event['message'][0:10] + "... " + " Your DeskSMS trial has expired! Please upgrade from within the DeskSMS Android application or at the https://desksms.appspot.com website!"
return True
def order_by(self):
return "date ASC"
def on_put(self, email, envelope, put):
logging.info(email)
try:
version_code = envelope['version_code']
logging.info(version_code)
version_code = int(version_code)
except:
version_code = 0
# we should have already received this in should_put
registration = self.registration
dirty_registration = False;
if version_code != registration.version_code:
registration.version_code = version_code
dirty_registration = True
registration_id = envelope.get('registration_id', None)
if registration_id and registration.registration_id != registration_id:
registration.registration_id = registration_id
dirty_registration = True
if not registration.subscription_expiration:
registration.subscription_expiration = SubscriptionHelper.calculate_free_expiration_date(registration.registration_date)
dirty_registration = True
if dirty_registration:
db.put_async(registration)
initial_sync = envelope['is_initial_sync']
all_events = envelope['data']
# don't send notifications on initial sync or if there's just an odd number of messages.
if initial_sync or len(all_events) > 20:
logging.info('bailing out of push notifications:')
logging.info(len(all_events))
logging.info(initial_sync)
return
results = {}
return_envelope = { 'data': results }
# sort it into date increasing order before we send messages off.
all_events = sorted(all_events, key=lambda event: event['date'])
user_contacts_messages = {}
for event in all_events:
try:
type = event.get('type', None)
# only forward incoming messages
if type != self.get_notify_type():
continue
number = event['number']
date = event['date']
result = {'error': 'unknown error'}
results['%s/%s' % (number, date)] = result
message = event.get('message', None)
if not message:
logging.error('message is none on event:')
logging.error(event)
continue
subject = event['subject']
name = event.get('name', None)
has_desksms_contact = event.get('has_desksms_contact', False)
if number is None or len(number) == 0:
logging.error('no number provided')
result['error'] = 'no number provided'
continue
if message is None or len(message) == 0:
logging.error('no message provided')
result['error'] = 'no message provided'
continue
entered_number = event.get('entered_number', None)
# during incoming SMS, we need to resolve the number to an address
# that the user is accustomed to contacting.
# this is the number that they have entered into their phone, if it
# exists. so, for the cleaned_number, let's prefer entered_number
# if it exists.
# let's hope this doesn't result in collisions...
# now, when we send messages via chat and email,
# we provide the send helpers with the user provided number
# if it exists.
if entered_number:
logging.info('preferring user provided number: ' + entered_number)
if not NumberHelper.are_similar(entered_number, number):
logging.error('entered number is not similar to actual number?')
logging.info(entered_number)
logging.info(number)
preferred_number = number
entered_number = None
else:
preferred_number = entered_number
else:
preferred_number = number
cleaned_number = NumberHelper.clean(preferred_number)
# this cleaned number is then mapped to the actual number
# as it is pulled directly from the SMS provider.
key_string = email + '/' + cleaned_number
last_message = UserContactLastMessage()
last_message.last_message = message
last_message.last_message_name = name
# now that we have our "preferred" number, map it to the actual network number
last_message.last_message_number = number
user_contacts_messages[key_string] = last_message
del result['error']
# if we do not have a property set, that's just weird.
# I just have this None check here, just in case, so shit works rather than doesn't work.
if registration.forward_xmpp == True or registration.forward_xmpp is None or preferred_number == 'DeskSMS':
logging.info('xmpp')
try:
XMPPSendHelper.send(email, preferred_number, message, name, has_desksms_contact)
result['success_xmpp'] = True
except Exception, exception:
result['success_xmpp'] = False
logging.error('error during sending xmpp')
logging.error(email)
logging.error(number)
logging.error(message)
logging.error(name)
logging.error(exception)
logging.error(traceback.format_exc(exception))
logging.info('done xmpp')
if ((registration.forward_email == True or registration.forward_email is None) and not self.expired) or preferred_number == 'DeskSMS':
logging.info('mail')
try:
mail_message = """
%s
===========================
Please follow your response with two empty lines to ensure proper delivery!
Unsubsubscribe? Toggle the email setting in the DeskSMS application on your phone.
- DeskSMS
""" % (message)
MailSendHelper.send(email, preferred_number, mail_message, name, subject)
result['success_email'] = True
except Exception, exception:
result['success_email'] = False
logging.error('error during sending mail')
logging.error(email)
logging.error(number)
logging.error(message)
logging.error(name)
logging.error(exception)
logging.error(traceback.format_exc(exception))
logging.info('done mail')
except Exception, exception:
logging.error('error processing incoming message')
logging.error('email: ' + email)
logging.error(traceback.format_exc(exception))
# let's toss all these user contact messages into memcached
# for xmpp
if registration.forward_xmpp:
logging.info('putting memcached messages')
memcache.set_multi(user_contacts_messages, 300, 'UserContactLastMessage/')
logging.info('putting user contact number mappings')
user_contacts_to_put = []
for key_string in user_contacts_messages:
logging.info(key_string)
user_contact = UserContact(key_name = key_string)
last_sms = user_contacts_messages[key_string]
number = last_sms.last_message_number
user_contact.number = number
user_contacts_to_put.append(user_contact)
if len(user_contacts_to_put) > 0:
if len(user_contacts_to_put) > 50:
logging.error('large put?')
logging.info('putting user contacts: %s' % len(user_contacts_to_put))
db.put_async(user_contacts_to_put)
registrations = envelope.get('registrations', None)
if registrations:
url_parts = self.request.path.split('/')
bucket = url_parts[len(url_parts) - 1]
bucket = urllib.unquote(bucket)
del envelope['registrations']
envelope_data = simplejson.dumps(envelope)
if len(envelope_data) > 900:
envelope_data = {}
for device_registration in registrations:
try:
PushHelper.push(email, { 'bucket': bucket, 'type': 'refresh', 'email': email, 'envelope': envelope_data }, registration_id = device_registration)
except Exception, exception:
logging.error(traceback.format_exc(exception))
# now, finally let's push to the extensions
# should just always assume there is a push client available?
# using memcached seems scary as then what if it gets purged before the timeout?
if registration.forward_web != False:
#success_web = False
try:
buyer_id = WhoamiHandler.get_buyer_id(email)
logging.info('sending web push')
push_data = { "tickle": True, "envelope": envelope }
push_data = simplejson.dumps(push_data)
post_data = {
'registration_id': buyer_id,
'data': push_data
}
post_data = urllib.urlencode(post_data)
logging.info(post_data)
rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, 'http://n1.clockworkmod.com:9981/event', post_data, "POST")
except Exception, exception:
logging.error(traceback.format_exc(exception))
#return_envelope['success_web'] = success_web
else:
logging.info('web push disabled')
return return_envelope
class CallHandler(PhoneEventHandler):
def get_object_type(self):
return Call
def new(self, email, data):
return Call(key_name = '%s/%s/%d' % (email, data['number'], data['date']))
def get_notify_type(self):
return 'missed'
class SmsHandler(PhoneEventHandler):
def get_object_type(self):
return Sms
@staticmethod
def newSms(email, number, date):
return Sms(key_name = '%s/%s/%d' % (email, number, date))
def new(self, email, data):
return SmsHandler.newSms(email, data['number'], data['date'])
def get_notify_type(self):
return 'incoming'
def query(self, email):
# see if we can optimize out this after_date query with memcache
after_date = self.get_request_int_argument('after_date')
before_date = self.get_request_int_argument('before_date')
max_date = self.get_request_int_argument('max_date')
if after_date is None or before_date is not None or max_date is not None:
return PhoneEventHandler.query(self, email)
# see if the last incoming sms is before the provided after_date
# and we can short circuit
cur_last_incoming_sms = memcache.get('LastIncomingSms/' + email)
if cur_last_incoming_sms is not None and cur_last_incoming_sms <= after_date:
logging.info('memcache hit')
logging.info(cur_last_incoming_sms)
return []
ret = PhoneEventHandler.query(self, email)
last_incoming_sms = after_date
# we can count on this to be returned in ascending order
for sms in ret:
# we use all sms, because we want outbox updates to be retrievable
# as well
last_incoming_sms = sms.date
if last_incoming_sms > cur_last_incoming_sms:
memcache.set('LastIncomingSms/' + email, last_incoming_sms)
else:
logging.info('last_incoming_sms < cur_last_incoming_sms')
logging.info(last_incoming_sms)
logging.info(cur_last_incoming_sms)
return ret
def on_put(self, email, envelope, put):
logging.info('clearing memcache')
memcache.delete('LastIncomingSms/' + email, 10)
return PhoneEventHandler.on_put(self, email, envelope, put)
class OutboxHandler(UserObjectHandler):
def where(self):
query = ''
values = ()
min_date = self.get_request_int_argument('min_date')
max_date = self.get_request_int_argument('max_date')
number = self.request.get('number', None)
if min_date is not None:
query += "AND date >= :%d " % (len(values) + 2)
values += min_date,
if max_date is not None:
query += "AND date <= :%d " % (len(values) + 2)
values += max_date,
if number is not None:
query += "AND number = :%d " % (len(values) + 2)
values += number,
return (query, values)
@staticmethod
def push_pending_outbox(email, for_sms = []):
key = db.Key.from_path('User', email)
registration = db.get(key)
if registration is None:
return (False, None)
data = db.GqlQuery("SELECT * FROM OutboxSms WHERE email=:1 ORDER BY date ASC", email)
#data = list(data)
# what happens when the message queue gets enormous cause the phone is off or something?
# there seems to be an eventual consistency issue here.
# doing a read then a write for the same element seems to fail and return nothing.
# This results in an empty push.
found_sms = {}
outbox = []
for outgoing_sms in data:
outbox_sms = {'number': outgoing_sms.number, 'message': outgoing_sms.message, 'date': outgoing_sms.date}
outbox.append(outbox_sms)
found_sms[outgoing_sms.key().name()] = outgoing_sms
for sms in for_sms:
if not found_sms.get(sms.key().name(), None):
outbox_sms = {'number': sms.number, 'message': sms.message, 'date': sms.date}
logging.info('fixed eventual consistency problem')
logging.info(sms.key().name())
outbox.append(outbox_sms)
# c2dm can not handle structured data, so json string it.
data = simplejson.dumps(outbox)
logging.info(data)
if len(data) > 900 or registration.registration_id.startswith('ios:'):
# if the data is too long (1024 max), ask the client to poll by not sending outbox data
return PushHelper.push(email, { 'type': 'outbox', 'email': email }, registration = registration)
else:
return PushHelper.push(email, { 'outbox': data, 'type': 'outbox', 'email': email }, registration = registration)
def should_put(self, email, envelope, put):
put_copy = list(put)
# also store the messages in the sms bucket as pending
for d in put_copy:
try:
o = SmsHandler.newSms(email, d.number, d.date)
o.message = d.message
o.email = email
o.type = 3
o.date = d.date
o.number = d.number
put.append(o)
except Exception, exception:
logging.error(exception)
logging.error(traceback.format_exc(exception))
return True
def on_put(self, email, envelope, put):
outgoing = [o for o in put if isinstance(o, OutboxSms)]
push_result = OutboxHandler.push_pending_outbox(email, outgoing)
ret = {}
if push_result[0]:
ret['success'] = True
else:
ret['error'] = push_result[1]
data = []
for sms in outgoing:
data.append(sms.date)
ret['data'] = data
return ret;
def get_object_type(self):
return OutboxSms
@staticmethod
def newOutboxSms(email, number):
date = int(time.time() * 1000)
return OutboxSms(key_name = '%s/%s/%d' % (email, number, date), date = date, email = email)
def new(self, email, data):
return OutboxHandler.newOutboxSms(email, data['number'])
def order_by(self):
return "date ASC"
class PushHelper(object):
google_auth = None
@staticmethod
def retrieveGoogleAuth():
if PushHelper.google_auth is not None:
return PushHelper.google_auth
url = "https://www.google.com/accounts/ClientLogin"
data = {
"accountType": "HOSTED_OR_GOOGLE",
"Email": "____YOUR_EMAIL____",
"Passwd": "____YOUR_PASSWORD____",
"source": "koush-desktopsms",
"service": "ac2dm"
}
data = urllib.urlencode(data)
f = urllib2.urlopen(url, data)
lines = f.read()
lines = lines.split('\n')
for line in lines:
if line.startswith('Auth'):
parts = line.split('=')
PushHelper.google_auth = parts[1]
return PushHelper.google_auth
return None
push_results = {
'QuotaExceeded': 'DeskSMS quota exceeded. Please try again later.',
'DeviceQuotaExceeded': 'Your push notification quota has been exceeded.',
'InvalidRegistration': 'Your device could not be contacted. Please try relogging into the DeskSMS Android application.',
'NotRegistered': 'Your device could not be contacted. Please try relogging into the DeskSMS Android application.',
'MessageTooBig': 'Your message was too long.',
'MissingCollapseKey': 'DeskSMS server error (collapse key).'
}
@staticmethod
def push(email_or_resource, data, collapse_key = None, registration = None, async = False, registration_id = None):
email = email_or_resource.split('/')[0].lower()
logging.info('attempting to push to %s' % (email))
if registration_id is None:
if registration is None:
key = db.Key.from_path('User', email)
registration = db.get(key)
if registration is None:
raise Exception('registration is unavailable')
registration_id = registration.registration_id
if registration_id.startswith("ios"):
parts = registration_id.split(':')
client = parts[1]
url = 'http://n1.clockworkmod.com:9981/apn/' + urllib.quote(client)
post_data = {
'data': urllib.urlencode(data)
}
post_data = urllib.urlencode(post_data)
logging.info(post_data)
if not async:
logging.info('sync request')
try:
try:
req = urllib2.Request(url)
f = urllib2.urlopen(req, post_data)
ret = f.read()
logging.info(ret)
data = simplejson.loads(ret)
if data.get('error', None):
return (False, data.get('error', None))
return (True, None)
except urllib2.HTTPError, error:
ret = error.read()
logging.info(ret)
data = simplejson.loads(ret)
return (False, data.get('response_message', 'Unknown HTTP error.'))
except Exception, exception:
logging.error(exception)
logging.error(traceback.format_exc(exception))
return (False, 'Parse error.')
else:
# this currently has no error handling, so always do it async
logging.info('async request')
rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, url, post_data, "POST")
return (True, 'success')
elif registration_id.startswith('gcm:'):
parts = registration_id.split(':')
registration_id = parts[1]
if collapse_key is None:
collapse_key = str(int(time.time()))
url = "https://android.googleapis.com/gcm/send"
post_data = {
'collapse_key': collapse_key,
'registration_ids': [ registration_id ]
}
post_data['data'] = data
post_data = simplejson.dumps(post_data)
logging.info(post_data)
if not async:
logging.info('sync request')
req = urllib2.Request(url)
req.add_header('Authorization', 'key=____YOUR___AUTH_____')
req.add_header('Content-Type', 'application/json')
try:
try:
f = urllib2.urlopen(req, post_data)
result = f.read()
except urllib2.HTTPError, error:
result = error.read()
logging.info('push result: ' + result)
json_result = simplejson.loads(result)
return (json_result.get('success', 0) == 1, result)
except Exception, exception:
logging.error(exception)
logging.error(traceback.format_exc(exception))
PushHelper.google_auth = None
return (False, 'Push service error.')
else:
headers = {
'Authorization': 'key=____YOUR___AUTH_____',
'Content-Type': 'application/json'
}
logging.info('async request')
rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, url, post_data, "POST", headers)
return rpc
else:
auth = PushHelper.retrieveGoogleAuth()
auth_header = 'GoogleLogin auth=' + auth
if auth is None:
raise Exception('google_auth is unavailable')
if collapse_key is None:
collapse_key = str(int(time.time()))
url = "http://android.apis.google.com/c2dm/send"
post_data = {
'collapse_key': collapse_key,
'registration_id': registration_id
}
headers = {
'Authorization': 'GoogleLogin auth=' + auth
}
for d in data:
post_data['data.%s' % (d)] = str(data[d]).encode('utf-8')
post_data = urllib.urlencode(post_data)
logging.info(post_data)
if not async:
logging.info('sync request')
req = urllib2.Request(url)
req.add_header('Authorization', auth_header)
try:
try:
f = urllib2.urlopen(req, post_data)
result = f.read()
except urllib2.HTTPError, error:
result = error.read()
logging.info('push result: ' + result)
pairs = result.split('=')
if pairs[0] == "id":
return (True, pairs[1])
push_error = PushHelper.push_results.get(pairs[1])
if not push_error:
push_error = "DeskSMS Server error."
logging.error(push_error)
return (False, push_error)
except Exception, exception:
logging.error(exception)
logging.error(traceback.format_exc(exception))
PushHelper.google_auth = None
return (False, 'Push service error.')
else:
logging.info('async request')
rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, url, post_data, "POST", { 'Authorization': auth_header })
return rpc
class ChatHandler(webapp2.RequestHandler):
def handle(self):
sender = self.request.get('from')
to = self.request.get('to')
body = self.request.get('body')
logging.info(sender)
body = body.strip()
if len(body) == 0:
logging.info('empty body')
return
try:
email = sender.split('/')[0].lower()
key = db.Key.from_path('User', email)
registration = db.get(key)
if registration is None:
logging.error('registration is unavailable')
return
logging.info('chat message from %s to %s: %s' % (sender, to, body))
cleaned_number = to.split('@')[0]
key = db.Key.from_path('UserContact', email + '/' + cleaned_number)
user_contact = db.get(key)
if user_contact and user_contact.number and len(user_contact.number) > 0:
if not NumberHelper.are_similar(cleaned_number, user_contact.number):
logging.error('chat: entered number is not similar to actual number?')
logging.info(user_contact.number)
logging.info(cleaned_number)
number = cleaned_number
user_contact.number = None
db.put_async(user_contact)
else:
number = user_contact.number
else: