-
Notifications
You must be signed in to change notification settings - Fork 1
/
sharexyz.py
executable file
·1801 lines (1491 loc) · 64.2 KB
/
sharexyz.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
# must be at the top
try:
import env
finally:
pass
import base64
import concurrent
import datetime
import glob
import io
import json
import mimetypes
import os
import secrets
import shutil
import string
import subprocess
import threading
import time
import tkinter as tk
import traceback
import webbrowser
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from itertools import islice
from operator import getitem
from typing import (
Callable,
Any,
List,
)
import boto3
import gi
import mss
import mss.tools
import pystray
import requests
from PIL import (
ImageGrab,
ImageTk,
Image,
)
gi.require_version("Gtk", "3.0")
gi.require_version("Keybinder", "3.0")
gi.require_version('Notify', '0.7')
from gi.repository import (
Gtk,
Keybinder,
GdkPixbuf,
Gdk,
Notify,
GObject,
)
from mss import ScreenShotError
from playsound import playsound
from pynput import keyboard
from screeninfo import get_monitors
class File:
VIDEO = ('.m1v', '.mpeg', '.mov', '.qt', '.mpa', '.mpg', '.mpe', '.avi', '.movie', '.mp4', '.mkv')
AUDIO = ('.ra', '.aif', '.aiff', '.aifc', '.wav', '.au', '.snd', '.mp3', '.mp2')
IMAGE = ('.ras', '.xwd', '.bmp', '.jpe', '.jpg', '.jpeg', '.xpm', '.ief', '.pbm', '.tif', '.gif', '.ppm', '.xbm',
'.tiff', '.rgb', '.pgm', '.png', '.pnm')
def __init__(self, file_name: str = '', extension: str = '', path: str = ''):
self._date = ''
self._file_name = file_name
self._path = path
print(f'PATH:"{path}"')
if not file_name:
self._date = datetime.datetime.utcnow().replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc)
self._file_name = str(self._date).split('+')[0] + extension
if self._path:
self._file_name = self._path.split('/')[-1]
if not self._date:
if ":" in self._file_name and not self._path:
self._date = datetime.datetime.strptime(self.clean_name, "%Y-%m-%d %H:%M:%S").replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc)
else:
self._date = datetime.datetime.utcnow().replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc)
self._extension = '.' + self._file_name.split('.')[-1] if '.' in self._file_name else ''
self._type = 'unknown'
if any(video_type in self._extension for video_type in self.VIDEO):
self._type = 'video'
if any(image_type in self._extension for image_type in self.IMAGE):
self._type = 'screenshot'
directory = env.SCREENSHOTS_DIR if self._extension == '.png' else env.VIDEOS_DIR
if not self._path:
self._path = os.path.join(directory, self.file_name)
debug_log(self)
def __str__(self):
return f"file_name={self.file_name}\n"\
f"type={self.type}\n"\
f"extension={self.extension}\n"\
f"file_path={self.file_path}\n"\
f"clean_name={self.clean_name}\n"\
f"date={self.date}\n"
@property
def file_name(self):
return self._file_name
@property
def type(self):
return self._type
@property
def extension(self):
return self._extension
@property
def file_path(self):
return self._path
@property
def clean_name(self):
return self._file_name[:-4].split('+')[0]
@property
def date(self):
return self._date
def log(*args) -> None:
with threading.Lock():
print(f'[{datetime.datetime.utcnow().replace(microsecond=0).time()} UTC] ', *args, flush=True)
with open(f'{os.path.join(env.LOGS_PATH, str(env.LOGS_SESSION))}.txt', 'a+') as output:
print(f'[{datetime.datetime.utcnow().replace(microsecond=0).time()} UTC] ', *args, file=output)
def debug_log(*args) -> None:
with open(f'{os.path.join(env.LOGS_PATH, str(env.LOGS_SESSION))}_DEBUG.txt', 'a+') as output:
print(f'[{datetime.datetime.utcnow().replace(microsecond=0).time()} UTC] ', *args, file=output)
def update_history_file(file: File):
env.HISTORY[file.file_name] = {}
env.HISTORY[file.file_name]['type'] = file.type
env.HISTORY[file.file_name]['date'] = file.date
env.HISTORY[file.file_name]['place'] = 'online'
if not env.UPLOAD_AFTER_TASK:
env.HISTORY[file.file_name]['place'] = 'local'
_generate_cache()
else:
env.ONLINE_HISTORY[file.file_name] = {}
env.ONLINE_HISTORY[file.file_name]['type'] = file.type
env.ONLINE_HISTORY[file.file_name]['date'] = file.date
env.ONLINE_HISTORY[file.file_name]['place'] = 'online'
_order_history()
def get_default_icon_path(dict_data):
if dict_data['type'] == 'unknown':
return os.path.join(env.ICONS_DIR, 'doc.png')
if dict_data['type'] == 'video':
if dict_data['place'] == 'local':
return os.path.join(env.ICONS_DIR, 'offline_video.png')
return os.path.join(env.ICONS_DIR, 'online_video.png')
if dict_data['place'] == 'online':
return os.path.join(env.ICONS_DIR, 'online_image.png')
return os.path.join(env.ICONS_DIR, 'offline_image.png')
def _clear_local_files_not_in_history():
log("Clearing old files")
for dir in [env.SCREENSHOTS_DIR, env.TEMP_PATH, env.VIDEOS_DIR]:
for file in os.listdir(dir):
if file not in env.HISTORY.keys():
os.remove(os.path.join(dir, file))
log("Cleared old files")
_ = ['ffmpeg -i https://s3.eu-central-1.amazonaws.com/cos-dev-attachments/ShareX/notsimon/nkxiAUcnmyvTlCHK.mp4 -ss 00:00:1 -vframes 1 -f image2 /run/media/simonl/Volume/Lib/sharexyz/data/temp/nkxiAUcnmyvTlCHK.png']
_ = ['ffmpeg -i https://s3.eu-central-1.amazonaws.com/cos-dev-attachments/ShareX/notsimon/BtSQwAfPKLjPOAno.mp4 -ss 00:00:01 -vframes 1 /run/media/simonl/Volume/Lib/sharexyz/data/temp/BtSQwAfPKLjPOAno.png']
def _generate_cache():
def get_thumbnail(inpt: str, data) -> List[str]:
if os.path.isfile(temp_file):
os.remove(temp_file)
cmd = ["ffmpeg",
"-i",
inpt,
"-ss",
"00:00:1",
"-vframes",
"1",
"-f",
"image2",
temp_file]
log(cmd)
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
proc.wait(15)
err = proc.stderr.read().decode("utf-8")
out = proc.stdout.read().decode("utf-8")
if 'Output file is empty' in err:
if os.path.isfile(temp_file):
os.remove(temp_file)
cmd.remove('-ss')
cmd.remove('00:00:1')
log(cmd)
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
proc.wait(15)
err = proc.stderr.read().decode("utf-8")
out = proc.stdout.read().decode("utf-8")
if 'does not contain an image sequence pattern or a pattern is invalid' in err:
err = "success:" + temp_file
if 'moov atom not found' in err:
err = "broken video"
data['broken_video'] = True
if 'oes not contain any stream' in err:
err = "broken mimetype"
data['broken_video'] = True
if '403 Forbidden' in err:
err = "403 Forbidden"
data['forbidden'] = True
log("ERR:", err)
log("OUT:", out)
return cmd
log('generate cache')
start = time.time()
_order_history()
for file_name, data in env.ONLINE_HISTORY.items():
if data.get('tried'):
continue
# print("TRIED ONLINE", file_name, data.get('tried'))
data['tried'] = True
# add url entry if there is none
if data['place'] == 'online' and not data.get('url'):
debug_log(f'file={file_name}, Adding url')
data['url'] = env.URL + file_name
# if history entry has a path and the path exists return
if env.ONLINE_HISTORY[file_name].get('icon_path') and os.path.isfile(env.ONLINE_HISTORY[file_name].get('icon_path')):
debug_log(f'file={file_name}, Icon path already exists: ', env.ONLINE_HISTORY[file_name].get('icon_path'))
continue
# create path, should be png always
temp_file = os.path.join(env.TEMP_PATH, file_name[:-4] + '.png')
# if the new path already exists update the history file and return
if os.path.isfile(temp_file):
env.ONLINE_HISTORY[file_name]['icon_path'] = temp_file
debug_log(f'file={file_name}, Temp Icon path already exists: ', temp_file)
continue
if data['type'] == 'unknown':
debug_log(f'file={file_name}, Data type unknown, getting icon path')
env.ONLINE_HISTORY[file_name]['icon_path'] = get_default_icon_path(env.ONLINE_HISTORY[file_name])
continue
if data['type'] == 'video':
debug_log(f'file={file_name}, Data type video, getting icon path')
if data['place'] == 'local':
debug_log(f'file={file_name}, local video')
get_thumbnail(os.path.join(env.VIDEOS_DIR, file_name), data)
if os.path.isfile(temp_file):
env.ONLINE_HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from local video SUCCESS', env.ONLINE_HISTORY[file_name])
else:
env.ONLINE_HISTORY[file_name]['icon_path'] = get_default_icon_path(env.ONLINE_HISTORY[file_name])
debug_log('thumbnail from local video FAILED', env.ONLINE_HISTORY[file_name])
continue
debug_log(f'file={file_name}, online video')
get_thumbnail(data['url'], data)
if os.path.isfile(temp_file):
env.ONLINE_HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from online video SUCCESS', env.ONLINE_HISTORY[file_name])
else:
env.ONLINE_HISTORY[file_name]['icon_path'] = get_default_icon_path(env.ONLINE_HISTORY[file_name])
debug_log('thumbnail from online video FAILED', env.ONLINE_HISTORY[file_name])
continue
if data['place'] == 'online':
debug_log(f'file={file_name}, online screenshot')
try:
img = Image.open(requests.get(data['url'], stream=True).raw)
img.save(temp_file)
debug_log(f'file={file_name}, online screenshot gotten')
except Exception as err:
if 'cannot identify image file' in str(err):
data['broken_screenshot'] = True
else:
traceback.print_exc()
log(f'file={file_name}, url={data["url"]}, online screenshot')
if os.path.isfile(temp_file):
env.ONLINE_HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from online picture SUCCESS', env.ONLINE_HISTORY[file_name])
else:
env.ONLINE_HISTORY[file_name]['icon_path'] = get_default_icon_path(env.ONLINE_HISTORY[file_name])
debug_log('thumbnail from online picture FAILED', env.ONLINE_HISTORY[file_name])
continue
debug_log(f'file={file_name}, local screenshot gotten')
shutil.copy2(os.path.join(env.SCREENSHOTS_DIR, file_name), temp_file)
env.ONLINE_HISTORY[file_name]['icon_path'] = temp_file
if os.path.isfile(temp_file):
env.ONLINE_HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from offline picture SUCCESS', env.ONLINE_HISTORY[file_name])
else:
env.ONLINE_HISTORY[file_name]['icon_path'] = get_default_icon_path(env.ONLINE_HISTORY[file_name])
debug_log('thumbnail from offline picture FAILED', env.ONLINE_HISTORY[file_name])
if not os.path.isfile(env.ONLINE_HISTORY[file_name]['icon_path']):
env.ONLINE_HISTORY[file_name]['icon_path'] = get_default_icon_path(data)
raise Exception("Icon path doesn't exist even though we think it does" + env.ONLINE_HISTORY[file_name])
for file_name, data in env.HISTORY.items():
if data.get('tried'):
continue
data['tried'] = True
# print("TRIED OFFLINE", file_name, data.get('tried'))
# add url entry if there is none
if data['place'] == 'online' and not data.get('url'):
debug_log(f'file={file_name}, Adding url')
data['url'] = env.URL + file_name
# if history entry has a path and the path exists return
if env.HISTORY[file_name].get('icon_path') and os.path.isfile(env.HISTORY[file_name].get('icon_path')):
debug_log(f'file={file_name}, Icon path already exists: ', env.HISTORY[file_name].get('icon_path'))
continue
# create path, should be png always
temp_file = os.path.join(env.TEMP_PATH, file_name[:-4] + '.png')
# if the new path already exists update the history file and return
if os.path.isfile(temp_file):
env.HISTORY[file_name]['icon_path'] = temp_file
debug_log(f'file={file_name}, Temp Icon path already exists: ', temp_file)
continue
if data['type'] == 'unknown':
debug_log(f'file={file_name}, Data type unknown, getting icon path')
env.HISTORY[file_name]['icon_path'] = get_default_icon_path(env.HISTORY[file_name])
continue
if data['type'] == 'video':
debug_log(f'file={file_name}, Data type video, getting icon path')
if data['place'] == 'local':
debug_log(f'file={file_name}, local video')
get_thumbnail(os.path.join(env.VIDEOS_DIR, file_name), data)
if os.path.isfile(temp_file):
env.HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from local video SUCCESS', env.HISTORY[file_name])
else:
env.HISTORY[file_name]['icon_path'] = get_default_icon_path(env.HISTORY[file_name])
debug_log('thumbnail from local video FAILED', env.HISTORY[file_name])
continue
debug_log(f'file={file_name}, online video')
get_thumbnail(data['url'], data)
if os.path.isfile(temp_file):
env.HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from online video SUCCESS', env.HISTORY[file_name])
else:
env.HISTORY[file_name]['icon_path'] = get_default_icon_path(env.HISTORY[file_name])
debug_log('thumbnail from online video FAILED', env.HISTORY[file_name])
continue
if data['place'] == 'online':
debug_log(f'file={file_name}, online screenshot')
try:
img = Image.open(requests.get(data['url'], stream=True).raw)
img.save(temp_file)
debug_log(f'file={file_name}, online screenshot gotten')
except:
traceback.print_exc()
data['reason'] = 'rekt'
if os.path.isfile(temp_file):
env.HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from online picture SUCCESS', env.HISTORY[file_name])
else:
env.HISTORY[file_name]['icon_path'] = get_default_icon_path(env.HISTORY[file_name])
debug_log('thumbnail from online picture FAILED', env.HISTORY[file_name])
continue
log(f'file={file_name}, local screenshot gotten')
shutil.copy2(os.path.join(env.SCREENSHOTS_DIR, file_name), temp_file)
env.HISTORY[file_name]['icon_path'] = temp_file
if os.path.isfile(temp_file):
env.HISTORY[file_name]['icon_path'] = temp_file
debug_log('thumbnail from offline picture SUCCESS', env.HISTORY[file_name])
else:
env.HISTORY[file_name]['icon_path'] = get_default_icon_path(env.HISTORY[file_name])
debug_log('thumbnail from offline picture FAILED', env.HISTORY[file_name])
if not os.path.isfile(env.HISTORY[file_name]['icon_path']):
env.HISTORY[file_name]['icon_path'] = get_default_icon_path(data)
raise Exception("Icon path doesn't exist even though we think it does" + env.HISTORY[file_name])
_order_history()
log(f'Cache generated, duration={time.time() - start}')
def compile_ordered_dict(dictio, nr_items: int = 0):
sorted_dict = OrderedDict(
sorted(
dictio.items(),
key=lambda x: datetime.datetime.strptime(str(getitem(x[1], 'date')).split('+')[0], "%Y-%m-%d %H:%M:%S").replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc),
reverse=True
)
)
sliced = islice(sorted_dict.items(), nr_items or len(sorted_dict))
return OrderedDict(sliced)
def _order_history():
env.HISTORY = compile_ordered_dict(env.HISTORY)
env.ONLINE_HISTORY = compile_ordered_dict(env.ONLINE_HISTORY)
log('_order_history Writing to history files')
with open(env.HISTORY_DIR, 'w+') as on_his:
on_his.write(json.dumps(env.HISTORY, indent=2, default=str))
with open(env.ONLINE_HISTORY_DIR, 'w+') as his:
his.write(json.dumps(env.ONLINE_HISTORY, indent=2, default=str))
def get_history_days() -> int:
days = 7 * (env.HISTORY_DAYS + 1)
return days
def validate_date_age(date: datetime.datetime):
if get_history_days() > 84:
return True
time_between_insertion = datetime.datetime.utcnow().replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc) - date.replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc)
return time_between_insertion.days < get_history_days()
def get_bucket_history(limit: int = 100):
def _get_type(fiel_name: str):
return 'video' if 'mp4' in fiel_name else 'screenshot'
def obj_last_modified(myobj):
return myobj.last_modified
session = boto3.Session(
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY")
)
# Then use the session to get the resource
s3 = session.resource('s3')
my_bucket = s3.Bucket(env.BUCKET_NAME)
sorted_objects = sorted(
my_bucket.objects.filter(
Prefix=env.get_bucket_folder()
),
key=obj_last_modified,
reverse=True
)
log("Online items:", len(list(sorted_objects)))
for my_bucket_object in sorted_objects:
# if not validate_date_age(my_bucket_object.last_modified):
# break
if not ('.mp4' in my_bucket_object.key or '.png' in my_bucket_object.key):
continue
name = my_bucket_object.key.split('/')[-1]
if env.ONLINE_HISTORY.get(name):
continue
if limit > 100:
env.ONLINE_HISTORY[name] = {
"date": my_bucket_object.last_modified.replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc),
"type": _get_type(my_bucket_object.key),
"place": "online",
"url": env.URL + name
}
else:
env.HISTORY[name] = {
"date": my_bucket_object.last_modified.replace(microsecond=0, tzinfo=datetime.timezone.utc).astimezone(tz=datetime.timezone.utc),
"type": _get_type(my_bucket_object.key),
"place": "online",
"url": env.URL + name
}
_order_history()
def _get_history():
def _get_local_history():
for directory in [env.SCREENSHOTS_DIR, env.VIDEOS_DIR]:
for file_name in os.listdir(directory):
print(file_name)
if env.HISTORY.get(file_name):
continue
if '-' not in file_name:
continue
file = File(file_name=file_name)
if not validate_date_age(file.date):
break
if not validate_date_age(file.date):
continue
env.HISTORY[file.file_name] = {
"date": file.date,
"type": file.type,
"place": "local"
}
setup_notify = NotificationBubble()
setup_notify.send_notification(
"Setting up...", "This may take a few minutes."
)
start = time.time()
thread_pool = ThreadPoolExecutor()
future = thread_pool.submit(get_bucket_history)
try:
future.result(15)
except:
traceback.print_exc()
future = thread_pool.submit(get_bucket_history, 101)
try:
future.result(15)
except:
traceback.print_exc()
_get_local_history()
_generate_cache()
debug_log(json.dumps(env.HISTORY, indent=2, default=str))
# for file in os.listdir(os.path.join(env.DATA_PATH, 'temp')):
# if file not in sliced_doct.keys():
# os.remove(os.path.join(env.DATA_PATH, 'temp', file))
# except:
# traceback.print_exc()
# finally:
# env.REFRESH_PROC = None
log(f'History downloaded, duration={time.time() - start}')
setup_notify.close()
def init_xclip_clipboard():
DEFAULT_SELECTION = 'c'
PRIMARY_SELECTION = 'p'
ENCODING = 'utf-8'
def copy_xclip(text, primary=False):
text = str(text) # Converts non-str values to str.
selection = DEFAULT_SELECTION
if primary:
selection = PRIMARY_SELECTION
p = subprocess.Popen(
['xclip', '-selection', selection],
stdin=subprocess.PIPE, close_fds=True
)
p.communicate(input=text.encode('utf-8'))
def paste_xclip(primary=False):
selection = DEFAULT_SELECTION
if primary:
selection = PRIMARY_SELECTION
p = subprocess.Popen(
['xclip', '-selection', selection, '-o'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True
)
stdout, stderr = p.communicate()
# Intentionally ignore extraneous output on stderr when clipboard is empty
return stdout.decode(ENCODING)
return copy_xclip, paste_xclip
copy, paste = init_xclip_clipboard()
def upload_file(file: File, keep=False):
def _upload_file(s3_client, file_name, path):
object_name = os.path.join(env.get_bucket_folder(), file_name)
log(
f'path={path}\n'
f'file_name={file_name}\n'
f'object_name={object_name}'
)
# mimetypes.add_type('video/mp4', '.mp4')
file_mime_type, _ = mimetypes.guess_type(file_name)
log(file_mime_type)
debug_log(file_mime_type)
extra_args = {
'ACL': 'public-read'
}
# if 'video/mp4' not in file_mime_type:
# log('not')
extra_args['ContentType'] = file_mime_type
try:
print(path, env.BUCKET_NAME, object_name, extra_args)
print(f"""aws_access_key_id={os.getenv("AWS_ACCESS_KEY_ID")},
aws_secret_access_key={os.getenv("AWS_SECRET_ACCESS_KEY")},
region_name={os.getenv("REGION_NAME")}""")
response = s3_client.upload_file(
path, env.BUCKET_NAME, object_name, ExtraArgs=extra_args
)
except:
traceback.print_exc()
return False
return True
s3_client = boto3.client(
's3',
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
region_name=os.getenv("REGION_NAME")
)
file_name_new = ''.join(
secrets.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(16)
) + file.extension
if keep:
shutil.copy2(file.file_path, os.path.join(env.UPLOADS_DIR, file_name_new))
file_new = File(path=os.path.join(env.UPLOADS_DIR, file_name_new))
else:
file_new = File(file_name_new)
os.rename(file.file_path, file_new.file_path)
if env.HISTORY.get(file.file_name):
del env.HISTORY[file.file_name]
env.HISTORY[file_name_new] = {}
env.HISTORY[file_name_new]['type'] = file_new.type
env.HISTORY[file_name_new]['date'] = file_new.date
if _upload_file(s3_client, file_new.file_name, file_new.file_path):
log('debug 2')
if not keep:
os.remove(file_new.file_path)
clipboard = env.URL + file_name_new
copy(clipboard)
log(f'Url={clipboard}')
env.HISTORY[file_name_new]['place'] = 'online'
env.HISTORY[file_name_new]['url'] = clipboard
env.ONLINE_HISTORY[file_name_new] = {}
env.ONLINE_HISTORY[file_name_new]['type'] = file_new.type
env.ONLINE_HISTORY[file_name_new]['date'] = file_new.date
env.ONLINE_HISTORY[file_name_new]['place'] = 'online'
env.ONLINE_HISTORY[file_name_new]['url'] = clipboard
notify.send_notification("Copied to clipboard", clipboard, clickable=True)
playsound(os.path.join(env.SOUNDS_DIR, 'upload_success.wav'))
log('debug x')
else:
log('debug 7')
os.system('xdg-open "%s"' % env.VIDEOS_DIR)
env.HISTORY[file_name_new]['place'] = 'local'
notify.send_notification(
"Failure!", "Upload failed. Check internet connection or poke simon if the issue persists."
)
playsound(os.path.join(env.SOUNDS_DIR, 'upload_failed.wav'))
_generate_cache()
env.WAITER['active'] = False
return file_name_new
def _kill_process(process_name: str):
# proc = subprocess.Popen([f'pidof {process_name}'], stdout=subprocess.PIPE, shell=True)
# stdout, _ = proc.communicate()
# decoded = stdout.decode('utf-8')
# debug_log(decoded)
subprocess.Popen([f'pkill -f {process_name}'], stdout=subprocess.PIPE, shell=True)
def run_with_timeout(func: Callable[..., Any], timeout: int, tries: int = 1, backoff: int = 3, raise_timeout: bool = False) -> Any:
"""
Runs a command with retries and timeout.
"""
# limit backoff and tries to respect gitlab time limits
tries = min(tries, 3) # limit to 3 tries because 6561 second wait if given 4 tries with 3 second exponential backoff
backoff = min(backoff, 5) # limit backoff because 1296 second wait if given 3 tries with 6 second exponential backoff
for index in range(tries):
try:
thread_pool_executor = ThreadPoolExecutor(None)
future = thread_pool_executor.submit(func)
return future.result(timeout)
except concurrent.futures._base.TimeoutError:
if index > 0:
log(f"run_with_timeout attempt={index + 1} failed, retrying after {backoff} seconds...")
time.sleep(backoff)
backoff *= backoff
if raise_timeout:
raise TimeoutError
class VideoRecorder:
def __init__(self):
self.file = File(extension='.mp4')
self.setting = env.RecordingMode(env.SYSTEM_CONFIG['mode'])
self.recording = False
self.proc = None
Keybinder.bind(env.SYSTEM_CONFIG['binds']['video'], self.take_video)
def kill_video(self):
if self.recording and self.proc:
self.recording = False
self.proc = None
try:
_kill_process('simplescreenrecorder')
except:
pass
env.WAITER['active'] = False
def take_video(self, keystring):
log('take video in')
if self.proc and self.proc.poll() is not None:
self.recording = False
env.WAITER['active'] = False
self.proc = None
if self.recording and self.proc:
def _wait_for_exit_safe():
for line in io.TextIOWrapper(self.proc.stderr, encoding="utf-8"):
log(line)
if 'kb/s' in line or 'Stopped page' in line or 'Standard input closed' in line:
break
def _save_recording():
try:
_, _ = self.proc.communicate(input=b"record-save\n")
except OSError:
pass
duration = self.start_time - time.time()
self.recording = False
save_notify = NotificationBubble()
save_notify.send_notification("Saving...", "")
threading.Thread(
target=_save_recording
).start()
run_with_timeout(_wait_for_exit_safe, min(10, max(3, int(duration / 6))))
self.proc = None
try:
_kill_process('simplescreenrecorder')
except:
pass
try:
if not env.UPLOAD_AFTER_TASK:
if env.OPEN_AFTER_SS:
os.system('xdg-open "%s"' % env.VIDEOS_DIR)
update_history_file(self.file)
save_notify.close()
env.WAITER['active'] = False
else:
upload_file(self.file)
# GLib.idle_add(lambda: upload_file(self.file))
except:
traceback.print_exc()
else:
self.start_time = time.time()
if env.WAITER['active']:
video_waiter_notify = NotificationBubble()
video_waiter_notify.send_notification(
"Please wait...", "Recording or uploading video."
)
log('Waiter active video')
return
env.WAITER['active'] = True
self.update_config()
self.start_recording()
log('take video out')
def update_config(self):
def _generate_config():
with open(os.path.join(env.CONFIG_PATH, f'{self.setting.name}.conf'), 'w+') as conf_file:
for header, settings in config.items():
log(header, settings)
conf_file.write(f'[{header}]\n')
for setting, value in settings.items():
conf_file.write(f'{setting}={value}\n')
conf_file.write('\n')
self.file = File(extension='.mp4')
self.setting = env.RecordingMode(env.SYSTEM_CONFIG['mode'])
config = json.load(open(os.path.join(env.CONFIG_PATH, f'{self.setting.name}.json')))
log(self.setting)
if self.setting.value == env.RecordingMode.Area.value:
canvas = ScreenshotCanvas(take_screenshot=False)
canvas.mainloop()
x, y, w, h = canvas.coordinates
config['input']['video_x'] = x
config['input']['video_y'] = y
config['input']['video_w'] = w - x
config['input']['video_h'] = h - y
config['output']['file'] = self.file.file_path
_generate_config()
log(config)
def start_recording(self):
try:
self.kill_video()
except:
pass
self.recording = True
self.proc = subprocess.Popen(
["simplescreenrecorder",
"--start-hidden",
"--start-recording",
f"--settingsfile={os.path.join(env.CONFIG_PATH, f'{self.setting.name}.conf')}"],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
# bufsize=0
)
env.RECORDING_PROC = self.proc
class ShareXYZTool(Gtk.Window):
def __init__(self):
super().__init__()
env.SCT = mss.mss()
env.VIDEO_RECORDER = VideoRecorder()
Keybinder.init()
Keybinder.bind(env.SYSTEM_CONFIG['binds']['screenshot'], self.take_screenshot)
Keybinder.bind(env.SYSTEM_CONFIG['binds']['waiter'], self.disable_waiter)
Keybinder.bind(env.SYSTEM_CONFIG['binds']['history'], HistoryWindow.reopen_history_window)
def take_screenshot(self, keystring):
log('take screenshot in')
if env.WAITER['active'] and not (env.RECORDING_PROC and env.RECORDING_PROC.poll is not None):
screenshot_waiter_notify = NotificationBubble()
screenshot_waiter_notify.send_notification(
"Please wait...", "Taking or uploading screenshot"
)
log("waiter active screenshot")
return
env.WAITER['active'] = True
canvas = ScreenshotCanvas()
canvas.mainloop()
env.WAITER['active'] = False
log('take screenshot out')
def disable_waiter(self, keystring):
env.WAITER['active'] = False
class ScreenshotCanvas(tk.Tk):
def __init__(self, take_screenshot: bool = True):
super().__init__()
self.withdraw()
self._take_screenshot = take_screenshot
self._bbox = None
abs_coord_x = self.winfo_pointerx() - self.winfo_vrootx()
monitor1 = get_monitors()[0]
monitor2 = get_monitors()[1]
if monitor1.x > monitor2.x:
monitor1 = get_monitors()[1]
monitor2 = get_monitors()[0]
log("y diff:", monitor2.y - monitor1.y)
bbox_monitor1 = (monitor1.x,
monitor1.y,
monitor1.width + env.MONITORS_OFFSET['monitor1']['x_offset'],
monitor1.height + env.MONITORS_OFFSET['monitor1']['y_offset'])
bbox_monitor2 = (monitor2.x,
monitor2.y,
monitor1.width + monitor2.width + env.MONITORS_OFFSET['monitor2']['x_offset'],
monitor2.height + env.MONITORS_OFFSET['monitor2']['y_offset'])
log(f"monit1:{bbox_monitor1}, monit2:{bbox_monitor2}")
self.monitor = monitor1
if abs_coord_x > monitor1.width:
self.monitor = monitor2
bbox = bbox_monitor1
self.geometry(f"+{self.monitor.x}+0")
if self.monitor.x > 0:
bbox = bbox_monitor2
self.attributes('-fullscreen', True)
self.first_tap = True
self.canvas = tk.Canvas(self)
self.canvas.pack(fill="both", expand=True)
image = ImageGrab.grab(bbox=bbox, include_layered_windows=False, all_screens=True)
self.image = ImageTk.PhotoImage(image)
self.photo = self.canvas.create_image(0, 0, image=self.image, anchor="nw")
self.lasx, self.lasy = 0, 0
self.x, self.y = 0, 0
self.rect, self.start_x, self.start_y = None, None, None
self.deiconify()
self.canvas.tag_bind(self.photo, "<ButtonPress-1>", self.on_button_press)
self.canvas.tag_bind(self.photo, "<B1-Motion>", self.on_move_press)
self.canvas.tag_bind(self.photo, "<ButtonRelease-1>", self.on_button_release)
self.canvas.tag_bind(self.photo, '<ButtonPress-3>', self.close_me)
self.canvas.bind_all(env.SYSTEM_CONFIG['binds']['destroy'], self.destroy_me)
def destroy_me(self, event):
log('destroy_me')
self.withdraw()
self.destroy()
def close_me(self, event):
log('close_me')
self.withdraw()
if self._take_screenshot:
try:
self.take_screenshot()
except:
traceback.print_exc()
self.destroy()
def on_button_press(self, event):
if self.first_tap:
self.start_x = event.x
self.start_y = event.y
self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, outline='red')
elif env.KEY_PRESSED == keyboard.Key.shift:
self.start_x = event.x
self.start_y = event.y
self.draw_rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, outline='red', width=4)
else:
self.lasx, self.lasy = event.x, event.y
self.canvas.create_line(
(self.lasx, self.lasy, event.x, event.y),
fill='red',
width=4
)
self.lasx, self.lasy = event.x, event.y
def on_move_press(self, event):
if self.first_tap:
curX, curY = (event.x, event.y)
self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)
elif env.KEY_PRESSED == keyboard.Key.shift:
curX, curY = (event.x, event.y)
self.canvas.coords(self.draw_rect, self.start_x, self.start_y, curX, curY)
else:
self.canvas.create_line(
(self.lasx, self.lasy, event.x, event.y),
fill='red',
width=4
)
self.lasx, self.lasy = event.x, event.y
def on_button_release(self, event):
if self.first_tap:
self._bbox = self.canvas.bbox(self.rect)
x, y, w, h = self._bbox
# make all values positive
if self.monitor.x == 0:
x = max(x, 0)
y = max(y, 0)
self._bbox = (x + env.MONITORS_OFFSET['monitor1']['x_offset'],
y + env.MONITORS_OFFSET['monitor1']['y_offset'],
w + env.MONITORS_OFFSET['monitor1']['x_offset'],
h + env.MONITORS_OFFSET['monitor1']['y_offset'])