-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathmain0.py
1931 lines (1643 loc) · 86.5 KB
/
main0.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
# -*- coding: utf-8-*-
import requests
import re
import json
import argparse
import POGOProtos
import POGOProtos.Enums_pb2
import POGOProtos.Networking
import POGOProtos.Networking.Envelopes_pb2
import POGOProtos.Networking.Responses_pb2
import POGOProtos.Networking.Requests
import POGOProtos.Networking.Requests.Messages_pb2
import POGOProtos.Map
import POGOProtos.Map.Pokemon_pb2
import POGOProtos.Data_pb2
import POGOProtos.Networking.Platform_pb2
import POGOProtos.Networking.Platform
import POGOProtos.Networking.Platform.Requests_pb2
import time
from datetime import datetime
import sys
import codecs
import math
import os
import random
import platform
import sqlite3
import pushbullet
from pushbullet import Pushbullet
import telepot
from geopy.geocoders import Nominatim
from s2sphere import CellId, LatLng, Cell
from gpsoauth import perform_master_login, perform_oauth
from shutil import move
from operator import itemgetter
from res.uk6 import generateLocation1, generateLocation2, generateRequestHash, generate_signature
import res.maplib as mapl
import ctypes
import threading
import Queue
import signal
def signal_handler(signal, frame):
sys.exit()
signal.signal(signal.SIGINT, signal_handler)
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
def format_address(input, fieldnum):
fields = input.split(', ')
output = fields[0]
for f in range(1,min(fieldnum,len(fields))):
output += ', ' + fields[f]
return output
def get_time():
return int(round(time.time() * 1000))
def getNeighbors(location):
level = 15
origin = CellId.from_lat_lng(LatLng.from_degrees(location[0], location[1])).parent(level)
max_size = 1 << 30
size = origin.get_size_ij(level)
face, i, j = origin.to_face_ij_orientation()[0:3]
walk = [origin.id(),
origin.from_face_ij_same(face, i, j - size, j - size >= 0).parent(level).id(),
origin.from_face_ij_same(face, i, j + size, j + size < max_size).parent(level).id(),
origin.from_face_ij_same(face, i - size, j, i - size >= 0).parent(level).id(),
origin.from_face_ij_same(face, i + size, j, i + size < max_size).parent(level).id(),
origin.from_face_ij_same(face, i - size, j - size, j - size >= 0 and i - size >= 0).parent(level).id(),
origin.from_face_ij_same(face, i + size, j - size, j - size >= 0 and i + size < max_size).parent(level).id(),
origin.from_face_ij_same(face, i - size, j + size, j + size < max_size and i - size >= 0).parent(level).id(),
origin.from_face_ij_same(face, i + size, j + size, j + size < max_size and i + size < max_size).parent(level).id()]
#origin.from_face_ij_same(face, i, j - 2*size, j - 2*size >= 0).parent(level).id(),
#origin.from_face_ij_same(face, i - size, j - 2*size, j - 2*size >= 0 and i - size >=0).parent(level).id(),
#origin.from_face_ij_same(face, i + size, j - 2*size, j - 2*size >= 0 and i + size < max_size).parent(level).id(),
#origin.from_face_ij_same(face, i, j + 2*size, j + 2*size < max_size).parent(level).id(),
#origin.from_face_ij_same(face, i - size, j + 2*size, j + 2*size < max_size and i - size >=0).parent(level).id(),
#origin.from_face_ij_same(face, i + size, j + 2*size, j + 2*size < max_size and i + size < max_size).parent(level).id(),
#origin.from_face_ij_same(face, i + 2*size, j, i + 2*size < max_size).parent(level).id(),
#origin.from_face_ij_same(face, i + 2*size, j - size, j - size >= 0 and i + 2*size < max_size).parent(level).id(),
#origin.from_face_ij_same(face, i + 2*size, j + size, j + size < max_size and i + 2*size < max_size).parent(level).id(),
#origin.from_face_ij_same(face, i - 2*size, j, i - 2*size >= 0).parent(level).id(),
#origin.from_face_ij_same(face, i - 2*size, j - size, j - size >= 0 and i - 2*size >=0).parent(level).id(),
#origin.from_face_ij_same(face, i - 2*size, j + size, j + size < max_size and i - 2*size >=0).parent(level).id()]
return walk
API_URL = 'https://pgorelease.nianticlabs.com/plfe/rpc'
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
random.seed()
#constant
time_1q = 900000
time_4q = 4 * time_1q
EARTH_Rmax = 6378137.0
EARTH_Rmin = 6356752.3
EARTH_Rrect = 6367000.0
Rsight = 70.0
#instance constants
num_cells = 9
time_hb = 10
time_socks5_retry = None
accuracy = random.random()*7+3
geolocator = Nominatim()
percinterval = 2
login_simu = True
threadnum = None
signature_lib = None
lock_network = threading.Lock()
lock_banfile = threading.Lock()
lock_capfile = threading.Lock()
lock_capinput = threading.Lock()
workdir = os.path.dirname(os.path.realpath(__file__))
fpath_settings = '{}/res/usersettings.json'.format(workdir)
fpath_data = '{}/webres/data.db'.format(workdir)
fpath_accs = '{}/res/accs.db'.format(workdir)
db_data = None
db_accs = None
#constants from settings
exclude_ids = None
pb = []
telegrams = []
telebot = None
PUSHPOKS = []
add_location_name = False
acc_tos = False
F_LIMIT = None
language = None
lang_code = None
wID = None
verbose = False
usespiral = False
mode_plan = False
dumb = False
locktime = None
scanrange = None
scaninterval = None
#application internal, don't need cleanup
safetysecs = 3
safetysecs_auto = True
num_hookers = None
synch_li = None
tries = 1
fname_spawnfile = None
silent = False
scannum = None
fpath_dir_plan = None
fpath_plan = None
location_str = None
learning = False
pres_curR = None
pres_runs = 0
pres_countmax = 0
pres_countall = 0
pres_empty = 0
scan_compromised = False
data_buffer = []
addlocation = None
smartscan = False
# need cleanup
LAT_C, LNG_C= [None, None]
all_loc = []
empty_loc = []
all_scans = []
scandata = {}
def get_encryption_lib_path():
# win32 doesn't mean necessarily 32 bits
if sys.platform == "win32" or sys.platform == "cygwin":
if platform.architecture()[0] == '64bit':
lib_name = "encrypt64bit.dll"
else:
lib_name = "encrypt32bit.dll"
elif sys.platform == "darwin":
lib_name = "libencrypt-osx-64.so"
elif os.uname()[4].startswith("arm") and platform.architecture()[0] == '32bit':
lib_name = "libencrypt-linux-arm-32.so"
elif os.uname()[4].startswith("aarch64") and platform.architecture()[0] == '64bit':
lib_name = "libencrypt-linux-arm-64.so"
elif sys.platform.startswith('linux'):
if "centos" in platform.platform():
if platform.architecture()[0] == '64bit':
lib_name = "libencrypt-centos-x86-64.so"
else:
lib_name = "libencrypt-linux-x86-32.so"
else:
if platform.architecture()[0] == '64bit':
lib_name = "libencrypt-linux-x86-64.so"
else:
lib_name = "libencrypt-linux-x86-32.so"
elif sys.platform.startswith('freebsd'):
lib_name = "libencrypt-freebsd-64.so"
elif sys.platform.startswith('sunos5'):
lib_name = "libencrypt-sunos5-x86-64.so"
else:
err = "Unexpected/unsupported platform '{}'.".format(sys.platform)
lprint(err)
raise Exception(err)
lib_path = os.path.join(os.path.dirname(__file__), "res", "libencrypt", lib_name)
if not os.path.isfile(lib_path):
err = "Could not find {} encryption library {}".format(sys.platform, lib_path)
lprint(err)
raise Exception(err)
return lib_path
def do_settings():
global language, LAT_C, LNG_C, scanrange, scaninterval, F_LIMIT, pb, PUSHPOKS, scannum, wID, acc_tos, exclude_ids, telebot,add_location_name
global time_socks5_retry,verbose,dumb,mode_plan,signature_lib,locktime,fname_spawnfile,threadnum,fpath_dir_plan,num_hookers,usespiral,hookurls,lang_code
signature_lib = ctypes.cdll.LoadLibrary(get_encryption_lib_path())
signature_lib.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_ubyte), ctypes.POINTER(ctypes.c_size_t)]
signature_lib.restype = ctypes.c_int
parser = argparse.ArgumentParser()
parser.add_argument('-id', '--id', help='group id')
parser.add_argument('-r', '--range_scan', help='scan range')
parser.add_argument('-hx', '--hex_spiral', help='use the old hex spiral pattern', action='store_true')
parser.add_argument('-t', '--time_scan', help='scan interval')
parser.add_argument('-lat', '--latitude', help='latitude')
parser.add_argument('-lng', '--longitude', help='longitude')
parser.add_argument('-loc', '--location', help='location')
parser.add_argument('-s', '--scannum', help='number of scans to run')
parser.add_argument('-tos', '--tosaccept', help='let accounts accept tos at start', action='store_true')
parser.add_argument('-v', '--verbose', help='makes it put out all found pokemon all the time', action='store_true')
parser.add_argument('-d','--dumb', help='disables smartscan', action='store_true')
parser.add_argument('-p', '--plan', help='load scan plans from planning folder', action='store_true')
args = parser.parse_args()
wID = args.id
scanrange = args.range_scan
scaninterval = args.time_scan
LAT_C = args.latitude
LNG_C = args.longitude
if args.location is not None:
url = 'https://maps.googleapis.com/maps/api/geocode/json'
params = {'sensor': 'false', 'address': args.location}
r = requests.get(url, params=params)
if r.status_code == 200:
spot = r.json()['results'][0]['geometry']['location']
LAT_C, LNG_C = [spot['lat'], spot['lng']]
else:
lprint('[-] Error: The coordinates for the specified location couldn\'t be retrieved, http code: {}'.format(r.status_code))
lprint('[-] The location parameter will be ignored.')
if args.tosaccept:
acc_tos = True
if args.verbose:
verbose = True
if args.dumb:
dumb = True
if wID is None:
wID = 0
else:
wID = int(wID)
if args.scannum is None:
scannum = 0
else:
scannum = int(args.scans)
if args.hex_spiral:
usespiral = True
if args.plan:
dumb = False
scannum = 0
mode_plan = True
fpath_dir_plan = '{}/res/learning/learn_plans/id{}'.format(workdir,wID)
try:
f = open(fpath_settings, 'r')
try:
allsettings = json.load(f)
except ValueError as e:
lprint('[-] Error: The settings file is not in a valid format, {}'.format(e))
f.close()
sys.exit()
finally:
if 'f' in vars() and not f.closed:
f.close()
time_socks5_retry = allsettings['time_socks5_retry']
hookurls = allsettings['urls_webhook']
F_LIMIT = int(allsettings['backup_size'] * 1024 * 1024)
if F_LIMIT == 0:
F_LIMIT = 9223372036854775807
if allsettings['notifications']['enabled']:
PUSHPOKS = set(allsettings['notifications']['push_ids'])
if allsettings['notifications']['add_location_name']:
add_location_name = True
if allsettings['notifications']['pushbullet']['enabled']:
for key in allsettings['notifications']['pushbullet']['api_key']:
try:
this_pb = Pushbullet(key)
if allsettings['notifications']['pushbullet']['use_channels']:
for channel in this_pb.channels:
if channel.channel_tag in allsettings['notifications']['pushbullet']['channel_tags']:
pb.append(channel)
else:
pb.append(this_pb)
except Exception as e:
lprint('[-] Pushbullet error, key {} is invalid, {}'.format(key, e))
lprint('[-] This pushbullet will be disabled.')
if allsettings['notifications']['telegram']['enabled']:
telebot = telepot.Bot(str(allsettings['notifications']['telegram']['bot_token']))
for chat_id in allsettings['notifications']['telegram']['chat_ids']:
telegrams.append(chat_id)
if (len(telegrams) + len(pb)) == 0:
PUSHPOKS = []
language = allsettings['language']
if language == 'german':
lang_code = 'de'
elif language == 'spanish':
lang_code = 'es'
elif language == 'zh-HK':
lang_code = 'zh-HK'
else:
lang_code = 'en'
exclude_ids = set(allsettings['exclude_ids'])
if scanrange is None:
scanrange = allsettings['range']
else:
scanrange = int(scanrange)
if scaninterval is None:
scaninterval = allsettings['scaninterval']
else:
scaninterval = int(scaninterval)
# ////////////////////////
idlist = []
for i in range(0, len(allsettings['profiles'])):
if allsettings['profiles'][i]['id'] == wID:
idlist.append(i)
accounts = []
if len(idlist) > 0:
if 'learn_file' in allsettings['profiles'][idlist[0]] and allsettings['profiles'][idlist[0]]['learn_file'] and not dumb:
fname_spawnfile = allsettings['profiles'][idlist[0]]['learn_file']
proxies = None
if 'proxy' in allsettings['profiles'][idlist[0]] and allsettings['profiles'][idlist[0]]['proxy']:
proxies = {'http': allsettings['profiles'][idlist[0]]['proxy'], 'https': allsettings['profiles'][idlist[0]]['proxy']}
lprint('[+] Using group proxy: {}'.format(allsettings['profiles'][idlist[0]]['proxy']))
for i in range(0, len(idlist)):
account = {'num': i, 'type': allsettings['profiles'][idlist[i]]['type'], 'user': allsettings['profiles'][idlist[i]]['username'], 'pw': allsettings['profiles'][idlist[i]]['password']}
if i > 0 and 'proxy' in allsettings['profiles'][idlist[i]] and allsettings['profiles'][idlist[i]]['proxy']:
account['proxy']={'http': allsettings['profiles'][idlist[i]]['proxy'], 'https': allsettings['profiles'][idlist[i]]['proxy']}
lprint('[{}] Using individual proxy: {}'.format(i,allsettings['profiles'][idlist[i]]['proxy']))
elif not proxies is None:
account['proxy'] = proxies
else:
account['proxy'] = None
accounts.append(account)
else:
lprint('[-] Error: No profile exists for the set id.')
sys.exit()
if LAT_C is None:
LAT_C = allsettings['profiles'][idlist[0]]['coordinates']['lat']
else:
LAT_C = float(LAT_C)
if LNG_C is None:
LNG_C = allsettings['profiles'][idlist[0]]['coordinates']['lng']
else:
LNG_C = float(LNG_C)
threadnum = len(accounts)
locktime = min(0.8* time_hb / threadnum, 0.1)
num_hookers = int(math.ceil(float(threadnum)/time_hb))
return accounts
def getEarthRadius(latrad):
return (1.0 / (((math.cos(latrad)) / EARTH_Rmax) ** 2 + ((math.sin(latrad)) / EARTH_Rmin) ** 2)) ** (1.0 / 2)
def login_google(account):
ANDROID_ID = '9774d56d682e549c'
SERVICE = 'audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com'
APP = 'com.nianticlabs.pokemongo'
APP_SIG = '321187995bc7cdc2b5fc91b11a96e2baa8602c62'
while True:
try:
login1 = perform_master_login(account['user'], account['pw'], ANDROID_ID)
while login1.get('Token') is None:
lprint('[{}] Google Login error, retrying... (step 1)'.format(account['num']))
time.sleep(2)
login1 = perform_master_login(account['user'], account['pw'], ANDROID_ID)
login2 = perform_oauth(account['user'], login1.get('Token'), ANDROID_ID, SERVICE, APP, APP_SIG)
while login2.get('Auth') is None:
lprint('[{}] Google Login error, retrying... (step 2)'.format(account['num']))
time.sleep(2)
login2 = perform_oauth(account['user'], login1.get('Token', ''), ANDROID_ID, SERVICE, APP, APP_SIG)
access_token = login2['Auth']
account['access_expire_timestamp'] = 7200000 - 30000 + get_time() #int(login2['Expiry'])*1000
account['access_token'] = access_token
return
except Exception as e:
lprint('[{}] Unexpected google login error: {}'.format(account['num'], e))
lprint('[{}] Retrying...'.format(account['num']))
time.sleep(1)
def login_ptc(account):
LOGIN_URL = 'https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize'
LOGIN_OAUTH = 'https://sso.pokemon.com/sso/oauth2.0/accessToken'
pattern = re.compile("access_token=(?P<access_token>.+?)&expires=(?P<expire_in>[0-9]+)")
r = None
step = 0
while True:
try:
new_session(account)
session = account['session']
step = 0
r = session.get(LOGIN_URL)
step = 1
jdata = json.loads(r.content)
step = 2
data = {
'lt': jdata['lt'],
'execution': jdata['execution'],
'_eventId': 'submit',
'username': account['user'],
'password': account['pw'],
}
step = 3
r = session.post(LOGIN_URL, data=data)
step = 4
ticket = re.sub('.*ticket=', '', r.history[0].headers['Location'])
step = 5
data1 = {
'client_id': 'mobile-app_pokemon-go',
'redirect_uri': 'https://www.nianticlabs.com/pokemongo/error',
'client_secret': 'w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR',
'grant_type': 'refresh_token',
'code': ticket,
}
r = session.post(LOGIN_OAUTH, data=data1)
step = 6
result = pattern.search(r.content)
step = 7
account['access_expire_timestamp'] = 7200000 - 30000 + get_time() #account['access_expire_timestamp'] = int(result.groupdict()["expire_in"])*1000 + get_time()
account['access_token'] = result.groupdict()["access_token"]
session.close()
return
except Exception as e:
if r is not None:
try:
answer = json.loads(r.content)
if answer.get('error_code',None) == 'users.login.activation_required':
lprint('[{}] Login error for {}, needs email verification.'.format(account['num'],account['user']))
exit()
elif answer.get('errors',None) is not None:
if answer['errors'][0].startswith('Your username or password is incorrect.'):
lprint('[{}] Login error for {}, incorrect username/password/account does not exist.'.format(account['num'], account['user']))
exit()
elif answer['errors'][0].startswith('As a security measure, your account has been disabled for 15 minutes'):
lprint('[{}] Login error for {}, incorrect username/password was entered 5 times, login for that account is disabled for 15 minutes.'.format(account['num'], account['user']))
exit()
else:
lprint('[{}] Login error for {}, {}.'.format(account['num'], account['user'],answer['errors']))
else:
lprint('[{}] Connection error, http code: {}, content: {}'.format(account['num'], r.status_code, answer))
except ValueError:
lprint('[{}] Ptc login error in step {}: {}'.format(account['num'], step, e))
else:
lprint('[{}] Ptc login error in step {}: {}'.format(account['num'], step, e))
lprint('[{}] Error happened before network request.'.format(account['num']))
lprint('[{}] Retrying...'.format(account['num']))
time.sleep(2)
def init_account_db():
global db_accs
db_accs = sqlite3.connect(fpath_accs,check_same_thread=False)
db_accs.text_factory = str
cursor_accs = db_accs.cursor()
cursor_accs.execute("CREATE TABLE IF NOT EXISTS accounts(user BLOB PRIMARY KEY, access_token BLOB, access_expire_timestamp INTEGER, api_url BLOB, auth_ticket__expire_timestamp_ms INTEGER, auth_ticket__start BLOB, auth_ticket__end BLOB)")
cursor_accs.execute("PRAGMA journal_mode = WAL")
db_accs.commit()
def new_session(account):
if account.get('session',None) is None:
session = requests.session()
session.verify = True
session.headers.update({'User-Agent': 'Niantic App'}) # session.headers.update({'User-Agent': 'niantic'})
if not account['proxy'] is None:
session.proxies.update(account['proxy'])
account['session'] = session
else:
account['session'].close()
account['session'].cookies.clear()
account['session_time'] = get_time()
account['session_hash'] = os.urandom(32)
account['api_url'] = API_URL
account['auth_ticket'] = None
def do_login(account):
lprint('[{}] Login for {} account: {}'.format(account['num'], account['type'], account['user']))
timenow = get_time()
cursor_accs = db_accs.cursor()
db_repeat = True
while db_repeat:
try:
acc_saved = cursor_accs.execute("SELECT access_token,access_expire_timestamp,api_url,auth_ticket__expire_timestamp_ms,auth_ticket__start,auth_ticket__end from accounts WHERE user = ?",[account['user']]).fetchone()
db_repeat = False
except sqlite3.OperationalError as e:
lprint('[-] Sqlite operational error: {}, account: {} Retrying...'.format(e, account['user']))
except sqlite3.InterfaceError as e:
lprint('[-] Sqlite interface error: {}, account: {} Retrying...'.format(e, account['user']))
if acc_saved is not None and timenow < acc_saved[1]:
new_session(account)
account['access_expire_timestamp'] = acc_saved[1]
account['access_token'] = acc_saved[0]
lprint('[{}] Reused RPC Session Token: {}'.format(account['num'], account['access_token']))
else:
do_full_login(account)
lprint('[{}] New RPC Session Token: {}'.format(account['num'], account['access_token']))
acc_saved = None
location = LAT_C, LNG_C
if acc_saved is not None and timenow < acc_saved[3]:
account['api_url'] = acc_saved[2]
account['auth_ticket'] = {'expire_timestamp_ms': acc_saved[3], 'start': acc_saved[4], 'end': acc_saved[5]}
lprint('[{}] Reused API endpoint: {}'.format(account['num'], account['api_url']))
else:
set_api_endpoint(location, account)
lprint('[{}] New API endpoint: {}'.format(account['num'], account['api_url']))
if acc_tos:
accept_tos(location, account)
account['captcha_needed'] = False
def do_full_login(account):
lock_network.acquire()
time.sleep(locktime)
lock_network.release()
if account['type'] == 'ptc':
login_ptc(account)
elif account['type'] == 'google':
login_google(account)
new_session(account)
else:
lprint('[{}] Error: Login type should be either ptc or google.'.format(account['num']))
sys.exit()
cursor_accs = db_accs.cursor()
while True:
try:
cursor_accs.execute("INSERT OR REPLACE INTO accounts VALUES(?,?,?,?,?,?,?)", [account['user'], account['access_token'], account['access_expire_timestamp'], account['api_url'], 0, '0', '0'])
db_accs.commit()
return
except sqlite3.OperationalError as e:
lprint('[-] Sqlite operational error: {}, account: {} Retrying...'.format(e, account['user']))
except sqlite3.InterfaceError as e:
lprint('[-] Sqlite interface error: {}, account: {} Retrying...'.format(e, account['user']))
def api_req(location, account, api_endpoint, access_token, *reqs, **auth):
session = account['session']
r = None
p_req = POGOProtos.Networking.Envelopes_pb2.RequestEnvelope()
p_req.request_id = get_time() * 1000000 + random.randint(1, 999999)
p_req.status_code = POGOProtos.Networking.Envelopes_pb2.GET_PLAYER
p_req.latitude, p_req.longitude, p_req.accuracy = location[0],location[1],accuracy
for s_req in reqs:
p_req.MergeFrom(s_req)
p_req.ms_since_last_locationfix = 989
if auth['useauth'] is None:
p_req.auth_info.provider = account['type']
p_req.auth_info.token.contents = access_token
p_req.auth_info.token.unknown2 = 59
ticket_serialized = p_req.auth_info.SerializeToString()
else:
p_req.auth_ticket.start = auth['useauth']['start']
p_req.auth_ticket.expire_timestamp_ms = auth['useauth']['expire_timestamp_ms']
p_req.auth_ticket.end = auth['useauth']['end']
ticket_serialized = p_req.auth_ticket.SerializeToString()
sig = POGOProtos.Networking.Envelopes_pb2.Signature()
sig.location_hash1 = generateLocation1(ticket_serialized, location[0], location[1], accuracy)
sig.location_hash2 = generateLocation2(location[0], location[1], accuracy)
for req in p_req.requests:
req_hash = generateRequestHash(ticket_serialized, req.SerializeToString())
sig.request_hash.append(req_hash)
sig.session_hash = account['session_hash']
sig.timestamp = get_time()
sig.timestamp_since_start = get_time() - account['session_time']
sig.unknown25 = -8537042734809897855
signature_proto = sig.SerializeToString()
request_sig = p_req.platform_requests.add()
request_sig.type = POGOProtos.Networking.Platform_pb2.SEND_ENCRYPTED_SIGNATURE
sig_env = POGOProtos.Networking.Platform.Requests_pb2.SendEncryptedSignatureRequest()
sig_env.encrypted_signature = generate_signature(signature_proto, signature_lib)
request_sig.request_message = sig_env.SerializeToString()
request_str = p_req.SerializeToString()
loopcount = 0
while True:
try:
lock_network.acquire()
time.sleep(locktime)
lock_network.release()
r = session.post(api_endpoint, data=request_str)
if r.status_code == 200:
p_ret = POGOProtos.Networking.Envelopes_pb2.ResponseEnvelope()
p_ret.ParseFromString(r.content)
return p_ret
elif r.status_code == 403:
if account['proxy'] is not None:
if account['proxy']['http'].startswith('socks5') and time_socks5_retry > 0:
lprint('[+] Socks5 Proxy detected. Sleeping and retrying after {} s.'.format(time_socks5_retry))
time.sleep(time_socks5_retry)
else:
lprint('[-] Access denied, your IP is blocked by the N-company. ({})'.format(account['user']))
sys.exit()
else:
lprint('[-] Access denied, your IP is blocked by the N-company.')
sys.exit()
elif r.status_code == 502:
lprint('[{}] Servers busy (502), retrying...'.format(account['num']))
time.sleep(2)
loopcount += 1
if loopcount > 4:
return None
else:
lprint('[-] Unexpected network error, http code: {}'.format(r.status_code))
return None
except requests.ConnectionError as e:
if re.search('Connection aborted', str(e)) is None:
lprint('[-] Unexpected connection error, error: {}'.format(e))
if r is not None:
lprint('[-] Unexpected connection error, http code: {}'.format(r.status_code))
else:
lprint('[-] Error happened before network request.')
lprint('[-] Retrying...')
time.sleep(1)
loopcount += 1
if loopcount > 4:
return None
except Exception as e:
lprint('[-] Unexpected connection error, error: {}'.format(e))
if r is not None:
lprint('[-] Unexpected connection error, http code: {}'.format(r.status_code))
else:
lprint('[-] Error happened before network request.')
lprint('[-] Retrying...')
time.sleep(1)
loopcount += 1
if loopcount > 4:
return None
def get_profile(rtype, location, account, *reqq):
req = POGOProtos.Networking.Envelopes_pb2.RequestEnvelope()
req1 = req.requests.add()
req1.request_type = POGOProtos.Networking.Envelopes_pb2.GET_PLAYER
if len(reqq) >= 1:
req1.MergeFrom(reqq[0])
req2 = req.requests.add()
req2.request_type = POGOProtos.Networking.Envelopes_pb2.GET_HATCHED_EGGS
if len(reqq) >= 2:
req2.MergeFrom(reqq[1])
req3 = req.requests.add()
req3.request_type = POGOProtos.Networking.Envelopes_pb2.CHECK_CHALLENGE
if len(reqq) >= 3:
req3.MergeFrom(reqq[2])
req4 = req.requests.add()
req4.request_type = POGOProtos.Networking.Envelopes_pb2.GET_INVENTORY
if len(reqq) >= 4:
req4.MergeFrom(reqq[3])
req5 = req.requests.add()
req5.request_type = POGOProtos.Networking.Envelopes_pb2.CHECK_AWARDED_BADGES
if len(reqq) >= 5:
req5.MergeFrom(reqq[4])
req6 = req.requests.add()
req6.request_type = POGOProtos.Networking.Envelopes_pb2.DOWNLOAD_SETTINGS
if len(reqq) >= 6:
req6.MergeFrom(reqq[5])
while True: # 1 for heartbeat, 2 for profile authorization, 53 for api endpoint, 52 for error, 102 session token invalid
time.sleep(time_hb)
response = api_req(location, account, account['api_url'], account['access_token'], req, useauth=account['auth_ticket'])
if response is not None and response.status_code in [1,2]:
if response.status_code == 2:
time.sleep(1)
continue
else:
captchaResponse = POGOProtos.Networking.Responses_pb2.CheckChallengeResponse()
captchaResponse.ParseFromString(response.returns[2])
if captchaResponse.show_challenge:
lprint('[{}] Captcha required: {}'.format(account['num'],captchaResponse.challenge_url))
account['captcha_needed'] = True
if response is None:
time.sleep(1)
lprint('[{}] Response error, retrying...'.format(account['num']))
do_full_login(account)
set_api_endpoint(location, account)
elif rtype == 1 and response.status_code in [1,2]:
return response
elif rtype == 53 or response.status_code == 53:
if response.auth_ticket is not None and response.auth_ticket.expire_timestamp_ms > 0:
account['auth_ticket'] = response.auth_ticket
account['auth_ticket'] = {'start': account['auth_ticket'].start, 'expire_timestamp_ms': account['auth_ticket'].expire_timestamp_ms, 'end': account['auth_ticket'].end}
if response.api_url is not None and response.api_url:
account['api_url'] = 'https://{}/rpc'.format(response.api_url)
if account['auth_ticket'] is not None and account['api_url'] != API_URL:
if rtype == 53:
return
else:
lprint('[+] API endpoint changed.')
else:
time.sleep(1)
lprint('[{}] auth/token error, refreshing login...'.format(account['num']))
do_full_login(account)
set_api_endpoint(location, account)
elif rtype in [406,601] and response.status_code in [1,2]:
return
elif response.status_code == 102:
timenow = get_time()
if timenow > account['access_expire_timestamp'] or timenow < account['auth_ticket']['expire_timestamp_ms']:
lprint('[+] Login refresh.')
do_full_login(account)
else:
lprint('[+] Authorization refresh.')
set_api_endpoint(location, account)
elif response.status_code == 52:
lprint('[{}] Servers busy (52), retrying...'.format(account['num']))
elif response.status_code == 3:
lprint('[{}] Account was banned. It\'ll be logged out.'.format(account['num']))
if not synch_li.empty():
synch_li.get()
synch_li.task_done()
elif rtype == 1:
addlocation.put(location,block=True,timeout=10)
addlocation.task_done()
lock_banfile.acquire()
try:
f = open('{}/res/banned{}.txt'.format(workdir, wID), 'a')
f.write('{}\n'.format(account['user']))
finally:
if 'f' in vars() and not f.closed:
f.close()
lock_banfile.release()
exit()
else:
lprint('[{}] Response error, unexpected status code: {}, retrying...'.format(account['num'], response.status_code))
lprint(response)
time.sleep(1)
def set_api_endpoint(location, account):
account['auth_ticket'] = None
get_profile(53, location, account)
cursor_accs = db_accs.cursor()
while True:
try:
cursor_accs.execute("INSERT OR REPLACE INTO accounts VALUES(?,?,?,?,?,?,?)", [account['user'], account['access_token'], account['access_expire_timestamp'], account['api_url'], account['auth_ticket']['expire_timestamp_ms'], account['auth_ticket']['start'], account['auth_ticket']['end']])
db_accs.commit()
return
except sqlite3.OperationalError as e:
lprint('[-] Sqlite operational error: {}, account: {} Retrying...'.format(e, account['user']))
except sqlite3.InterfaceError as e:
lprint('[-] Sqlite interface error: {}, account: {} Retrying...'.format(e, account['user']))
def heartbeat(location, account):
global safetysecs
m1 = POGOProtos.Networking.Envelopes_pb2.RequestEnvelope().requests.add()
m1.request_type = POGOProtos.Networking.Envelopes_pb2.GET_MAP_OBJECTS
m11 = POGOProtos.Networking.Requests.Messages_pb2.GetMapObjectsMessage()
walk = getNeighbors(location)
m11.cell_id.extend(walk)
m11.since_timestamp_ms.extend([0] * len(walk))
m11.latitude = location[0]
m11.longitude = location[1]
m1.request_message = m11.SerializeToString()
timenow = get_time()
if timenow > account['access_expire_timestamp']:
lprint('[+] Login refresh.')
do_full_login(account)
set_api_endpoint(location, account)
elif timenow > account['auth_ticket']['expire_timestamp_ms']:
lprint('[+] Authorization refresh.')
set_api_endpoint(location,account)
time_pre = get_time()
response = get_profile(1, location, account, m1)
time_post = get_time()
heartbeat = POGOProtos.Networking.Responses_pb2.GetMapObjectsResponse()
heartbeat.ParseFromString(response.returns[0])
if safetysecs_auto and time_post-time_pre < time_hb*2000:
safetysecs = 0.5+max(time_post - heartbeat.map_cells[0].current_timestamp_ms,0)/1000.0
return heartbeat
def accept_tos(location, account):
m1 = POGOProtos.Networking.Envelopes_pb2.RequestEnvelope().requests.add()
m1.request_type = POGOProtos.Networking.Envelopes_pb2.MARK_TUTORIAL_COMPLETE
m11 = POGOProtos.Networking.Requests.Messages_pb2.MarkTutorialCompleteMessage()
m11.tutorials_completed.append(POGOProtos.Enums_pb2.LEGAL_SCREEN)
m11.send_marketing_emails = False
m11.send_push_notifications = False
m1.request_message = m11.SerializeToString()
get_profile(406, location, account, m1)
def answer_captcha(location, account,answer):
m1 = POGOProtos.Networking.Envelopes_pb2.RequestEnvelope().requests.add()
m1.request_type = POGOProtos.Networking.Envelopes_pb2.VERIFY_CHALLENGE
m11 = POGOProtos.Networking.Requests.Messages_pb2.VerifyChallengeMessage()
m11.token = answer
m1.request_message = m11.SerializeToString()
get_profile(601, location, account, m1)
def init_data():
global db_data
db_data = sqlite3.connect(fpath_data,check_same_thread=False)
cursor_data = db_data.cursor()
cursor_data.execute("CREATE TABLE IF NOT EXISTS spawns(spawnid INTEGER PRIMARY KEY, latitude REAL, longitude REAL, spawntype INTEGER, pokeid INTEGER, expiretime INTEGER, fromtime INTEGER, profile INTEGER)")
cursor_data.execute("PRAGMA journal_mode = WAL")
db_data.commit()
def update_data():
timenow = int(round(time.time(),0))
cursor_data = db_data.cursor()
for l in range(0,len(data_buffer)):
[pokeid, spawnid, latitude, longitude, expiretime, addinfo] = data_buffer.pop()
db_repeat = True
while db_repeat:
try:
cursor_data.execute("INSERT OR REPLACE INTO spawns VALUES(?,?,?,?,?,?,?,?)", [spawnid, round(latitude, 5), round(longitude, 5), addinfo, pokeid, expiretime, timenow, wID])
db_repeat = False
except sqlite3.OperationalError as e:
lprint('[-] Sqlite operational error: {} Retrying...'.format(e))
while True:
try:
db_data.commit()
return
except sqlite3.OperationalError as e:
lprint('[-] Sqlite operational error: {} Retrying...'.format(e))
def lprint(message):
sys.stdout.write(u'{}\n'.format(message))
def get_planid(plan):
if plan['type'] == 'seikur0_s2':
id = 'seikur0_s2__{}'.format(plan['token'])
elif plan['type'] == 'seikur0_spir':
id = 'seikur0_spir__{}_{}__{}'.format(plan['location'][0],plan['location'][1],plan['range'])
elif plan['type'] == 'seikur0_circle':
id = 'seikur0_circle__{}_{}__{}'.format(plan['location'][0],plan['location'][1],plan['radius'])
elif plan['type'] == 'raw':
id = 'raw__{}_{}__{}'.format(plan['locations'][0][0],plan['locations'][0][1],plan['id'])
if plan.get('subplan_index',None) is not None and plan.get('subplans',None) is not None:
id = '{}__{}_{}'.format(id,plan['subplan_index'],plan['subplans'])
id = '{}__{}'.format(id,Rsight)
return id
def get_plan_locations(plan):
global LAT_C,LNG_C,location_str
grid = mapl.Hexgrid()
if plan['type'] == 'seikur0_s2':
cid = CellId.from_token(plan['token'])
ll_location = LatLng.from_point(Cell(cid).get_center())
location = (ll_location.lat().degrees, ll_location.lng().degrees)
locations = grid.cover_cell(cid)
elif plan['type'] == 'seikur0_spir':
location = plan['location']
scanrange = plan['range']
locations = mapl.get_area_spiral(location, scanrange)
elif plan['type'] == 'seikur0_circle':
location = plan['location']
radius = plan['radius']
locations = grid.cover_circle(location,radius)
elif plan['type'] == 'raw': #must contain plan['id']
locations = plan['locations']
location = locations[0]
else:
return None
ind_max = len(locations)
ind_part = int(math.ceil(float(ind_max) / plan.get('subplans',1)))
ind = plan.get('subplan_index',1) - 1
locations = locations[0 + ind_part * ind:min(ind_max, ind_part * (ind + 1))]
LAT_C, LNG_C = locations[0]
try:
location_str = 'Location: ({})'.format(geolocator.reverse('{},{}'.format(location[0], location[1]),language=lang_code).address)
except:
location_str = 'Lat: {}, Lng: {}'.format(LAT_C, LNG_C)
return locations
def set_locations():
global all_loc,empty_loc,all_scans,scandata,smartscan,fname_spawnfile,fpath_iscan,fpath_plan
all_loc = []
empty_loc = []
all_scans = []
if mode_plan:
smartscan = False
if not smartscan:
scandata.clear()
if mode_plan:
list_files = []