-
Notifications
You must be signed in to change notification settings - Fork 1
/
snapchat.py
executable file
·505 lines (374 loc) · 14 KB
/
snapchat.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
import requests
import hashlib
import json
import time
from datetime import datetime
from Crypto.Cipher import AES
if False:
import logging
import httplib
httplib.HTTPConnection.debuglevel = 1
class Snapchat:
URL = 'https://feelinsonice-hrd.appspot.com/bq'
SECRET = 'iEk21fuwZApXlz93750dmW22pw389dPwOk' # API Secret
STATIC_TOKEN = 'm198sOkJEn37DjqZ32lpRu76xmw288xSQ9' # API Static Token
BLOB_ENCRYPTION_KEY = 'M02cnQ51Ji97vwT4' # Blob Encryption Key
HASH_PATTERN = '0001110111101110001111010101111011010001001110011000110001000110'; # Hash pattern
USERAGENT = 'Snapchat/6.0.0 (iPhone; iOS 7.0.2; gzip)' # The default useragent
SNAPCHAT_VERSION = '4.0.0' # Snapchat Application Version
MEDIA_IMAGE = 0 # Media: Image
MEDIA_VIDEO = 1 # Media: Video
MEDIA_VIDEO_NOAUDIO = 2 # Media: Video without audio
MEDIA_FRIEND_REQUEST = 3 # Media: Friend Request
MEDIA_FRIEND_REQUEST_IMAGE = 4 # Media: Image from unconfirmed friend
MEDIA_FRIEND_REQUEST_VIDEO = 5 # Media: Video from unconfirmed friend
MEDIA_FRIEND_REQUEST_VIDEO_NOAUDIO = 6 # Media: Video without audio from unconfirmed friend
STATUS_NONE = -1 # Snap status: None
STATUS_SENT = 0 # Snap status: Sent
STATUS_DELIVERED = 1 # Snap status: Delivered
STATUS_OPENED = 2 # Snap status: Opened
STATUS_SCREENSHOT = 3 # Snap status: Screenshot
FRIEND_CONFIRMED = 0 # Friend status: Confirmed
FRIEND_UNCONFIRMED = 1 # Friend status: Unconfirmed
FRIEND_BLOCKED = 2 # Friend status: Blocked
FRIEND_DELETED = 3 # Friend status: Deleted
PRIVACY_EVERYONE = 0 # Privacy setting: Accept snaps from everyone
PRIVACY_FRIENDS = 1 # Privacy setting: Accept snaps only from friends
def __init__(self, username=None, password=None):
self.username = None
self.auth_token = None
self.logged_in = False
self.cipher = AES.new(Snapchat.BLOB_ENCRYPTION_KEY, AES.MODE_ECB)
if username and password:
self.login(username, password)
def _pad(self, data, blocksize=16):
"""Pads data using PKCS5."""
pad = blocksize - (len(data) % blocksize)
return data + chr(pad) * pad
def _hash(self, first, second):
"""Implementation of Snapchat's weird hashing function."""
# Append the secret key to the values.
first = Snapchat.SECRET + str(first)
second = str(second) + Snapchat.SECRET
# Hash the values.
hash1 = hashlib.sha256(first).hexdigest()
hash2 = hashlib.sha256(second).hexdigest()
# Create the final hash by combining the two we just made.
result = ''
for pos, included in enumerate(Snapchat.HASH_PATTERN):
if included == '0':
result += hash1[pos]
else:
result += hash2[pos]
return result
def _timestamp(self):
"""Generates a timestamp in microseconds."""
return int(time.time() * 1000)
def _encrypt(self, data):
"""Encrypt the blob."""
data = self._pad(data)
return self.cipher.encrypt(data)
def _decrypt(self, data):
"""Decrypt the blob."""
data = self._pad(data)
return self.cipher.decrypt(data)
def _parse_field(self, dictionary, key, bool=False):
"""Correctly parse a field from a dictionary object.
Takes care of missing keys, and empty fields.
:param dictionary: The dictionary.
:param key: The key for the dictionary.
:param bool: Whether or not the value should be a boolean"""
if key not in dictionary:
if bool:
return False
return None
value = dictionary[key]
if not value:
if bool:
return False
return None
return value
def _parse_datetime(self, dt):
"""Gracefully concert and parse a text timestamp in microseconds."""
try:
return datetime.fromtimestamp(dt / 1000)
except:
return dt
def is_media(self, data):
"""Check if the blob is a valid media type."""
# Check for JPG header.
if data[0] == chr(0xff) and data[1] == chr(0xd8):
return 'jpg'
# Check for MP4 header.
if data[0] == chr(0x00) and data[1] == chr(0x00):
return 'mp4'
return False
def post(self, endpoint, data, params, file=None):
"""Submit a post request to the Snapchat API.
:param endpoint: The service to submit the request to, i.e. '/upload'.
:param data: The data to upload.
:param params: Request specific authentication, typically a tuple of form (KEY, TIME).
:param file: Optional field for submitting file content in multipart messages.
"""
data['req_token'] = self._hash(params[0], params[1])
data['version'] = Snapchat.SNAPCHAT_VERSION
headers = {
'User-Agent': Snapchat.USERAGENT
}
url = Snapchat.URL + endpoint
if file:
r = requests.post(url, data, headers=headers, files={'data': file})
else:
r = requests.post(url, data, headers=headers)
# If the status code isn't 200, it's a failed request.
if r.status_code != 200:
if False:
print 'Post returned code: ', r.status_code, 'for request', endpoint, data
print 'Error content:'
print r.content
return False
# If possible, try to return a json object.
try:
return json.loads(r.content)
except:
return r.content
def login(self, username, password):
"""Login to Snapchat."""
timestamp = self._timestamp()
data = {
'username': username,
'password': password,
'timestamp': timestamp
}
params = [
Snapchat.STATIC_TOKEN,
timestamp
]
result = self.post('/login', data, params)
if 'auth_token' in result:
self.auth_token = result['auth_token']
if 'username' in result:
self.username = result['username']
if self.auth_token and self.username:
self.logged_in = True
return result
def logout(self):
"""Logout of Snapchat."""
if not self.logged_in:
return False
timestamp = self._timestamp()
data = {
'username': username,
'timestamp': timestamp
}
params = [
self.auth_token,
timestamp
]
result = self.post('/logout', data, params)
if not result:
self.logged_in = False
return True
return False
def register(self, username, password, email, birthday):
"""Registers a new username for the Snapchat service.
:param username: The username of the new user.
:param password: The password of the new user.
:param email: The email of the new user.
:param birthday: The birthday of the new user (yyyy-mm-dd).
"""
timestamp = self._timestamp()
data = {
'birthday': birthday,
'password': password,
'email': email,
'timestamp': timestamp
}
params = [
Snapchat.STATIC_TOKEN,
timestamp
]
# Perform email/password registration.
result = self.post('/register', data, params)
timestamp = self._timestamp()
if 'token' not in result:
return False
data = {
'email': email,
'username': username,
'timestamp': timestamp
}
params = [
Snapchat.STATIC_TOKEN,
timestamp
]
# Perform username registration.
result = self.post('/registeru', data, params)
# Store the authentication token if the server sent one.
if 'auth_token' in result:
self.auth_token = result['auth_token']
# Store the username if the server sent it.
if 'username' in result:
self.username = result['username']
return result
def upload(self, type, filename):
"""Upload a video or image to Snapchat.
You must call send() after uploading the image for someone the receive it.
:param type: The type of content being uploaded, i.e. Snapchat.MEDIA_VIDEO.
:param filename: The filename of the content.
:returns: The media_id of the file if successful.
"""
if not self.logged_in:
return False
timestamp = self._timestamp()
# TODO: media_ids are GUIDs now.
media_id = self.username.upper() + '~' + str(timestamp)
data = {
'media_id': media_id,
'type': type,
'timestamp': timestamp,
'username': self.username
}
params = [
self.auth_token,
timestamp
]
# Read the file and encrypt it.
with open(filename, 'rb') as fin:
encrypted_data = self._encrypt(fin.read())
result = self.post('/upload', data, params, encrypted_data)
if result:
return False
return media_id
def send(self, media_id, recipients, time=10):
"""Send a Snapchat.
You must have uploaded the video or image using upload() to get the media_id.
:param media_id: The unique id for the media.
:param recipients: A list of usernames to send the Snap to.
:param time: Viewing time for the Snap (in seconds).
"""
if not self.logged_in:
return False
# If we only have one recipient, convert it to a list.
if not isinstance(recipients, list):
recipients = [recipients]
timestamp = self._timestamp()
data = {
'media_id': media_id,
'recipient': ','.join(recipients),
'time': time,
'timestamp': timestamp,
'username': self.username
}
params = [
self.auth_token,
timestamp
]
result = self.post('/send', data, params)
return result <> False
def get_updates(self):
"""Get all events pertaining to the user. (User, Snaps, Friends)."""
if not self.logged_in:
return False
timestamp = self._timestamp()
data = {
'timestamp': timestamp,
'username': self.username
}
params = [
self.auth_token,
timestamp
]
result = self.post('/all_updates', data, params)
return result
def get_snaps(self):
"""Get all snaps for the user."""
updates = self.get_updates()
if not updates:
return False
snaps = updates['updates_response']['snaps']
result = []
print self._timestamp()
for snap in snaps:
# Make the fields more readable.
snap_readable = {
'id': self._parse_field(snap, 'id'),
'media_id': self._parse_field(snap, 'c_id'),
'media_type': self._parse_field(snap, 'm'),
'time': self._parse_field(snap, 't'),
'sender': self._parse_field(snap, 'sn'),
'recipient': self._parse_field(snap, 'rp'),
'status': self._parse_field(snap, 'st'),
'screenshot_count': self._parse_field(snap, 'c'),
'sent': self._parse_datetime(snap['sts']),
'opened': self._parse_datetime(snap['ts'])
}
result.append(snap_readable)
return result
def get_media(self, id):
"""Download a snap.
:param id: The unique id of the snap (NOT media_id).
:returns: The media in a byte string.
"""
if not self.logged_in:
return False
timestamp = self._timestamp()
data = {
'id': id,
'timestamp': timestamp,
'username': self.username
}
params = [
self.auth_token,
timestamp
]
result = self.post('/blob', data, params)
if not result:
return False
if self.is_media(result):
return result
result = self._decrypt(result)
if self.is_media(result):
return result
return False
def find_friends(self, numbers, country='US'):
"""Finds friends based on phone numbers.
:param numbers: A list of phone numbers.
:param country: The country code (US is default).
:returns: List of user objects found.
"""
if not self.logged_in:
return False
timestamp = self._timestamp()
data = {
'countryCode': country,
'numbers': json.dumps(numbers),
'timestamp': timestamp,
'username': self.username
}
params = [
self.auth_token,
timestamp
]
result = self.post('/find_friends', data, params)
print result
if 'results' in result:
return result['results']
return result
def clear_feed(self):
"""Clear the user's feed."""
if not self.logged_in:
return False
timestamp = self._timestamp()
data = {
'timestamp': timestamp,
'username': self.username
}
params = [
self.auth_token,
timestamp
]
result = self.post('/clear', data, params)
if not result:
return True
return False