-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscmapdb.py
3054 lines (2575 loc) · 98.3 KB
/
scmapdb.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
# Python 3 required
# There's a bug somewhere that causes file handles to build up, so you might need to
# set "ulimit -n" to something high like 4096 (1024 isn't enough), make sure to do it for root too if using crontab
# pip3 install lxml patool csselect
# to set up pushing to multiple github accounts from a single user you need to create an .ssh/config file.
# Be sure to use the ssh clone urls, not https. See the push commands in this script for git-dir usage.
# What I did was clone to a separate folder then copy the .git from the other folder and rename to .git_data.
# Example ssh config:
'''
Host github.com
HostName github.com
User wootguy
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
IdentitiesOnly yes
Host wootdata.github.com
HostName github.com
User wootdata
PreferredAuthentications publickey
IdentityFile ~/.ssh/wootdata
IdentitiesOnly yes
'''
# TODO / Feature requests:
# scmapdb repack file recovered but it overwrites default content (decay I think, point_checkpoint.as)
# scmapdb add "unreleased" category
from lxml import html
from lxml import etree
from datetime import datetime
from glob import glob
from pathlib import Path
import urllib.request, requests, mimetypes
import shutil, os.path, subprocess, stat, sys, time, filecmp, platform, io, contextlib, traceback
import patoolib, codecs, json, collections, hashlib, zlib, re, string
import socket
from requests.packages.urllib3.exceptions import InsecureRequestWarning
use_cache = True
force_zip_cache = False # always use zip cache, even if it's out of date
debug_zip = False
debug_repack = False # Don't delete the "repack" folder
unpack_nested = False # unpack nested archives
include_extras = False # move extras to a special subfolder instead of deleting them
verbose = True
log_to_file = True
include_readmes = True # include mapname_readme.txt files in the repack
domain_name = 'http://scmapdb.wikidot.com'
# maps that won't be included in The Big One map pack due to file conflicts or something
blacklisted_bigone_maps = ['afraid-of-monsters', 'absolute-redemption-for-sven-co-op']
# maps that should be ignored since they're older versions of something, but are kept on the DB for historical purposes
blacklisted_maps = ['afraid-of-monsters', 'absolute-redemption-for-sven-co-op']
all_maps = []
default_content = []
work_dir = os.getcwd()
map_list_fname = 'maplist.txt'
link_rules_fname = 'link_rules.txt'
default_content_fname = 'resguy_default_content.txt'
map_download_dir = 'downloads'
map_pool_dir = 'content_pool'
old_pool_dir = 'old_content' # old versions of files go here
bigone_dir = 'bigone'
bifone_extras_dir = 'bigone_extras'
map_repack_dir = os.path.join(map_download_dir, 'repack')
map_pack_dir = os.path.join(map_download_dir, 'map_packs')
cache_dir = 'cache'
logs_dir = 'logs'
map_cache_dir = os.path.join(cache_dir, 'maps')
map_pack_cache_dir = os.path.join(cache_dir, 'map_packs')
page_cache_dir = os.path.join(cache_dir, 'pages')
zip_level = "-mx1" # "-mx1"
zip_type = "zip" # "7z"
linux_7zip = '7zz'
rsync_dst = open("rsync_dst.txt").read().strip() if os.path.exists('rsync_dst.txt') else ''
rsync_port = '2022'
file_permissions = stat.S_IREAD | stat.S_IWRITE | stat.S_IRGRP | stat.S_IROTH
dom = None
sound_exts = ['aiff', 'asf', 'asx', 'dls', 'flac', 'fsb', 'it', 'm3u', 'midi', 'mid', 'mod', 'mp2', 'pls',
's3m', 'vag', 'wax', 'wma', 'xm', 'wav', 'ogg', 'mp3', 'au'
]
valid_exts = ['bsp', 'mdl', 'spr', 'res', 'txt', 'tga', 'bmp', 'conf', 'gmr',
'gsr', 'wad', 'cfg', 'as', 'save'
] + sound_exts
pool_json = {}
map_json = {}
link_rules = {}
master_json = collections.OrderedDict({})
master_json_name = 'data.json'
pool_json_name = 'pool.json'
bigone_json_name = 'bigone.json'
in_progress_name = "UPDATE_IN_PROGRESS"
link_json = {}
link_json_name = os.path.join(cache_dir, 'links.json')
LOG_MOVED = 1
LOG_ADDED = 2
LOG_INVALID_EXT = 3
LOG_INVALID_LOC = 4
LOG_WEIRD_LOC = 5
LOG_OVERWRITE = 6
LOG_NOT_NEEDED = 7
LOG_DUPLICATE = 8
LOG_RECOVERED = 9
LOG_RENAMED = 10
LOG_BIT_EXTRA = 256
LOG_BIT_MASK = 256
# Hide the fact that we're a bot (not very nice, but otherwise we can't download certain maps like AOMDC)
opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30')]
urllib.request.install_opener(opener)
def read_cached_page(file):
if os.path.isfile(file):
c = open(file, 'rb')
contents = c.read()
c.close()
if len(contents) > 0:
date = datetime.utcfromtimestamp( int(os.path.getmtime(file)) )
print("Using cached page (%s)" % date.strftime("%Y/%m/%d %H:%M UTC") )
return contents
else:
os.remove(file)
return ''
def get_map_urls(mapname, is_map_pack=False, skip_cache=False):
global dom
global use_cache
global map_json
global link_json
global page_cache_dir
dl_type = 'mappack' if is_map_pack else 'map'
cache_path = os.path.join(page_cache_dir, '%s_%s.html' % (dl_type, safe_map_name(mapname)))
thumb_path = os.path.join(page_cache_dir, 'img', '%s_%s.jpg' % (dl_type, safe_map_name(mapname)))
page_contents = read_cached_page(cache_path) if not skip_cache else ''
if not len(page_contents):
page_contents = ''
try:
page_contents = read_url_safe("%s/%s:%s" % (domain_name, dl_type, mapname))
except urllib.error.HTTPError as e:
print(e)
return []
c = open(cache_path, 'wb')
c.write(page_contents)
c.close()
map_json['scrape_date'] = int(os.path.getmtime(cache_path))
dom = html.fromstring(page_contents)
links = dom.cssselect('#page-content div.dl a')
# download the thumbnail
if skip_cache:
thumb = dom.cssselect(".gallery-box .gallery-item img")
if len(thumb) == 0:
print("Page has no images: %s" % mapname)
else:
thumb = thumb[0]
file_contents = ''
try:
file_contents = read_url_safe(thumb.attrib['src'])
except urllib.error.HTTPError as e:
print(e)
return []
if not os.path.exists(os.path.dirname(thumb_path)):
os.makedirs(os.path.dirname(thumb_path))
c = open(thumb_path, 'wb')
c.write(file_contents)
c.close()
use_idx = -1
if mapname in link_rules:
use_idx = link_rules[mapname]
print("Forcing link %s of %s" % (use_idx, len(links)))
ret = []
idx = -1
for link in links:
if 'href' not in link.attrib:
continue
old_href = href = link.attrib['href']
if href.startswith('javascript') or href.startswith('/map:') or href.startswith('/help:') or \
href.lower().startswith('#feedback') or href == 'http://www.svencoop.com/support.php':
continue
idx += 1
if use_idx != -1:
if idx != use_idx:
continue
print("Link rules says we should use this link: %s" % href)
if old_href in link_json:
# Use cached direct link if possible
href = link_json[href]
print("Using cached link: %s" % href)
else:
# Get direct link from download link
if 'dropbox.com' in href:
# Add dl=1 to link to bypass download page
href = href.split('?')[0] + '?dl=1'
# UPDATE 11/2017: This no longer works. You need to use their API now I guess.
print("Dropbox links not supported")
continue
if 'gamebanana.com' in href:
#print("GameBanana links not supported")
#continue
# Strip queries that start with # from href (for example '#FileInfo_<numbers>', they're not needed)
if '#' in href:
href = href.split('#')[0]
gbpttn = re.compile(r'^https?://(?:www\.)?(?:(?P<direct>files)\.)?gamebanana\.com/(?P<type>maps|dl|mods|gamefiles)(?:/download)?/(?P<id>.+)')
match = gbpttn.match(href)
if not match:
print("[Gamebanana] Failed to parse URL: %s" % href)
continue
direct, page_type, item_id = match.group('direct'), match.group('type'), match.group('id')
# Follow link redirect. This includes the following URIs: /maps and /gamefiles.
if page_type in ['maps', 'gamefiles']:
try:
with urllib.request.urlopen(href) as gb_html:
old_url = href
href = gb_html.geturl()
print("[Gamebanana] Redirected URL from %s to %s" % (old_url, href))
except:
print("[Gamebanana] Failed to follow URL %s" % href)
continue
# Refresh group match with new url. TODO: improve this, remove duplicate.
direct, page_type, item_id = match.group('direct'), match.group('type'), match.group('id')
# At this point we have links with /mods uri and we need to query the API for the download link.
if page_type == 'mods':
gbjson = None
# Note: API will throw a except if the mod ID is invalid. No need to check http error codes for now.
try:
with urllib.request.urlopen("https://gamebanana.com/apiv7/Mod/%s?_csvProperties=_aFiles" % item_id) as gb_data:
gbjson = json.load(gb_data)
except:
print("[Gamebanana] Failed to query API. Mod ID: %s, URL: %s" % (item_id, href))
continue
# There may be more than a single file in the mod id, we don't know which one to pick.
if len(gbjson["_aFiles"]) > 1:
print("[Gamebanana] Found multiple files in mod ID %s, skipping..." % item_id)
continue
# Let's hope the first and only file is the correct one.
href = gbjson["_aFiles"][0]["_sDownloadUrl"] # assume index 0 always exists
if 'mediafire.com' in href:
print("Link to mediafire ignored (bots aren't allowed to download from there).")
continue
if 'drive.google.com' in href:
print("Google Drive links not supported")
continue
if 'onedrive.live.com' in href:
print("Microsoft One Drive links not supported")
continue
if old_href != href:
link_json[old_href] = href
with open(link_json_name, 'w') as outfile:
json.dump(link_json, outfile)
if len(href):
ret.append(href)
else:
print("Failed to get direct link from %s" % link.attrib['href'])
return ret
# assumes dom is set
def get_bsp_filenames():
global dom
if dom is None:
print("Failed to get BSP filenames (no dom)")
return []
for i in range(100):
fname_label = dom.cssselect('.wiki-content-table > tr:nth-child(%s) > td:nth-child(1) > strong' % (i+1))
if len(fname_label) > 0:
fname_label = fname_label[0].text_content()
if '.bsp' in fname_label:
bsps = dom.cssselect('.wiki-content-table > tr:nth-child(%s) > td:nth-child(2)' % (i+1))
if (len(bsps)) > 0:
bsps = bsps[0].text_content()
return bsps.split(', ')
else:
print("bsp section didn't have any names in it")
else:
break
print("Failed to get BSP filenames")
def get_map_info():
global dom
if dom is None:
print("Failed to get map info (no dom)")
return {}
info = {}
title = dom.cssselect('#page-title')
if len(title) > 0:
info['title'] = title[0].text_content()
else:
print("Failed to get title from DOM")
rev = dom.cssselect('#page-info')
if len(rev) > 0:
rev = rev[0].text_content()
rev_int = int( rev[rev.find("page revision: ") + len("page revision: "):rev.find(",")] )
info['rev'] = rev_int
try:
# not all times have the comma
rev_time = rev[rev.find("last edited: ") + len("last edited: "):].replace(",", "")
rev_time = datetime.strptime(rev_time, "%d %b %Y %H:%M").timetuple()
rev_time = int(time.mktime(rev_time) / 60)
info['rev_time'] = rev_time
except Exception as e:
print(e)
print("Failed to parse revision time <%s>" % rev_time)
else:
print("Failed to get map revision from DOM")
for i in range(100):
fname_label = dom.cssselect('#page-content .actualcontent .wiki-content-table > tr:nth-child(%s) > td:nth-child(1) > strong' % (i+1))
if len(fname_label) > 0:
fname_label = fname_label[0].text_content()
if 'Author' in fname_label or 'Converted by' in fname_label:
author = dom.cssselect('#page-content .actualcontent .wiki-content-table > tr:nth-child(%s) > td:nth-child(2)' % (i+1))
if len(author) > 0:
info['author'] = author[0].text_content()
else:
break
if 'author' not in info:
print("Failed to get map author from DOM")
info['tags'] = []
map_tags = dom.cssselect('#page-content .tags_in_body > a')
for tag in map_tags:
info['tags'].append(tag.text_content())
info['rating'] = 0
info['votes'] = 0
map_rating = dom.cssselect('#page-content .actualcontent2 > p > strong')
map_votes = dom.cssselect('#page-content .actualcontent2 > p > span')
if len(map_rating) > 0 and len(map_votes) > 0:
info['rating'] = float(map_rating[0].text_content())
info['votes'] = int(map_votes[0].text_content().split()[0][1:])
else:
print("Failed to get map rating from DOM")
regex = '(january|february|march|april|may|june|july|august|september|october|november|december)+\s*\d\d,\s*\d\d\d\d'
for i in range(100):
fname_label = dom.cssselect('#page-content .actualcontent .wiki-content-table > tr:nth-child(%s) > td:nth-child(1) > strong' % (i+1))
if len(fname_label) > 0:
fname_label = fname_label[0].text_content()
if 'Date of release' in fname_label:
dates = dom.cssselect('#page-content .actualcontent .wiki-content-table > tr:nth-child(%s) > td:nth-child(2)' % (i+1))
if len(dates) > 0:
date = re.search(regex, dates[0].text_content(), re.IGNORECASE)
if date:
info['release_date'] = date.group(0)
else:
break
if 'release_date' not in info:
print("Failed to get map release date from DOM")
return info
def map_zip_exists(map):
global zip_type
safe_name = safe_map_name(map)
zip = os.path.join(map_download_dir, "%s.%s" % (safe_name, zip_type))
return os.path.isfile(zip)
def is_map_outdated(map):
global page_cache_dir
zip_deleted = not map_zip_exists(map)
#if map in master_json and ('failed' in master_json[map] or 'default' in master_json[map]):
#if map in master_json and ('default' in master_json[map]):
# zip_deleted = False
page_contents = ''
try:
page_contents = read_url_safe("%s/map:%s" % (domain_name, map))
except urllib.error.HTTPError as e:
print(e)
if "404" in "%s" % e:
print("The DB page was deleted!")
return False
else:
time.sleep(1)
return is_map_outdated(map)
mdom = html.fromstring(page_contents)
rev = mdom.cssselect('#page-info')
if len(rev) > 0:
rev = rev[0].text_content()
rev = int( rev[rev.find("page revision: ") + len("page revision: "):rev.find(",")] )
if zip_deleted or map not in master_json or 'rev' not in master_json[map] or master_json[map]['rev'] < rev:
# update cached page
cache_path = os.path.join(page_cache_dir, 'map_%s.html' % safe_map_name(map))
os.makedirs(page_cache_dir, exist_ok=True)
c = open(cache_path, 'wb')
c.write(page_contents)
c.close()
return True
else:
print("OH NO LAST EDIT DIV IS GONE")
return False
def delete_map_from_json(map):
global master_json
print("Removing map: %s" % map)
remove_pool_references(map)
num_refs_removed = remove_pool_references(map)
if map in master_json:
del master_json[map]
with open(master_json_name, 'w') as outfile:
json.dump(master_json, outfile)
print("Deleted from data.json")
print("Removed %s pool file references" % num_refs_removed)
def update_map_list():
global master_json
global all_maps
global master_json_name
print("")
print("Getting list of all maps...")
print("")
old_map_list = []
if os.path.isfile(map_list_fname):
with open(map_list_fname) as f:
old_map_list = f.read().splitlines()
new_maps = []
removed_maps = []
all_maps = []
page = 1
max_page = -1
while max_page == -1 or page <= max_page:
root = html.fromstring(read_url_safe("%s/tag:all/p/%s" % (domain_name, page)))
# get max page if unknown
if max_page == -1:
page_num = root.cssselect('#page-content div.lister-container-wrap div.pager > span.pager-no')
page_num = int(page_num[0].text_content().split()[-1])
if page_num < 0 or page_num > 100:
print("Error: Max page parsed incorrectly or last page is >100. Exiting.")
break
else:
max_page = page_num
print("Check page %s of %s" % (page, max_page))
links = root.cssselect('#page-content div.lister-container-wrap div.lister-item-title > p > a')
for link in links:
href = link.attrib['href']
map = href.split('/map:')[-1]
all_maps.append(map)
if map not in old_map_list:
new_maps.append(map)
print("New map: %s" % map)
#print( href )
page += 1
for map in old_map_list:
if map not in all_maps:
removed_maps.append(map)
delete_map_from_json(map)
f = open('maplist.txt', 'wb')
for c in all_maps:
f.write(('%s\r\n' % c).encode("utf-8"))
f.close()
print("Map list updated. %s maps added. %s maps removed." % (len(new_maps), len(removed_maps)))
return new_maps
# check that the archive is actually an archive
def validate_archive(archive_path):
global debug_zip
debug_zip = False
ext = archive_path.split('.')[-1].lower()
# check if we downloaded a 404 page
sz = os.path.getsize(archive_path)
if sz < 1024*1024: # no 404 page should be more than a megabyte
with open(archive_path) as file:
try:
contents = file.read()
raise Exception("Downloaded text file instead of archive")
except UnicodeDecodeError as e:
# probably a binary file
pass
if ext == '7z':
zip_archive_path = archive_path.replace('\\', '/')
program_name = "7za.exe" if platform.system() == "Windows" else linux_7zip
try:
with open(os.devnull, 'w') as devnull:
args = [program_name, 'l', zip_archive_path]
zip_stdout=None if debug_zip else devnull
subprocess.check_call(args, stdout=zip_stdout)
except Exception as e:
if debug_zip:
print("Failed to open %s" % archive_path)
print(e)
return False
elif ext == 'bsp':
return True
else:
save = os.dup(1), os.dup(2)
null_fds = [os.open(os.devnull, os.O_RDWR) for x in [0,1]]
try:
if not debug_zip:
# suppress stdout/stderr
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
with open(os.devnull, "w") as f, contextlib.redirect_stdout(f):
with open(os.devnull, "w") as f2, contextlib.redirect_stderr(f2):
patoolib.list_archive(archive_path, verbosity=0, interactive=False)
except Exception as e:
if not debug_zip:
# restore stdout/stderr
os.dup2(save[0], 1)
os.dup2(save[1], 2)
os.close(null_fds[0])
os.close(null_fds[1])
os.close(save[0])
os.close(save[1])
pass
if debug_zip or True:
print("Failed to open %s" % archive_path)
print(e)
return False
if not debug_zip:
# restore stdout/stderr
os.dup2(save[0], 1)
os.dup2(save[1], 2)
os.close(null_fds[0])
os.close(null_fds[1])
os.close(save[0])
os.close(save[1])
return True
def extract_archive(archive_path, out_path, bsp_name=""):
global debug_zip
global unpack_nested
if not os.path.exists(out_path):
os.makedirs(out_path)
ext = archive_path.split('.')[-1].lower()
if ext == '7z':
zip_out_path = out_path.replace('\\', '/')
zip_archive_path = archive_path.replace('\\', '/')
program_name = "7za.exe" if platform.system() == "Windows" else linux_7zip
try:
with open(os.devnull, 'w') as devnull:
args = [program_name, 'x', '-aos', '-o%s' % zip_out_path, zip_archive_path]
zip_stdout=None if debug_zip else devnull
subprocess.check_call(args, stdout=zip_stdout)
except Exception as e:
if debug_zip:
print("Failed to unpack %s (maybe dl'd a 404 page?)" % archive_path)
print(e)
return False
elif ext == 'bsp':
# I saw someone just upload a bsp by itself. We can just copy these.
fname = os.path.basename(archive_path)
if bsp_name:
fname = bsp_name + ".bsp"
shutil.copy(archive_path, os.path.join(out_path, fname))
else:
save = os.dup(1), os.dup(2)
null_fds = [os.open(os.devnull, os.O_RDWR) for x in [0,1]]
try:
if not debug_zip:
# suppress stdout/stderr
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
with open(os.devnull, "w") as f, contextlib.redirect_stdout(f):
with open(os.devnull, "w") as f2, contextlib.redirect_stderr(f2):
patoolib.extract_archive(archive_path, outdir=out_path, verbosity=0)
except Exception as e:
if not debug_zip:
# restore stdout/stderr
os.dup2(save[0], 1)
os.dup2(save[1], 2)
os.close(null_fds[0])
os.close(null_fds[1])
os.close(save[0])
os.close(save[1])
pass
if debug_zip or True:
print("Failed to unpack %s (maybe dl'd a 404 page?)" % archive_path)
print(e)
return False
if not debug_zip:
# restore stdout/stderr
os.dup2(save[0], 1)
os.dup2(save[1], 2)
os.close(null_fds[0])
os.close(null_fds[1])
os.close(save[0])
os.close(save[1])
nested_archives = list(find_files(out_path, '*.rar'))
nested_archives += list(find_files(out_path, '*.zip'))
nested_archives += list(find_files(out_path, '*.7z'))
if unpack_nested and len(nested_archives) > 0:
nested = nested_archives[0]
print('Unpacking nested archive: %s' % nested)
os.remove(archive_path)
shutil.move(nested, archive_path)
shutil.rmtree(out_path)
return extract_archive(archive_path, out_path)
return True
def download_map_pack(packname):
os.makedirs(map_pack_dir, exist_ok=True)
os.makedirs(map_pack_cache_dir, exist_ok=True)
safe_pack_name = safe_map_name(packname)
pack_path = os.path.join(map_pack_dir, safe_pack_name)
if packname == 'svencoop':
file_name = os.path.join(map_pack_cache_dir, 'svencoop.7z')
got_it = os.path.isfile(file_name)
else:
links = get_map_urls(packname, True)
got_it = False
file_name=''
for link in links:
ext = link.split('.')[-1]
if len(ext) < 1:
print("File with no extension!")
continue
file_name = os.path.join(map_pack_dir, '%s.%s' % (safe_pack_name, ext))
# Check if we already got this one
cache_archive_path = os.path.join(map_pack_cache_dir, '%s.%s' % (safe_pack_name, ext))
if use_cache and os.path.isfile(cache_archive_path):
shutil.copy(cache_archive_path, file_name)
got_it = True
print("Using cached package")
break
print("Downloading %s from: %s" % (safe_pack_name, link))
try:
download_file_safe(link, file_name)
if use_cache:
shutil.copy(file_name, cache_archive_path)
got_it = True
break
except ValueError as e:
print(e)
print("Skipping invalid URL: %s" % link)
except Exception as e:
print("Download failed: %s" % e)
if got_it:
print("Unpacking %s" % file_name)
if not extract_archive(file_name, os.path.join(map_pack_dir, safe_pack_name)):
return False
os.remove(file_name)
# fix up paths
all_files = find_files(pack_path, '*')
for pack_file in all_files:
pack_file = pack_file.split(pack_path)[-1][1:]
fix_asset(pack_file, repack_dir=pack_path)
return True
return False
def recover_missing_file(pack_path, file):
global verbose
file = file.replace("\\","/")
parts = file.split("/")
tree = pool_json
for part in parts:
if part in tree:
tree = tree[part]
else:
tree = None
break
if not tree:
if verbose:
print("Missing file: %s" % file)
if os.path.isfile(os.path.join(map_pool_dir, file)):
# File exists, but no map in the DB includes it anymore
print("file not in pool.json but it DOES exist: %s" % file)
return False
else:
return False
pool_file = os.path.join(map_pool_dir, file)
if not os.path.isfile(pool_file):
print("Missing pool file: %s" % pool_file)
return False
dest_file = os.path.join(pack_path, file)
if not os.path.exists(os.path.dirname(dest_file)):
os.makedirs(os.path.dirname(dest_file))
shutil.copy(pool_file, dest_file)
os.chmod(dest_file, file_permissions)
if verbose:
print("Recovered missing file: %s" % file)
return True
# TODO: Generate all res files in series at once (big speed boost for AOM series)
def gen_res_file(pack_path, mapname, recover_missing=True):
res_content = []
res_file = os.path.join('maps', '%s.res' % mapname)
res_path = os.path.join(pack_path, res_file)
if os.path.exists(res_path) and not os.path.exists(res_path + ".old"):
shutil.move(res_path, res_path + ".old")
if os.path.exists(res_path + '2'):
os.remove(res_path + '2')
if os.path.exists(res_path + '3'):
os.remove(res_path + '3')
shutil.copy(default_content_fname, pack_path + "/" + default_content_fname)
os.chdir(pack_path)
program_path = os.path.join(work_dir,'resguy' + ('.exe' if platform.system() == "Windows" else ""))
resguy_output = ''
try:
with open(os.devnull, 'w') as devnull:
args = [program_path, mapname, '-extra2', '-missing3', '-printskip', '-icase']
try:
output = subprocess.check_output(args)
except subprocess.CalledProcessError as e:
output = e.output
output = output.decode('ascii', 'ignore')
if platform.system() != "Windows":
output = output.replace('\n', '\r\n')
output = output[output.find('Generating .res file'):] # Skip "Loading default content" and control chars
if 'resguy_log' not in map_json:
resguy_output = ''
else:
resguy_output = map_json['resguy_log'] + '\r\n' + ('- ' * 30) + '\r\n\r\n'
resguy_output += output
#print(output)
except Exception as e:
print(e)
os.chdir(work_dir)
if platform.system() != "Windows" and os.path.exists(res_path):
# Convert unix-style line endings to windows-style
fileContents = open(res_path,"r").read()
f = open(res_path, "w", newline="\r\n")
f.write(fileContents)
f.close()
# Log missing files & try to find replacements
missing_res_path = res_path + '3'
num_missing = 0
num_recover = 0
missing_files = []
if os.path.exists(missing_res_path):
with open(missing_res_path) as f:
missing_files = f.read().splitlines()
for f in missing_files:
if recover_missing_file(pack_path, f):
num_recover += 1
else:
#num_missing += 1
map_json['missing_files'].add(f.lower())
if num_recover > 0:
if 'recover' in map_json:
map_json['recover'] += num_recover
else:
map_json['recover'] = num_recover
if os.path.isfile(res_path):
os.remove(res_path)
if os.path.isfile(missing_res_path):
os.remove(missing_res_path)
if os.path.isfile(res_path + '2'):
os.remove(res_path + '2')
return gen_res_file(pack_path, mapname, False)
map_json['resguy_log'] = resguy_output
if os.path.exists(res_path):
with open(res_path) as f:
res_content = f.read().splitlines()
res_content = [x for x in res_content if len(x) and x[0] != '/']
# Log differences between .res files
if 'res_diff' not in map_json:
map_json['res_diff'] = collections.OrderedDict({})
map_json['res_diff'][mapname] = []
if os.path.exists(res_path) and os.path.exists(res_path + ".old"):
with open(res_path) as f:
new_res = f.read().splitlines()
with open(res_path + ".old", "rb") as f:
old_res = f.read().decode("utf-8", "ignore").splitlines()
new_res = [x.strip() for x in new_res]
old_res = [x.strip() for x in old_res]
new_res = [x for x in new_res if len(x) and x[0] != '/']
old_res = [x for x in old_res if len(x) and x[0] != '/']
added = [x for x in new_res if x not in old_res]
for entry in added:
map_json['res_diff'][mapname].append('+' + entry)
removed = [x for x in old_res if x not in new_res]
for entry in removed:
map_json['res_diff'][mapname].append('-' + entry)
elif os.path.exists(res_path):
with open(res_path) as f:
new_res = f.read().splitlines()
new_res = [x for x in new_res if len(x) and x[0] != '/']
for entry in new_res:
map_json['res_diff'][mapname].append('+' + entry)
elif os.path.exists(res_path + '.old'):
with open(res_path + '.old') as f:
old_res = f.read().splitlines()
old_res = [x for x in old_res if len(x) and x[0] != '/']
for entry in old_res:
map_json['res_diff'][mapname].append('-' + entry)
return res_content
def repack_map_from_map_pack(mapname, bsp_filenames, packname):
global debug_zip
global zip_level
global zip_type
global include_readmes
safe_mapname = safe_map_name(mapname)
safe_pack_name = safe_map_name(packname)
pack_path = os.path.join(map_pack_dir, safe_pack_name)
if not os.path.exists(pack_path):
if not download_map_pack(packname):
print("Failed to pack %s. Map pack not downloaded." % safe_mapname)
return False
# Check to make sure the bsps actually exist
new_bsp_filenames = []
mapDir = os.path.join(pack_path,'maps')
map_dir_files_lower = [x.lower() for x in os.listdir(mapDir)]
for bsp in bsp_filenames:
mapExists = False
searchMap = '%s.bsp' % bsp
for file in os.listdir(mapDir):
if file.lower() == searchMap:
new_bsp_filenames.append(file[:-4])
mapExists = True
break
if not mapExists:
print("Warning: %s.bsp does not exist!" % bsp)
all_bsps = find_files(os.path.join(pack_path, 'maps'), '*.bsp')
for b in all_bsps:
if bsp.lower() in b.lower():
b = b.split(os.sep)[-1].replace('.bsp', '')
if b not in new_bsp_filenames:
new_bsp_filenames.append(b)
print("Packing map with similar filename: %s.bsp" % b)
bsp_filenames = new_bsp_filenames
pack_files = []
map_json['missing_files'] = set()
for bsp in bsp_filenames:
res_file = os.path.join('maps', '%s.res' % bsp)
res_path = os.path.join(pack_path, res_file)
print("Finding content for %s.bsp" % bsp)
content = []
possible_content = [os.path.join('maps', '%s.bsp' % bsp),
os.path.join('maps', '%s.cfg' % bsp),
os.path.join('maps', '%s_skl.cfg' % bsp),
os.path.join('maps', '%s_motd.txt' % bsp),
os.path.join('maps', '%s_detail.txt' % bsp)]
if include_readmes:
possible_content.append(os.path.join('maps', '%s_readme.txt' % bsp))
pack_path_files = [os.path.join('maps', x) for x in os.listdir(mapDir)]
pack_path_files_lower = [x.lower() for x in pack_path_files]
for c in possible_content:
for p in pack_path_files:
if p.lower() == c.lower():
pack_files.append(p)
break
if include_readmes:
# Rename old-style readmes
old_readme_name = os.path.join('maps', '%s.txt' % bsp)
new_readme_name = os.path.join('maps', '%s_readme.txt' % bsp)
for p in pack_path_files:
if p.lower() == old_readme_name.lower():
if not os.path.exists(os.path.join(pack_path, new_readme_name)):
shutil.copyfile(os.path.join(pack_path, p), os.path.join(pack_path, new_readme_name))
pack_files.append(new_readme_name)
if verbose:
print("Renaming old-style readme")
break
gen_res_file(pack_path, bsp)
if os.path.isfile(res_path):
pack_files.append(res_file)
res_lines = []
with open(res_path) as f:
res_lines = f.read().splitlines()
# Add server-only files to list so they aren't removed from the archive
if os.path.exists(res_path + '2'):
#print("got res2 for %s" % bsp)
with open(res_path + '2' ) as f:
res_lines += f.read().splitlines()
#else:
#print("no res2 for %s" % bsp)
for line in res_lines:
line = line.strip()
if not line or line[0] == '/':
continue # skip comments
line_path = line.replace('/', os.sep)
if os.path.isfile(os.path.join(pack_path,line_path)):
pack_files.append(line_path)
else:
print("Res file lists non-existant file: %s" % line_path)
map_json['missing'] = len(map_json['missing_files'])