forked from Kalanyr/gogrepoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgogrepo.py
executable file
·2399 lines (2085 loc) · 108 KB
/
gogrepo.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
#!python3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__appname__ = 'gogrepo.py'
__author__ = 'eddie3, kalynr'
__version__ = 'k0.3a'
__url__ = 'https://github.com/kalanyr/gogrepo'
# imports
import os
import sys
import threading
import logging
import contextlib
import json
import html5lib
import pprint
import time
import zipfile
import hashlib
import getpass
import argparse
import codecs
import io
import datetime
import shutil
import socket
import xml.etree.ElementTree
import copy
import logging.handlers
import platform
#import subprocess
import ctypes
# python 2 / 3 imports
import requests
import re
import OpenSSL
import glob
try:
# python 2
from Queue import Queue
import cookielib as cookiejar
from httplib import BadStatusLine
from urlparse import urlparse, unquote
from urllib import urlencode
from urllib2 import HTTPError, URLError, HTTPCookieProcessor, build_opener, Request
from itertools import izip_longest as zip_longest
from StringIO import StringIO
except ImportError:
# python 3
from queue import Queue
import http.cookiejar as cookiejar
from http.client import BadStatusLine
from urllib.parse import urlparse, urlencode, unquote
from urllib.request import HTTPCookieProcessor, HTTPError, URLError, build_opener, Request
from itertools import zip_longest
from io import StringIO
if (platform.system() == "Windows"):
import ctypes.wintypes
# 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
# bypass the hardcoded "Netscape HTTP Cookie File" check
if hasattr(cookiejar.MozillaCookieJar.magic_re, "search"):
cookiejar.MozillaCookieJar.magic_re = re.compile(r'.*')
else:
cookiejar.MozillaCookieJar.magic_re = r'.*'
# configure logging
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 = 10485760*3 , backupCount = 10, 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'.'
COOKIES_FILENAME = r'gog-cookies.dat'
NETSCAPE_COOKIES_FILENAME = r'cookies.txt'
NETSCAPE_COOKIES_TMP_FILENAME = r'cookies.txt.tmp'
MANIFEST_FILENAME = r'gog-manifest.dat'
RESUME_MANIFEST_FILENAME = r'gog-resume-manifest.dat'
SERIAL_FILENAME = r'!serial.txt'
INFO_FILENAME = r'!info.txt'
# global web utilities
global_cookies = cookiejar.LWPCookieJar(COOKIES_FILENAME)
cookieproc = HTTPCookieProcessor(global_cookies)
opener = build_opener(cookieproc)
treebuilder = html5lib.treebuilders.getTreeBuilder('etree')
parser = html5lib.HTMLParser(tree=treebuilder, namespaceHTMLElements=False)
# 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 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
HTTP_RETRY_COUNT = 3
HTTP_TIMEOUT = 30
HTTP_GAME_DOWNLOADER_THREADS = 4
HTTP_PERM_ERRORCODES = (404, 403, 503)
USER_AGENT = 'GOGRepoK/' + str(__version__)
# Save manifest data for these os and lang combinations
DEFAULT_OS_LIST = ['windows']
DEFAULT_LANG_LIST = ['en']
# These file types don't have md5 data from GOG
SKIP_MD5_FILE_EXT = ['.txt', '.zip']
# 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())
ORPHAN_DIR_NAME = '!orphaned'
DOWNLOADING_DIR_NAME = '!downloading'
ORPHAN_DIR_EXCLUDE_LIST = [ORPHAN_DIR_NAME, DOWNLOADING_DIR_NAME, '!misc']
ORPHAN_FILE_EXCLUDE_LIST = [INFO_FILENAME, SERIAL_FILENAME]
RESUME_SAVE_THRESHOLD = 50
LONGTITLE_DIR = True
STORE_HASH = True
#temporary request wrapper while testing sessions module in context of update. Will replace request when complete
def update_request(session, url, args=None, byte_range=None, retries=HTTP_RETRY_COUNT, delay=None, stream=False):
"""Performs web request to url with optional retries, delay, and byte range.
"""
_retry = False
if delay is not None:
time.sleep(delay)
try:
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 update_request(session=session, url=url, args=args, byte_range=byte_range, retries=retries-1, delay=HTTP_RETRY_DELAY)
return response
def request(url, args=None, byte_range=None, retries=HTTP_RETRY_COUNT, delay=HTTP_FETCH_DELAY):
"""Performs web request to url with optional retries, delay, and byte range.
"""
_retry = False
time.sleep(delay)
try:
if args is not None:
enc_args = urlencode(args)
enc_args = enc_args.encode('ascii') # needed for Python 3
else:
enc_args = None
req = Request(url, data=enc_args)
if byte_range is not None:
req.add_header('Range', 'bytes=%d-%d' % byte_range)
page = opener.open(req)
except (HTTPError, URLError, socket.error, BadStatusLine) as e:
if isinstance(e, HTTPError):
if e.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(url=url, args=args, byte_range=byte_range, retries=retries-1, delay=HTTP_RETRY_DELAY)
return contextlib.closing(page)
# --------------------------
# 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 load_cookies():
# try to load as default lwp format
try:
global_cookies.load()
return
except IOError:
pass
# try to import as mozilla 'cookies.txt' format
try:
with codecs.open(NETSCAPE_COOKIES_FILENAME,"rU",'utf-8') as f1:
with codecs.open(NETSCAPE_COOKIES_TMP_FILENAME,"w",'utf-8') as f2:
for line in f1:
line = line.replace(u"#HttpOnly_", u"")
line=line.strip()
if not (line.startswith(u"#")):
if (u"gog.com" in line):
f2.write(line+u"\n")
tmp_jar = cookiejar.MozillaCookieJar(NETSCAPE_COOKIES_TMP_FILENAME)
tmp_jar.load()
for c in tmp_jar:
global_cookies.set_cookie(c)
global_cookies.save()
return
except IOError:
pass
error('failed to load cookies, did you login first?')
raise SystemExit(1)
def load_manifest(filepath=MANIFEST_FILENAME):
info('loading local manifest...')
try:
with codecs.open(filepath, 'rU', '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_manifest(items):
info('saving manifest...')
try:
with codecs.open(MANIFEST_FILENAME, '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(MANIFEST_FILENAME, '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, 'rU', '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:
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:
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 KeyError:
game.galaxyDownloads = []
try:
a = game.sharedDownloads
except KeyError:
game.sharedDownloads = []
try:
_ = game.old_title
except AttributeError:
game.old_title = None
if (game.old_title is not None):
src_dir = os.path.join(savedir, game.old_title)
dst_dir = os.path.join(savedir, game.title)
if os.path.isdir(src_dir):
try:
if os.path.exists(dst_dir):
info("orphaning destination clash '{}'".format(dst_dir))
if not dryrun:
shutil.move(dst_dir, orphan_root_dir)
info(' -> renaming directory "{}" -> "{}"'.format(src_dir, dst_dir))
if not dryrun:
shutil.move(src_dir, dst_dir)
except:
error(' -> rename failed "{}" -> "{}"'.format(olditem.title, newitem.title))
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.title)
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):
info("orphaning deztination clash '{}'".format(dst_file))
dest_dir = os.path.join(orphan_root_dir, game.title)
if not os.path.isdir(dest_dir):
if not dryrun:
os.makedirs(dest_dir)
if not dryrun:
shutil.move(dst_file, dest_dir)
info(' -> renaming file "{}" -> "{}"'.format(src_file, dst_file))
if not dryrun:
shutil.move(src_file, dst_file)
except:
error(' -> rename failed "{}" -> "{}"'.format(src_file, dst_file))
if not dryrun:
item.prev_verified = False
def handle_game_updates(olditem, newitem, strict):
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.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')
if olditem.serial != newitem.serial:
info(' -> serial key has changed')
#Done this way for backwards compatability. Would be faster to do each separately.
for oldDownload in olditem.downloads+olditem.galaxyDownloads+olditem.sharedDownloads:
for newDownload in newitem.downloads+newitem.galaxyDownloads+newitem.sharedDownloads:
if oldDownload.md5 is not None:
if oldDownload.md5 == newDownload.md5 and oldDownload.size == newDownload.size and oldDownload.lang == newDownload.lang:
newDownload.prev_verified = oldDownload.prev_verified
if oldDownload.name != newDownload.name:
info(' -> in title "{}" a download has changed name "{}" -> "{}"'.format(newitem.title, oldDownload.name, newDownload.name))
newDownload.old_name = oldDownload.name
else:
if oldDownload.size == newDownload.size and oldDownload.name == newDownload.name:
if not strict:
newDownload.prev_verified = oldDownload.prev_verified
for oldExtra in olditem.extras:
for newExtra in newitem.extras:
if (oldExtra.md5 != None):
if oldExtra.md5 == oldExtra.md5 and oldExtra.size == newExtra.size:
if oldExtra.name != newExtra.name:
newExtra.prev_verified = oldExtra.prev_verified
info(' -> in title "{}" an extra has changed name "{}" -> "{}"'.format(newitem.title, oldExtra.name, newExtra.name))
newExtra.old_name = oldExtra.name
else:
if oldExtra.name == newExtra.name and oldExtra.size == newExtra.size:
if not strict:
newExtra.prev_verified = oldExtra.prev_verified
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 = response.url.replace('?', '.xml?')
chunk_response = update_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))
return None
else:
raise
except xml.etree.ElementTree.ParseError:
warn('xml parsing error occurred trying to get md5 data for {}'.format(chunk_url))
return None
return None
def fetch_file_info(d, fetch_md5, updateSession):
# fetch file name/size
#try:
response = update_request(updateSession, d.href, byte_range=(0, 0))
#except ContentDecodingError as e:
#info('decoding failed because getting 0 bytes')
#response = e.response
d.name = unquote(urlparse(response.url).path.split('/')[-1])
d.size = int(response.headers['Content-Range'].split('/')[-1])
# fetch file md5
if fetch_md5:
file_ext = os.path.splitext(urlparse(response.url).path)[1].lower()
if file_ext not in SKIP_MD5_FILE_EXT:
try:
tmp_md5_url = response.url.replace('?', '.xml?')
md5_response = update_request(updateSession, tmp_md5_url)
shelf_etree = xml.etree.ElementTree.fromstring(md5_response.content)
d.md5 = shelf_etree.attrib['md5']
except requests.HTTPError as e:
if e.response.status_code == 404:
warn("no md5 data found for {}".format(d.name))
else:
raise
except xml.etree.ElementTree.ParseError:
warn('xml parsing error occurred trying to get md5 data for {}'.format(d.name))
def filter_downloads(out_list, downloads_list, lang_list, os_list, updateSession):
"""filters any downloads information against matching lang and os, translates
them, and extends them into out_list
"""
filtered_downloads = []
downloads_dict = dict(downloads_list)
# hold list of valid languages languages as known by gogapi json stuff
valid_langs = []
for lang in lang_list:
valid_langs.append(LANG_TABLE[lang])
# check if lang/os combo passes the specified filter
for lang in downloads_dict:
if lang in valid_langs:
for os_type in downloads_dict[lang]:
if os_type in os_list:
for download in downloads_dict[lang][os_type]:
# passed the filter, create the entry
d = AttrDict(desc=download['name'],
os_type=os_type,
lang=lang,
version=download['version'],
href=GOG_HOME_URL + download['manualUrl'],
md5=None,
name=None,
size=None,
prev_verified=False,
old_name=None
)
try:
fetch_file_info(d, True, updateSession)
except requests.HTTPError:
warn("failed to fetch %s" % d.href)
filtered_downloads.append(d)
out_list.extend(filtered_downloads)
def filter_extras(out_list, extras_list, updateSession):
"""filters and translates extras information and adds them into out_list
"""
filtered_extras = []
for extra in extras_list:
d = AttrDict(desc=extra['name'],
os_type='extra',
lang='',
version=None,
href=GOG_HOME_URL + extra['manualUrl'],
md5=None,
name=None,
size=None,
prev_verified=False,
old_name = None
)
try:
fetch_file_info(d, False, updateSession)
except requests.HTTPError:
warn("failed to fetch %s" % d.href)
filtered_extras.append(d)
out_list.extend(filtered_extras)
def filter_dlcs(item, dlc_list, lang_list, os_list, updateSession):
"""filters any downloads/extras information against matching lang and os, translates
them, and adds them to the item downloads/extras
dlcs can contain dlcs in a recursive fashion, and oddly GOG does do this for some titles.
"""
for dlc_dict in dlc_list:
filter_downloads(item.downloads, dlc_dict['downloads'], lang_list, os_list, updateSession)
filter_downloads(item.galaxyDownloads, dlc_dict['galaxyDownloads'], lang_list, os_list, updateSession)
filter_extras(item.extras, dlc_dict['extras'], updateSession)
filter_dlcs(item, dlc_dict['dlcs'], lang_list, os_list, updateSession) # recursive
def deDuplicateList(duplicatedList, existingItems):
deDuplicatedList = []
for update_item in duplicatedList:
if update_item.name is not None:
dummy_item = copy.copy(update_item)
deDuplicatedName = deDuplicateName(dummy_item, existingItems)
if deDuplicatedName is not None:
if (update_item.name != deDuplicatedName):
info(' -> ' + update_item.name + ' already exists in this game entry with a different size and/or md5, this file renamed to ' + deDuplicatedName)
update_item.name = deDuplicatedName
deDuplicatedList.append(update_item)
else:
info(' -> ' + update_item.name + ' already exists in this game entry with same size/md5, skipping adding this file to the manifest')
else:
#Placeholder for an item coming soon, pass through
deDuplicatedList.append(update_item)
return deDuplicatedList
def deDuplicateName(potentialItem, clashDict):
try:
#Check if Name Exists
existingList = clashDict[potentialItem.name]
try:
#Check if this md5 / size pair have already been resolved
idx = existingList.index((potentialItem.md5, potentialItem.size))
return None
except ValueError:
root, ext = os.path.splitext(potentialItem.name)
if (ext != ".bin"):
potentialItem.name = root + "("+str(len(existingList)) + ")" + 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
potentialItem.name = root + "("+str(len(existingList)) + ")" + ext
else:
potentialItem.name = root[:setDelimiter] + "("+str(len(existingList)) + ")" + root[setDelimiter:] + ext
existingList.append((potentialItem.md5, potentialItem.size)) #Mark as resolved
return deDuplicateName(potentialItem, clashDict)
except KeyError:
#No Name Clash
clashDict[potentialItem.name] = [(potentialItem.md5, potentialItem.size)]
return potentialItem.name
def process_path(path):
fpath = path
if sys.version_info[0] <= 2:
if isinstance(fpath, str):
fpath = fpath.decode('utf-8')
fpath = os.path.abspath(fpath)
raw_fpath = u'\\\\?\\%s' % fpath
return raw_fpath
def is_numeric_id(s):
try:
int(s)
return True
except ValueError:
return False
def process_argv(argv):
p1 = argparse.ArgumentParser(description='%s (%s)' % (__appname__, __url__), add_help=False)
sp1 = p1.add_subparsers(help='command', dest='command', title='commands')
sp1.required = True
g1 = sp1.add_parser('login', help='Login to GOG and save a local copy of your authenticated cookie')
g1.add_argument('username', action='store', help='GOG username/email', nargs='?', default=None)
g1.add_argument('password', action='store', help='GOG password', nargs='?', default=None)
g1.add_argument('-nolog', action='store_true', help = 'doesn\'t writes log file gogrepo.log')
g1 = sp1.add_parser('update', help='Update locally saved game manifest from GOG server')
g1.add_argument('-resumemode', action="store", choices=['noresume','resume','onlyresume'], default='resume', help="how to handle resuming if necessary")
g1.add_argument('-strictverify', action="store_true", help="clear previously verified unless md5 match")
g2 = g1.add_mutually_exclusive_group()
g2.add_argument('-os', action='store', help='operating system(s)', nargs='*', default=[])
g2.add_argument('-skipos', action='store', help='skip operating system(s)', nargs='*', default=[])
g3 = g1.add_mutually_exclusive_group()
g3.add_argument('-lang', action='store', help='game language(s)', nargs='*', default=[])
g3.add_argument('-skiplang', action='store', help='skip game language(s)', nargs='*', default=[])
g1.add_argument('-skiphidden', action='store_true', help='skip games marked as hidden')
g1.add_argument('-installers', action='store', choices = ['galaxy','standalone','both'], default = 'standalone', help='GOG Installer type to use: galaxy, standalone or both. Default: standalone ')
g4 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g4.add_argument('-skipknown', action='store_true', help='skip games already known by manifest')
g4.add_argument('-updateonly', action='store_true', help='only games marked with the update tag')
g5 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g5.add_argument('-ids', action='store', help='id(s)/titles(s) of (a) specific game(s) to update', nargs='*', default=[])
g5.add_argument('-skipids', action='store', help='id(s)/titles(s) of (a) specific game(s) not to update', nargs='*', default=[])
g5.add_argument('-id', action='store', help='(deprecated) id or title of the game in the manifest to download')
g1.add_argument('-wait', action='store', type=float,
help='wait this long in hours before starting', default=0.0) # sleep in hr
g1.add_argument('-nolog', action='store_true', help = 'doesn\'t writes log file gogrepo.log')
g1 = sp1.add_parser('download', help='Download all your GOG games and extra files')
g1.add_argument('savedir', action='store', help='directory to save downloads to', nargs='?', default='.')
g1.add_argument('-dryrun', action='store_true', help='display, but skip downloading of any files')
g1.add_argument('-skipgalaxy', action='store_true', help='skip downloading Galaxy installers')
g1.add_argument('-skipstandalone', action='store_true', help='skip downloading standlone installers')
g1.add_argument('-skipshared', action = 'store_true', help ='skip downloading installers shared between Galaxy and standalone')
g2 = g1.add_mutually_exclusive_group()
g2.add_argument('-skipextras', action='store_true', help='skip downloading of any GOG extra files')
g2.add_argument('-skipgames', action='store_true', help='skip downloading of any GOG game files (deprecated, use -skipgalaxy -skipstandalone -skipshared instead)')
g3 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g3.add_argument('-ids', action='store', help='id(s) or title(s) of the game in the manifest to download', nargs='*', default=[])
g3.add_argument('-skipids', action='store', help='id(s) or title(s) of the game(s) in the manifest to NOT download', nargs='*', default=[])
g3.add_argument('-id', action='store', help='(deprecated) id or title of the game in the manifest to download')
g1.add_argument('-wait', action='store', type=float,
help='wait this long in hours before starting', default=0.0) # sleep in hr
g4 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g4.add_argument('-skipos', action='store', help='skip downloading game files for operating system(s)', nargs='*', default=[x for x in VALID_OS_TYPES if x not in DEFAULT_OS_LIST])
g4.add_argument('-os', action='store', help='download game files only for operating system(s)', nargs='*', default=DEFAULT_OS_LIST)
g5 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g5.add_argument('-lang', action='store', help='download game files only for language(s)', nargs='*', default=DEFAULT_LANG_LIST)
g5.add_argument('-skiplang', action='store', help='skip downloading game files for language(s)', nargs='*', default=[x for x in VALID_LANG_TYPES if x not in DEFAULT_LANG_LIST])
g1.add_argument('-nolog', action='store_true', help = 'doesn\'t writes log file gogrepo.log')
g1 = sp1.add_parser('import', help='Import files with any matching MD5 checksums found in manifest')
g1.add_argument('src_dir', action='store', help='source directory to import games from')
g1.add_argument('dest_dir', action='store', help='directory to copy and name imported files to')
g2 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g2.add_argument('-skipos', action='store', help='skip importing game files for operating system(s)', nargs='*', default=[x for x in VALID_OS_TYPES if x not in DEFAULT_OS_LIST])
g2.add_argument('-os', action='store', help='import game files only for operating system(s)', nargs='*', default=DEFAULT_OS_LIST)
g3 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g3.add_argument('-skiplang', action='store', help='skip importing game files for language(s)', nargs='*', default=[x for x in VALID_LANG_TYPES if x not in DEFAULT_LANG_LIST])
g3.add_argument('-lang', action='store', help='import game files only for language(s)', nargs='*', default=DEFAULT_LANG_LIST)
#Code path available but commented out and hardcoded as false due to lack of MD5s on extras.
#g4 = g1.add_mutually_exclusive_group()
#g4.add_argument('-skipextras', action='store_true', help='skip downloading of any GOG extra files')
#g4.add_argument('-skipgames', action='store_true', help='skip downloading of any GOG game files (deprecated, use -skipgalaxy -skipstandalone -skipshared instead)')
g1.add_argument('-nolog', action='store_true', help = 'doesn\'t writes log file gogrepo.log')
g1.add_argument('-skipgalaxy', action='store_true', help='skip downloading Galaxy installers')
g1.add_argument('-skipstandalone', action='store_true', help='skip downloading standlone installers')
g1.add_argument('-skipshared', action = 'store_true', help ='skip downloading installers shared between Galaxy and standalone')
g5 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g5.add_argument('-ids', action='store', help='id(s) or title(s) of the game in the manifest to import', nargs='*', default=[])
g5.add_argument('-skipids', action='store', help='id(s) or title(s) of the game(s) in the manifest to NOT import', nargs='*', default=[])
g1 = sp1.add_parser('backup', help='Perform an incremental backup to specified directory')
g1.add_argument('src_dir', action='store', help='source directory containing gog items')
g1.add_argument('dest_dir', action='store', help='destination directory to backup files to')
g5 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g5.add_argument('-ids', action='store', help='id(s) or title(s) of the game in the manifest to backup', nargs='*', default=[])
g5.add_argument('-skipids', action='store', help='id(s) or title(s) of the game(s) in the manifest to NOT backup', nargs='*', default=[])
g2 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g2.add_argument('-skipos', action='store', help='skip backup of game files for operating system(s)', nargs='*', default=[x for x in VALID_OS_TYPES if x not in DEFAULT_OS_LIST])
g2.add_argument('-os', action='store', help='backup game files only for operating system(s)', nargs='*', default=DEFAULT_OS_LIST)
g3 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g3.add_argument('-skiplang', action='store', help='skip backup of game files for language(s)', nargs='*', default=[x for x in VALID_LANG_TYPES if x not in DEFAULT_LANG_LIST])
g3.add_argument('-lang', action='store', help='backup game files only for language(s)', nargs='*', default=DEFAULT_LANG_LIST)
g4 = g1.add_mutually_exclusive_group()
g4.add_argument('-skipextras', action='store_true', help='skip backup of any GOG extra files')
g4.add_argument('-skipgames', action='store_true', help='skip backup of any GOG game files')
g1.add_argument('-skipgalaxy', action='store_true', help='skip backup of any GOG Galaxy installer files')
g1.add_argument('-skipstandalone', action='store_true', help='skip backup of any GOG standalone installer files')
g1.add_argument('-skipshared', action='store_true', help ='skip backup of any installers included in both the GOG Galalaxy and Standalone sets')
g1.add_argument('-nolog', action='store_true', help = 'doesn\'t writes log file gogrepo.log')
g1 = sp1.add_parser('verify', help='Scan your downloaded GOG files and verify their size, MD5, and zip integrity')
g1.add_argument('gamedir', action='store', help='directory containing games to verify', nargs='?', default='.')
g1.add_argument('-forceverify', action='store_true', help='also verify files that are unchanged (by gogrepo) since they were last successfully verified')
g1.add_argument('-skipmd5', action='store_true', help='do not perform MD5 check')
g1.add_argument('-skipsize', action='store_true', help='do not perform size check')
g1.add_argument('-skipzip', action='store_true', help='do not perform zip integrity check')
g2 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g2.add_argument('-delete', action='store_true', help='delete any files which fail integrity test')
g2.add_argument('-clean', action='store_true', help='clean any files which fail integrity test')
g3 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g3.add_argument('-ids', action='store', help='id(s) or title(s) of the game in the manifest to verify', nargs='*', default=[])
g3.add_argument('-skipids', action='store', help='id(s) or title(s) of the game[s] in the manifest to NOT verify', nargs='*', default=[])
g3.add_argument('-id', action='store', help='(deprecated) id or title of the game in the manifest to verify')
g4 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g4.add_argument('-skipos', action='store', help='skip verification of game files for operating system(s)', nargs='*', default=[x for x in VALID_OS_TYPES if x not in DEFAULT_OS_LIST])
g4.add_argument('-os', action='store', help='verify game files only for operating system(s)', nargs='*', default=DEFAULT_OS_LIST)
g5 = g1.add_mutually_exclusive_group() # below are mutually exclusive
g5.add_argument('-skiplang', action='store', help='skip verification of game files for language(s)', nargs='*', default=[x for x in VALID_LANG_TYPES if x not in DEFAULT_LANG_LIST])
g5.add_argument('-lang', action='store', help='verify game files only for language(s)', nargs='*', default=DEFAULT_LANG_LIST)
g6 = g1.add_mutually_exclusive_group()
g6.add_argument('-skipextras', action='store_true', help='skip verification of any GOG extra files')
g6.add_argument('-skipgames', action='store_true', help='skip verification of any GOG game files')
g1.add_argument('-skipgalaxy', action='store_true', help='skip verification of any GOG Galaxy installer files')
g1.add_argument('-skipstandalone', action='store_true', help='skip verification of any GOG standalone installer files')
g1.add_argument('-skipshared', action='store_true', help ='skip verification of any installers included in both the GOG Galalaxy and Standalone sets')
g1.add_argument('-nolog', action='store_true', help = 'doesn\'t writes log file gogrepo.log')
g1 = sp1.add_parser('clean', help='Clean your games directory of files not known by manifest')
g1.add_argument('cleandir', action='store', help='root directory containing gog games to be cleaned')
g1.add_argument('-dryrun', action='store_true', help='do not move files, only display what would be cleaned')
g1.add_argument('-nolog', action='store_true', help = 'doesn\'t writes log file gogrepo.log')
g1 = p1.add_argument_group('other')
g1.add_argument('-h', '--help', action='help', help='show help message and exit')
g1.add_argument('-v', '--version', action='version', help='show version number and exit',
version="%s (version %s)" % (__appname__, __version__))
# parse the given argv. raises SystemExit on error
args = p1.parse_args(argv[1:])
if not args.nolog:
rootLogger.addHandler(loggingHandler)
if args.command == 'update' or args.command == 'download' or args.command == 'backup' or args.command == 'import' or args.command == 'verify':
for lang in args.lang+args.skiplang: # validate the language
if lang not in VALID_LANG_TYPES:
error('error: specified language "%s" is not one of the valid languages %s' % (lang, VALID_LANG_TYPES))
raise SystemExit(1)
for os_type in args.os+args.skipos: # validate the os type
if os_type not in VALID_OS_TYPES:
error('error: specified os "%s" is not one of the valid os types %s' % (os_type, VALID_OS_TYPES))
raise SystemExit(1)
return args
# --------
# Commands
# --------
def cmd_login(user, passwd):
"""Attempts to log into GOG and saves the resulting cookiejar to disk.
"""
login_data = {'user': user,
'passwd': passwd,
'auth_url': None,
'login_token': None,
'two_step_url': None,
'two_step_token': None,
'two_step_security_code': None,
'login_success': False,
}
global_cookies.clear() # reset cookiejar
# prompt for login/password if needed
if login_data['user'] is None:
login_data['user'] = input("Username: ")
if login_data['passwd'] is None:
login_data['passwd'] = getpass.getpass()
info("attempting gog login as '{}' ...".format(login_data['user']))
# fetch the auth url
with request(GOG_HOME_URL, delay=0) as page:
etree = html5lib.parse(page, namespaceHTMLElements=False)
for elm in etree.findall('.//script'):
if elm.text is not None and 'GalaxyAccounts' in elm.text:
authCandidates = elm.text.split("'")
for authCandidate in authCandidates:
if 'auth' in authCandidate:
testAuth = urlparse(authCandidate)
if testAuth.scheme == "https":
login_data['auth_url'] = authCandidate
break
if login_data['auth_url']:
break
if not login_data['auth_url']:
error("cannot find auth url, please report to the maintainer")
exit()
# fetch the login token
with request(login_data['auth_url'], delay=0) as page:
etree = html5lib.parse(page, namespaceHTMLElements=False)
# Bail if we find a request for a reCAPTCHA
if len(etree.findall('.//div[@class="g-recaptcha form__recaptcha"]')) > 0:
error("cannot continue, gog is asking for a reCAPTCHA :( try again in a few minutes.")
return
for elm in etree.findall('.//input'):
if elm.attrib['id'] == 'login__token':
login_data['login_token'] = elm.attrib['value']
break
# perform login and capture two-step token if required
with request(GOG_LOGIN_URL, delay=0, args={'login[username]': login_data['user'],
'login[password]': login_data['passwd'],
'login[login]': '',
'login[_token]': login_data['login_token']}) as page:
etree = html5lib.parse(page, namespaceHTMLElements=False)
if 'two_step' in page.geturl():
login_data['two_step_url'] = page.geturl()
for elm in etree.findall('.//input'):
if elm.attrib['id'] == 'second_step_authentication__token':
login_data['two_step_token'] = elm.attrib['value']
break
elif 'on_login_success' in page.geturl():
login_data['login_success'] = True
# perform two-step if needed
if login_data['two_step_url'] is not None:
login_data['two_step_security_code'] = input("enter two-step security code: ")
# Send the security code back to GOG
with request(login_data['two_step_url'], delay=0,