-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcommon.py
1621 lines (1335 loc) · 61.7 KB
/
common.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
from __future__ import print_function, unicode_literals
import datetime
import io
import re
import shutil
import sys, os, platform, subprocess, json
import threading
import time
import traceback
import tempfile
import webbrowser
import zlib
import commandLineParser
import installConfiguration
try:
"".decode("utf-8")
def decodeStr(string):
return string.decode("utf-8")
except AttributeError:
def decodeStr(string):
return string
try:
from urllib.request import urlopen, Request
from urllib.parse import urlparse, quote
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
from urlparse import urlparse
from urllib import quote
try:
import ssl
if ssl.OPENSSL_VERSION_NUMBER < 0x10001000: # Version 1.0.1, first to support TLS 1.1 and 1.2
SSL_VERSION_IS_OLD = True
else:
SSL_VERSION_IS_OLD = False
except ImportError:
# No SSL at all
SSL_VERSION_IS_OLD = True
try:
from html.parser import HTMLParser
except:
from HTMLParser import HTMLParser
try:
from typing import Optional, List, Tuple, Dict, Callable, Any
except:
pass
class NullOrTemp:
printError = True
# Workaround for some Windows systems where os.devnull (the 'nul' device) doesn't work
# On these systems, devnull will be replaced with a temporary file instead.
# See here for details:
# - https://github.com/jupyter/notebook/issues/2651#issuecomment-315628876
# - https://github.com/ipython/ipython/issues/9023
@staticmethod
def open():
try:
return open(os.devnull, 'w')
except:
if NullOrTemp.printError:
NullOrTemp.printError = False
traceback.print_exc()
print(">>>> WARNING: os.devnull not working! Using temporary file instead.")
return tempfile.TemporaryFile()
def findWorkingExecutablePath(executable_paths, flags):
#type: (List[str], List[str]) -> str
"""
Try to execute each path in executable_paths to see which one can be called and returns exit code 0
The 'flags' argument is any extra flags required to make the executable return 0 exit code
:param executable_paths: a list [] of possible executable paths (eg. "./7za", "7z")
:param flags: a list [] of any extra flags like "-h" required to make the executable have a 0 exit code
:return: the path of the valid executable, or None if no valid executables found
"""
extra_paths = []
if Globals.DEVELOPER_MODE:
if Globals.IS_WINDOWS:
bundled_dev_path = 'bootstrap/higu_win_installer_32/install_data'
elif Globals.IS_MAC:
bundled_dev_path = 'bootstrap/higu_mac_installer/install_data'
elif Globals.IS_LINUX:
bundled_dev_path = 'bootstrap/higu_linux64_installer/install_data'
for path in executable_paths:
extra_paths.append(os.path.join(bundled_dev_path, path))
with NullOrTemp.open() as os_devnull:
for path in executable_paths + extra_paths:
try:
if subprocess.call([path] + flags, stdout=os_devnull, stderr=os_devnull) == 0:
return path
except:
pass
return None
# Python 2 Compatibility
def read_input():
try:
return input()
except:
return raw_input()
def printErrorMessage(text):
"""
Prints message in red if stdout is a tty
"""
try:
if sys.stdout.isatty:
print("\x1b[1m\x1b[31m" + text + "\x1b[0m")
else:
print(text)
except AttributeError:
print(text)
################################################## Global Variables#####################################################
class Globals:
GITHUB_MASTER_BASE_URL = "https://raw.githubusercontent.com/07th-mod/python-patcher/master/"
# The installer info version this installer is compatibile with
# Increment it when you make breaking changes to the json files
JSON_VERSION = 12
# Define constants used throughout the script. Use function calls to enforce variables as const
IS_WINDOWS = platform.system() == "Windows"
IS_LINUX = platform.system() == "Linux"
IS_MAC = platform.system() == "Darwin"
# Set os string matching string used in the JSON file, for convenience
OS_STRING = "windows"
if IS_LINUX:
OS_STRING = "linux"
elif IS_MAC:
OS_STRING = "mac"
# This variable force installation of mod assets from another operating system
# Should be either "windows", "linux", or "mac" as per above OS_STRING values
FORCE_ASSET_OS_STRING = None
ARIA_EXECUTABLE = None
SEVEN_ZIP_EXECUTABLE = None
CURL_EXECUTABLE = None # Not required, but if available will be used to download filenames on systems with old SSL versions
CURL_USE_BUNDLED_CERT = None
LOG_FOLDER = 'INSTALLER_LOGS'
LOG_BASENAME = datetime.datetime.now().strftime('MOD-INSTALLER-LOG-%Y-%m-%d_%H-%M-%S.txt')
LOG_FILE_PATH = os.path.join(LOG_FOLDER, LOG_BASENAME)
LOGS_ZIP_FILE_PATH = "07th-mod-logs.zip"
# Set to 'True' in main.py if installData.json is detected on disk
DEVELOPER_MODE = False
DEBUG_THREAD_INFO = False
"""Print to console when threads start or stop (these print statements have been manually added)"""
DEBUG_BROWSER_REQUESTS = False
DEBUG_GAME_SCAN_VERBOSE = False
BUILD_INFO = 'Build info not yet retrieved'
INSTALL_LOCK_FILE_PATH = 'lockfile.lock'
IS_PYTHON_2 = sys.version_info.major == 2
FREE_SPACE_ESTIMATE_SCALING = 4
FREE_SPACE_ESTIMATE_FIXED = 5000000000
URL_FILE_SIZE_LOOKUP_TABLE = {}
PERMISSON_DENIED_ERROR_MESSAGE = "Permission error: See our installer wiki FAQ about this error at https://07th-mod.com/wiki/Installer/faq/#extraction-stage-fails-i-get-an-acess-denied-error-when-overwriting-files"
PROTON_ERROR_MESSAGE = ("It looks like you have installed the game under Proton or Wine\n"
"Please select the game in your Steam Library, right click, choose Properties, then under 'Compatability' force the use of 'Steam Linux Runtime'\n"
"For a video showing how to do this, see here: https://www.youtube.com/watch?v=f1GvONkE9S0\n"
"\n"
"If you deliberately want to install under Proton or Wine, follow the 'Linux Wine' instructions here: https://07th-mod.com/wiki/Higurashi/Higurashi-Part-1---Voice-and-Graphics-Patch/\n"
"\n")
PROTON_WITH_ASSETS_OVERRIDE_MESSAGE = "NOTE: Game is running under Proton/Wine, but user has deliberately selected which OS's assets to install, so it is OK"
CA_CERT_PATH = None
URLOPEN_CERT_PATH = None
URLOPEN_IS_BROKEN = False
NATIVE_LAUNCHER_PATH = None
GIT_TAG = None
"""The git tag associated with this installer release. Can be None if installer run directly from source"""
BUILD_DATE = None
"""The date this installer was built. Can be None if installer run directly from source"""
INSTALLER_IS_LATEST = (None, "")
"""True if installer is latest released version, False if installer is not latest, None if can't determine if is latest
The second part of the tuple is set to a descriptive message explaining the version status"""
LAUNCH_BROWSER = True
"""Normally the Python scripts launch the browser to view the web interface. However if the Rust side handles
launching a webview or browser we want to avoid opening the browser twice, which can be done by setting this
variable to False (set by command line arg)
Currently this is only used when the Rust launcher on Windows opens a Webview, so launching browser is not necessary"""
@staticmethod
def scanForCURL():
# For now, just try to find a curl executable at all, don't check internet connectivity or if TLS is working
# Later in chooseCurlCertificate() we will check certs
Globals.CURL_EXECUTABLE = findWorkingExecutablePath(["curl", "curl_bundled"], ['-V'])
# this function must be run AFTER scanCertLocation()
@staticmethod
def chooseCurlCertificate():
# For now, this only executes if curl is available
if Globals.CURL_EXECUTABLE is None:
print("chooseCurlCertificate(): CURL not available: Not testing certificates.")
return
def testCurlHeaders(url, certPath):
args = [Globals.CURL_EXECUTABLE]
if certPath is not None:
args += ['--cacert', certificate_path]
args += ['-I', url]
with NullOrTemp.open() as os_devnull:
return subprocess.call(args, stdout=os_devnull, stderr=os_devnull) == 0
# Try:
# 1. Default Cert (whatever CURL uses when you don't specify argument)
# 2. On Linux, we scan for certs on the user's computer and store the first found one. Try this.
# 3. Try the certificate we bundle with the installer. We try this last becuase it might be out of date, depending on when the installer was last released.
paths_to_try = [None, Globals.CA_CERT_PATH, "curl-ca-bundle.crt"]
for certificate_path in paths_to_try:
if not testCurlHeaders('https://github.com/', certificate_path):
print("chooseCurlCertificate(): Failed to download headers using CURL from github.com using cert [{}]".format(certificate_path))
continue
print("chooseCurlCertificate(): Will use certificate [{}] when using cURL".format(certificate_path))
Globals.CA_CERT_PATH = certificate_path
return
print("chooseCurlCertificate(): ERROR: No certificates were found to work, tried [{}] Probably can't use installer!".format(paths_to_try))
# this function must be run AFTER scanCertLocation()
@staticmethod
def chooseURLOpenCertificate():
def testURLOpenHeaders(url, certPath):
try:
urlopen(url, context=ssl.create_default_context(cafile=certPath))
return True
except Exception as error:
print("Error: chooseURLOpenCertificate() Failed: {}".format(error))
return False
# Try:
# 1. Default Cert (whatever CURL uses when you don't specify argument)
# 2. On Linux, we scan for certs on the user's computer and store the first found one. Try this.
# 3. Try the certificate we bundle with the installer. We try this last becuase it might be out of date, depending on when the installer was last released.
paths_to_try = [None, Globals.CA_CERT_PATH, "curl-ca-bundle.crt"]
for certificate_path in paths_to_try:
if not testURLOpenHeaders(Request('https://github.com/', headers={"User-Agent": ""}), certificate_path):
print("chooseURLOpenCertificate(): Failed to download headers using urlOpen from github.com using cert [{}]".format(certificate_path))
continue
print("chooseURLOpenCertificate(): Will use certificate [{}] for URLOpen()".format(certificate_path))
Globals.URLOPEN_CERT_PATH = certificate_path
return
print("chooseURLOpenCertificate(): ERROR: No certificates were found to work, tried [{}] Probably can't use installer!".format(paths_to_try))
@staticmethod
def scanForAria():
ariaSearchPaths = ["./aria2c", "./.aria2c", "aria2c"]
Globals.ARIA_EXECUTABLE = findWorkingExecutablePath(ariaSearchPaths, ['https://github.com/', '--dry-run=true'])
if Globals.ARIA_EXECUTABLE is None:
print("\nWARNING: aria2 failed to download 07th-mod website. Using fallback detection method.")
Globals.ARIA_EXECUTABLE = findWorkingExecutablePath(ariaSearchPaths, ['-h'])
if Globals.ARIA_EXECUTABLE is None:
# TODO: automatically download and install dependencies
raise Exception("ERROR: aria2c executable not found (aria2c). Please install the dependencies for your platform.")
else:
print("Found aria2c at [{}]".format(Globals.ARIA_EXECUTABLE))
@staticmethod
def scanForSevenZip():
Globals.SEVEN_ZIP_EXECUTABLE = findWorkingExecutablePath(["./7za64", "./7za", "./.7za", "7za", "./7z", "7z"], ['-h'])
if Globals.SEVEN_ZIP_EXECUTABLE is None:
# TODO: automatically download and install dependencies
raise Exception("ERROR: 7-zip executable not found (7za or 7z). Please install the dependencies for your platform.")
else:
print("Found 7-zip at [{}]".format(Globals.SEVEN_ZIP_EXECUTABLE))
@staticmethod
def scanForExecutables():
startAndJoinThreads(
[makeThread(t) for t in [Globals.scanForCURL, Globals.scanForAria, Globals.scanForSevenZip]]
)
@staticmethod
def macUnQuarantineExecutable(path):
errorString = None
try:
exit_code = subprocess.call(["xattr", "-d", "com.apple.quarantine", path])
if exit_code != 0:
errorString = "xattr returned exit code {}".format(exit_code)
except Exception as e:
errorString = str(e)
if errorString is not None:
print("""Error removing quarantine: {}
You can try manually running [{}] once so the installer can use the file.""".format(errorString, path))
@staticmethod
def loadCachedDownloadSizes(modList):
"""
In normal mode:
- Load cached download sizes from Github (`cachedDownloadSizes.json` in repo root).
- On failure to retrieve, will leave the lookup table as an empty dict
In developer mode:
- Load cached download sizes from `cachedDownloadSizes.json` on disk
- If any URLs from installData.json are missing, this function will automatically update `cachedDownloadSizes.json`
:param modList: The JSON object returned by common.getModList()
"""
try:
if Globals.DEVELOPER_MODE:
downloadSizesDict, _error = getJSON('cachedDownloadSizes.json', isURL=False)
else:
downloadSizesDict, _error = getJSON(Globals.GITHUB_MASTER_BASE_URL + 'cachedDownloadSizes.json', isURL=True)
if downloadSizesDict is None:
print("ERROR: Failed to retrieve cachedDownloadSizes.json file")
else:
Globals.URL_FILE_SIZE_LOOKUP_TABLE = downloadSizesDict
# In developer mode, check that all URLs in the json file also exist in the downloadList.
# If they don't, regenerate the downloadList
if Globals.DEVELOPER_MODE:
if sys.version_info >= (3, 0):
import cacheDownloadSizes
for urlToCheck in cacheDownloadSizes.getAllURLsFromModList(modList):
if urlToCheck not in Globals.URL_FILE_SIZE_LOOKUP_TABLE:
print("DEVELOPER: cachedDownloadSizes.json is missing url {} - regenerating list".format(urlToCheck))
try:
cacheDownloadSizes.generateCachedDownloadSizes()
except:
msg = "Failed to regenerate cachedDownloadSizes.json. Please check installer log for 'Could not query URL' to determine which URL in installData.json failed to load, and for other errors."
print("DEVELOPER: " + msg)
try:
from tkinter import messagebox
messagebox.showerror("Cached Download Regeneration Failure", msg)
except:
pass
break
else:
print("DEVELOPER: skipping cachedDownloadSizes.json regeneration as you are running Python 2. Please use Python 3 to regenerate the download size cache.")
except Exception:
print("Developer ERROR: Failed to read URL File Size Lookup Table")
traceback.print_exc()
@staticmethod
def getBuildInfo():
if Globals.DEVELOPER_MODE:
Globals.BUILD_DATE = "{}".format(datetime.datetime.now())
Globals.GIT_TAG = "v0.0.0-dev-build"
Globals.BUILD_INFO = "Git Tag: {}\nBuild Date:{}".format(Globals.GIT_TAG, Globals.BUILD_DATE)
return
try:
with open('build_info.json', 'r') as build_info_file:
buildInfo = json.load(build_info_file)
Globals.BUILD_DATE = buildInfo['build_date']
Globals.GIT_TAG = buildInfo['git_tag']
Globals.BUILD_INFO = "Git Tag: {}\nBuild Date:{}".format(Globals.GIT_TAG, Globals.BUILD_DATE)
except Exception as e:
Globals.BUILD_INFO = None
print("Failed to retrieve build info: {}".format(e))
traceback.print_exc()
@staticmethod
def loadInstallerLatestStatus():
try:
latestVersion = getLatestInstallerVersion()
currentVersion = Globals.GIT_TAG
if currentVersion is None or latestVersion is None:
Globals.INSTALLER_IS_LATEST = (None, "WARNING: Version status unknown. Current: {} Latest: {}".format(currentVersion, latestVersion))
elif latestVersion == currentVersion:
Globals.INSTALLER_IS_LATEST = (True, "Installer is latest version: {}".format(currentVersion))
else:
Globals.INSTALLER_IS_LATEST = (False, "WARNING: This installer [{}] is outdated. Latest installer is [{}]".format(currentVersion, latestVersion))
except Exception as e:
Globals.INSTALLER_IS_LATEST = (None, "WARNING: Version status unknown")
print("Failed to determine whether installer was latest version: {}".format(e))
traceback.print_exc()
print("> {}".format(Globals.INSTALLER_IS_LATEST[1]))
@staticmethod
def scanCertLocation():
if Globals.IS_LINUX:
# List of cert locations from https://github.com/golang/go/blob/master/src/crypto/x509/root_linux.go
for possibleCertLocation in [
"/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
"/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
"/etc/ssl/ca-bundle.pem", # OpenSUSE
"/etc/pki/tls/cacert.pem", # OpenELEC
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
"/etc/ssl/cert.pem", # Alpine Linux
]:
if os.path.exists(possibleCertLocation):
Globals.CA_CERT_PATH = possibleCertLocation
print("[Linux] CA Cert - found at: {}".format(Globals.CA_CERT_PATH))
return
@staticmethod
def getURLOpenContext():
context = None
if Globals.URLOPEN_CERT_PATH:
context = ssl.create_default_context(cafile=Globals.URLOPEN_CERT_PATH)
return context
# You can use the 'exist_ok' of python3 to do this already, but not in python 2
def makeDirsExistOK(directoryToMake):
if os.path.exists(directoryToMake):
return
# Only return once the folder has actually been created
for i in range(5):
try:
os.makedirs(directoryToMake)
except Exception as e:
print("Attempt {} to create {} failed: {}".format(i, directoryToMake, e))
if os.path.exists(directoryToMake):
return
time.sleep(1)
raise Exception("Couldn't create directory {}".format(directoryToMake))
def tryShowInFileBrowser(path):
trySystemOpen(path, True)
def trySystemOpen(path, normalizePath=False):
"""
Tries to open a given path using the system 'open' function
The path can be a on-disk folder or a URL
NOTE: this function call does not block! (uses subprocess.Popen)
NOTE: paths won't open properly on windows if they contain backslashes. Set 'normalizePath' to handle this problem.
:param path: the path to show
:return: true if successful, false otherwise
"""
try:
if normalizePath:
path = os.path.normpath(path)
print("Attempting to open path {} in system browser...".format(path))
if not os.path.exists(path):
print("WARNING: Path {} does not exist - system open will probably fail!".format(path))
if Globals.IS_WINDOWS:
return subprocess.Popen(["explorer", path]) == 0
elif Globals.IS_MAC:
return subprocess.Popen(["open", path]) == 0
else:
return subprocess.Popen(["xdg-open", path]) == 0
except Exception as e:
print("Failed to show path {} in browser:\n{}".format(path, e))
return False
def openURLInBrowser(url):
webbrowser.open(url, new=2, autoraise=True)
#TODO: capture both stdout and stderr
# TODO: in the future, this function could be simplified (remove aria2c specific hacks) by:
# - using --summary-interval=5 for aria2c to force the long summary to be printed more often (which gives a newline)
# - OR running aria2c in RPC mode
# 7z would also need to be checked on all platforms as working correctly.
# lineMonitor must be an object with a "process(line)" function, which will be called at each newline, %, or ']' char
# It can be used to monitor the output of the process being run.
def runProcessOutputToTempFile(arguments, ariaMode=False, sevenZipMode=False, lineMonitor=None):
print("----- BEGIN EXECUTING COMMAND: [{}] -----".format(" ".join(arguments)))
# need universal_newlines=True so stdout is opened in normal. However, this might result in garbled japanese(unicode) characters!
# to fix this properly, you would need to make a custom class which takes in raw bytes using stdout.read(10)
# and then periodically convert newline delimited sections of the text to utf-8 (or whatever encoding), and catch bad encoding errors
# See comments on https://stackoverflow.com/a/15374326/848627 and answer https://stackoverflow.com/a/48880977/848627
# drojf: Removed universal_newlines, to fix issues with non-windows locales breaking this part of the installer
# see https://stackoverflow.com/questions/38181494/what-is-the-difference-between-using-universal-newlines-true-with-bufsize-1-an?rq=1
# The default bufsize works fine on Windows (seems to be line buffered, or maybe the flush() works as expected on Windows)
proc = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def readUntilEOF(proc, fileLikeObject):
stringBuffer = []
while proc.poll() is None:
try:
fileLikeObject.flush()
while True:
if Globals.IS_PYTHON_2:
character = fileLikeObject.read(1)
else:
character = fileLikeObject.read(1).decode(encoding='utf-8', errors='replace')
if character:
if character == '\r':
character = ' '
stringBuffer.append(character)
writeOutBuffer = False
writeOutCausedByNewline = False
# Write out buffer if newline detected
if character == '\n':
writeOutBuffer = True
writeOutCausedByNewline = True
# Insert newline after ']' characters
if ariaMode and character == ']':
stringBuffer.append('\n')
writeOutBuffer = True
# Insert newline after % characters
if sevenZipMode and character == '%':
stringBuffer.append('\n')
writeOutBuffer = True
if writeOutBuffer:
line = ''.join(stringBuffer)
if writeOutCausedByNewline:
print(line, end='')
else:
print(line.lstrip(), end='')
if lineMonitor:
lineMonitor.process(line)
stringBuffer = []
else:
break
except Exception as e:
#reduce cpu usage if some exception is continously thrown
print("Error in [runProcessOutputToTempFile()]: {}".format(traceback.format_exc()))
time.sleep(.1)
# Monitor stderr on one thread, and monitor stdout on main thread
t = threading.Thread(target=readUntilEOF, args=(proc, proc.stderr))
t.start()
readUntilEOF(proc, proc.stdout)
print("--------------- EXECUTION FINISHED ---------------\n")
return proc.returncode
#when calling this function, use named arguments to avoid confusion!
def aria(downloadDir=None, inputFile=None, url=None, followMetaLink=False, useIPV6=False, outputFile=None):
"""
Calls aria2c with some default arguments:
Note about continuing downloads/control file save frequency
By default, aria2c saves the control file every 60s, or when aria2c is closed non-forcefully.
This means that if you close aria2c forcefully, you will lose up to the last 1 minute of download.
This value can be changed with --auto-save-interval=<SEC>, but we have left it as the default here.
:param downloadDir: The directory to store the downloaded file(s)
:param inputFile: The path to a file containing multiple URLS to download (see aria2c documentation)
:param outputFile: When downloading a single file, if this is specified, it will be downloaded with the given name
:return Returns the exit code of the aria2c call
"""
arguments = [
Globals.ARIA_EXECUTABLE,
"--file-allocation=none", # Pre-allocate space where the downloaded file will be saved
'--continue=true', # Allow continuing the download of a partially downloaded file (is this flag actually necessary?)
'--retry-wait=5', # Seconds to wait between retries
'-m 0', # max number of retries (0=unlimited). In some cases, like server rejects download, aria2c won't retry.
'-x 1', # max connections to the same server
'-s 8', # how many mirrors to use to download each file - currently we only have one download source though
'-j 1', # how many files to download at the same time (eg number of separate urls which can be downloaded in parallel)
'--auto-file-renaming=false',
# By default, if aria2c detects a file already exists with the same name, and is different size to the file
# being downloaded (lets call this 'test.zip'), it will save to a different name ('test.2.zip', 'test.3.zip' etc)
# This option prevents this from happening. Continuing existing downloads where the file size is the same is still supported.
'--allow-overwrite=true',
# By default, aria2c will just error out if auto-renaming is disabled. Enabling this option allows aria2c to overwrite existing files,
# if they cannot be continued (by the --continue argument)
]
if followMetaLink:
arguments.append('--follow-metalink=mem')
arguments.append('--check-integrity=true') # check integrity when using metalink
else:
arguments.append('--follow-metalink=false')
if not useIPV6:
arguments.append('--disable-ipv6=true')
#Add an extra command line argument if the function argument has been provided
if downloadDir:
arguments.append('-d ' + downloadDir)
if inputFile:
arguments.append('--input-file=' + inputFile)
if url:
arguments.append(url)
if outputFile:
arguments.append("--out=" + outputFile)
if Globals.CA_CERT_PATH is not None:
arguments.append("--ca-certificate=" + Globals.CA_CERT_PATH)
# On linux, there is some problem where the console buffer is not read by runProcessOutputToTempFile(...) until
# a newline is printed. I was unable to fix this properly, however setting 'summary-interval' (default 60s) lower will
# force a newline to be printed every 5 seconds/the console output to flush.
if Globals.IS_LINUX:
arguments.append('--summary-interval=5')
# with open('seven_zip_stdout.txt', "w", buffering=100) as outfile:
# return subprocess.call(arguments, stdout=outfile)
return runProcessOutputToTempFile(arguments, ariaMode=True)
class SevenZipMonitor:
regexSevenZipError = re.compile(r'^\s*ERROR:.*')
def __init__(self):
self.error_access_denied = False
self.error_delete_output_file = False
self.error_data = False
self.unknown_error_string = None
def process(self, line):
if SevenZipMonitor.regexSevenZipError.match(line):
got_error = False
if 'Data Error' in line:
self.error_data = True
got_error = True
if 'Access is denied' in line:
self.error_access_denied = True
got_error = True
if 'Can not delete output file' in line:
self.error_access_denied = True
got_error = True
if not got_error:
self.unknown_error_string = line
def getErrorMessage(self):
errors = []
if self.error_access_denied or self.error_delete_output_file:
errors.append(Globals.PERMISSON_DENIED_ERROR_MESSAGE)
if self.error_data:
errors.append("Archive Corrupted Error: This error should never happen - please send the 07th-mod team your install log")
if self.unknown_error_string:
errors.append("Unknown Error: {}. You may want to check our Installer FAQ: https://07th-mod.com/wiki/Higurashi/Higurashi-Part-1---Voice-and-Graphics-Patch/#installer-faq-and-troubleshooting or get help on our Discord Server: https://discord.gg/pf5VhF9".format(self.unknown_error_string))
return '\n'.join(errors)
def sevenZipExtract(archive_path, outputDir=None, lineMonitor=None):
arguments = [Globals.SEVEN_ZIP_EXECUTABLE,
"x",
archive_path,
"-aoa", # overwrite All existing files without prompt (-ao means 'overwrite mode', a means 'All')
"-bso1", # redirect standard Output messages to stdout
"-bsp1", # redirect Progress update messages to stdout
"-bse2", # redirect Error messages to stderr
]
if outputDir:
arguments.append('-o' + outputDir)
return runProcessOutputToTempFile(arguments, sevenZipMode=True, lineMonitor=lineMonitor)
def sevenZipTest(archive_path):
"""
Validate/Test a 7-zip archive.
:param archive_path: The path to the archive to test
:return: The 7-zip return code as an int (0 is Success),
"""
arguments = [Globals.SEVEN_ZIP_EXECUTABLE,
"t",
archive_path,
"-bso1", # redirect standard Output messages to stdout
"-bsp1", # redirect Progress update messages to stdout
"-bse2", # redirect Error messages to stderr
]
return runProcessOutputToTempFile(arguments, sevenZipMode=True)
def preloadModUpdatesHTML():
html, errorInfo = getJSON("https://github.com/07th-mod/python-patcher-updates/releases/latest/download/updates.json", isURL=True)
if errorInfo is not None:
print('WARNING: Failed to get mod updates from server')
print(errorInfo)
return html
def getJSON(jsonURI, isURL):
#type: (str, bool) -> (Dict, Exception)
"""
:param jsonURI: Path to a file or URL to download
:param isURL: Specify whether the URI is for a URL or path
:return:
"""
tmpdir = None
file = None
try:
if isURL:
jsonString = downloadFile(jsonURI, is_text=True)
info = json.loads(jsonString)
else:
file = io.open(jsonURI, "r", encoding='utf-8')
info = json.load(file)
except HTTPError as error:
return None, error
except Exception as anyError:
return None, anyError
finally:
if file is not None:
file.close()
return info, None
def getModList(jsonURI, isURL):
"""
Gets the list of available mods from the 07th Mod server
:return: A list of mod info objects
:rtype: list[dict]
"""
info, exception = getJSON(jsonURI, isURL)
if info is None:
if exception is HTTPError:
raise Exception("""------------------------------------------------------------------------
Error: Couldn't reach Github to download mod list! ({})
Please check the following:
- You have a working internet connection
- Check if you can manually download the following file ({})
- Check our Wiki for more solutions: https://www.07th-mod.com/wiki/Installer/faq/
Detailed Error: {}
------------------------------------------------------------------------""".format(jsonURI, jsonURI, exception))
else:
raise Exception("""------------------------------------------------------------------------
Error while reading JSON: {}
Please check the following:
- Tell the developers
- You have a working internet connection
- Check if you can manually download the following file ({})
- Check our Wiki for more solutions: https://www.07th-mod.com/wiki/Installer/faq/
------------------------------------------------------------------------""".format(exception, jsonURI))
try:
version = info["version"]
if version > Globals.JSON_VERSION:
printErrorMessage("Your installer is out of date.")
printErrorMessage("Please download the latest version of the installer and try again.")
raise Exception("""-------------------------------------------------------------------------------
Your installer is out of date.
Please download the latest version of the installer and try again.
Your installer is compatible with mod listings up to version {} but the latest listing is version {}
-------------------------------------------------------------------------------""".format(Globals.JSON_VERSION, version))
except KeyError:
print("Warning: The mod info listing is missing a version number. Things might not work.")
return info
return info["mods"]
def printSupportedGames(modList):
"""
Prints a list of games that have mods available for them
:param list[dict] modList: The list of available mods
"""
print("Supported games:")
for game in set(x["target"] for x in modList):
print(" " + game)
def makeExecutable(executablePath):
current = os.stat(executablePath)
os.chmod(executablePath, current.st_mode | 0o111)
def getMetalinkFilenames(url):
import xml.etree.ElementTree as ET
root = ET.fromstring(downloadFile(url, is_text=True))
def getTagNoNamespace(tag):
return tag.split('}')[-1]
# return the 'name' attribute of each 'file' node.
# ignore namespaces by removing the {stuff} part of the tag
filename_length_pairs = []
for fileNode in root.iter():
if getTagNoNamespace(fileNode.tag) == 'file':
length = 0
fileURL = None
for fileNodeChild in fileNode:
if getTagNoNamespace(fileNodeChild.tag) == 'size':
try:
length = int(fileNodeChild.text)
except:
pass
if getTagNoNamespace(fileNodeChild.tag) == 'url':
fileURL = fileNodeChild.text
filename_length_pairs.append((fileNode.attrib['name'], length, fileURL))
return filename_length_pairs
class SevenZipException(Exception):
def __init__(self, errorReason):
# type: (str) -> None
self.errorReason = errorReason # type: str
def __str__(self):
return self.errorReason
# Split archives are usually something like 'test.7z.001', 'test.7z.002' or 'test.zip.013'
split_file_regex = re.compile(r'\.(\d+)$')
def extractOrCopyFile(filename, sourceFolder, destinationFolder, copiedOutputFileName=None):
makeDirsExistOK(destinationFolder)
sourcePath = os.path.join(sourceFolder, filename)
if '.7z' in filename.lower() or '.zip' in filename.lower():
split_extension = split_file_regex.search(filename.lower())
if split_extension:
split_archive_number = int(split_extension.group(1))
# Assume archive numbers start at 1
# Only process split archives where the index is '1', ignore all others as they will be processed automatically
if split_archive_number != 1:
return
monitor = SevenZipMonitor()
if sevenZipExtract(sourcePath, outputDir=destinationFolder, lineMonitor=monitor) != 0:
raise SevenZipException("{}\n\n Could not extract [{}]".format(monitor.getErrorMessage(), sourcePath))
else:
try:
shutil.copy(sourcePath, os.path.join(destinationFolder, copiedOutputFileName if copiedOutputFileName else filename))
except shutil.SameFileError:
print("Source and Destination are the same [{}]. No action taken.".format(sourcePath))
def prettyPrintFileSize(fileSizeBytesWithSign):
#type: (int) -> str
fileSizeBytes = fileSizeBytesWithSign
sign = ''
if fileSizeBytesWithSign < 0:
fileSizeBytes = -fileSizeBytesWithSign
sign = '-'
if fileSizeBytes >= 1e9:
return "{}{:.1f}".format(sign, fileSizeBytes / 1e9) + ' GB'
elif fileSizeBytes >= 1e6:
return "{}{:.0f}".format(sign, fileSizeBytes / 1e6) + ' MB'
elif fileSizeBytes > 0:
return "{}{:.0f}".format(sign, fileSizeBytes / 1e3) + ' KB'
else:
return "0 KB"
class DownloadAndVerifyError(Exception):
def __init__(self, errorReason):
# type: (str) -> None
self.errorReason = errorReason # type: str
def __str__(self):
return self.errorReason
class DownloaderAndExtractor:
"""
####################################################################################################################
#
# Downloads and/or Extracts a list of ModFile objects
#
# Usage: Call 'download' then 'extract'.
# If you have metalinks in your path, callin only 'extract' may require fetching the metafiles to determine what
# to extract
#
# a ModFile is an object which contains a url and a priority (int). The priority extraction order.
# See the modfile class for more information
# You can use the FullInstallConfig.buildFileListSorted() to generate the modFileList, which handles
# ordering the ModFiles and using different modfiles on different operating systems/steam/mg installs
#
# Metafile Handling:
# - For metafiles, we need to look for filenames within each metafile to know what to extract
# - The order of the download and extraction is maintained through the list ordering.
#
# Archive Handling:
# - Archives will be extracted in to the downloadTempDir folder
#
# Other file handling:
# - Any other types of files will be copied (overwritten) from the downloadTempDir to the extractionDir
# - If the path of the file is the same as the destination (a no op), the file won't be copied (it will do nothing)
#
# Folder Creation:
# - All folders will be created if they don't already exist
#
# Failure Modes:
# - if any downloads or extractions fail, the script will terminate
# - TODO: could improve success rate by retrying aria downloads multiple times
#
####################################################################################################################
:param modFileList: The a list of ModFile objects which will be downloaded and/or extracted
:param downloadTempDir: The folder where downloads will be saved
:param extractionDir: The folder where archives will be extracted to, and where any files will be copied to
:return:
"""
MAX_DOWNLOAD_ATTEMPTS_METALINK = 10
MAX_DOWNLOAD_ATTEMPTS = 3
class ExtractableItem:
def __init__(self, filename, length, destinationPath, fromMetaLink, remoteLastModified, fileURL=None):
self.filename = filename
self.length = length
self.destinationPath = os.path.normpath(destinationPath)
self.fromMetaLink = fromMetaLink
self.remoteLastModified = remoteLastModified
self.fileURL = fileURL
def __repr__(self):
return '[{} ({})] to [{}] {}'.format(self.filename, prettyPrintFileSize(self.length), self.destinationPath, "(metalink)" if self.fromMetaLink else "")
def clearDownloadIfNeededAndWriteControlFile(self, downloadDir):
# Files from metalinks are checksummed, so clearing old downloads is not required
if self.fromMetaLink:
return
# If remote has no date modified, assume file needs to be cleared
if self.remoteLastModified is None:
print("ExtractableItem: Clearing [{}] as remote has no last-modified".format(self.filename))
self._tryDeleteOldDownloadAndAriaFile(downloadDir)
return
# If local date modified is different, clear the file and update control file
localDateModifiedControlPath = os.path.join(downloadDir, self._dateModifiedControlFilename())
localLastModified = self._readLocalDateModified(localDateModifiedControlPath)
if self._normalizeDateModified(localLastModified) != self._normalizeDateModified(self.remoteLastModified):
print("ExtractableItem: Clearing [{}] as local [{}] and remote [{}] last-modified differ"
.format(self.filename, localLastModified, self.remoteLastModified))
self._tryDeleteOldDownloadAndAriaFile(downloadDir)
self._updateLocalDateModified(localDateModifiedControlPath)
else:
# Take no action if local and remote date modified is the same - can resume the download normally
pass
@staticmethod
def _normalizeDateModified(lastModifiedStringOrNone):
#type: (Optional[str]) -> Optional[str]
return None if lastModifiedStringOrNone is None else lastModifiedStringOrNone.strip()
def _dateModifiedControlFilename(self):
return self.filename + ".dateModified"
def _readLocalDateModified(self, localDateModifiedControlPath):
if not os.path.exists(localDateModifiedControlPath):
return None
try:
with io.open(localDateModifiedControlPath, "r", encoding='UTF-8') as f:
return f.read()
except Exception as e:
print("Failed to load date modified file {}: {}".format(localDateModifiedControlPath, e))
return None
def _updateLocalDateModified(self, localDateModifiedControlPath):
try:
with io.open(localDateModifiedControlPath, "w", encoding='UTF-8') as f:
f.write(self.remoteLastModified)
except Exception as e:
print("Failed to write date modified file {}: {}".format(localDateModifiedControlPath, e))
def _tryDeleteOldDownloadAndAriaFile(self, downloadDir):