-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
3707 lines (3111 loc) · 155 KB
/
main.py
File metadata and controls
3707 lines (3111 loc) · 155 KB
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
__version__="1.964"
__author__="Searinox Navras"
"""
INIT
"""
import base64
import time
import datetime
import json
import threading
import sys
import os
import shutil
import ssl
import urllib3
import ctypes
import win32con
import win32process
from PyQt5.QtCore import (PYQT_VERSION_STR,QObject,pyqtSignal,QByteArray,Qt,QEvent,QTimer,QCoreApplication,qInstallMessageHandler)
from PyQt5.QtWidgets import (QApplication,QLabel,QListView,QWidget,QSystemTrayIcon,QMenu,QLineEdit,QMainWindow,QFrame,QAbstractItemView,QGroupBox)
from PyQt5.QtGui import (QIcon,QImage,QPixmap,QFont,QColor,QStandardItemModel,QStandardItem,QCursor,QKeySequence)
def Get_B64_Resource(input_path):
import resources_base64
return resources_base64.Get_Resource(input_path)
PYQT5_MAX_SUPPORTED_COMPILE_VERSION="5.12.2"
MAX_BOT_USERS_BY_CPU_ARCHITECTURE={"32":36,"64":100}
TELEGRAM_API_REQUEST_TIMEOUT_SECONDS=4
TELEGRAM_API_MAX_GLOBAL_IMS=30
TELEGRAM_API_MAX_GLOBAL_TIME_INTERVAL_SECONDS=1
TELEGRAM_API_UPLOAD_TIMEOUT_SECONDS=60*60
TELEGRAM_API_DOWNLOAD_CHUNK_BYTES=256*256
TELEGRAM_API_MAX_UPLOAD_ALLOWED_FILESIZE_BYTES=1024*1024*50
TELEGRAM_API_MAX_DOWNLOAD_ALLOWED_FILESIZE_BYTES=1024*1024*20
TELEGRAM_API_MAX_IM_SIZE_BYTES=4096
BOT_MESSAGE_RELEVANCE_TIMEOUT_SECONDS=30
BOT_LOCK_PASSWORD_CHARACTERS_MIN=4
BOT_LOCK_PASSWORD_CHARACTERS_MAX=32
WEB_REQUEST_CONNECT_TIMEOUT_SECONDS=5
MAX_7ZIP_TASKS_PER_USER=3
UI_COMMAND_HISTORY_MAX=50
UI_OUTPUT_ENTRIES_MAX=5000
MAINTHREAD_HEARTBEAT_SECONDS=0.1
PENDING_ACTIVITY_HEARTBEAT_SECONDS=0.05
MAINTHREAD_IDLE_PRIORITY_CHECK_SECONDS=60
COMMAND_CHECK_INTERVAL_ACTIVE_SECONDS=0.18
COMMAND_CHECK_INTERVAL_MINIMIZED_SECONDS=0.4
SERVER_TIME_RESYNC_INTERVAL_SECONDS=60*60*8
BOT_LISTENER_THREAD_HEARTBEAT_SECONDS=0.8
FILE_READ_ATTEMPTS_MAX=5
FILE_READ_ATTEMPT_FAIL_RETRY_DELAY_SECONDS=0.25
USER_MESSAGE_HANDLER_THREAD_HEARTBEAT_SECONDS=0.1
USER_MESSAGE_HANDLER_SENDMSG_WAIT_POLLING_SECONDS=0.1
UI_CLIPBOARD_COPY_TIMEOUT_SECONDS=1
UI_CLIPBOARD_COPY_MAX_REPEAT_INTERVAL_SECONDS=0.1
TASKS_7ZIP_THREAD_HEARTBEAT_SECONDS=0.2
TASKS_7ZIP_UPDATE_INTERVAL_SECONDS=1.25
TASKS_7ZIP_DELETE_TIMEOUT_SECONDS=1.5
UI_LOG_UPDATE_INTERVAL_MINIMUM_SECONDS=0.055
UI_SCALE_MODIFIER=1.125
FONTS={"<reference_point_size>":8,
"general":{"type":"Monospace","scale":1,"properties":[]},
"status":{"type":"Arial","scale":1,"properties":["bold"]},
"log":{"type":"Consolas","scale":1,"properties":["bold"]}}
COLOR_SCHEME={"window_text":"000000",
"window_background":"FFFFF0",
"selection_text":"FFFFF0",
"selection_background":"3B3BFF",
"background_IO":"000000",
"background_IO_disabled":"3D3D3D",
"input_text":"00FF00",
"scrollbar_text":"000000",
"scrollbar_background":"CFCFA4",
"scrollarea_background":"E8E8BB",
"status_username":"0000B0",
"status_ok":"009000",
"status_warn":"907F00",
"status_error":"903030",
"output_border":"282828",
"output":{"<DEFAULT>":"FFFFFF",
"MAINTHRD":"A0FFFF",
"BOTLSTNR":"FFA0FF",
"MSGHNDLR":"FFFFA0",
"7ZTSKHND":"FFC85A",
"UCONSOLE":"A0FFA0"}}
STARTUP_MESSAGE_ADDITIONAL_TEXT="COMMAND LINE:\n"+\
"/minimized: starts the application minimized to system tray\n"+\
"/stdout: output log to stdout in addition to window"
"""
DEFS
"""
GetTickCount64=ctypes.windll.kernel32.GetTickCount64
GetTickCount64.restype=ctypes.c_uint64
GetTickCount64.argtypes=()
def Versions_Str_Equal_Or_Less(version_expected,version_actual):
version_compliant=False
compared_versions=[]
for compared_version in [version_expected,version_actual]:
compared_versions+=[[int(number.strip()) for number in compared_version.split(".")]]
if compared_versions[1][0]<=compared_versions[0][0]:
if compared_versions[1][0]<compared_versions[0][0]:
version_compliant=True
elif compared_versions[1][1]<=compared_versions[0][1]:
if compared_versions[1][1]<compared_versions[0][1]:
version_compliant=True
elif compared_versions[1][2]<=compared_versions[0][2]:
version_compliant=True
return version_compliant
def Get_Runtime_Environment():
retval={"working_dir":"","running_from_source":False,"arguments":[]}
sys_exe=sys.executable
retval["arguments"]=sys.argv
retval["working_dir"]=os.path.realpath(os.path.dirname(sys_exe))
retval["system32"]=os.path.join(os.environ["WINDIR"],"System32")
if os.path.basename(sys_exe).lower()=="python.exe":
if len(retval["arguments"])>0:
if retval["arguments"][0].replace("\"","").lower().strip().endswith(".py"):
retval["working_dir"]=os.path.realpath(os.path.dirname(retval["arguments"][0]))
retval["arguments"]=retval["arguments"][1:]
retval["running_from_source"]=True
return retval
def Make_TLS_Connection_Pool(input_allowed_TLS_algorithms):
ssl_cert_context=ssl.create_default_context()
ssl_cert_context.check_hostname=True
ssl_cert_context.set_ciphers(input_allowed_TLS_algorithms)
ssl_cert_context.verify_mode=ssl.CERT_REQUIRED
ssl_cert_context.options|=ssl.OP_NO_SSLv2
ssl_cert_context.options|=ssl.OP_NO_SSLv3
ssl_cert_context.options|=ssl.OP_NO_TLSv1
ssl_cert_context.options|=ssl.OP_NO_TLSv1_1
return urllib3.PoolManager(cert_reqs="CERT_REQUIRED",ssl_context=ssl_cert_context)
def terminate_with_backslash(input_string):
if input_string.endswith("\\")==False:
return f"{input_string}\\"
return input_string
def sanitize_path(input_path):
for bad_pattern in ["\\\\","\\.\\","\\.\\","?","*","|","<",">","\""]:
if bad_pattern in input_path:
return "<BAD PATH>"
if len(input_path)-1>len(input_path.replace(":","")):
return "<BAD PATH>"
return input_path
def OS_Uptime_Seconds():
return GetTickCount64()/1000.0
def readable_size(input_size):
if input_size<1024:
return f"{str(input_size)} Bytes"
if input_size<1024**2:
return f"{str(round(input_size/1024.0,2))} KB"
if input_size<1024**3:
return f"{str(round(input_size/1024.0**2,2))} MB"
return f"{str(round(input_size/1024.0**3,2))} GB"
"""
OBJS
"""
class ShellProcess(object):
def __init__(self,input_path_system32,input_command):
result=win32process.CreateProcess(None,f"\"{input_path_system32}cmd.exe\" /c \"{input_command} \"",None,None,0,win32process.CREATE_NO_WINDOW|win32process.CREATE_UNICODE_ENVIRONMENT,None,None,win32process.STARTUPINFO())
if result:
self.process_handle=result[0]
self.process_ID=result[2]
return
def IS_RUNNING(self):
return win32process.GetExitCodeProcess(self.process_handle)==win32con.STILL_ACTIVE
def PID(self):
return self.process_ID
def WAIT(self):
global PENDING_ACTIVITY_HEARTBEAT_SECONDS
while self.IS_RUNNING()==True:
time.sleep(PENDING_ACTIVITY_HEARTBEAT_SECONDS)
return
class Logger(object):
def __init__(self,input_path_system32,input_log_path=""):
self.logging_path=input_log_path
self.log_file_handle=None
self.log_lock=threading.Lock()
self.output_stdout=threading.Event()
self.output_stdout.clear()
self.active_signaller=None
if self.logging_path!="":
ShellProcess(input_path_system32,f"\"{input_path_system32}compact.exe\" /a /c \"{input_log_path}\"").WAIT()
self.is_active=threading.Event()
self.is_active.clear()
return
def ACTIVATE(self):
try:
self.log_file_handle=open(self.logging_path,"a")
except:
try:
self.log_file_handle.close()
except:
pass
self.log_file_handle=None
self.is_active.set()
if self.log_file_handle is None:
self.LOG("WARNING: Default target log file could not be written to. Logging will not save to file.")
return
def LOG_TO_STDOUT(self,input_state):
if input_state==True:
self.output_stdout.set()
else:
self.output_stdout.clear()
return
def DEACTIVATE(self):
self.log_lock.acquire()
self.is_active.clear()
try:
if self.log_file_handle is not None:
try:
self.log_file_handle.close()
except:
pass
self.log_file_handle=None
except:
pass
self.log_lock.release()
return
def ATTACH_SIGNALLER(self,input_signaller):
self.log_lock.acquire()
self.active_signaller=input_signaller
self.log_lock.release()
return
def DETACH_SIGNALLER(self):
self.log_lock.acquire()
self.active_signaller=None
self.log_lock.release()
return
def LOG(self,source,input_data=""):
if self.is_active.is_set()==False:
return
if input_data!="":
source_literal=str(source)
input_literal=str(input_data)
else:
source_literal=""
input_literal=str(source)
source=""
if source!="":
source_literal=f" [{source_literal}] "
else:
source_literal=" "
msg=f"{str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))}{source_literal}{input_literal}\n"
self.log_lock.acquire()
if self.is_active.is_set()==False:
self.log_lock.release()
return
if self.log_file_handle is not None:
try:
self.log_file_handle.write(msg)
self.log_file_handle.flush()
except:
pass
if self.output_stdout.is_set()==True:
try:
sys.stdout.write(msg)
except:
pass
if self.active_signaller is not None:
try:
self.active_signaller.SEND_EVENT("logger_new_entry",msg)
except:
pass
self.log_lock.release()
return
class Time_Provider(object):
def __init__(self,input_allowed_TLS_algorithms,time_API_instances):
global WEB_REQUEST_CONNECT_TIMEOUT_SECONDS
self.request_pool=Make_TLS_Connection_Pool(input_allowed_TLS_algorithms)
self.time_API_instances=time_API_instances
self.request_timeout=urllib3.Timeout(connect=WEB_REQUEST_CONNECT_TIMEOUT_SECONDS,read=WEB_REQUEST_CONNECT_TIMEOUT_SECONDS)
self.origin_time=datetime.datetime(1970,1,1)
self.lock_time_delta=threading.Lock()
self.lock_subscribers=threading.Lock()
self.lock_sync=threading.Lock()
self.time_delta=0
self.signal_subscribers=[]
return
def ADD_SUBSCRIBER(self,input_subscriber):
self.lock_subscribers.acquire()
if input_subscriber not in self.signal_subscribers:
self.signal_subscribers+=[input_subscriber]
self.lock_subscribers.release()
return
def REMOVE_SUBSCRIBER(self,input_subscriber):
self.lock_subscribers.acquire()
for i in range(len(self.signal_subscribers)):
if self.signal_subscribers[i]==input_subscriber:
del self.signal_subscribers[i]
break
self.lock_subscribers.release()
return
def CURRENT_SERVER_TIME(self):
self.lock_time_delta.acquire()
get_delta=self.time_delta
self.lock_time_delta.release()
return round(OS_Uptime_Seconds()+get_delta,3)
def SYNC(self):
time_difference=0
self.lock_sync.acquire()
success=self.update_server_time_from_internet()
if success==True:
time_difference=self.current_local_machine_time_delta_str()
self.lock_subscribers.acquire()
for subscriber in self.signal_subscribers:
subscriber.SEND_EVENT("report_timesync_clock_bias",time_difference)
self.lock_subscribers.release()
self.lock_sync.release()
return {"success":success,"time_difference":time_difference}
def retrieve_current_UTC_internet_time(self):
time_obtained=False
for time_API in self.time_API_instances:
try:
response=self.request_pool.request(method="GET",url=time_API["url"],preload_content=True,chunked=False,timeout=self.request_timeout)
if response.status!=200:
continue
timestr=str(response.data,"utf8")
quot1=timestr.find(time_API["start"])
quot1+=len(time_API["start"])
quot2=quot1+timestr[quot1:].find(time_API["end"])
quot2+=len(time_API["end"])
timestr=timestr[quot1:quot2-1].strip()
decpoint=timestr.find(".")
if decpoint>-1:
declen=len(timestr)-decpoint-1
if declen>4:
timestr=timestr[:-declen+4]
else:
timestr=f"{timestr}.0"
time_obtained=True
break
except:
pass
if time_obtained==False:
raise Exception("Could not get time.")
timestr.replace(" ","T")
current_time=datetime.datetime.strptime(timestr,"%Y-%m-%dT%H:%M:%S.%f")
return (current_time-self.origin_time).total_seconds()
def update_server_time_from_internet(self):
update_success=False
try:
get_new_delta=self.retrieve_current_UTC_internet_time()-OS_Uptime_Seconds()
update_success=True
except:
pass
if update_success==True:
self.lock_time_delta.acquire()
self.time_delta=get_new_delta
self.lock_time_delta.release()
return update_success
def current_local_machine_time_delta_str(self):
time_difference=round(float((datetime.datetime.utcnow()-self.origin_time).total_seconds())-self.CURRENT_SERVER_TIME(),3)
if time_difference>0:
retval=f"+{str(time_difference)}"
else:
retval=str(time_difference)
return retval
class Task_Handler_7ZIP(object):
def __init__(self,input_path_system32,input_path_7zip,input_7zip_binary_base64,input_max_per_user,input_logger=None):
global TASKS_7ZIP_DELETE_TIMEOUT_SECONDS
self.path_system32=input_path_system32
self.instances_7zip=[]
self.lock_instances_7zip=threading.Lock()
self.lock_list_end_tasks=threading.Lock()
self.active_logger=input_logger
self.working_thread=threading.Thread(target=self.work_loop)
self.working_thread.daemon=True
self.binary_7zip_read=None
self.has_quit=threading.Event()
self.has_quit.clear()
self.request_exit=threading.Event()
self.request_exit.clear()
self.max_tasks_per_user=input_max_per_user
self.list_end_tasks_PIDs=[]
self.list_end_tasks_users=[]
self.task_delete_timeout_milliseconds=TASKS_7ZIP_DELETE_TIMEOUT_SECONDS*1000
self.path_7zip_bin=os.path.join(input_path_7zip,"7z.exe")
write_7z_binary=None
try:
write_7z_binary=open(self.path_7zip_bin,"w+b")
write_7z_binary.write(base64.decodebytes(input_7zip_binary_base64))
self.binary_7zip_read=open(self.path_7zip_bin,"rb")
write_7z_binary.close()
except:
for close_binary in [write_7z_binary,self.binary_7z_read]:
if close_binary is not None:
try:
close_binary.close()
except:
pass
write_7z_binary=None
self.binary_7zip_read=None
raise Exception("The 7-ZIP binary could not be written. Make sure you have write permissions to the application folder.")
return
def log(self,input_text):
if self.active_logger is not None:
self.active_logger.LOG("7ZTSKHND",input_text)
return
def START(self):
self.working_thread.start()
return
def REQUEST_STOP(self):
self.request_exit.set()
return
def CONCLUDE(self):
global PENDING_ACTIVITY_HEARTBEAT_SECONDS
while self.IS_RUNNING()==True:
time.sleep(PENDING_ACTIVITY_HEARTBEAT_SECONDS)
self.working_thread.join()
try:
self.binary_7zip_read.close()
except:
self.binary_7zip_read=None
return
def IS_RUNNING(self):
return self.has_quit.is_set()==False
def GET_MAX_TASKS_PER_USER(self):
return self.max_tasks_per_user
def NEW_TASK(self,target_path,originating_user):
if self.request_exit.is_set()==True:
return {"result":"ERROR","full_target":""}
if os.path.isfile(target_path)==True:
folder_path=target_path[:target_path.rfind("\\")+1]
else:
folder_path=target_path[:target_path[:-1].rfind("\\")+1]
if folder_path=="":
folder_path=target_path[:target_path[:-1].rfind(":")+1]
archive_filename=target_path[target_path.rfind("\\")+1:]
if archive_filename=="":
archive_filename=target_path[target_path[:-1].rfind("\\")+1:]
if archive_filename[-1].endswith("\\")==True:
archive_filename=archive_filename[:-1]
archive_filename_path=archive_filename
archive_filename=archive_filename.replace(":","")
zip_command=f"\"{self.path_7zip_bin}\" a -mx9 -t7z \"{archive_filename}.7z.TMP\" \"{archive_filename_path}\""
folder_command=f"cd/ & cd /d \"{folder_path}\""
rename_command=f"ren \"{archive_filename}.7z.TMP\" \"{archive_filename}.7z\""
prompt_commands=f"{folder_command} & {zip_command} & {rename_command}"
folder_path=terminate_with_backslash(folder_path)
full_target=folder_path+archive_filename.lower()
if os.path.exists(f"{full_target}.7z")==False:
self.lock_instances_7zip.acquire()
user_task_total=0
for instance in self.instances_7zip:
if instance["user"]==originating_user:
user_task_total+=1
if user_task_total==self.max_tasks_per_user:
self.lock_instances_7zip.release()
return {"result":"MAXREACHED","full_target":""}
if self.request_exit.is_set()==True:
self.lock_instances_7zip.release()
return {"result":"ERROR","full_target":""}
try:
new_process=ShellProcess(self.path_system32,prompt_commands)
self.instances_7zip+=[{"process":new_process,"temp_file":f"{full_target}.7z.TMP","user":originating_user,"new":True}]
self.lock_instances_7zip.release()
return {"result":"CREATED","full_target":full_target}
except:
self.lock_instances_7zip.release()
return {"result":"ERROR","full_target":""}
else:
return {"result":"EXISTS","full_target":full_target}
def GET_TASKS(self):
retval=[]
self.lock_instances_7zip.acquire()
for instance in self.instances_7zip:
target_location=instance["temp_file"]
if target_location.lower().endswith(".7z.tmp"):
target_location=target_location[:-len(".7z.tmp")]
retval+=[{"pid":instance["process"].PID(),"target":target_location,"user":instance["user"]}]
self.lock_instances_7zip.release()
return retval
def END_TASKS(self,input_users,input_PIDs=[]):
self.lock_list_end_tasks.acquire()
self.list_end_tasks_users+=input_users
self.list_end_tasks_PIDs+=input_PIDs
self.lock_list_end_tasks.release()
return
def work_loop(self):
global TASKS_7ZIP_THREAD_HEARTBEAT_SECONDS
global TASKS_7ZIP_UPDATE_INTERVAL_SECONDS
get_end_task_list_PIDs=[]
get_end_task_list_users=[]
update_interval_milliseconds=TASKS_7ZIP_UPDATE_INTERVAL_SECONDS*1000
self.log("7-ZIP Task Handler started.")
last_update=GetTickCount64()-update_interval_milliseconds
while self.request_exit.is_set()==False:
time.sleep(TASKS_7ZIP_THREAD_HEARTBEAT_SECONDS)
if GetTickCount64()-last_update>=update_interval_milliseconds:
self.update_7zip_tasks()
last_update=GetTickCount64()
self.lock_list_end_tasks.acquire()
if len(self.list_end_tasks_PIDs)+len(self.list_end_tasks_users)>0:
get_end_task_list_PIDs=self.list_end_tasks_PIDs[:]
self.list_end_tasks_PIDs=[]
get_end_task_list_users=self.list_end_tasks_users[:]
self.list_end_tasks_users=[]
self.lock_list_end_tasks.release()
if len(get_end_task_list_PIDs)+len(get_end_task_list_users)>0:
self.end_7zip_tasks(get_end_task_list_users,get_end_task_list_PIDs)
get_end_task_list_PIDs=[]
get_end_task_list_users=[]
self.update_7zip_tasks()
self.end_7zip_tasks(["*"])
self.log("7-ZIP Task Handler has exited.")
self.has_quit.set()
return
def update_7zip_tasks(self):
self.lock_instances_7zip.acquire()
for i in reversed(range(len(self.instances_7zip))):
if self.instances_7zip[i]["new"]==True:
self.instances_7zip[i]["new"]=False
self.log(f"Task with PID={str(self.instances_7zip[i]['process'].PID())} TEMP=\"{self.instances_7zip[i]['temp_file']}\" has been added.")
still_running=True
try:
still_running=self.instances_7zip[i]["process"].IS_RUNNING()
except:
pass
if still_running==False:
self.log(f"Task with PID={str(self.instances_7zip[i]['process'].PID())} TEMP=\"{self.instances_7zip[i]['temp_file']}\" has finished.")
del self.instances_7zip[i]
self.lock_instances_7zip.release()
return
def end_7zip_tasks(self,list_users,list_PIDs=[]):
global PENDING_ACTIVITY_HEARTBEAT_SECONDS
taskkill_list=[]
terminate_all=False
terminated_total=0
if len(list_users)==1:
if list_users[0]=="*":
terminate_all=True
self.lock_instances_7zip.acquire()
for i in reversed(range(len(self.instances_7zip))):
get_PID=self.instances_7zip[i]["process"].PID()
get_user=self.instances_7zip[i]["user"].lower()
terminate=False
if terminate_all==True:
terminate=True
elif any(username.lower()==get_user for username in list_users):
terminate=True
else:
for i in range(len(list_PIDs)):
if list_PIDs[i]==get_PID:
terminate=True
del list_PIDs[i]
break
if terminate==True:
self.log(f"Terminating ongoing 7-ZIP batch with PID={str(get_PID)} and temporary file \"{self.instances_7zip[i]['temp_file'].lower()}\".")
taskkill_list+=[{"process":ShellProcess(self.path_system32,f"\"{self.path_system32}taskkill.exe\" /f /t /pid {str(get_PID)}"),"file":self.instances_7zip[i]["temp_file"]}]
del self.instances_7zip[i]
terminated_total+=1
self.lock_instances_7zip.release()
for taskkill in taskkill_list:
taskkill["process"].WAIT()
for taskkill in taskkill_list:
delete_attempt_made=False
start_time=GetTickCount64()
while (os.path.isfile(taskkill["file"])==True and GetTickCount64()-start_time<self.task_delete_timeout_milliseconds) or delete_attempt_made==False:
try:
delete_attempt_made=True
os.remove(taskkill["file"])
except:
time.sleep(PENDING_ACTIVITY_HEARTBEAT_SECONDS)
if terminated_total==0:
self.log("No 7-ZIP tasks were terminated.")
return
class Telegram_Message_Rate_Limiter(object):
def __init__(self,input_max_messages,input_time_interval_seconds):
self.timer_list=[]
self.max_messages=input_max_messages
self.time_interval_milliseconds=input_time_interval_seconds*1000
self.request_exit=threading.Event()
self.request_exit.clear()
self.lock_timerlist=threading.Lock()
return
def timer_list_size_and_cleanup(self):
for i in reversed(range(len(self.timer_list))):
if self.timer_list[i]<GetTickCount64()-self.time_interval_milliseconds:
del self.timer_list[i]
else:
break
return len(self.timer_list)
def WAIT_FOR_CLEAR_AND_SEND(self):
global PENDING_ACTIVITY_HEARTBEAT_SECONDS
if self.request_exit.is_set()==True:
return
send_ok=False
while send_ok==False and self.request_exit.is_set()==False:
self.lock_timerlist.acquire()
if self.timer_list_size_and_cleanup()>=self.max_messages-1:
self.lock_timerlist.release()
time.sleep(PENDING_ACTIVITY_HEARTBEAT_SECONDS/1000)
else:
self.timer_list+=[GetTickCount64()]
self.lock_timerlist.release()
send_ok=True
return
def DEACTIVATE(self):
self.request_exit.set()
return
class Telegram_Bot(object):
def __init__(self,input_token,input_allowed_TLS_algorithms):
global WEB_REQUEST_CONNECT_TIMEOUT_SECONDS
global TELEGRAM_API_REQUEST_TIMEOUT_SECONDS
global TELEGRAM_API_UPLOAD_TIMEOUT_SECONDS
self.request_pool=Make_TLS_Connection_Pool(input_allowed_TLS_algorithms)
self.timeout_web=urllib3.Timeout(connect=WEB_REQUEST_CONNECT_TIMEOUT_SECONDS,read=TELEGRAM_API_REQUEST_TIMEOUT_SECONDS)
self.timeout_download=urllib3.Timeout(connect=WEB_REQUEST_CONNECT_TIMEOUT_SECONDS,read=TELEGRAM_API_REQUEST_TIMEOUT_SECONDS)
self.timeout_upload=urllib3.Timeout(connect=WEB_REQUEST_CONNECT_TIMEOUT_SECONDS,read=TELEGRAM_API_UPLOAD_TIMEOUT_SECONDS)
self.bot_token=input_token
self.is_stopped=threading.Event()
self.is_stopped.clear()
self.active_rate_limiter=None
self.base_web_url=f"https://api.telegram.org/bot{self.bot_token}/"
self.base_file_url=f"https://api.telegram.org/file/bot{self.bot_token}/"
return
def perform_web_request(self,input_method,input_url,input_args):
if self.active_rate_limiter is not None:
if input_method=="POST":
self.active_rate_limiter.WAIT_FOR_CLEAR_AND_SEND()
if self.is_stopped.is_set()==True:
return {"ok":False,"result":None}
response=None
try:
response=self.request_pool.request(method=input_method,fields=input_args,url=input_url,preload_content=True,chunked=False,timeout=self.timeout_web)
response=json.loads(response.data)
except:
pass
if response is not None:
if "ok" in response:
if "description" in response:
return {"ok":response["ok"],"result":response["description"]}
elif "result" in response:
return {"ok":response["ok"],"result":response["result"]}
return {"ok":False,"result":None}
def file_download_get_stream(self,input_id,input_args=None):
if self.is_stopped.is_set()==True:
return None
response=None
try:
response=self.request_pool.request(method="GET",fields=input_args,url=self.base_file_url+input_id,preload_content=False,chunked=False,timeout=self.timeout_download)
except:
pass
if response is not None:
if response.status in [200,201]:
return response
return None
def file_upload_from_handle(self,input_chat_id,input_file_handle):
if self.is_stopped.is_set()==True:
return "Bot is stopped."
if self.active_rate_limiter is not None:
self.active_rate_limiter.WAIT_FOR_CLEAR_AND_SEND()
if self.is_stopped.is_set()==True:
return "Bot is stopped."
try:
input_file_handle.seek(0,2)
file_size=input_file_handle.tell()
if file_size==0:
return "Empty file."
if file_size>TELEGRAM_API_MAX_UPLOAD_ALLOWED_FILESIZE_BYTES:
return "File too big."
input_file_handle.seek(0,0)
file_name=os.path.basename(input_file_handle.name)
response=self.request_pool.request(method="POST",fields={"chat_id":input_chat_id,"document":(file_name,input_file_handle.read())},url=f"{self.base_web_url}sendDocument",preload_content=True,chunked=True,timeout=self.timeout_upload)
if response is None or response.status not in [200,201]:
return "Upload error."
except:
return "Upload error."
return ""
def Get_Bot_Info(self):
if self.is_stopped.is_set()==True:
raise Exception("Bot is stopped.")
response=self.perform_web_request("GET",f"{self.base_web_url}getMe",None)
if response["ok"]==True:
return response["result"]
else:
if response["result"] is not None:
if type(response["result"])==str:
if response["result"].lower().strip()=="not found":
raise Exception("Invalid token.")
raise Exception("Response error.")
def Get_Messages(self,input_id):
if self.is_stopped.is_set()==True:
raise Exception("Bot is stopped.")
response=self.perform_web_request("GET",f"{self.base_web_url}getUpdates",{"offset":input_id,"allowed_updates":["message"]})
if response["ok"]==True:
return response["result"]
raise Exception("Response error.")
def Send_Message(self,input_chat_id,input_message):
if self.is_stopped.is_set()==True:
raise Exception("Bot is stopped.")
response=self.perform_web_request("POST",f"{self.base_web_url}sendMessage",{"chat_id":input_chat_id,"text":input_message})
if response["ok"]==True:
return response["result"]
raise Exception("Response error.")
def Send_File(self,input_chat_id,input_file_path):
global FILE_READ_ATTEMPT_FAIL_RETRY_DELAY_SECONDS
global FILE_READ_ATTEMPTS_MAX
if self.is_stopped.is_set()==True:
return "Bot is stopped."
file_open_attempts=0
file_handle=None
while file_handle is None and file_open_attempts<FILE_READ_ATTEMPTS_MAX and self.is_stopped.is_set()==False:
try:
file_handle=open(input_file_path,"rb",buffering=0)
except:
file_handle=None
file_open_attempts+=1
if file_open_attempts<FILE_READ_ATTEMPTS_MAX and self.is_stopped.is_set()==False:
time.sleep(FILE_READ_ATTEMPT_FAIL_RETRY_DELAY_SECONDS)
if self.is_stopped.is_set()==True or file_handle is None:
return "Access error."
result=self.file_upload_from_handle(input_chat_id,file_handle)
try:
if file_handle is not None:
file_handle.close()
except:
pass
return result
def Get_File_Info(self,input_id):
if self.is_stopped.is_set()==True:
return None
response=self.perform_web_request("GET",f"{self.base_web_url}getFile",{"file_id":input_id})
if response["ok"]==True:
return response["result"]
raise Exception("Response error.")
def Get_File(self,input_id,input_path):
global TELEGRAM_API_DOWNLOAD_CHUNK_BYTES
if self.is_stopped.is_set()==True:
return "Bot is stopped."
if "/" not in input_id and "\\" not in input_id:
try:
input_id=self.Get_File_Info(input_id)["file_path"]
except:
return "Request error."
file_contents=self.file_download_get_stream(input_id)
if file_contents is not None:
file_handle=None
try:
file_handle=open(input_path,"wb")
for chunk in file_contents.stream(TELEGRAM_API_DOWNLOAD_CHUNK_BYTES):
if self.is_stopped.is_set()==True:
raise Exception("Bot is stopped.")
file_handle.write(chunk)
file_handle.close()
return ""
except:
if file_handle is not None:
try:
file_handle.close()
except:
pass
try:
os.remove(input_path)
except:
pass
return "Download error."
else:
return "Response error."
def ATTACH_MESSAGE_RATE_LIMITER(self,input_ratelimiter):
self.active_rate_limiter=input_ratelimiter
return
def DEACTIVATE(self):
self.is_stopped.set()
try:
self.request_pool.clear()
self.request_pool.pools=None
except:
pass
self.request_pool=None
return
class Bot_Listener(object):
def __init__(self,input_token,input_allowed_TLS_algorithms,username_list,input_timeprovider,input_signaller,input_logger=None):
self.active_logger=input_logger
self.request_exit=threading.Event()
self.request_exit.clear()
self.has_quit=threading.Event()
self.has_quit.clear()
self.is_ready=threading.Event()
self.is_ready.clear()
self.last_ID_checked=-1
self.start_time=0
self.active_time_provider=input_timeprovider
self.active_UI_signaller=input_signaller
self.working_thread=threading.Thread(target=self.work_loop)
self.working_thread.daemon=True
self.listen_users=username_list
self.name=""
self.messagelist_lock={}
for username in self.listen_users:
self.messagelist_lock[username]=threading.Lock()
self.user_messages={}
for username in self.listen_users:
self.user_messages[username]=[]
self.bot_handle=Telegram_Bot(input_token,input_allowed_TLS_algorithms)
return
def log(self,input_text):
if self.active_logger is not None:
self.active_logger.LOG("BOTLSTNR",input_text)
return
def START(self):
self.working_thread.start()
def REQUEST_STOP(self):
self.bot_handle.DEACTIVATE()
self.request_exit.set()
return
def IS_RUNNING(self):
return self.has_quit.is_set()==False
def CONCLUDE(self):
global PENDING_ACTIVITY_HEARTBEAT_SECONDS
while self.IS_RUNNING()==True:
time.sleep(PENDING_ACTIVITY_HEARTBEAT_SECONDS)
self.working_thread.join()
return
def IS_READY(self):
return self.is_ready.is_set()==True
def work_loop(self):
bot_bind_ok=False
activation_fail_announce=False
last_check_status=False