-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathupdate.py
5206 lines (4176 loc) · 188 KB
/
update.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
"""
Update Script for Rick Dangerous' Insanium/R.P.E
https://github.com/h3xp/RickDangerousUpdate
"""
from asyncio import streams
from genericpath import isdir, isfile
from http.client import OK
import os
import zipfile
import platform
#from distutils.dir_util import copy_tree
import distutils.dir_util
import json
from pathlib import Path
import re
import tempfile
import requests
import logging
import urllib.request
from Crypto.Cipher import AES
from Crypto.Util import Counter
from mega.crypto import base64_to_a32, base64_url_decode, decrypt_attr, decrypt_key, a32_to_str, get_chunks, str_to_a32
from mega.errors import RequestError
import xml.etree.ElementTree as ET
import datetime
import shutil
import sys
import configparser
import subprocess
from dialog import Dialog
from packaging import version
import copy
import traceback
import time
d = Dialog()
d.autowidgetsize = True
logger = logging.getLogger(__name__)
update_available_result = "no connection"
tool_ini = "/home/pi/.update_tool/update_tool.ini"
genres = {}
update_being_processed = "None"
def print_files(current_files: dict, file_list: list, log_file: str, spacer="\t", starter="-"):
for file in file_list:
if file in current_files:
values = current_files[file]
file_sizes = ""
if values[0] == "ADDED":
file_sizes = f"(current size: {values[2]})"
elif values[0] == "UPDATED":
file_sizes = f"(current size: {values[2]}, previous size: {values[3]})"
elif values[0] == "DELETED":
file_sizes = f"(previous size: {values[3]})"
log_this(log_file, f"{starter}\"{file}\"{spacer}{file_sizes}")
return
def list_info_in_update(current_files: dict, path: str, log_file: str, directories: list):
files = {}
files_added = []
files_deleted = []
files_updated = []
pre_processing = []
post_processing = []
log_this(log_file, "")
log_this(log_file, "")
log_this(log_file, "**********")
log_this(log_file, f"Now Processing: \"{os.path.basename(path)}\" [{convert_filesize(str(os.path.getsize(path)))}]")
log_this(log_file, "**********")
with zipfile.ZipFile(path, 'r') as zip_ref:
if "read me do this first!.txt" in zip_ref.namelist():
zip_ref.extract("read me do this first!.txt", "/tmp")
with open("/tmp/read me do this first!.txt", 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
previous_size = None
file_dir = get_file_dir(line, directories)
if len(file_dir) > 0:
if line in current_files:
values = current_files[line]
#previous_size = convert_filesize(values[2])
previous_size = values[2]
current_files[line] = ["DELETED", os.path.basename(path), None, previous_size]
files_deleted.append(line)
if "read me pre-process!.txt" in zip_ref.namelist():
zip_ref.extract("read me pre-process!.txt", "/tmp")
with open("/tmp/read me pre-process!.txt", 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
pre_processing.append(line)
if "read me post-process!.txt" in zip_ref.namelist():
zip_ref.extract("read me post-process!.txt", "/tmp")
with open("/tmp/read me post-process!.txt", 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
post_processing.append(line)
for file_listing in zip_ref.infolist():
#info_dict = parse_zipinfo(file_listing)
#print(f"{file_listing.filename}\t{file_listing.file_size}")
file = "/" + file_listing.filename
file_dir = get_file_dir(file, directories)
if len(file_dir) > 0:
print(file)
status = ""
file_size = convert_filesize(str(file_listing.file_size))
if file in current_files.keys():
values = current_files[file]
if values[0] == "DELETED":
files_added.append(file)
current_files[file] = ["ADDED", os.path.basename(file), file_size, None]
else:
files_updated.append(file)
current_files[file] = ["UPDATED", os.path.basename(file), file_size, values[2]]
else:
files_added.append(file)
current_files[file] = ["ADDED", os.path.basename(file), file_size, None]
if len(files_deleted) > 0:
log_this(log_file, "")
log_this(log_file,"DELETED")
files_deleted = print_sort(files_deleted, directories)
print_files(current_files, files_deleted, log_file)
if len(pre_processing) > 0:
log_this(log_file, "")
log_this(log_file,"PRE-PROCESSING COMMANDS")
for pre_cmd in pre_processing:
log_this(log_file, pre_cmd)
if len(files_added) > 0:
log_this(log_file, "")
log_this(log_file,"ADDED")
files_added = print_sort(files_added, directories)
print_files(current_files, files_added, log_file)
if len(files_updated) > 0:
log_this(log_file, "")
log_this(log_file,"UPDATED")
files_updated = print_sort(files_updated, directories)
print_files(current_files, files_updated, log_file)
if len(post_processing) > 0:
log_this(log_file, "")
log_this(log_file,"POST-PROCESSING COMMANDS")
for post_cmd in post_processing:
log_this(log_file, post_cmd)
return
def get_org_files(dirs: list):
files = {}
for dir in dirs:
print(f"Getting {dir}...")
os.chdir(dir)
subprocess.check_output(["/bin/bash","-c","find . -ls > /tmp/full_dir_listing.txt"])
with open("/tmp/full_dir_listing.txt", 'r') as file:
lines = file.readlines()
for line in lines:
loc = line.find("./")
if loc >= 0:
str = line[loc:].replace("\\ ", " ").replace("./", dir).strip()
if os.path.isfile(str):
size = convert_filesize(get_parsed_part(line, 7))
files[str] = size
log_this("/tmp/org_full_dir_listing.txt", str + "\t" + files[str])
files = {}
with open("/tmp/org_full_dir_listing.txt", 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
file = line.split("\t")
files[file[0]] = ("ADDED", "Current Filesystem State", file[1], None)
#file_dir = get_file_dir(file[0])
#if len(file_dir) > 0:
#print(file[0])
#files[file[0]] = ("ADDED", "Current Filesystem State", file[1], None)
if os.path.isfile("/tmp/full_dir_listing.txt"):
os.remove("/tmp/full_dir_listing.txt")
if os.path.isfile("/tmp/org_full_dir_listing.txt"):
os.remove("/tmp/org_full_dir_listing.txt")
return files
def print_sort(file_list: list, directories: list):
retval = []
dirs = {}
for file in file_list:
file_dir = get_file_dir(file, directories)
if len(file_dir) > 0:
files = []
if file_dir in dirs:
files = dirs[file_dir]
files.append(file)
dirs[file_dir] = files
sorted_dirs = sorted(dirs.keys())
for sorted_dir in sorted_dirs:
files = dirs[sorted_dir]
files.sort()
for file in files:
retval.append(file)
return retval
def get_file_dir(filename: str, directories: list):
#rom_path = "/home/pi/RetroPie/roms/"
#if rom_path in filename:
for directory in directories:
if directory not in filename:
continue
current_file = filename.replace(os.path.basename(filename), "")
if current_file.find("/") >= 0:
#rom_dir = rom_path + current_file[0:current_file.find("/")]
file_dir = filename[0:filename.rindex("/") + 1]
file_name = filename.replace(file_dir, "")
if len(file_name.strip()) == 0:
return ""
return file_dir
return ""
def get_parsed_part(line: str, part: int):
retval = ""
i = 0
pos = 0
while i < part:
retval = ""
while line[pos:pos+1] == " ":
pos += 1
i += 1
while line[pos:pos+1] != " ":
retval += line[pos:pos+1]
pos += 1
return retval.strip()
def get_manual_updates_story():
log_file = "/home/pi/.update_tool/manual_updates_story.txt"
dir_list = get_config_value("ALWAYS_OVERWRITE", "relevant_directories")
directories = dir_list.strip().split(",")
megadrive = check_drive()
update_dir = get_valid_path_portion(get_default_update_dir())
update_dir = manual_updates_dialog(update_dir, False)
update_dir = get_config_value("CONFIG_ITEMS", "update_dir")
# forcing this to a directory
updates = official_improvements_dialog(update_dir=get_config_value("CONFIG_ITEMS", "update_dir"), process_improvements=False)
if updates is None or len(updates) == 0:
d.msgbox("No updates selected!")
return
updates = sort_official_updates(updates)
print("Getting current filesystem state, then processing...")
current_files = get_org_files(directories)
log_this(log_file, "**********", overwrite=True)
log_this(log_file, "Manual Updates Story!")
log_this(log_file, "**********")
log_this(log_file, "")
log_this(log_file, "These are the changes to your filesystem that would happen from applying these updates...")
log_this(log_file, "")
log_this(log_file, "Directories processed:")
for directory in directories:
log_this(log_file, "- " + directory)
log_this(log_file, "")
log_this(log_file, "Updates evaulated:")
for update in updates:
log_this(log_file, "- " + os.path.join(update_dir, update[0]))
for update in updates:
print("Processing \"" + os.path.join(update_dir, update[0]) + "\"...")
list_info_in_update(current_files, os.path.join(update_dir, update[0]), log_file, directories)
cls()
d.textbox(log_file, title=f"Contents of {log_file}")
return
def safe_write_backup(file_path: str, file_time=""):
if file_time == "":
file_time = datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S")
shutil.copy2(file_path, file_path + "--" + file_time)
return file_time
def safe_write_check(file_path: str, file_time: str):
if os.path.getsize(file_path) == 0:
# this somehow failed badly
shutil.copy2(file_path + "--" + file_time, file_path)
return False
os.remove(file_path + "--" + file_time)
return True
def get_git_repo():
if os.path.exists(tool_ini):
git_repo = get_config_value("CONFIG_ITEMS", "git_repo")
if git_repo is not None:
return git_repo
return "https://raw.githubusercontent.com/h3xp/RickDangerousUpdate"
def get_git_branch():
if os.path.exists(tool_ini):
git_branch = get_config_value("CONFIG_ITEMS", "git_branch")
if git_branch is not None:
return git_branch
return "main"
def get_overlay_systems():
retval = [[], []]
path = "/opt/retropie/configs"
for file in os.listdir(path):
if file == "all":
continue
system = os.path.join(path, file)
if os.path.isdir(system):
if os.path.isfile(os.path.join(system, "retroarch.cfg")):
with open(os.path.join(system, "retroarch.cfg"), 'r') as configfile:
system_overlay = False
overlay_on = False
lines = configfile.readlines()
for line in lines:
if "input_overlay" in line:
pos = line.find("=")
if pos > 0:
if len(line[pos].strip()) > 0:
if file not in retval[0]:
retval[0].append(file)
if line.strip()[0:1] != "#":
if file not in retval[1]:
retval[1].append(file)
retval[0].sort()
return retval
def read_ini(ini_file: str):
if os.path.isfile(ini_file):
config = configparser.ConfigParser()
config.optionxform = str
config.read(ini_file)
return config
return None
def read_config():
if os.path.exists(tool_ini):
if os.path.isfile(tool_ini):
config = configparser.ConfigParser()
config.optionxform = str
config.read(tool_ini)
return config
return None
def get_ini_section(ini_file: str, section: str):
config = read_ini(ini_file)
if config is not None:
if config.has_section(section):
return config.items(section)
return None
def get_config_section(section: str):
config = read_config()
if config is not None:
if config.has_section(section):
return config.items(section)
return None
def get_ini_value(ini_file: str, section: str, key: str, return_none=True):
config = read_ini(ini_file)
if config is not None:
if config.has_option(section, key):
return config[section][key]
if return_none == False:
return ""
return None
def get_config_value(section: str, key: str, return_none=True):
config = read_config()
if config is not None:
if config.has_option(section, key):
return config[section][key]
if return_none == False:
return ""
return None
def is_valid_mega_link(url: str):
pattern = re.compile("^https://mega\.nz/((folder|file)/([^#]+)#(.+)|#(F?)!([^!]+)!(.+))$")
if pattern.match(url):
return True
return False
def retrieve_mega_config(read_config: bool):
mega_dir = get_config_value("CONFIG_ITEMS","mega_dir")
if is_valid_mega_link(mega_dir):
mega_config = configparser.ConfigParser()
mega_config.optionxform = str
mega_ini = f"/home/pi/.update_tool/mega_{mega_dir.split('/')[-1]}.ini"
if read_config:
mega_config.read(mega_ini)
return mega_config,mega_ini
return None,None
def get_mega_config_section(section: str):
mega_config,mega_ini = retrieve_mega_config(True)
if mega_config is not None:
if mega_config.has_section(section):
return mega_config.items(section)
return None
def get_mega_config_value(section: str, key: str):
mega_config,mega_ini = retrieve_mega_config(True)
if mega_config is not None:
if mega_config.has_option(section, key):
return mega_config[section][key]
return None
def set_config_value(section: str, key: str, value: str):
config = read_config()
if config is not None:
if config.has_section(section) == False:
config.add_section(section)
config[section][key] = value
with open(tool_ini, 'w') as configfile:
config.write(configfile)
return True
return False
def set_mega_config_value(section: str, key: str, value: str):
mega_config,mega_ini = retrieve_mega_config(True)
if mega_config is not None:
if mega_config.has_section(section) == False:
mega_config.add_section(section)
mega_config[section][key] = value
with open(mega_ini, 'w') as configfile:
mega_config.write(configfile)
return True
return False
def mega_ini_check():
mega_config,mega_ini = retrieve_mega_config(False)
# if the mega ini files does not exist then initialize it
if os.path.exists(mega_ini) == False:
mega_config.add_section("INSTALLED_UPDATES")
with open(mega_ini, 'w') as configfile:
mega_config.write(configfile)
return True
def restart_es():
runcmd("sudo reboot")
#runcmd("touch /tmp/es-restart && pkill -f \"/opt/retropie/supplementary/.*/emulationstation([^.]|$)\"")
#runcmd("sudo systemctl restart [email protected]")
return
def cronjob_exists(unique):
output = runcmd("crontab -l 2>/dev/null")
if unique in output:
return True
else:
return False
def autostart_exists(unique):
output = runcmd("cat /opt/retropie/configs/all/autostart.sh")
if unique in output:
return True
else:
return False
def toggle_countofficialonly():
if os.path.exists(tool_ini):
if get_config_value('CONFIG_ITEMS', 'count_official_only') == "True":
toggle = "False"
toggle_msg = "disabled"
else:
toggle = "True"
toggle_msg = "enabled"
set_config_value('CONFIG_ITEMS', 'count_official_only', toggle)
d.msgbox('Count official games ' + toggle_msg + '! Reboot to apply changes')
main_dialog()
else:
d.msgbox('To use this feature make sure to install the tool.')
main_dialog()
def toggle_autoclean():
if os.path.exists(tool_ini):
if get_config_value('CONFIG_ITEMS', 'auto_clean') == "True":
toggle = "False"
toggle_msg = "disabled"
else:
toggle = "True"
toggle_msg = "enabled"
set_config_value('CONFIG_ITEMS', 'auto_clean', toggle)
d.msgbox('Auto clean ' + toggle_msg + '! Reboot to apply changes')
main_dialog()
else:
d.msgbox('To use this feature make sure to install the tool.')
main_dialog()
def remove_notification():
runcmd("crontab -l | sed '/.update_tool/d' | crontab")
runcmd("sed '/update_tool/d' /opt/retropie/configs/all/autostart.sh >/tmp/ut.$$ ; mv /tmp/ut.$$ /opt/retropie/configs/all/autostart.sh")
return
def select_notification():
if os.path.exists(tool_ini):
previous_method = get_config_value('CONFIG_ITEMS', 'display_notification')
code, tag = d.radiolist("Choose which notification method you want to use",
choices=[("False", "Do not notify about game updates", previous_method == "False"),
("Theme", "Notify about game updates via themes", previous_method == "Theme"),
("Tool", "Notify about game updates via update tool", previous_method == "Tool")],
title="Game Update Notification",
ok_label="Set Method")
if code == d.OK:
remove_notification()
if tag in ["Theme", "Tool"]:
runcmd("( echo 'update_tool notify' ; cat /opt/retropie/configs/all/autostart.sh ) >/tmp/ut.$$ ; mv /tmp/ut.$$ /opt/retropie/configs/all/autostart.sh")
set_config_value('CONFIG_ITEMS', 'display_notification', tag)
d.msgbox('Display Notification ' + tag + '!\n\n Reboot to apply changes')
#if code == d.OK and previous_method != tag:
# if tag == "False":
# if previous_method == "Theme":
# runcmd("crontab -l | sed '/.update_tool/d' | crontab")
# if previous_method == "Tool":
# runcmd("sed '/update_tool/d' /opt/retropie/configs/all/autostart.sh >/tmp/ut.$$ ; mv /tmp/ut.$$ /opt/retropie/configs/all/autostart.sh")
# if tag == "Theme":
# if not cronjob_exists("update_tool"):
# runcmd("( crontab -l 2>/dev/null ; echo '@reboot python3 /home/pi/.update_tool/notification.py' ) | crontab")
# if previous_method == "Tool":
# runcmd("sed '/update_tool/d' /opt/retropie/configs/all/autostart.sh >/tmp/ut.$$ ; mv /tmp/ut.$$ /opt/retropie/configs/all/autostart.sh")
# if tag == "Tool":
# if not autostart_exists("update_tool"):
# runcmd("( echo 'update_tool notify' ; cat /opt/retropie/configs/all/autostart.sh ) >/tmp/ut.$$ ; mv /tmp/ut.$$ /opt/retropie/configs/all/autostart.sh")
# if previous_method == "Theme":
# runcmd("crontab -l | sed '/.update_tool/d' | crontab")
# set_config_value('CONFIG_ITEMS', 'display_notification', tag)
# d.msgbox('Display Notification ' + tag + '!\n\n Reboot to apply changes')
else:
d.msgbox('To use this feature make sure to install the tool.')
return
def is_update_applied(key: str, modified_timestamp: str):
if os.path.exists(tool_ini) == False:
return False
mega_config,mega_ini = retrieve_mega_config(True)
if mega_config.has_option("INSTALLED_UPDATES", key):
return mega_config["INSTALLED_UPDATES"][key] == str(modified_timestamp)
return False
def uninstall():
git_repo = get_git_repo()
git_branch = get_git_branch()
runcmd(f"bash <(curl '{git_repo}/{git_branch}/install.sh' -s -N) -remove")
return
def update():
git_repo = get_git_repo()
git_branch = get_git_branch()
runcmd(f"bash <(curl '{git_repo}/{git_branch}/install.sh' -s -N) -update")
return
def install():
git_repo = get_git_repo()
git_branch = get_git_branch()
megadrive = check_drive()
runcmd(f"bash <(curl '{git_repo}/{git_branch}/install.sh' -s -N) {megadrive}")
return
def status_bar(total_size: float, current_size: float, start_time: datetime, complete=False, start_char="\t"):
current_time = datetime.datetime.utcnow()
percent_complete = round((current_size / total_size) * 100)
if percent_complete > 99 and not complete:
percent_complete = 99
kbs = return_bps(current_size, (current_time - start_time).total_seconds())
pad = (12 - len(kbs))
if not complete:
print(f"{start_char}{percent_complete if percent_complete < 100 else 99}% complete: [{'='*percent_complete}>{' '*(99 - percent_complete)}] ({kbs}) (total elapsed time: {str(current_time - start_time)[:-7]}){' '*pad}", end = "\r")
else:
print(f"{start_char}100% complete: [{'='*100}] ({kbs}) (total elapsed time: {str(current_time - start_time)[:-7]}){' '*pad}")
return
def return_bps(bytes: float, seconds: float):
retval = ""
units = ["B", "KB", "MB", "GB"]
unit = "B"
count = 0
filesize = bytes / seconds
while (filesize) >= 1000:
count += 1
filesize /= 1024
if count == 0:
retval = "%0.2f" % filesize + " " + unit + "/s"
else:
retval = "%0.2f" % filesize + " " + units[count] + "/s"
return retval
def download_file(file_handle,
file_key,
file_data,
dest_path,
dest_filename=None):
k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5],
file_key[2] ^ file_key[6], file_key[3] ^ file_key[7])
iv = file_key[4:6] + (0, 0)
meta_mac = file_key[6:8]
start_time = datetime.datetime.utcnow()
# Seems to happens sometime... When this occurs, files are
# inaccessible also in the official also in the official web app.
# Strangely, files can come back later.
if 'g' not in file_data:
raise RequestError('File not accessible anymore')
file_url = file_data['g']
file_size = file_data['s']
attribs = base64_url_decode(file_data['at'])
attribs = decrypt_attr(attribs, k)
print(f"\t{0}% complete: [>{' '*99}]", end = "\r")
file_name = attribs['n']
input_file = requests.get(file_url, stream=True).raw
if dest_path is None:
dest_path = ''
else:
dest_path += '/'
with tempfile.NamedTemporaryFile(mode='w+b',
prefix='megapy_',
delete=False) as temp_output_file:
k_str = a32_to_str(k)
counter = Counter.new(128,
initial_value=((iv[0] << 32) + iv[1]) << 64)
aes = AES.new(k_str, AES.MODE_CTR, counter=counter)
mac_str = '\0' * 16
mac_encryptor = AES.new(k_str, AES.MODE_CBC,
mac_str.encode("utf8"))
iv_str = a32_to_str([iv[0], iv[1], iv[0], iv[1]])
i = None
for chunk_start, chunk_size in get_chunks(file_size):
#percent_complete = round(((chunk_start + chunk_size) / file_size) * 100)
#print(f"\t{percent_complete if percent_complete < 100 else 99}% complete: [{'='*percent_complete}>{' '*(99 - percent_complete)}]", end = "\r")
status_bar(file_size, (chunk_start + chunk_size), start_time)
chunk = input_file.read(chunk_size)
chunk = aes.decrypt(chunk)
temp_output_file.write(chunk)
encryptor = AES.new(k_str, AES.MODE_CBC, iv_str)
for i in range(0, len(chunk) - 16, 16):
block = chunk[i:i + 16]
encryptor.encrypt(block)
# fix for mega limit
if i is None:
return None
# fix for files under 16 bytes failing
if file_size > 16:
i += 16
else:
i = 0
block = chunk[i:i + 16]
if len(block) % 16:
block += b'\0' * (16 - (len(block) % 16))
mac_str = mac_encryptor.encrypt(encryptor.encrypt(block))
file_info = os.stat(temp_output_file.name)
logger.info('%s of %s downloaded', file_info.st_size,
file_size)
file_mac = str_to_a32(mac_str)
# check mac integrity
if (file_mac[0] ^ file_mac[1],
file_mac[2] ^ file_mac[3]) != meta_mac:
raise ValueError('Mismatched mac')
output_path = Path(dest_path + file_name)
#print(f"\t100% complete: [{'='*100}]")
status_bar(file_size, file_size, start_time, complete=True)
shutil.move(temp_output_file.name, output_path)
return output_path
def get_file_data(file_id: str, root_folder: str):
data = [{'a': 'g', 'g': 1, 'n': file_id}]
response = requests.post(
"https://g.api.mega.co.nz/cs",
params={'id': 0, # self.sequence_num
'n': root_folder},
data=json.dumps(data)
)
json_resp = response.json()
return json_resp[0]
# def get_nodes_in_shared_folder(root_folder: str) -> dict:
def get_nodes_in_shared_folder(root_folder: str):
data = [{"a": "f", "c": 1, "ca": 1, "r": 1}]
response = requests.post(
"https://g.api.mega.co.nz/cs",
params={'id': 0, # self.sequence_num
'n': root_folder},
data=json.dumps(data)
)
json_resp = response.json()
return json_resp[0]["f"]
# def parse_folder_url(url: str) -> Tuple[str, str]:
def parse_folder_url(url: str):
"Returns (public_handle, key) if valid. If not returns None."
REGEXP1 = re.compile(
r"mega.[^/]+/folder/([0-z-_]+)#([0-z-_]+)(?:/folder/([0-z-_]+))*")
REGEXP2 = re.compile(
r"mega.[^/]+/#F!([0-z-_]+)[!#]([0-z-_]+)(?:/folder/([0-z-_]+))*")
m = re.search(REGEXP1, url)
if not m:
m = re.search(REGEXP2, url)
if not m:
print("Not a valid URL")
return None
root_folder = m.group(1)
key = m.group(2)
# You may want to use m.groups()[-1]
# to get the id of the subfolder
return (root_folder, key)
# def decrypt_node_key(key_str: str, shared_key: str) -> Tuple[int, ...]:
def decrypt_node_key(key_str: str, shared_key: str):
encrypted_key = base64_to_a32(key_str.split(":")[1])
return decrypt_key(encrypted_key, shared_key)
def convert_filesize(file_size: str):
retval = ""
filesize = float(file_size)
units = ["KB", "MB", "GB"]
unit = "B"
count = 0
while (filesize) >= 1000:
count += 1
filesize /= 1024
if count == 0:
retval = str(round(filesize)) + " " + unit
elif count == 1:
retval = str(round(filesize)) + " " + units[count - 1]
else:
retval = str(round(filesize, count - 1)) + " " + units[count - 1]
return retval
def get_available_updates(megadrive: str, status=False):
if status == True:
print()
print("Finding available updates...")
(root_folder, shared_enc_key) = parse_folder_url(megadrive)
shared_key = base64_to_a32(shared_enc_key)
nodes = get_nodes_in_shared_folder(root_folder)
available_updates = []
for node in nodes:
key = decrypt_node_key(node["k"], shared_key)
if node["t"] == 0: # Is a file
k = (key[0] ^ key[4], key[1] ^ key[5],
key[2] ^ key[6], key[3] ^ key[7])
elif node["t"] == 1: # Is a folder
k = key
attrs = decrypt_attr(base64_url_decode(node["a"]), k)
file_name = attrs["n"]
file_id = node["h"]
modified_date = node["ts"]
if node["t"] == 0:
file_size = convert_filesize(node["s"])
available_updates.append([file_name, file_id, modified_date, file_size, node["s"]])
return available_updates
def download_update(ID, destdir, megadrive, size):
(root_folder, shared_enc_key) = parse_folder_url(megadrive)
shared_key = base64_to_a32(shared_enc_key)
nodes = get_nodes_in_shared_folder(root_folder)
for node in nodes:
key = decrypt_node_key(node["k"], shared_key)
if node["t"] == 0: # Is a file
k = (key[0] ^ key[4], key[1] ^ key[5],
key[2] ^ key[6], key[3] ^ key[7])
elif node["t"] == 1: # Is a folder
k = key
attrs = decrypt_attr(base64_url_decode(node["a"]), k)
file_id = node["h"]
if file_id == ID:
print(f"Downloading: {attrs['n']} ({size})...")
file_data = get_file_data(file_id, root_folder)
file_path = download_file(file_id, key, file_data, str(destdir))
return file_path
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
def runcmd(command):
code = subprocess.check_output(["/bin/bash","-c",command])
return str(code, "UTF-8")
#return os.popen(command).read()
def copyfile(localpath, filepath):
shutil.copy(localpath, filepath)
def copydir(source_path, target_path):
#copy_tree(source_path, target_path)
distutils.dir_util._path_created = {}
distutils.dir_util.copy_tree(source_path, target_path)
def fix_permissions():
runcmd('sudo chown -R pi:pi ~/RetroPie/roms/ && sudo chown -R pi:pi ~/.emulationstation/')
d.msgbox("Done! Permissions have been reset!")
main_dialog()
def permissions_dialog():
code = d.yesno('Your permissions seem to be wrong, which is a known bug in this image.\nThis might prevent you from '
'saving configurations, gamestates and metadata.\nDo you want this script to fix this issue for you?\n')
if code == d.OK:
fix_permissions()
return
def check_wrong_permissions():
output = runcmd("find /home/pi/RetroPie/roms -user root")
# output = runcmd('ls -la /home/pi/RetroPie/ | grep roms | cut -d \' \' -f3,4')
# if output.rstrip() != 'pi pi':
if len(output) > 0:
permissions_dialog()
else:
output = runcmd('ls -la /home/pi/.emulationstation/gamelists/retropie | grep " gamelist.xml$" | cut -d \' \' -f3,4')
if "pi" not in output.rstrip():
permissions_dialog()
def get_node(element: ET.Element, name: str, return_none=False):
ret_val = None if return_none == True else ""
src_node = element.find(name)
if src_node is not None:
if src_node.text is not None:
return str(src_node.text)
return ret_val
def clear_do_not_overwrite_tags(gamelist: str):
org_gamelist = gamelist + "-pre"
if os.path.isfile(gamelist):
os.rename(gamelist, org_gamelist)
if os.path.isfile(org_gamelist):
runcmd(f"grep -e \<lastplayed\> -e \<playcount\> -e \<favorite\> -v {org_gamelist} > {gamelist}")
if os.path.isfile(gamelist):
os.remove(org_gamelist)
return
def clean_recent(collection: str):
paths = []
if os.path.exists(collection):
with open(collection, 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
line = line.strip()
if line + "\n" not in paths and os.path.isfile(line):
paths.append(line + "\n")
paths.sort()
with open(collection, 'w', encoding='utf-8') as file:
file.writelines(paths)
return
def write_all_roms(gamelist: str, full_path: str, collection: str):
paths = []
src_tree = ET.parse(gamelist)
src_root = src_tree.getroot()
for src_game in src_root.iter("game"):
path = get_node(src_game, "path", return_none=True).strip()