forked from eddie3/gogrepo
-
Notifications
You must be signed in to change notification settings - Fork 38
/
gogrepoc.py
executable file
·3992 lines (3525 loc) · 196 KB
/
gogrepoc.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
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__appname__ = 'gogrepoc.py'
__author__ = 'eddie3,kalaynr'
__version__ = '0.4.0-a'
__url__ = 'https://github.com/kalanyr/gogrepoc'
# imports
import unicodedata
import os
import sys
import threading
import logging
import html5lib
import pprint
import time
import zipfile
import hashlib
import getpass
import argparse
import codecs
import io
import datetime
import shutil
import xml.etree.ElementTree
import copy
import logging.handlers
import ctypes
import requests
import re
import OpenSSL
import platform
import locale
import zlib
from fnmatch import fnmatch
import email.utils
import signal
if sys.version_info[0] < 3 or ( sys.version_info[0] < 4 and sys.version_info[1] < 7):
import dateutil #pip package name is python-dateutil
# python 2 / 3 imports
try:
# python 2
from Queue import Queue
from urlparse import urlparse,unquote,urlunparse,parse_qs
from itertools import izip_longest as zip_longest
from StringIO import StringIO
except ImportError:
# python 3
from queue import Queue
from urllib.parse import urlparse, unquote, urlunparse,parse_qs
from itertools import zip_longest
from io import StringIO
if (platform.system() == "Windows"):
import ctypes.wintypes
if (platform.system() == "Darwin"):
import CoreFoundation #import CFStringCreateWithCString, CFRelease, kCFStringEncodingASCII
import objc #import pyobjc_id
if not ((platform.system() == "Darwin") or (platform.system() == "Windows")):
try:
import PyQt5.QtDBus
except ImportError:
pass
# python 2 / 3 renames
try: input = raw_input
except NameError: pass
# optional imports
try:
from html2text import html2text
except ImportError:
def html2text(x): return x
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
CREATE_NEW = 0x1
OPEN_EXISTING = 0x3
FILE_BEGIN = 0x0
# lib mods
# configure logging
LOG_MAX_MB = 180
LOG_BACKUPS = 9
logFormatter = logging.Formatter("%(asctime)s | %(message)s", datefmt='%H:%M:%S')
rootLogger = logging.getLogger('ws')
rootLogger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler(sys.stdout)
loggingHandler = logging.handlers.RotatingFileHandler('gogrepo.log', mode='a+', maxBytes = 1024*1024*LOG_MAX_MB , backupCount = LOG_BACKUPS, encoding=None, delay=True)
loggingHandler.setFormatter(logFormatter)
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
# logging aliases
info = rootLogger.info
warn = rootLogger.warning
debug = rootLogger.debug
error = rootLogger.error
log_exception = rootLogger.exception
# filepath constants
GAME_STORAGE_DIR = r'.'
TOKEN_FILENAME = r'gog-token.dat'
MANIFEST_FILENAME = r'gog-manifest.dat'
RESUME_MANIFEST_FILENAME = r'gog-resume-manifest.dat'
CONFIG_FILENAME = r'gog-config.dat'
SERIAL_FILENAME = r'!serial.txt'
INFO_FILENAME = r'!info.txt'
#github API URLs
REPO_HOME_URL = "https://api.github.com/repos/kalanyr/gogrepoc"
NEW_RELEASE_URL = "/releases/latest"
# GOG URLs
GOG_HOME_URL = r'https://www.gog.com'
GOG_ACCOUNT_URL = r'https://www.gog.com/account'
GOG_LOGIN_URL = r'https://login.gog.com/login_check'
#GOG Galaxy URLs
GOG_AUTH_URL = r'https://auth.gog.com/auth'
GOG_GALAXY_REDIRECT_URL = r'https://embed.gog.com/on_login_success'
GOG_CLIENT_ID = '46899977096215655'
GOG_SECRET = '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9'
GOG_TOKEN_URL = r'https://auth.gog.com/token'
GOG_EMBED_URL = r'https://embed.gog.com'
# GOG Constants
GOG_MEDIA_TYPE_GAME = '1'
GOG_MEDIA_TYPE_MOVIE = '2'
# HTTP request settings
HTTP_FETCH_DELAY = 1 # in seconds
HTTP_RETRY_DELAY = 5 # in seconds #If you reduce this such that the wait between the first and third try is less than 10 seconds, you're gonna have a bad time with the 503 error.
HTTP_RETRY_COUNT = 4
HTTP_TIMEOUT = 60
HTTP_GAME_DOWNLOADER_THREADS = 4
HTTP_PERM_ERRORCODES = (404, 403) #503 was in here GOG uses it as a request to wait for a bit when it's under stress. The time out appears to be ~10 seconds in such cases.
USER_AGENT = 'GOGRepoC/' + str(__version__)
# Language table that maps two letter language to their unicode gogapi json name
LANG_TABLE = {'en': u'English', # English
'bl': u'\u0431\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438', # Bulgarian
'ru': u'\u0440\u0443\u0441\u0441\u043a\u0438\u0439', # Russian
'gk': u'\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', # Greek
'sb': u'\u0421\u0440\u043f\u0441\u043a\u0430', # Serbian
'ar': u'\u0627\u0644\u0639\u0631\u0628\u064a\u0629', # Arabic
'br': u'Portugu\xeas do Brasil', # Brazilian Portuguese
'jp': u'\u65e5\u672c\u8a9e', # Japanese
'ko': u'\ud55c\uad6d\uc5b4', # Korean
'fr': u'fran\xe7ais', # French
'cn': u'\u4e2d\u6587', # Chinese
'cz': u'\u010desk\xfd', # Czech
'hu': u'magyar', # Hungarian
'pt': u'portugu\xeas', # Portuguese
'tr': u'T\xfcrk\xe7e', # Turkish
'sk': u'slovensk\xfd', # Slovak
'nl': u'nederlands', # Dutch
'ro': u'rom\xe2n\u0103', # Romanian
'es': u'espa\xf1ol', # Spanish
'pl': u'polski', # Polish
'it': u'italiano', # Italian
'de': u'Deutsch', # German
'da': u'Dansk', # Danish
'sv': u'svenska', # Swedish
'fi': u'Suomi', # Finnish
'no': u'norsk', # Norsk
}
VALID_OS_TYPES = ['windows', 'linux', 'mac']
VALID_LANG_TYPES = list(LANG_TABLE.keys())
if (sys.version_info[0] >= 3):
universalLineEnd = ''
else:
universalLineEnd = 'U'
if (sys.version_info[0] == 3 and sys.version_info[1] >= 8) or sys.version_info[0] >= 4 :
storeExtend = 'extend'
else:
storeExtend = 'store'
DEFAULT_FALLBACK_LANG = 'en'
# Save manifest data for these os and lang combinations
sysOS = platform.system()
sysOS = sysOS.lower()
if sysOS == 'darwin':
sysOS = 'mac'
if not (sysOS in VALID_OS_TYPES):
sysOS = 'linux'
DEFAULT_OS_LIST = [sysOS]
sysLang,_ = locale.getlocale()
if (sysLang is not None):
sysLang = sysLang[:2]
sysLang = sysLang.lower()
if not (sysLang in VALID_LANG_TYPES):
sysLang = 'en'
DEFAULT_LANG_LIST = [sysLang]
#if DEFAULT_FALLBACK_LANG not in DEFAULT_LANG_LIST:
# DEFAULT_LANG_LIST.push(DEFAULT_FALLBACK_LANG)
# These file types don't have md5 data from GOG
SKIP_MD5_FILE_EXT = ['.txt', '.zip',''] #Removed tar.gz as it can have md5s and is actually parsed as .gz so wasn't working
for i in range(1,21):
n = i
a = "." + f'{n:03}'
SKIP_MD5_FILE_EXT.append(a)
INSTALLERS_EXT = ['.exe','.bin','.dmg','.pkg','.sh']
ORPHAN_DIR_NAME = '!orphaned'
DOWNLOADING_DIR_NAME = '!downloading'
PROVISIONAL_DIR_NAME = '!provisional'
IMAGES_DIR_NAME = '!images'
ORPHAN_DIR_EXCLUDE_LIST = [ORPHAN_DIR_NAME,DOWNLOADING_DIR_NAME,IMAGES_DIR_NAME, '!misc']
ORPHAN_FILE_EXCLUDE_LIST = [INFO_FILENAME, SERIAL_FILENAME]
RESUME_SAVE_THRESHOLD = 50
MANIFEST_SYNTAX_VERSION = 1
RESUME_MANIFEST_SYNTAX_VERSION = 1
token_lock = threading.RLock()
#request wrapper
def request(session,url,args=None,byte_range=None,retries=HTTP_RETRY_COUNT,delay=None,stream=False,data=None):
"""Performs web request to url with optional retries, delay, and byte range.
"""
_retry = False
if delay is not None:
time.sleep(delay)
renew_token(session)
try:
if data is not None:
if byte_range is not None:
response = session.post(url, params=args, headers= {'Range':'bytes=%d-%d' % byte_range},timeout=HTTP_TIMEOUT,stream=stream,data=data)
else:
response = session.post(url, params=args,stream=stream,timeout=HTTP_TIMEOUT,data=data)
else:
if byte_range is not None:
response = session.get(url, params=args, headers= {'Range':'bytes=%d-%d' % byte_range},timeout=HTTP_TIMEOUT,stream=stream)
else:
response = session.get(url, params=args,stream=stream,timeout=HTTP_TIMEOUT)
response.raise_for_status()
except (requests.HTTPError, requests.URLRequired, requests.Timeout,requests.ConnectionError,OpenSSL.SSL.Error) as e:
if isinstance(e, requests.HTTPError):
if e.response.status_code in HTTP_PERM_ERRORCODES: # do not retry these HTTP codes
warn('request failed: %s. will not retry.', e)
raise
if retries > 0:
_retry = True
else:
raise
if _retry:
warn('request failed: %s (%d retries left) -- will retry in %ds...' % (e, retries, HTTP_RETRY_DELAY))
return request(session=session,url=url, args=args, byte_range=byte_range, retries=retries-1, delay=HTTP_RETRY_DELAY,stream=stream,data=data)
return response
#Request Head weapper
def request_head(session,url,args=None,retries=HTTP_RETRY_COUNT,delay=None):
"""Performs web head request to url with optional retries, delay,
"""
_retry = False
if delay is not None:
time.sleep(delay)
renew_token(session)
try:
response = session.head(url, params=args,timeout=HTTP_TIMEOUT)
response.raise_for_status()
except (requests.HTTPError, requests.URLRequired, requests.Timeout,requests.ConnectionError,OpenSSL.SSL.Error) as e:
if isinstance(e, requests.HTTPError):
if e.response.status_code in HTTP_PERM_ERRORCODES: # do not retry these HTTP codes
warn('request failed: %s. will not retry.', e)
raise
if retries > 0:
_retry = True
else:
raise
if _retry:
warn('request failed: %s (%d retries left) -- will retry in %ds...' % (e, retries, HTTP_RETRY_DELAY))
return request_head(session=session,url=url, args=args, retries=retries-1, delay=HTTP_RETRY_DELAY)
return response
def renew_token(session,retries=HTTP_RETRY_COUNT,delay=None):
with token_lock:
_retry = False
if delay is not None:
time.sleep(delay)
time_now = time.time()
try:
if time_now + 300 > session.token['expiry']:
info('refreshing token')
try:
token_response = session.get(GOG_TOKEN_URL,params={'client_id':'46899977096215655' ,'client_secret':'9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9', 'grant_type': 'refresh_token','refresh_token': session.token['refresh_token']})
token_response.raise_for_status()
except Exception as e:
if retries > 0:
_retry = True
else:
error(e)
error('Could not renew token, Please login again.')
sys.exit(1)
if _retry:
warn('token refresh failed: %s (%d retries left) -- will retry in %ds...' % (e, retries, HTTP_RETRY_DELAY))
return renew_token(session=session, retries=retries-1, delay=HTTP_RETRY_DELAY)
token_json = token_response.json()
for item in token_json:
session.token[item] = token_json[item]
session.token['expiry'] = time_now + token_json['expires_in']
save_token(session.token)
session.headers['Authorization'] = "Bearer " + session.token['access_token']
info('refreshed token')
except AttributeError:
#Not a Token based session
pass
# --------------------------
# Helper types and functions
# --------------------------
class AttrDict(dict):
def __init__(self, **kw):
self.update(kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, val):
self[key] = val
class ConditionalWriter(object):
"""File writer that only updates file on disk if contents chanaged"""
def __init__(self, filename):
self._buffer = None
self._filename = filename
def __enter__(self):
self._buffer = tmp = StringIO()
return tmp
def __exit__(self, _exc_type, _exc_value, _traceback):
tmp = self._buffer
if tmp:
pos = tmp.tell()
tmp.seek(0)
file_changed = not os.path.exists(self._filename)
if not file_changed:
with codecs.open(self._filename, 'r', 'utf-8') as orig:
for (new_chunk, old_chunk) in zip_longest(tmp, orig):
if new_chunk != old_chunk:
file_changed = True
break
if file_changed:
with codecs.open(self._filename, 'w', 'utf-8') as overwrite:
tmp.seek(0)
shutil.copyfileobj(tmp, overwrite)
def slugify(value, allow_unicode=False):
'''
The below block comment applies to this function in it's entirety (including the header except for the BSD License text itself and this comment )
'''
'''
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Django nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize("NFKC", value)
else:
value = (
unicodedata.normalize("NFKD", value)
.encode("ascii", "ignore")
.decode("ascii")
)
value = re.sub(r"[^\w\s-]", "", value.lower())
return re.sub(r"[-\s]+", "-", value).strip("-_")
def path_preserving_split_ext(path):
path_without_extensions = os.path.join(os.path.dirname(path),os.path.basename(path).rsplit(os.extsep,1)[0]) #Need to improve this to handle eg tar.gz
extension = os.extsep + os.path.basename(path).rsplit(os.extsep,1)[1]
return [path_without_extensions,extension]
def move_with_increment_on_clash(src,dst,count=0):
if (count == 0):
potDst = dst
else:
root,ext = path_preserving_split_ext(dst)
if (ext != ".bin"):
potDst = root + "("+str(count) + ")" + ext
else:
#bin file, adjust name to account for gogs weird extension method
setDelimiter = root.rfind("-")
try:
setPart = int(root[setDelimiter+1:])
except ValueError:
#This indicators a false positive. The "-" found was part of the file name not a set delimiter.
setDelimiter = -1
if (setDelimiter == -1):
#not part of a bin file set , some other binary file , treat it like a non .bin file
potDst = root + "("+str(count) + ")" + ext
else:
potDst = root[:setDelimiter] + "("+str(count) + ")" + root[setDelimiter:] + ext
warn('Unresolved destination clash for "{}" detected. Trying "{}"'.format(dst,potDst))
if not os.path.exists(potDst):
shutil.move(src,potDst)
else:
move_with_increment_on_clash(src,dst,count+1)
def load_manifest(filepath=MANIFEST_FILENAME):
info('loading local manifest...')
try:
with codecs.open(filepath, 'r' + universalLineEnd, 'utf-8') as r:
# ad = r.read().replace('{', 'AttrDict(**{').replace('}', '})')
ad = r.read()
compiledregexopen = re.compile(r"'changelog':.*?'downloads':|({)",re.DOTALL)
compiledregexclose = re.compile(r"'changelog':.*?'downloads':|(})",re.DOTALL)
compiledregexmungeopen = re.compile(r"[AttrDict(**]+{")
compiledregexmungeclose = re.compile(r"}\)+")
def myreplacementopen(m):
if m.group(1):
return "AttrDict(**{"
else:
return m.group(0)
def myreplacementclose(m):
if m.group(1):
return "})"
else:
return m.group(0)
mungeDetected = compiledregexmungeopen.search(ad)
if mungeDetected:
warn("detected AttrDict error in manifest")
ad = compiledregexmungeopen.sub("{",ad)
ad = compiledregexmungeclose.sub("}",ad)
warn("fixed AttrDict in manifest")
ad = compiledregexopen.sub(myreplacementopen,ad)
ad = compiledregexclose.sub(myreplacementclose,ad)
if (sys.version_info[0] >= 3):
ad = re.sub(r"'size': ([0-9]+)L,",r"'size': \1,",ad)
db = eval(ad)
if (mungeDetected):
save_manifest(db)
return eval(ad)
except IOError:
return []
def save_manifest(items,filepath=MANIFEST_FILENAME,update_md5_xml=False,delete_md5_xml=False):
if update_md5_xml:
#existing_md5s = []
all_items_by_title = {}
# make convenient dict with title/dirname as key
for item in items:
try:
_ = item.folder_name
except AttributeError:
item.folder_name = item.title
all_items_by_title[item.folder_name] = item
if os.path.isdir("!md5_xmls"):
info ("Cleaning up " + "!md5_xmls")
for cur_dir in sorted(os.listdir("!md5_xmls")):
cur_fulldir = os.path.join("!md5_xmls", cur_dir)
if os.path.isdir(cur_fulldir):
if cur_dir not in all_items_by_title:
#ToDo: Maybe try to rename ? Content file names will probably change when renamed (and can't be recognised by md5s as partial downloads) so maybe not wortwhile ?
info("Removing outdated directory " + cur_fulldir)
if not dryrun:
shutil.rmtree(cur_fulldir)
else:
# dir is valid game folder, check its files
expected_dirnames = []
expected_dirnames.append("downloads")
for cur_dir_file in os.listdir(cur_fulldir):
if os.path.isdir(os.path.join("!md5_xmls", cur_dir, cur_dir_file)):
if cur_dir_file not in expected_dirnames:
info("Removing incorrect subdirectory " + os.path.join("!md5_xmls", cur_dir, cur_dir_file))
shutil.rmtree(os.path.join("!md5_xmls", cur_dir, cur_dir_file))
else:
cur_fulldir2 = os.path.join("!md5_xmls", cur_dir,cur_dir_file)
os_types = []
for game_item in all_items_by_title[cur_dir].downloads:
if game_item.os_type not in os_types:
os_types.append(game_item.os_type)
for cur_dir_file in os.listdir(cur_fulldir2):
if os.path.isdir(os.path.join(cur_fulldir2,cur_dir_file)):
if cur_dir_file not in os_types:
info("Removing incorrect subdirectory " + os.path.join(cur_fulldir2,cur_dir_file))
shutil.rmtree(os.path.join(cur_fulldir2, cur_dir_file))
else:
cur_fulldir3 = os.path.join(cur_fulldir2,cur_dir_file)
os_game_items = [x for x in all_items_by_title[cur_dir].downloads if x.os_type == cur_dir_file]
for game_item in os_game_items:
langs = []
for game_item in os_game_items:
if game_item.lang not in langs:
langs.append(game_item.lang)
for cur_dir_file in os.listdir(cur_fulldir3):
if os.path.isdir(os.path.join(cur_fulldir3,cur_dir_file)):
if cur_dir_file not in langs:
info("Removing incorrect subdirectory " + os.path.join(cur_fulldir3,cur_dir_file))
shutil.rmtree(os.path.join(cur_fulldir3, cur_dir_file))
else:
cur_fulldir4 = os.path.join(cur_fulldir3,cur_dir_file)
lang_os_game_items = [x for x in all_items_by_title[cur_dir].downloads if x.lang == cur_dir_file]
for cur_dir_file in os.listdir(cur_fulldir4):
expected_filenames = []
for game_item in lang_os_game_items:
expected_filenames.append(game_item.name + ".xml")
for cur_dir_file in os.listdir(cur_fulldir4):
if os.path.isdir(os.path.join(cur_fulldir4, cur_dir_file)):
info("Removing subdirectory(?!) " + os.path.join(downloadingdir, cur_dir, cur_dir_file))
shutil.rmtree(os.path.join(cur_fulldir4, cur_dir_file)) #There shouldn't be subdirectories here ?? Nuke to keep clean.
else:
if cur_dir_file not in expected_filenames:
info("Removing outdated file " + os.path.join(cur_fulldir4, cur_dir_file))
os.remove(os.path.join(cur_fulldir4, cur_dir_file))
else:
info("Removing invalid file " + os.path.join(cur_fulldir3, cur_dir_file))
os.remove(os.path.join(cur_fulldir3, cur_dir_file))
else:
info("Removing invalid file " + os.path.join(cur_fulldir2, cur_dir_file))
os.remove(os.path.join(cur_fulldir2, cur_dir_file))
else:
info("Removing invalid file " + os.path.join("!md5_xmls", cur_dir, cur_dir_file))
os.remove(os.path.join("!md5_xmls",cur_dir, cur_dir_file))
if update_md5_xml or delete_md5_xml:
if not os.path.isdir("!md5_xmls"):
os.makedirs("!md5_xmls")
for item in items:
try:
_ = item.folder_name
except:
item.folder_name = item.title
info("Handling MD5 XML info for " + item.folder_name)
fname = os.path.join("!md5_xmls",item.folder_name)
if not os.path.isdir(fname):
os.makedirs(fname)
for download in item.downloads:
ffdir = os.path.join(fname,"downloads",download.os_type,download.lang)
if not os.path.isdir(ffdir):
os.makedirs(ffdir)
ffname = os.path.join(ffdir,download.name + ".xml")
#rffname = os.path.join(".",ffname)
try:
text = download.gog_data.md5_xml.text
#existing_md5s.append(ffname)
if (update_md5_xml):
with ConditionalWriter(ffname) as fd_xml:
fd_xml.write(text)
if (delete_md5_xml):
del download.gog_data.md5_xml["text"]
except AttributeError:
pass
#all_md5s = glob.glob() Can't recursive glob before 3.5 so have to do this the hardway
save_manifest_core(items,filepath)
def save_manifest_core(items,filepath=MANIFEST_FILENAME):
info('saving manifest...')
try:
with codecs.open(filepath, 'w', 'utf-8') as w:
print('# {} games'.format(len(items)), file=w)
pprint.pprint(items, width=123, stream=w)
info('saved manifest')
except KeyboardInterrupt:
with codecs.open(filepath, 'w', 'utf-8') as w:
print('# {} games'.format(len(items)), file=w)
pprint.pprint(items, width=123, stream=w)
info('saved manifest')
raise
def save_resume_manifest(items):
info('saving resume manifest...')
try:
with codecs.open(RESUME_MANIFEST_FILENAME, 'w', 'utf-8') as w:
print('# {} games'.format(len(items)-1), file=w)
pprint.pprint(items, width=123, stream=w)
info('saved resume manifest')
except KeyboardInterrupt:
with codecs.open(RESUME_MANIFEST_FILENAME, 'w', 'utf-8') as w:
print('# {} games'.format(len(items)-1), file=w)
pprint.pprint(items, width=123, stream=w)
info('saved resume manifest')
raise
def load_resume_manifest(filepath=RESUME_MANIFEST_FILENAME):
info('loading local resume manifest...')
try:
with codecs.open(filepath, 'r' + universalLineEnd, 'utf-8') as r:
ad = r.read().replace('{', 'AttrDict(**{').replace('}', '})')
if (sys.version_info[0] >= 3):
ad = re.sub(r"'size': ([0-9]+)L,",r"'size': \1,",ad)
return eval(ad)
except IOError:
return []
def save_config_file(items):
info('saving config...')
try:
with codecs.open(CONFIG_FILENAME, 'w', 'utf-8') as w:
print('# {} games'.format(len(items)-1), file=w)
pprint.pprint(items, width=123, stream=w)
info('saved config')
except KeyboardInterrupt:
with codecs.open(CONFIG_FILENAME, 'w', 'utf-8') as w:
print('# {} games'.format(len(items)-1), file=w)
pprint.pprint(items, width=123, stream=w)
info('saved resume manifest')
raise
def load_config_file(filepath=CONFIG_FILENAME):
info('loading config...')
try:
with codecs.open(filepath, 'r' + universalLineEnd, 'utf-8') as r:
ad = r.read().replace('{', 'AttrDict(**{').replace('}', '})')
#if (sys.version_info[0] >= 3):
# ad = re.sub(r"'size': ([0-9]+)L,",r"'size': \1,",ad)
return eval(ad)
except IOError:
return []
def open_notrunc(name, bufsize=4*1024):
flags = os.O_WRONLY | os.O_CREAT
if hasattr(os, "O_BINARY"):
flags |= os.O_BINARY # windows
fd = os.open(name, flags, 0o666)
return os.fdopen(fd, 'wb', bufsize)
def open_notruncwrrd(name, bufsize=4*1024):
flags = os.O_RDWR | os.O_CREAT
if hasattr(os, "O_BINARY"):
flags |= os.O_BINARY # windows
fd = os.open(name, flags, 0o666)
return os.fdopen(fd, 'r+b', bufsize)
def hashstream(stream,start,end):
stream.seek(start)
readlength = (end - start)+1
hasher = hashlib.md5()
try:
buf = stream.read(readlength)
hasher.update(buf)
except Exception:
log_exception('')
raise
return hasher.hexdigest()
def hashfile(afile, blocksize=65536):
afile = open(afile, 'rb')
hasher = hashlib.md5()
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest()
def test_zipfile(filename):
"""Opens filename and tests the file for ZIP integrity. Returns True if
zipfile passes the integrity test, False otherwise.
"""
try:
with zipfile.ZipFile(filename, 'r') as f:
if f.testzip() is None:
return True
except (zipfile.BadZipfile,zlib.error):
return False
return False
def pretty_size(n):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if n < 1024 or unit == 'TB':
break
n = n / 1024 # start at KB
if unit == 'B':
return "{0}{1}".format(n, unit)
else:
return "{0:.2f}{1}".format(n, unit)
def get_total_size(dir):
total = 0
for (root, dirnames, filenames) in os.walk(dir):
for f in filenames:
total += os.path.getsize(os.path.join(root, f))
return total
def item_checkdb(search_id, gamesdb):
for i in range(len(gamesdb)):
if search_id == gamesdb[i].id:
return i
return None
def handle_game_renames(savedir,gamesdb,dryrun):
info("scanning manifest for renames...")
orphan_root_dir = os.path.join(savedir, ORPHAN_DIR_NAME)
if not os.path.isdir(orphan_root_dir):
os.makedirs(orphan_root_dir)
for game in gamesdb:
try:
_ = game.galaxyDownloads
except AttributeError:
game.galaxyDownloads = []
try:
a = game.sharedDownloads
except AttributeError:
game.sharedDownloads = []
try:
_ = game.old_title
except AttributeError:
game.old_title = None
try:
_ = game.folder_name
except AttributeError:
game.folder_name = game.title
try:
_ = game.old_folder_name
except AttributeError:
game.old_folder_name = game.old_title
if (game.old_folder_name is not None):
src_dir = os.path.join(savedir, game.old_folder_name)
dst_dir = os.path.join(savedir, game.folder_name)
if os.path.isdir(src_dir):
try:
if os.path.exists(dst_dir):
warn("orphaning destination clash '{}'".format(dst_dir))
if not dryrun:
move_with_increment_on_clash(dst_dir, os.path.join(orphan_root_dir,game.folder_name))
info(' -> renaming directory "{}" -> "{}"'.format(src_dir, dst_dir))
if not dryrun:
move_with_increment_on_clash(src_dir,dst_dir)
except Exception:
error(' -> rename failed "{}" -> "{}"'.format(game.old_folder_name, game.folder_name))
for item in game.downloads+game.galaxyDownloads+game.sharedDownloads+game.extras:
try:
_ = item.old_name
except AttributeError:
item.old_name = None
if (item.old_name is not None):
game_dir = os.path.join(savedir, game.folder_name)
src_file = os.path.join(game_dir,item.old_name)
dst_file = os.path.join(game_dir,item.name)
if os.path.isfile(src_file):
try:
if os.path.exists(dst_file):
warn("orphaning destination clash '{}'".format(dst_file))
dest_dir = os.path.join(orphan_root_dir, game.folder_name)
if not os.path.isdir(dest_dir):
if not dryrun:
os.makedirs(dest_dir)
if not dryrun:
move_with_increment_on_clash(dst_file, os.path.join(dest_dir,item.name))
info(' -> renaming file "{}" -> "{}"'.format(src_file, dst_file))
if not dryrun:
move_with_increment_on_clash(src_file,dst_file)
item.old_name = None #only once
except Exception:
error(' -> rename failed "{}" -> "{}"'.format(src_file, dst_file))
if not dryrun:
item.prev_verified = False
def handle_game_updates(olditem, newitem,strict, update_downloads_strict, update_extras_strict):
try:
_ = olditem.galaxyDownloads
except AttributeError:
olditem.galaxyDownloads = []
try:
a = olditem.sharedDownloads
except AttributeError:
olditem.sharedDownloads = []
try:
a = olditem.folder_name
except AttributeError:
olditem.folder_name = olditem.title
try:
a = newitem.folder_name
except AttributeError:
newitem.folder_name = newitem.title
if newitem.has_updates:
info(' -> gog flagged this game as updated')
if olditem.title != newitem.title:
info(' -> title has changed "{}" -> "{}"'.format(olditem.title, newitem.title))
newitem.old_title = olditem.title
if olditem.folder_name != newitem.folder_name:
info(' -> folder name has changed "{}" -> "{}"'.format(olditem.folder_name, newitem.folder_name))
newitem.old_folder_name = olditem.folder_name
if olditem.long_title != newitem.long_title:
try:
info(' -> long title has change "{}" -> "{}"'.format(olditem.long_title, newitem.long_title))
except UnicodeEncodeError:
pass
if olditem.changelog != newitem.changelog and newitem.changelog not in [None, '']:
info(' -> changelog was updated')
try:
if olditem.serials != newitem.serials:
info(' -> serial key(s) have changed')
except AttributeError:
if olditem.serial != '':
info(' -> gogrepoc serial key format has changed')
if olditem.serial != newitem.serial:
info(' -> serial key has changed')
#Done this way for backwards compatability. Would be faster to do each separately.
for newDownload in newitem.downloads+newitem.galaxyDownloads+newitem.sharedDownloads:
candidate = None
for oldDownload in olditem.downloads+olditem.galaxyDownloads+olditem.sharedDownloads:
if oldDownload.md5 is not None:
if oldDownload.md5 == newDownload.md5 and oldDownload.size == newDownload.size and oldDownload.lang == newDownload.lang:
if oldDownload.name == newDownload.name:
candidate = oldDownload #Match already exists
break #Can't be overriden so end it now
if oldDownload.name != newDownload.name and ( candidate == None or candidate.md5 == None ) : #Will not override and gets overridden by a perfect match (also allows only one match)
candidate = oldDownload
else:
if oldDownload.size == newDownload.size and oldDownload.name == newDownload.name and oldDownload.lang == newDownload.lang and candidate == None:
candidate = AttrDict(**oldDownload.copy())
if strict:
try:
candidate.prev_verified = False
except AttributeError:
pass
if candidate != None:
try:
newDownload.prev_verified = candidate.prev_verified
except AttributeError:
newDownload.prev_verified = False
try:
newDownload.old_updated = candidate.old_updated #Propogate until actually updated.
except AttributeError:
newDownload.old_updated = None
try:
newDownload.force_change = candidate.force_change
except AttributeError:
newDownload.force_change = False #An entry lacking force_change will also lack old_updated so this gets handled later
if candidate.md5 != None and candidate.md5 == newDownload.md5:
newDownload.old_updated = newDownload.updated #MD5s match , so whatever the update was it doesn't matter
if candidate.name != newDownload.name:
info(' -> in folder_name "{}" a download has changed name "{}" -> "{}"'.format(newitem.folder_name,candidate.name,newDownload.name))
newDownload.old_name = candidate.name
if update_downloads_strict and (newDownload.updated == None or ( newDownload.old_updated != newDownload.updated )): #shouldn't matter if updated is None in this section but preservign the logic for the stand alone function which may be dealing with a partially updated manifest
info(' -> in folder_name "{}" a download "{}" has probably been updated (update date {} -> {}) and has been marked for change."'.format(newitem.folder_name,newDownload.name,newDownload.old_updated,newDownload.updated))
newDownload.force_change = True
else:
#New file entry, presume changed
newDownload.force_change = True
for newExtra in newitem.extras:
candidate = None
for oldExtra in olditem.extras:
if (oldExtra.md5 != None):
if oldExtra.md5 == oldExtra.md5 and oldExtra.size == newExtra.size:
if oldExtra.name == newExtra.name:
candidate = oldExtra #Match already exists
break #Can't be overriden so end it now
if oldExtra.name != newExtra.name and (candidate == None or candidate.md5 == None):
candidate = oldExtra
else:
if oldExtra.name == newExtra.name and oldExtra.size == newExtra.size and candidate == None:
candidate = AttrDict(**oldExtra.copy())
if strict:
try:
#candidate.force_change = True
candidate.prev_verified = False
except AttributeError:
pass
if candidate != None:
try:
newExtra.prev_verified = candidate.prev_verified
except AttributeError:
newExtra.prev_verified = False
try:
newExtra.force_change = candidate.force_change
except AttributeError:
newExtra.force_change = False #An entry lacking force_change will also lack old_updated so this gets handled later
try:
newExtra.old_updated = candidate.old_updated #Propogate until actually updated.
except AttributeError:
newExtra.old_updated = None
if candidate.md5 != None and candidate.md5 == newExtra.md5:
newExtra.old_updated = newExtra.updated #MD5s match , so whatever the update was it doesn't matter
if candidate.name != newExtra.name:
info(' -> in folder_name "{}" an extra has changed name "{}" -> "{}"'.format(newitem.folder_name,candidate.name,newExtra.name))
newExtra.old_name = candidate.name
if update_extras_strict and (newExtra.updated == None or ( newExtra.old_updated != newExtra.updated )): #shouldn't matter if updated is None in this section but preservign the logic for the stand alone function which may be dealing with a partially updated manifest
info(' -> in folder_name "{}" an extra "{}" has perhaps been updated (update date {} -> {}) and has been marked for change."'.format(newitem.folder_name,newExtra.name,newExtra.old_updated,newExtra.updated))
newExtra.force_change = True
else:
#New file entry, presume changed
newExtra.force_change = True
def fetch_chunk_tree(response, session):
file_ext = os.path.splitext(urlparse(response.url).path)[1].lower()
if file_ext not in SKIP_MD5_FILE_EXT:
try:
chunk_url = append_xml_extension_to_url_path(response.url)
chunk_response = request(session,chunk_url)
shelf_etree = xml.etree.ElementTree.fromstring(chunk_response.content)
return shelf_etree
except requests.HTTPError as e:
if e.response.status_code == 404:
warn("no md5 data found for {}".format(chunk_url))
else:
warn("unexpected error fetching md5 data for {}".format(chunk_url))
debug("The handled exception was:")
if rootLogger.isEnabledFor(logging.DEBUG):
log_exception('')
debug("End exception report.")
return None
except xml.etree.ElementTree.ParseError:
warn('xml parsing error occurred trying to get md5 data for {}'.format(chunk_url))
debug("The handled exception was:")
if rootLogger.isEnabledFor(logging.DEBUG):
log_exception('')
debug("End exception report.")
return None
except requests.exceptions.ConnectionError as e:
warn("unexpected connection error fetching md5 data for {}".format(chunk_url) + " This error may be temporary. Please retry in 24 hours.")