-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathrush.py
executable file
·2262 lines (1959 loc) · 77.4 KB
/
rush.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
import string
import os
import re
import zipfile
import secrets
import signal
import psutil
import tempfile
import atexit
import heapq
import sentry_sdk
import itertools
import pathlib
import sys
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def writelines(self, datas):
self.stream.writelines(datas)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout.reconfigure(encoding='utf-8')
sys.stdout = Unbuffered(sys.stdout)
if os.name == 'nt':
import win_unicode_console
win_unicode_console.enable()
def start_rcfarm():
if DEBUG:
try:
sys.stdout = sys.stderr = open('/Users/aka/drive/ysfc/cli/debug.log', 'a+')
except:
sys.stdout = sys.stderr = open('/dev/null', 'w')
else:
sys.stdout = sys.stderr = open('/dev/null', 'w')
sys.stdin.close()
start()
import csv
from enum import Enum
from cmd2 import ansi
import uuid
import threading
from threading import Thread
from datetime import datetime
from collections import defaultdict
# import timeago
import pprint
import subprocess
import math
import json
import requests
import tableformatter as tf
tf.TableColors.set_color_library('none')
import sqlite3
import sys
import traceback
import os
from urllib.parse import urlparse, parse_qs, urlunparse, urlencode
import random
import time
import io
from itertools import groupby
import concurrent
import argparse
import cmd2
import appdirs
from util import cc_type
from messaging import get_task_pub_socket, get_task_tail_socket
if hasattr(sys, "_MEIPASS"):
DIR = sys._MEIPASS
else:
DIR = os.path.dirname(sys.argv[0])
VERSION = '0.2.44'
DEBUG = os.getenv('DEBUG') is not None
if DEBUG:
import logging
logging.basicConfig(level=logging.DEBUG)
RC_POOL_EXE = 'rcpool' if os.name != 'nt' else 'rcpool.exe'
RC_LOGIN_EXE = 'rclogin' if os.name != 'nt' else 'rclogin.exe'
TASK_CONSUMER_EXE = 'task_consumer' if os.name != 'nt' else 'task_consumer-windows-8.1-amd64.exe'
APP_DIR = appdirs.user_data_dir("RushAIO", "RushAIO")
PIDFILE = os.path.join(APP_DIR, "tcpid")
os.makedirs(os.path.join(APP_DIR, 'chrome'), exist_ok=True)
os.makedirs(os.path.join(APP_DIR, 'config'), exist_ok=True)
RECAP_PROXIES_FN = os.path.join(APP_DIR, 'recap_proxies.json')
ZONEINFO_ZIP = os.path.join(DIR, 'external', 'zoneinfo.zip')
if os.name == "nt":
CHROMIUM = os.path.join(APP_DIR, 'chrome', 'chrome.exe')
CHROMIUM_ZIP = os.path.join(DIR, 'chrome', 'chromium_win.zip')
else:
CHROMIUM = os.path.join(APP_DIR, 'chrome', 'Chromium.app/Contents/MacOS/Chromium')
CHROMIUM_ZIP = os.path.join(DIR, 'chrome', 'chromium_mac.zip')
RUSH_DB = os.getenv('RUSH_DB', os.path.join(APP_DIR, 'rush.db'))
PROFILE_FIELDS=["profile_name", "email","ship_name","ship_phone","ship_address1","ship_address2","ship_city","ship_zip","ship_state","ship_country","card_name","card_address1","card_address2","card_city","card_zip","card_state","card_country","card_phone","card_number","card_cvc","card_expmonth","card_expyear","size"]
class TaskStatus(Enum):
STOPPED = 'Stopped'
STARTING = 'Starting'
RUSHING = 'Rushing'
FAIL = 'Failed'
COOKED = 'Cooked'
class ProxyDistribution(Enum):
RANDOM = 1
SPECIFIC = 2
from zipfile import ZipFile, ZipInfo
class ZipFileWithPermissions(ZipFile):
""" Custom ZipFile class handling file permissions. """
def _extract_member(self, member, targetpath, pwd):
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
targetpath = super()._extract_member(member, targetpath, pwd)
attr = member.external_attr >> 16
if attr != 0:
os.chmod(targetpath, attr)
return targetpath
def row_to_dict(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def read_profiles_from_file(fn):
try:
with open(os.path.expanduser(fn), newline='', encoding='utf-8') as f:
return read_profiles_from_buf(f)
except Exception as e:
with open(os.path.expanduser(fn), newline='', encoding='utf-8-sig') as f:
return read_profiles_from_buf(f)
def read_profiles_from_buf(buf):
r = csv.DictReader(buf)
profiles = []
for row in r:
header = list(row.keys())
if header != PROFILE_FIELDS:
raise Exception(f'Invalid profile format: incorrect column names. Extra: {set(header) - set(PROFILE_FIELDS)} Missing: {set(PROFILE_FIELDS) - set(header)}')
try:
ship = {}
bill = {}
card = {}
profile = {'Name': row['profile_name'], 'ShippingAddress': ship, 'BillingAddress': bill, 'Card': card, 'Size': None}
profile['Email'] = row['email'].replace(' ', '')
ship['address1'] = row['ship_address1']
ship['address2'] = row['ship_address2']
ship['city'] = row['ship_city']
ship['zipcode'] = row['ship_zip']
ship['stateCode'] = row['ship_state'].upper()
if len(ship['stateCode']) != 2:
raise Exception(f'Invalid ship_state: must be 2-letter state code, not "{ship["stateCode"]}"')
ship['country'] = row['ship_country'].replace('United States', 'US').replace('USA', 'US').upper()
if len(ship['country']) != 2:
raise Exception(f'Invalid ship_country: must be 2-letter country code, not "{ship["country"]}"')
ship['firstName'] = ' '.join(row['ship_name'].split()[:-1])
ship['lastName'] = row['ship_name'].split()[-1]
ship['phoneNumber'] = row['ship_phone']
if len(ship['phoneNumber']) < 10:
# todo nice list of required fields + errfmt
raise Exception('Missing ship_phone (should be at least 10 digits)')
if row['card_address1']:
bill['address1'] = row.get('card_address1')
bill['address2'] = row.get('card_address2')
bill['city'] = row.get('card_city')
bill['zipcode'] = row.get('card_zip')
bill['stateCode'] = row.get('card_state')
bill['country'] = row.get('card_country')
bill['country'] = bill['country'].replace('United States', 'US').replace('USA', 'US')
bill['firstName'] = ' '.join(row['ship_name'].split()[:-1])
bill['lastName'] = row.get('card_name').split()[-1]
bill['phoneNumber'] = row.get('card_phone')
else:
bill['address1'] = row.get('card_address1') or row['ship_address1']
bill['address2'] = row.get('card_address2') or row['ship_address2']
bill['city'] = row.get('card_city') or row['ship_city']
bill['zipcode'] = row.get('card_zip') or row['ship_zip']
bill['stateCode'] = row.get('card_state') or row['ship_state']
bill['country'] = row.get('card_country') or row['ship_country']
bill['country'] = bill['country'].replace('United States', 'US').replace('USA', 'US')
bill['firstName'] = ' '.join((row.get('card_name') or row['ship_name']).split()[:-1])
bill['lastName'] = (row.get('card_name') or row['ship_name']).split()[-1]
bill['phoneNumber'] = row.get('card_phone') or row['ship_phone']
if len(bill['stateCode']) != 2:
raise Exception(f'Invalid card_state: must be 2-letter state code, not "{bill["stateCode"]}"')
if len(bill['country']) != 2:
raise Exception(f'Invalid card_country: must be 2-letter country code, not "{bill["country"]}"')
if len(bill['phoneNumber']) < 10:
# todo nice list of required fields + errfmt
raise Exception('Invalid card_phone (should be at least 10 digits)')
card['number'] = row['card_number']
if len(card['number']) < 13 or not card['number'].isdigit():
raise Exception(f'Invalid profile format: card number is {card["number"]}')
card['cvc'] = row['card_cvc']
card['cardType'] = cc_type(card['number'])
if card['cardType'] is None:
raise Exception(f'Could not determine card type (visa,master,amex,discover,...). Check card number: {card["number"]}')
card['holder'] = row.get('card_name') or row.get('ship_name')
card['expirationMonth'] = int(row['card_expmonth'])
card['expirationYear'] = int(row['card_expyear'])
card['paymentMethodId'] = "CREDIT_CARD"
card['lastFour'] = ''.join(card['number'][-4:])
profile['Size'] = row.get('size')
for key, value in profile.items():
if type(value) is str:
profile[key] = value.strip()
profiles.append(profile)
except Exception as e:
print('Warning: skipping profile, bad format', traceback.format_exc(1), row)
continue
return profiles
def profiles_to_csv(profs):
b = io.StringIO()
w = csv.DictWriter(b, fieldnames=PROFILE_FIELDS)
w.writeheader()
for p in profs:
ship = p['ShippingAddress']
bill = p['BillingAddress']
card = p['Card']
pp = {
"profile_name": p.get('Name', str(uuid.uuid4())[:8]),
"email": p['Email'],
"ship_name": ' '.join([ship['firstName'], ship['lastName']]),
"ship_phone": ship['phoneNumber'],
"ship_address1": ship['address1'],
"ship_address2": ship['address2'],
"ship_city": ship['city'],
"ship_zip": ship['zipcode'],
"ship_state": ship['stateCode'],
"ship_country": ship['country'],
"card_name": card['holder'],
"card_phone": bill['phoneNumber'],
"card_address1": bill['address1'],
"card_address2": bill['address2'],
"card_city": bill['city'],
"card_zip": bill['zipcode'],
"card_state": bill['stateCode'],
"card_country": bill['country'],
"card_number": card['number'],
"card_cvc": card['cvc'],
"card_expmonth": card['expirationMonth'],
"card_expyear": card['expirationYear'],
"size": p.get('Size', ""),
}
w.writerow(pp)
return b.getvalue()
def validate_profile(p):
pass
SIZES = [
"3K",
"4K",
"4.5K",
"5K",
"5.5K",
"6K",
"6.5K",
"7K",
"7.5K",
"8K",
"8.5K",
"9K",
"9.5K",
"10K",
"10.5K",
"11K",
"11.5K",
"12K",
"12.5K",
"13K",
"13.5K",
"1",
"1.5",
"2",
"2.5",
"3",
"3.5",
"4",
"4.5",
"5",
"5.5",
"6",
"6.5",
"7",
"7.5",
"8",
"8.5",
"9",
"9.5",
"10",
"10.5",
"11",
"11.5",
"12",
"12.5",
"13",
"13.5",
"14",
"14.5",
"15",
"15.5",
"16",
"16.5",
"17",
]
class ResourceShare:
def __init__(self, key=lambda resource: resource):
self.pq = []
self.entry_finder = {}
self.REMOVED = '<removed-resource>'
self.counter = itertools.count()
self.key_fn = key
"""
trie of profile names +
profile name -> profile dict +
"""
def add(self, resource, priority=0):
'Add a new resource or update the priority of an existing resource'
if self.key_fn(resource) in self.entry_finder:
self.remove(resource)
count = next(self.counter)
entry = [priority, count, resource]
self.entry_finder[self.key_fn(resource)] = entry
heapq.heappush(self.pq, entry)
def has(self, resource):
return self.key_fn(resource) in self.entry_finder
def remove(self, resource):
'Mark an existing resource as REMOVED. Raise KeyError if not found.'
entry = self.entry_finder.pop(self.key_fn(resource))
entry[-1] = self.REMOVED
def pop(self):
'Remove and return the lowest priority resource. Raise KeyError if empty.'
while self.pq:
priority, count, resource = heapq.heappop(self.pq)
if resource != self.REMOVED:
del self.entry_finder[self.key_fn(resource)]
return resource
raise KeyError('pop from an empty priority queue')
def popincr(self, testfn=lambda x: True):
#
s = time.time()
cnt = 0
to_re_add = []
ll = len(self.pq)
while self.pq and cnt <= ll:
cnt += 1
priority, count, resource = heapq.heappop(self.pq)
if resource != self.REMOVED:
del self.entry_finder[self.key_fn(resource)]
if testfn(resource):
# print('tested positive', resource)
self.add(resource, priority=priority+1)
for pri, rr in to_re_add:
self.add(rr, priority=pri)
return resource
else:
to_re_add.append((priority, resource))
# self.add(resource, priority=priority)
for pri, resource in to_re_add:
self.add(resource, priority=pri)
raise KeyError('pop from an empty priority queue')
# pqbak = self.pq.copy()
# cnt = 0
# ll = len(self.pq)
# while self.pq and cnt <= ll:
# cnt += 1
# priority, count, resource = heapq.heappop(self.pq)
# if resource != self.REMOVED:
# if testfn(resource):
# self.pq = pqbak
# self.add(resource, priority=priority+1)
# return resource
# self.pq = pqbak
# raise KeyError('pop from an empty priority queue')
def decr(self, resource):
if resource in self.entry_finder:
priority, count, resource = self.entry_finder[self.key_fn(resource)]
self.add(resource, priority=max(0,priority-1))
def all_priority(self):
h = self.pq.copy()
hp = [heapq.heappop(h) for i in range(len(h))]
return [(h[0], h[2]) for h in hp if h[2] != self.REMOVED]
def all(self):
h = self.pq.copy()
hp = [heapq.heappop(h) for i in range(len(h))]
return [h[2] for h in hp if h[2] != self.REMOVED]
# for _, __, resource in self.pq.copy():
# if resource is not self.REMOVED:
def unescape_backslash(str_):
if os.name == 'posix':
return str_.replace('\\', '')
else:
return str_
parser = argparse.ArgumentParser()
subp = parser.add_subparsers(title='rush', help='rush help')
key_parser = subp.add_parser('key')
key_cmds = key_parser.add_subparsers(title='license key commands', help='Activate License')
key_activate = key_cmds.add_parser('activate')
key_activate.add_argument('key')
prof_parser = subp.add_parser('profile', help='profile help')
prof_cmds = prof_parser.add_subparsers(title='profile commands', help='Import profiles')
prof_imp = prof_cmds.add_parser('import')
prof_imp.add_argument('csv_file', nargs='+')
prof_remove = prof_cmds.add_parser('remove')
prof_remove.add_argument('profile_name')
prof_remove_all = prof_cmds.add_parser('remove-all')
prof_remove_all.add_argument('--name')
prof_list = prof_cmds.add_parser('list')
prof_show = prof_cmds.add_parser('show')
prof_show.add_argument('name')
proxy_parser = subp.add_parser('proxy', help='proxy help')
proxy_cmds = proxy_parser.add_subparsers(title='proxy commands')
proxy_imp = proxy_cmds.add_parser('import')
proxy_imp.add_argument('proxy_txt_file', nargs='+')
proxy_imp.add_argument('--group', default='default')
proxy_add = proxy_cmds.add_parser('add')
proxy_add.add_argument('proxy')
proxy_add.add_argument('--group', default='default')
proxy_list = proxy_cmds.add_parser('list')
proxy_list.add_argument('--group')
proxy_remove = proxy_cmds.add_parser('remove')
proxy_remove.add_argument('proxy')
proxy_remove.add_argument('--group')
proxy_remove_all_p = proxy_cmds.add_parser('remove-all')
proxy_remove_all_p.add_argument('--group')
# TODO
# proxy_test = proxy_cmds.add_parser('test')
# proxy_test.add_argument('proxy')
vault_parser = subp.add_parser('vault', help='vault help')
vault_cmds = vault_parser.add_subparsers(title='vault commands')
vault_add = vault_cmds.add_parser('add')
vault_add.add_argument('site')
vault_add.add_argument('email')
vault_add.add_argument('password')
vault_remove = vault_cmds.add_parser('remove')
vault_remove.add_argument('site')
vault_remove.add_argument('email')
vault_list = vault_cmds.add_parser('list')
task_parser = subp.add_parser('task', help='task')
task_cmds = task_parser.add_subparsers(title='task commands')
task_tail = task_cmds.add_parser('tail')
task_list = task_cmds.add_parser('list')
task_list.add_argument('--status', help='Task status', nargs='+', choices=[t.value for t in list(TaskStatus)])
task_status = task_cmds.add_parser('status')
task_status.add_argument('--watch', action='store_true', default=False)
task_watch = task_cmds.add_parser('watch')
task_watch.add_argument('--watch', action='store_true', default=True)
task_data = task_cmds.add_parser('data')
task_data.add_argument('--watch', action='store_true', default=True)
task_edit = task_cmds.add_parser('edit')
task_edit.add_argument('--url')
task_edit.add_argument('--new-url')
task_add = task_cmds.add_parser('add')
task_add.add_argument('--url', help='URL of product or URL of page for keyword-based product lookup', required=True)
task_add.add_argument('--profile', help='(Optional) Profile name. Defaults to random profile (recommended for task count > 1), prioritizing profiles assigned to fewest tasks')
task_add.add_argument('--size', help=f'(Optional) Size (overrides profile size) ({",".join(SIZES)})')
task_add.add_argument('--count', default=1, type=int, help='(Optional, default 1) Task Count. If set to >1, uses random profile, overriding --profile option')
task_add_prox = task_add.add_mutually_exclusive_group()
task_add_prox.add_argument('--proxy', help='Proxy string. Defaults to random proxy. Specify "none" to disable proxy')
task_add_prox.add_argument('--proxy-group', help='Proxy group name. Defaults to "default"', default='default')
task_add.add_argument('--keywords', nargs='+', help='Keywords that must exist in product name')
task_add.add_argument('--start', action='store_true', default=False)
task_add.add_argument('--delay', type=int)
task_start = task_cmds.add_parser('start')
task_start.add_argument('task_id', nargs='+')
task_start_all = task_cmds.add_parser('start-all')
task_start_all.add_argument('--site')
task_start_all.add_argument('--url')
task_start_all.add_argument('--limit', type=int)
task_start_all.add_argument('--profile')
task_start_all.add_argument('--proxy-group')
task_stop = task_cmds.add_parser('stop')
task_stop.add_argument('task_id', nargs='+')
task_stop_all = task_cmds.add_parser('stop-all')
task_stop_all.add_argument('--state')
task_stop_all.add_argument('--status')
task_stop_all.add_argument('--site')
task_stop_all.add_argument('--limit', type=int)
task_stop_all.add_argument('--profile')
task_stop_all.add_argument('--proxy-group')
task_remove = task_cmds.add_parser('remove')
task_remove.add_argument('task_id')
task_remove_all = task_cmds.add_parser('remove-all')
task_remove_all.add_argument('--site')
task_remove_all.add_argument('--status')
task_remove_all.add_argument('--profile')
task_remove_all.add_argument('--proxy-group')
# task_success = task_cmds.add_parser('success')
# recap_parser = subp.add_parser('recap', help='recap')
# recap_cmds = recap_parser.add_subparsers(title='Recap Commands')
# recap_proxy = recap_cmds.add_parser('proxy')
# recap_proxy_cmds = recap_proxy.add_subparsers(title='recap proxy commands')
# recap_proxy_imp = recap_proxy_cmds.add_parser('import')
# recap_proxy_imp.add_argument('proxy_txt_file', nargs='+')
# recap_proxy_add = recap_proxy_cmds.add_parser('add')
# recap_proxy_add.add_argument('proxy')
# recap_proxy_list = recap_proxy_cmds.add_parser('list')
# recap_proxy_remove = recap_proxy_cmds.add_parser('remove')
# recap_proxy_remove.add_argument('proxy')
# recap_proxy_remove_all_p = recap_proxy_cmds.add_parser('remove-all')
# recap_proxy_litport_rotate = recap_proxy_cmds.add_parser('litport-rotate')
# recap_proxy_litport_rotate.add_argument('--url', required=True)
# recap_proxy_litport_rotate.add_argument('--count', required=True)
# recap_login = recap_cmds.add_parser('login')
# recap_login.add_argument('--proxy')
# recap_logout = recap_cmds.add_parser('logout')
# recap_logout.add_argument('email')
# recap_logout_all = recap_cmds.add_parser('logout-all')
# recap_list = recap_cmds.add_parser('list')
# recap_list_logins = recap_cmds.add_parser('list-logins')
# recap_score = recap_cmds.add_parser('score')
# recap_score.add_argument('--proxy')
# recap_score.add_argument('--email')
# recap_score.add_argument('--loop', action='store_true', default=False)
# recap_score.add_argument('--delay', type=int, default=0)
# recap_score.add_argument('--sources', nargs='+')
config_parser = subp.add_parser('config', help='RushAIO configuration')
config_cmds = config_parser.add_subparsers(title='Configuration')
config_set_webhook = config_cmds.add_parser('set-webhook')
config_set_webhook.add_argument('webhook')
def normalize_proxy(proxy):
parsed = urlparse(proxy)
if parsed.scheme not in ('http', 'socks5'):
parsed = urlparse('http://' + proxy)
hostname = parsed.hostname
if hostname and '::' in hostname:
hostname = '[' + hostname + ']'
try:
if parsed.scheme not in ('http', 'socks5'):
raise ValueError()
credentials = f'{parsed.username}{":"+ parsed.password if parsed.password else ""}@' if parsed.username else ''
return f'{parsed.scheme}://{credentials}{hostname}{":" + str(parsed.port) if parsed.port else ""}'
except ValueError:
try:
host, port, user, password = proxy.split(":")
return f'http://{user}:{password}@{host}:{port}'
except Exception:
return None
def uniq_psort(seq, key=None):
if key is None:
key = lambda x: x
seen = set()
seen_add = seen.add
return [x for x in seq if not (key(x) in seen or seen_add(key(x)))]
def find_dupes(seq, key=None):
if key is None:
key = lambda x: x
seen = set()
dupes = []
for x in seq:
if key(x) in seen:
dupes.append(x)
else:
seen.add(key(x))
return dupes
class TaskRow():
def __init__(self, task):
self.task = task
for k,v in task.items():
setattr(self, k, v)
def __len__(self):
return len(self.task.keys())
@property
def level_(self):
return int(self._level_) if hasattr(self, '_level_') and (type(self._level_) is int or (type(self._level_) is str and self._level_.isdigit())) else 0
def get_product(self):
return self.product if hasattr(self, 'product') else '/'.join([s for s in self.url.split('/')[-2:] if s not in ('product', 'products')])
def get_site(self):
return self.url
# up = urlparse(self.url)
# return up.scheme + "://" + up.hostname
def get_size(self):
has_size_override = self.size not in ("",None)
if has_size_override:
return self.size
elif self.size == "":
return "Random"
else:
profile = self.profile or getattr(self, 'profileInUse', None)
if type(profile) is str:
try:
profile = json.loads(profile)
except Exception:
pass
if profile:
try:
return profile['Size']
except Exception:
return f'Random'
elif getattr(self, 'profileInUse', None):
return self.profileInUse['Size'] or 'Random'
else:
return 'Random'
def get_proxy(self):
proxy_distribution = getattr(self, 'proxy_distribution', ProxyDistribution.RANDOM.value if self.proxy is None else ProxyDistribution.SPECIFIC.value)
proxy_group = getattr(self, 'proxy_group', '') or ''
if proxy_group:
proxy_group = f'({proxy_group}) '
active_proxy = f'({self.proxy})' if self.proxy else ''
return f'Random {proxy_group}{active_proxy}' if proxy_distribution == ProxyDistribution.RANDOM.value else self.proxy # self.proxy or f"Random{' (' + self.proxyInUse + ')' if getattr(self, 'proxyInUse', None) else ''}"
def get_profile_name(self):
if self.profile:
try:
return json.loads(self.profile)['Name']
except Exception:
return f"Random ({self.profile})"
else:
return f"Random {'(' + self.profileInUse['Name'] + ')' if getattr(self, 'profileInUse', None) else ''}"
# def get_last_updated(self):
# if getattr(self, 'updated_at', None):
# return timeago.format(self.updated_at, datetime.now())
# else:
# return ''
from queue import Queue
es_queue = Queue()
def es_log():
pass
class App(cmd2.Cmd):
prompt = "(Rush) "
intro = "Type 'help' to explore commands"
def __init__(self):
cmd2.Cmd.__init__(self, allow_cli_args=False, persistent_history_file=os.path.join(APP_DIR, 'rush_history'))
# To hide commands from displaying in the help menu, add their function name to
# the exclude_from_help list
# self.hidden_commands.append('py')
# To remove built-in commands entirely, delete their "do_*" function from the
# cmd2.Cmd class
del cmd2.Cmd.do_alias
del cmd2.Cmd.do_edit
del cmd2.Cmd.do_macro
del cmd2.Cmd.do_py
del cmd2.Cmd.do_run_pyscript
del cmd2.Cmd.do_run_script
# del cmd2.Cmd.do_set
del cmd2.Cmd.do_shell
del cmd2.Cmd.do_shortcuts
if DEBUG:
self.poutput(f'on main thread: {threading.current_thread() is threading.main_thread()} ({threading.current_thread()})')
self.stop_task_consumer()
if DEBUG:
self.poutput('set up task db')
c = db_conn.cursor()
c.execute('''DROP TABLE IF EXISTS tasks;''')
c.execute('''CREATE TABLE IF NOT EXISTS tasks2(
id varchar(32) primary key not null,
url text,
profile text,
proxy text,
size text,
state text,
status text,
keywords text,
status_level short);
''')
c.execute('''CREATE INDEX IF NOT EXISTS tasks2_proxy_state ON tasks2(proxy, state)''')
c.execute('''CREATE TABLE IF NOT EXISTS proxy(
url varchar(256) primary key not null
);''')
c.execute('''CREATE TABLE IF NOT EXISTS profile(
name varchar(256) primary key not null,
blob text
);''')
c.execute('''UPDATE tasks2 SET state = 'Stopped';''')
c.execute('PRAGMA case_sensitive_like=OFF;')
# c.close()
if DEBUG:
self.poutput('commit')
db_conn.commit()
if DEBUG:
self.poutput('alter table')
#mig1
try:
c = db_conn.cursor()
c.execute('''ALTER TABLE tasks2 ADD proxy_distribution int''');
c.execute('''UPDATE tasks2 SET proxy_distribution=? WHERE length(proxy) == 0 or proxy is null;''', (ProxyDistribution.RANDOM.value,));
db_conn.commit()
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
#mig2
try:
c = db_conn.cursor()
c.execute('''ALTER TABLE proxy ADD pgroup varchar(256);''');
c.execute('''CREATE INDEX IF NOT EXISTS proxy_pgroup ON proxy(pgroup);''')
c.execute('''UPDATE proxy SET pgroup='default' WHERE pgroup is null OR length(pgroup) = 0;''');
db_conn.commit()
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
try:
c = db_conn.cursor()
c.execute('''UPDATE proxy SET pgroup='default' WHERE pgroup is null OR length(pgroup) = 0;''');
except Exception:
if DEBUG:
traceback.print_exc()
#mig3
try:
c = db_conn.cursor()
c.execute('''ALTER TABLE tasks2 ADD proxy_group varchar(256);''');
db_conn.commit()
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
c = db_conn.cursor()
c.execute('''UPDATE tasks2 SET proxy_group='default' WHERE proxy_group is null OR length(proxy_group) = 0;''');
db_conn.commit()
#mig4
try:
c = db_conn.cursor()
c.execute('''PRAGMA table_info(proxy);''');
row = row_to_dict(c, c.fetchone())
if row['name'] != 'id':
c.execute('''ALTER TABLE proxy RENAME TO proxybak;''');
c.execute('''CREATE TABLE IF NOT EXISTS proxy(
id INTEGER PRIMARY KEY,
url varchar(256) not null,
pgroup varchar(256),
UNIQUE(pgroup,url)
);''')
c.execute('''INSERT INTO proxy (url,pgroup) SELECT url, pgroup from proxybak;''')
db_conn.commit()
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
#mig5
c = db_conn.cursor()
c.execute('''CREATE INDEX IF NOT EXISTS proxy_pgroup ON proxy(pgroup)''')
db_conn.commit()
# mig6
try:
c = db_conn.cursor()
c.execute('''ALTER TABLE tasks2 ADD profile_in_use text;''');
db_conn.commit()
c = db_conn.cursor()
c.execute('''SELECT id,profile FROM tasks2;''')
for tid, profile in c.fetchall():
if profile and profile[0] == '{':
try:
pname = json.loads(profile)['Name']
c.execute('''UPDATE tasks2 SET profile_in_use=? WHERE id = ?''', (pname, tid))
except Exception:
if DEBUG:
traceback.print_exc()
pass
db_conn.commit()
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
c = db_conn.cursor()
c.execute('''CREATE INDEX IF NOT EXISTS tasks2_prof_state ON tasks2(profile_in_use, state)''')
c.execute('''CREATE INDEX IF NOT EXISTS tasks2_state_url_prof ON tasks2(state, url, profile_in_use, profile)''')
db_conn.commit()
#mig7
try:
c = db_conn.cursor()
c.execute('''ALTER TABLE tasks2 ADD delay int;''')
db_conn.commit()
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
#mig8
c = db_conn.cursor()
c.execute('''CREATE INDEX IF NOT EXISTS tasks2_state_url_prof_pgroup ON tasks2(state, url, profile_in_use, profile, proxy_group)''')
# c.execute('''DROP INDEX tasks2_state_url_prof ON tasks2(state, url, profile_in_use, profile, proxy_group)''')
db_conn.commit()
#mig9
c = db_conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS vault(
key varchar(256) primary key not null,
secret varchar(256)
);''')
db_conn.commit()
#mig10
#mig7
try:
c = db_conn.cursor()
c.execute('''ALTER TABLE tasks2 ADD modified int;''')
db_conn.commit()
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
if DEBUG:
self.poutput('import json')
self.success_log = []
try:
with open(os.path.join(APP_DIR, 'success.json')) as f:
self.success_log = json.load(f)
except FileNotFoundError:
pass
except json.decoder.JSONDecodeError:
pass
try:
with open(os.path.join(APP_DIR, 'profiles.json')) as f:
for p in json.load(f):
try:
c = db_conn.cursor()
c.execute("INSERT INTO profile (name, blob) VALUES (?, ?)", (p['Name'],json.dumps(p)))
db_conn.commit()
except sqlite3.IntegrityError:
pass
os.unlink(os.path.join(APP_DIR, 'profiles.json'))
except FileNotFoundError:
pass
except json.decoder.JSONDecodeError:
os.unlink(os.path.join(APP_DIR, 'profiles.json'))
if DEBUG:
self.poutput('import proxies')
try:
with open(os.path.join(APP_DIR, 'proxies.json')) as f:
for p in json.load(f):
try:
c = db_conn.cursor()
c.execute("INSERT INTO proxy (url) VALUES (?)", (p,))
db_conn.commit()
except sqlite3.IntegrityError:
pass
os.unlink(os.path.join(APP_DIR, 'proxies.json'))
except FileNotFoundError:
pass
except json.decoder.JSONDecodeError:
os.unlink(os.path.join(APP_DIR, 'proxies.json'))
self.key = ''
try:
with open(os.path.join(APP_DIR, 'key')) as f:
self.key = f.read()
except FileNotFoundError:
pass
if not self.key:
self.pwarning('UNACTIVATED - activate with `key activate`')
self.litport_rotations = []
self.started_task_manager = False
try:
self.task_socket, self.task_socket_init_evt = get_task_pub_socket()
if os.getenv('NOCONSUMER') != '1':
self.start_task_consumer()
except Exception:
if DEBUG:
traceback.print_exc()
self.pwarning('Warning: Read-Only Instance (Another Instance Active On This Computer)')
# if os.name == 'posix':
# subprocess.call("ps aux | grep firef | grep RushAIO | awk '{print $2}' | xargs kill", shell=True)
# self.poutput('Launching harvesters...')
# from multiprocessing import Process
# def handler():
# pass
# self.rcfarm = Process(target=start_rcfarm)
# self.rcfarm.start()
# signal.signal(signal.SIGINT, original_sigint_handler)
# signal.signal(signal.SIGTERM, handler)
# with
# pid = os.fork()
# if pid == 0:
# if os.getenv('RCDBG') == '1':
# f = open('/Users/aka/drive/ysfc/cli/debug.log', 'a+')
# else:
# f = open(os.devnull, 'w')
# sys.stdout = f