forked from relikd/ipa-archive
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.py
More file actions
1412 lines (1196 loc) · 52.7 KB
/
main.py
File metadata and controls
1412 lines (1196 loc) · 52.7 KB
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
#!/usr/bin/env python3
from typing import TYPE_CHECKING, Iterable
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote, unquote
from urllib.request import Request, urlopen, urlretrieve
from argparse import ArgumentParser
from sys import stderr
import plistlib
import sqlite3
import json
import gzip
import os
import re
import subprocess
import tempfile
from PIL import Image, PngImagePlugin, ImageFile
# Increase limit for large metadata chunks
PngImagePlugin.MAX_TEXT_CHUNK = 100 * 1024 * 1024 # 100MB
ImageFile.LOAD_TRUNCATED_IMAGES = True
import warnings
with warnings.catch_warnings(): # hide macOS LibreSSL warning
warnings.filterwarnings('ignore')
from remotezip import RemoteZip # pip install remotezip
if TYPE_CHECKING:
from zipfile import ZipInfo
import platform
USE_ZIP_FILESIZE = False
NESTED_SEP = '##'
# Detect OS and set pngdefry binary name
if platform.system() == 'Windows':
PNGDEFRY_BIN = Path(__file__).parent / 'pngdefry' / 'pngdefry.exe'
else:
PNGDEFRY_BIN = Path(__file__).parent / 'pngdefry' / 'pngdefry'
re_info_plist = re.compile(r'((?:Payload/)?([^/]+\.app))/Info.plist', re.IGNORECASE)
# re_links = re.compile(r'''<a\s[^>]*href=["']([^>]+\.ipa)["'][^>]*>''')
re_archive_url = re.compile(
r'https?://archive.org/(?:metadata|details|download)/([^/]+)(?:/.*)?')
CACHE_DIR = Path(__file__).parent / 'data'
CACHE_DIR.mkdir(exist_ok=True)
def main():
CacheDB().init()
parser = ArgumentParser()
cli = parser.add_subparsers(metavar='command', dest='cmd', required=True)
cmd = cli.add_parser('add', help='Add urls to cache')
cmd.add_argument('urls', metavar='URL', nargs='+',
help='Search URLs for .ipa links. Use "continue" to resume interrupted progress.')
cmd = cli.add_parser('update', help='Update all urls')
cmd.add_argument('urls', metavar='URL', nargs='*', help='URLs or index')
cmd = cli.add_parser('run', help='Download and process pending urls')
cmd.add_argument('-force', '-f', action='store_true',
help='Reindex local data / populate DB.'
'Make sure to export fsize before!')
cmd.add_argument('-retry', '-r', action='store_true',
help='Automatically retry entries that fail.')
cmd.add_argument('pk', metavar='PK', type=int,
nargs='*', help='Primary key')
cmd = cli.add_parser('export', help='Export data')
cmd.add_argument('export_type', choices=['json', 'fsize'],
help='Export to json or temporary-filesize file')
cmd = cli.add_parser('err', help='Handle problematic entries')
cmd.add_argument('err_type', choices=['reset', 'fix', 'clear'],
help='reset: Set all done=3 to 0. fix: Reset and retry until no progress is made. clear: DELETE all entries with done=3 or done=4 from database.')
cmd = cli.add_parser('get', help='Lookup value')
cmd.add_argument('get_type', choices=['url', 'img', 'ipa'],
help='Get data field or download image.')
cmd.add_argument('pk', metavar='PK', type=int,
nargs='+', help='Primary key')
cmd = cli.add_parser('set', help='(Re)set value')
cmd.add_argument('set_type', choices=['err'], help='Data field/column')
cmd.add_argument('pk', metavar='PK', type=int,
nargs='+', help='Primary key')
cli.add_parser('fix-imgs', help='Check and fix missing images')
cmd = cli.add_parser('clear-queue', help='DELETE pending entries from the database')
cmd.add_argument('queue_type', choices=['run', 'add'], metavar='type',
help='run: Processing queue (done=0), add: Scraping queue')
args = parser.parse_args()
if args.cmd == 'add':
if args.urls == ['continue']:
queue = CacheDB().getScrapeQueue()
if not queue:
print('Nothing to resume.')
else:
print(f'Resuming {len(queue)} collections...')
for url in queue:
addNewUrl(url, resume=True)
else:
# Add all URLs to queue first so they can be resumed if interrupted
db = CacheDB()
for url in args.urls:
db.addToScrapeQueue(url)
for url in args.urls:
addNewUrl(url, resume=False)
print('done.')
elif args.cmd == 'update':
queue = args.urls or CacheDB().getUpdateUrlIds(sinceNow='-7 days')
if queue:
for i, url in enumerate(queue):
updateUrl(url, i + 1, len(queue))
print('done.')
else:
print('Nothing to do.')
elif args.cmd == 'run':
DB = CacheDB()
if args.pk:
for pk in args.pk:
url = DB.getUrl(pk)
print(pk, ': process', url)
if loadIpa(pk, url, overwrite=True):
DB.setDone(pk)
else:
DB.setError(pk, done=3)
else:
if args.force:
print('Resetting done state ...')
DB.setAllUndone(whereDone=1)
while True:
old_done_count = DB.count(done=1)
processPending()
new_done_count = DB.count(done=1)
if args.retry and new_done_count > old_done_count:
err_count = DB.count(done=3)
if err_count > 0:
print(f'\nFixed {new_done_count - old_done_count} entries. {err_count} errors remain. Retrying...')
DB.setAllUndone(whereDone=3)
continue
break
# After run, always check for missing images
fix_missing_images(DB)
elif args.cmd == 'err':
DB = CacheDB()
if args.err_type == 'reset':
print('Resetting error state ...')
DB.setAllUndone(whereDone=3)
elif args.err_type == 'clear':
count = DB.deleteAllErrors()
print(f'Successfully deleted {count} error entries from the database.')
elif args.err_type == 'fix':
while True:
err_count = DB.count(done=3)
if err_count == 0:
print('No errors to fix.')
break
print(f'Resetting {err_count} errors and retrying...')
DB.setAllUndone(whereDone=3)
old_done_count = DB.count(done=1)
processPending()
new_done_count = DB.count(done=1)
if new_done_count <= old_done_count:
print(f'No more progress. {DB.count(done=3)} errors remain.')
break
print(f'Fixed {new_done_count - old_done_count} entries. Retrying remaining errors...')
elif args.cmd == 'export':
if args.export_type == 'json':
export_json()
elif args.export_type == 'fsize':
export_filesize()
elif args.cmd == 'get':
DB = CacheDB()
if args.get_type == 'url':
for pk in args.pk:
print(pk, ':', DB.getUrl(pk))
elif args.get_type == 'img':
for pk in args.pk:
url = DB.getUrl(pk)
print(pk, ': load image', url)
loadIpa(pk, url, overwrite=True, image_only=True)
elif args.get_type == 'ipa':
dir = Path('ipa_download')
dir.mkdir(exist_ok=True)
for pk in args.pk:
url = DB.getUrl(pk)
print(pk, ': load ipa', url)
urlretrieve(url, dir / f'{pk}.ipa', printProgress)
print(end='\r')
elif args.cmd == 'set':
DB = CacheDB()
if args.set_type == 'err':
for pk in args.pk:
print(pk, ': set done=4')
DB.setPermanentError(pk)
elif args.cmd == 'fix-imgs':
fix_missing_images(CacheDB())
elif args.cmd == 'clear-queue':
count = CacheDB().clearQueue(type=args.queue_type)
print(f'Successfully cleared {count} {args.queue_type} entries from the database.')
def fix_missing_images(DB: 'CacheDB'):
missing = []
print("Checking for missing images...")
# Only iterate over the unique master images (~58k)
# We skip entries where done=4 because those are known to be broken/unfixable
entries = list(DB.getUniqueImagePks())
total = len(entries)
for i, (pk, img_pk) in enumerate(entries):
if i % 1000 == 0:
print(f"\rChecked {i}/{total} unique images...", end="")
img_path = diskPath(img_pk, '.jpg')
if not img_path.exists():
# Use the master pk to trigger the reload
missing.append(img_pk)
print(f"\rChecked {total}/{total} unique images. Done.")
if not missing:
print("No missing images found.")
else:
print(f"Found {len(missing)} missing unique images. Fixing...")
for pk in missing:
url = DB.getUrl(pk)
print(f"[{pk}] Fix unique image: {url}")
# Get current state to handle retry logic
res = DB._db.execute("SELECT done FROM idx WHERE pk=?", [pk]).fetchone()
state = res[0] if res else 1
loadIpa(pk, url, overwrite=True, image_only=True)
if not diskPath(pk, ".jpg").exists():
if state == 1:
print(f" [WARN] [{pk}] Still no image. Setting to retry state (done=2).")
DB._db.execute("UPDATE idx SET done=2 WHERE image_pk=?", [pk])
DB._db.commit()
else:
print(f" [ERROR] [{pk}] Still no image after retry. Marking as permanent error.")
# Mark ALL entries sharing this image as permanent error
uids = DB._db.execute("SELECT pk FROM idx WHERE image_pk=?", [pk]).fetchall()
for (uid,) in uids:
DB.setPermanentError(uid)
print("done.")
###############################################
# Database
###############################################
class CacheDB:
def __init__(self) -> None:
self._db = sqlite3.connect(CACHE_DIR / 'ipa_cache.db')
self._db.execute('pragma busy_timeout=5000')
def init(self):
self._db.execute('''
CREATE TABLE IF NOT EXISTS urls(
pk INTEGER PRIMARY KEY,
url TEXT NOT NULL UNIQUE,
date INTEGER DEFAULT (strftime('%s','now'))
);
''')
self._db.execute('''
CREATE TABLE IF NOT EXISTS idx(
pk INTEGER PRIMARY KEY,
base_url INTEGER NOT NULL,
path_name TEXT NOT NULL,
done INTEGER DEFAULT 0,
fsize INTEGER DEFAULT 0,
min_os INTEGER DEFAULT NULL,
platform INTEGER DEFAULT NULL,
title TEXT DEFAULT NULL,
bundle_id TEXT DEFAULT NULL,
version TEXT DEFAULT NULL,
image_pk INTEGER DEFAULT NULL,
UNIQUE(base_url, path_name) ON CONFLICT ABORT,
FOREIGN KEY (base_url) REFERENCES urls (pk) ON DELETE RESTRICT
);
''')
self._db.execute('''
CREATE TABLE IF NOT EXISTS scrape_queue(
url TEXT PRIMARY KEY
);
''')
self._db.execute('''
CREATE TABLE IF NOT EXISTS scanned_archives(
base_url_id INTEGER,
archive_name TEXT,
size INTEGER,
crc TEXT,
PRIMARY KEY(base_url_id, archive_name),
FOREIGN KEY (base_url_id) REFERENCES urls (pk) ON DELETE CASCADE
);
''')
def __del__(self) -> None:
self._db.close()
def addToScrapeQueue(self, url: str):
self._db.execute('INSERT OR IGNORE INTO scrape_queue (url) VALUES (?);', [url])
self._db.commit()
def removeFromScrapeQueue(self, url: str):
self._db.execute('DELETE FROM scrape_queue WHERE url=?;', [url])
self._db.commit()
def getScrapeQueue(self) -> 'list[str]':
x = self._db.execute('SELECT url FROM scrape_queue;')
return [row[0] for row in x.fetchall()]
def isArchiveScanned(self, baseUrlId: int, name: str, size: int, crc: str) -> bool:
x = self._db.execute('''SELECT 1 FROM scanned_archives
WHERE base_url_id=? AND archive_name=? AND size=? AND crc=?;''',
[baseUrlId, name, size, crc])
return x.fetchone() is not None
def markArchiveScanned(self, baseUrlId: int, name: str, size: int, crc: str):
self._db.execute('''INSERT OR REPLACE INTO scanned_archives
(base_url_id, archive_name, size, crc) VALUES (?,?,?,?);''',
[baseUrlId, name, size, crc])
self._db.commit()
def getNestedIpasFromIdx(self, baseUrlId: int, archiveName: str) -> 'list[tuple[str, int, str]]':
prefix = archiveName + NESTED_SEP
x = self._db.execute('''SELECT path_name, fsize FROM idx
WHERE base_url=? AND path_name LIKE ?;''', [baseUrlId, prefix + '%'])
return [(row[0], row[1], None) for row in x.fetchall()]
def clearScannedArchives(self, baseUrlId: int = None):
if baseUrlId:
self._db.execute('DELETE FROM scanned_archives WHERE base_url_id=?;', [baseUrlId])
else:
self._db.execute('DELETE FROM scanned_archives;')
self._db.commit()
# Get URL
def getIdForBaseUrl(self, url: str) -> 'int|None':
x = self._db.execute('SELECT pk FROM urls WHERE url=?', [url])
row = x.fetchone()
return row[0] if row else None
def getBaseUrlForId(self, uid: int) -> 'str|None':
x = self._db.execute('SELECT url FROM urls WHERE pk=?', [uid])
row = x.fetchone()
return row[0] if row else None
def getId(self, baseUrlId: int, pathName: str) -> 'int|None':
x = self._db.execute('''SELECT pk FROM idx
WHERE base_url=? AND path_name=?;''', [baseUrlId, pathName])
row = x.fetchone()
return row[0] if row else None
def getUrl(self, uid: int) -> str:
x = self._db.execute('''SELECT url, path_name FROM idx
INNER JOIN urls ON urls.pk=base_url WHERE idx.pk=?;''', [uid])
base, path = x.fetchone()
# Convert the internal ## separator to a slash for the final URL
path = path.replace(NESTED_SEP, '/')
return base + '/' + quote(path)
def hasImage(self, bundle_id: str, version: str) -> 'int|None':
if not bundle_id or not version:
return None
res = self._db.execute('''
SELECT image_pk FROM idx
WHERE bundle_id=? AND version=? AND image_pk IS NOT NULL
LIMIT 1''', [bundle_id, version]).fetchone()
if res:
pk = res[0]
if diskPath(pk, '.jpg').exists():
return pk
return None
# Insert URL
def insertBaseUrl(self, base: str) -> int:
try:
x = self._db.execute('INSERT INTO urls (url) VALUES (?);', [base])
self._db.commit()
return x.lastrowid # type: ignore
except sqlite3.IntegrityError:
x = self._db.execute('SELECT pk FROM urls WHERE url = ?;', [base])
return x.fetchone()[0]
def insertIpaUrls(
self, baseUrlId: int, entries: 'Iterable[tuple[str, int, str]]'
) -> int:
''' :entries: must be iterable of `(path_name, filesize, crc32)` '''
self._db.executemany('''
INSERT OR IGNORE INTO idx (base_url, path_name, fsize) VALUES (?,?,?);
''', ((baseUrlId, path, size) for path, size, _crc in entries))
self._db.commit()
return self._db.total_changes
# Update URL
def getUpdateUrlIds(self, *, sinceNow: str) -> 'list[int]':
x = self._db.execute('''SELECT pk FROM urls
WHERE date IS NULL OR date < strftime('%s','now', ?)
''', [sinceNow])
return [row[0] for row in x.fetchall()]
def markBaseUrlUpdated(self, uid: int) -> None:
self._db.execute('''
UPDATE urls SET date=strftime('%s','now') WHERE pk=?''', [uid])
self._db.commit()
def updateIpaUrl(self, baseUrlId: int, entry: 'tuple[str, int, str]') \
-> 'int|None':
''' :entry: must be `(path_name, filesize, crc32)` '''
uid = self.getId(baseUrlId, entry[0])
if uid:
self._db.execute('UPDATE idx SET done=0, fsize=? WHERE pk=?;',
[entry[1], uid])
self._db.commit()
return uid
if self.insertIpaUrls(baseUrlId, [entry]) > 0:
x = self._db.execute('SELECT MAX(pk) FROM idx;')
return x.fetchone()[0]
return None
# Export JSON
def jsonUrlMap(self) -> 'dict[int, str]':
x = self._db.execute('SELECT pk, url FROM urls')
rv = {}
for pk, url in x:
rv[pk] = url
return rv
def enumJsonIpa(self, *, done: int) -> Iterable[tuple]:
yield from self._db.execute('''
SELECT pk, platform, IFNULL(min_os, 0),
TRIM(IFNULL(title,
REPLACE(path_name,RTRIM(path_name,REPLACE(path_name,'/','')),'')
)) as tt, IFNULL(bundle_id, ""),
version, base_url, path_name, fsize / 1024,
image_pk
FROM idx WHERE done=?
ORDER BY tt COLLATE NOCASE, min_os, platform, version;''', [done])
def getUniqueImagePks(self) -> Iterable[tuple[int, int]]:
''' Returns (pk, image_pk) for each unique image_pk, excluding known errors (done=4) '''
yield from self._db.execute('''
SELECT MIN(pk), image_pk
FROM idx
WHERE done IN (1, 2) AND image_pk IS NOT NULL
GROUP BY image_pk
''')
# Filesize
def enumFilesize(self) -> Iterable[tuple]:
yield from self._db.execute('SELECT pk, fsize FROM idx WHERE fsize>0;')
def setFilesize(self, uid: int, size: int) -> None:
if size > 0:
self._db.execute('UPDATE idx SET fsize=? WHERE pk=?;', [size, uid])
self._db.commit()
# Process Pending
def count(self, *, done: int) -> int:
x = self._db.execute('SELECT COUNT() FROM idx WHERE done=?;', [done])
return x.fetchone()[0]
def getPendingQueue(self, *, done: int, batchsize: int) \
-> 'list[tuple[int, str, str]]':
# url || "/" || REPLACE(REPLACE(path_name, '#', '%23'), '?', '%3F')
x = self._db.execute('''SELECT idx.pk, url, path_name
FROM idx INNER JOIN urls ON urls.pk=base_url
WHERE done=? LIMIT ?;''', [done, batchsize])
return x.fetchall()
def setAllUndone(self, *, whereDone: int) -> None:
self._db.execute('UPDATE idx SET done=0 WHERE done=?;', [whereDone])
self._db.commit()
def deleteAllErrors(self) -> int:
'''
DELETE all entries with done=3 or done=4 from database.
Will also delete all plist and image files for these entries.
'''
# First find IDs to delete
x = self._db.execute('SELECT pk FROM idx WHERE done IN (3, 4);')
ids = [row[0] for row in x.fetchall()]
# Delete files
for uid in ids:
for ext in ['.plist', '.png', '.jpg']:
fname = diskPath(uid, ext)
if fname.exists():
os.remove(fname)
# DELETE from DB
x = self._db.execute('DELETE FROM idx WHERE done IN (3, 4);')
self._db.commit()
return x.rowcount
def clearQueue(self, type: str = 'run') -> int:
'''
DELETE entries from the database.
run: pending entries (done=0) from idx table.
add: scraping queue and scanned archives cache.
'''
if type == 'run':
x = self._db.execute('DELETE FROM idx WHERE done=0;')
self._db.commit()
return x.rowcount
elif type == 'add':
x1 = self._db.execute('DELETE FROM scrape_queue;')
x2 = self._db.execute('DELETE FROM scanned_archives;')
self._db.commit()
return x1.rowcount
return 0
def setError(self, uid: int, *, done: int) -> None:
self._db.execute('UPDATE idx SET done=? WHERE pk=?;', [done, uid])
self._db.commit()
def setPermanentError(self, uid: int) -> None:
'''
Set done=4 and all file related columns to NULL.
Will also delete all plist, and image files for {uid} in CACHE_DIR
'''
self._db.execute('''
UPDATE idx SET done=4, min_os=NULL, platform=NULL, title=NULL,
bundle_id=NULL, version=NULL WHERE pk=?;''', [uid])
self._db.commit()
for ext in ['.plist', '.png', '.jpg']:
fname = diskPath(uid, ext)
if fname.exists():
os.remove(fname)
def setDone(self, uid: int) -> None:
plist_path = diskPath(uid, '.plist')
if not plist_path.exists():
return
with open(plist_path, 'rb') as fp:
try:
plist = plistlib.load(fp)
except Exception as e:
print(f'ERROR: [{uid}] PLIST: {e}', file=stderr)
self.setError(uid, done=3)
return
bundleId = plist.get('CFBundleIdentifier')
title = plist.get('CFBundleDisplayName') or plist.get('CFBundleName')
v_short = str(plist.get('CFBundleShortVersionString', ''))
v_long = str(plist.get('CFBundleVersion', ''))
version = v_short or v_long
if version != v_long and v_long:
version += f' ({v_long})'
# minOS = [int(x) for x in plist.get('MinimumOSVersion', '0').split('.')]
raw = plist.get('MinimumOSVersion')
if raw is not None:
raw = str(raw)
# Handle empty / missing MinimumOSVersion (log once per UID)
if not raw or raw.strip() == "":
if not hasattr(self, "_warned_empty_min_os"):
self._warned_empty_min_os = set()
if uid not in self._warned_empty_min_os:
print(f"[WARN] Empty MinimumOSVersion for uid={uid}")
self._warned_empty_min_os.add(uid)
minOS = [0]
else:
minOS = [int(x) for x in raw.split('.') if x.isdigit()]
minOS += [0, 0, 0] # ensures at least 3 components are given
platforms = sum(1 << int(x) for x in plist.get('UIDeviceFamily', []))
if not platforms and minOS[0] in [0, 1, 2, 3]:
platforms = 1 << 1 # fallback to iPhone for old versions
# Find existing image for same bundle_id and version
image_pk = uid
if bundleId and version:
res = self._db.execute('''
SELECT image_pk FROM idx
WHERE bundle_id=? AND version=? AND image_pk IS NOT NULL
LIMIT 1''', [bundleId, version]).fetchone()
if res:
potential_img_pk = res[0]
if diskPath(potential_img_pk, '.jpg').exists():
image_pk = potential_img_pk
# If we found a duplicate, we can delete our own image if it exists
for ext in ['.jpg', '.png']:
p = diskPath(uid, ext)
if p.exists():
os.remove(p)
self._db.execute('''
UPDATE idx SET
done=1, min_os=?, platform=?, title=?, bundle_id=?, version=?, image_pk=?
WHERE pk=?;''', [
(minOS[0] * 10000 + minOS[1] * 100 + minOS[2]) or None,
platforms or None,
title or None,
bundleId or None,
version or None,
image_pk,
uid,
])
self._db.commit()
###############################################
# [add] Process HTML link list
###############################################
def addNewUrl(url: str, resume: bool = False) -> None:
DB = CacheDB()
archiveId = extractArchiveOrgId(url)
if not archiveId:
return
# Pre-calculate base URL ID
baseUrl = urlForArchiveOrgId(archiveId)
baseUrlId = DB.insertBaseUrl(baseUrl)
if not resume:
# If explicitly adding a new URL, clear previous scan cache for this URL
# as requested "process a new URL from the beginning"
print(f'Starting fresh scan for: {url}')
DB.clearScannedArchives(baseUrlId)
# Add to resume queue
DB.addToScrapeQueue(url)
json_file = pathToListJson(archiveId)
entries = downloadListArchiveOrg(baseUrlId, archiveId, json_file, resume=resume)
inserted = DB.insertIpaUrls(baseUrlId, entries)
# If successful, remove from queue
DB.removeFromScrapeQueue(url)
print(f'new links added: {inserted} of {len(entries)}')
def extractArchiveOrgId(url: str) -> 'str|None':
match = re_archive_url.match(url)
if not match:
print(f'[WARN] not an archive.org url. Ignoring "{url}"', file=stderr)
return None
return match.group(1)
def urlForArchiveOrgId(archiveId: str) -> str:
return f'https://archive.org/download/{archiveId}'
def pathToListJson(archiveId: str, *, tmp: bool = False) -> Path:
if tmp:
return CACHE_DIR / 'url_cache' / f'tmp_{archiveId}.json.gz'
return CACHE_DIR / 'url_cache' / f'{archiveId}.json.gz'
def getNestedIpas(url: str, zipPath: str) -> 'list[tuple[str, int, str]]':
'''
Peeks into a zip file on Archive.org and returns a list of .ipa files found inside.
Path format: "Archive.zip##Internal/Path/App.ipa"
'''
print(f' peeking into zip: {zipPath}')
try:
with RemoteZip(url) as rz:
return [(f'{zipPath}{NESTED_SEP}{info.filename}', info.file_size, None)
for info in rz.infolist()
if info.filename.lower().endswith('.ipa') and info.file_size > 0]
except Exception as e:
print(f' [WARN] could not peek into zip {zipPath}: {e}', file=stderr)
return []
def getNestedIpasViaViewArchive(url: str, archivePath: str) -> 'list[tuple[str, int, str]]':
'''
Peeks into a non-zip archive (RAR, 7z, tar) on Archive.org using its view_archive.php bridge.
This avoids downloading the whole archive just to list its contents.
'''
print(f' peeking into archive (via bridge): {archivePath}')
try:
# Construct the bridge URL
bridge_url = url
if not bridge_url.endswith('/'):
bridge_url += '/'
req = Request(bridge_url, headers={'User-Agent': 'Mozilla/5.0'})
with urlopen(req) as res:
html = res.read().decode('utf-8', errors='ignore')
# Regex to find files inside the table
pattern = r'<tr><td><a [^>]*href="[^"]*">([^<]+)</a><td><td>[^<]*<td [^>]*size">(\d+)</tr>'
matches = re.findall(pattern, html)
return [(f'{archivePath}{NESTED_SEP}{name}', int(size), None)
for name, size in matches
if name.lower().endswith('.ipa') and int(size) > 0]
except Exception as e:
print(f' [WARN] could not peek into archive {archivePath}: {e}', file=stderr)
return []
def downloadListArchiveOrg(
baseUrlId: int, archiveId: str, json_file: Path, *, force: bool = False, resume: bool = False
) -> 'list[tuple[str, int, str]]':
''' :returns: List of `(path_name, file_size, crc32)` '''
# store json for later
if force or not json_file.exists():
json_file.parent.mkdir(exist_ok=True)
print(f'load: {archiveId}')
req = Request(f'https://archive.org/metadata/{archiveId}/files')
req.add_header('Accept-Encoding', 'deflate, gzip')
with urlopen(req) as page:
with open(json_file, 'wb') as fp:
while True:
block = page.read(8096)
if not block:
break
fp.write(block)
# read saved json from disk
try:
with gzip.open(json_file, 'rb') as fp:
data = json.load(fp)
except (EOFError, OSError, json.JSONDecodeError) as e:
print(f'[WARN] Cache file corrupted for {archiveId} ({e}). Re-downloading...', file=stderr)
if json_file.exists():
json_file.unlink()
return downloadListArchiveOrg(baseUrlId, archiveId, json_file, force=True, resume=resume)
# process and add to DB
if 'result' not in data:
if 'error' in data:
print(f'[ERROR] Archive.org: {data["error"]}', file=stderr)
return []
baseUrl = urlForArchiveOrgId(archiveId)
rv = []
DB = CacheDB()
for x in data['result']:
if x.get('source') != 'original':
continue
name = x['name']
size = int(x.get('size', 0))
crc = x.get('crc32')
name_lower = name.lower()
if name_lower.endswith('.ipa'):
rv.append((name, size, crc))
elif name_lower.endswith('.zip'):
if resume and DB.isArchiveScanned(baseUrlId, name, size, crc):
# Skip re-peeking, fetch from idx
cached = DB.getNestedIpasFromIdx(baseUrlId, name)
if cached:
print(f' skipping already scanned zip: {name}')
rv.extend(cached)
continue
url = f'{baseUrl}/{quote(name)}'
nested_ipas = getNestedIpas(url, name)
# Efficiently insert as we go to avoid data loss on crash
DB.insertIpaUrls(baseUrlId, nested_ipas)
DB.markArchiveScanned(baseUrlId, name, size, crc)
rv.extend(nested_ipas)
elif name_lower.endswith(('.rar', '.7z', '.tar', '.tar.gz', '.tgz')) and not name_lower.endswith('_archive.torrent'):
if resume and DB.isArchiveScanned(baseUrlId, name, size, crc):
# Skip re-peeking, fetch from idx
cached = DB.getNestedIpasFromIdx(baseUrlId, name)
if cached:
print(f' skipping already scanned archive: {name}')
rv.extend(cached)
continue
url = f'{baseUrl}/{quote(name)}'
nested_ipas = getNestedIpasViaViewArchive(url, name)
# Efficiently insert as we go
DB.insertIpaUrls(baseUrlId, nested_ipas)
DB.markArchiveScanned(baseUrlId, name, size, crc)
rv.extend(nested_ipas)
return rv
###############################################
# [update] Re-index existing URL caches
###############################################
def updateUrl(url_or_uid: 'str|int', proc_i: int, proc_total: int):
baseUrlId, url = _lookupBaseUrl(url_or_uid)
if not baseUrlId or not url:
print(f'[ERROR] Ignoring "{url_or_uid}". Not found in DB', file=stderr)
return
archiveId = extractArchiveOrgId(url) or '' # guaranteed to return str
print(f'Updating [{proc_i}/{proc_total}] {archiveId}')
old_json_file = pathToListJson(archiveId)
new_json_file = pathToListJson(archiveId, tmp=True)
old_entries = set(downloadListArchiveOrg(baseUrlId, archiveId, old_json_file, resume=True))
new_entries = set(downloadListArchiveOrg(baseUrlId, archiveId, new_json_file, resume=True))
old_diff = old_entries - new_entries
new_diff = new_entries - old_entries
DB = CacheDB()
if old_diff or new_diff:
c_del = 0
c_new = 0
for old_entry in old_diff: # no need to sort
uid = DB.getId(baseUrlId, old_entry[0])
if uid:
print(f' rm: [{uid}] {old_entry}')
DB.setPermanentError(uid)
c_del += 1
else:
print(f' [ERROR] could not find old entry {old_entry[0]}',
file=stderr)
for new_entry in sorted(new_diff):
uid = DB.updateIpaUrl(baseUrlId, new_entry)
if uid:
print(f' add: [{uid}] {new_entry}')
c_new += 1
else:
print(f' [ERROR] updating {new_entry[0]}', file=stderr)
print(f' updated -{c_del}/+{c_new} entries.')
os.rename(new_json_file, old_json_file)
else:
print(' no changes.')
DB.markBaseUrlUpdated(baseUrlId)
if new_json_file.exists():
os.remove(new_json_file)
def _lookupBaseUrl(url_or_index: 'str|int') -> 'tuple[int|None, str|None]':
if isinstance(url_or_index, str):
if url_or_index.isnumeric():
url_or_index = int(url_or_index)
if isinstance(url_or_index, int):
baseUrlId = url_or_index
url = CacheDB().getBaseUrlForId(baseUrlId)
else:
archiveId = extractArchiveOrgId(url_or_index)
if not archiveId:
return None, None
url = urlForArchiveOrgId(archiveId)
baseUrlId = CacheDB().getIdForBaseUrl(url)
return baseUrlId, url
###############################################
# [run] Process pending urls from DB
###############################################
def processPending():
processed = 0
with ThreadPoolExecutor(max_workers=10) as executor:
while True:
DB = CacheDB()
pending = DB.count(done=0)
batch = DB.getPendingQueue(done=0, batchsize=100)
del DB
if not batch:
print('Queue empty. done.')
break
batch = [(processed + i + 1, pending - i - 1, *x)
for i, x in enumerate(batch)]
for uid, success in executor.map(_procSinglePendingWrapper, batch):
processed += 1
DB = CacheDB()
fsize = onceReadSizeFromFile(uid)
if fsize:
DB.setFilesize(uid, fsize)
if success:
DB.setDone(uid)
print(f' [DONE] [{uid}]')
else:
DB.setError(uid, done=3)
print(f' [FAILED] [{uid}]')
del DB
DB = CacheDB()
err_count = DB.count(done=3)
if err_count > 0:
print()
print('URLs with Error:', err_count)
for uid, base, path_name in DB.getPendingQueue(done=3, batchsize=10):
print(f' - [{uid}] {base}/{quote(path_name)}')
def _procSinglePendingWrapper(args):
return procSinglePending(*args)
def procSinglePending(
processed: int, pending: int, uid: int, base_url: str, path_name
) -> 'tuple[int, bool]':
full_path = path_name
display_path = path_name.replace(NESTED_SEP, ' -> ')
print(f'[{processed}|{pending} queued]: load[{uid}] {display_path}')
DB = CacheDB()
url = DB.getUrl(uid)
del DB
try:
return uid, loadIpa(uid, url)
except Exception as e:
print(f'ERROR: [{uid}] {e}', file=stderr)
return uid, False
def onceReadSizeFromFile(uid: int) -> 'int|None':
size_path = diskPath(uid, '.size')
if size_path.exists():
with open(size_path, 'r') as fp:
size = int(fp.read())
os.remove(size_path)
return size
return None
###############################################
# Process IPA zip
###############################################
def loadIpa(uid: int, url: str, *,
overwrite: bool = False, image_only: bool = False) -> bool:
basename = diskPath(uid, '')
basename.parent.mkdir(exist_ok=True, mode=0o755)
img_path = basename.with_suffix('.png')
plist_path = basename.with_suffix('.plist')
if not overwrite and plist_path.exists():
return True
# Support both old format (##) and new format (nested slash)
inner_path = None
# Handle the ## separator (possibly quoted as %23%23)
for sep in [NESTED_SEP, quote(NESTED_SEP)]:
if sep in url:
base_url, inner_path = url.split(sep, 1)
url = base_url
inner_path = unquote(inner_path)
break
# Check for implicit nested path (archive.rar/file.ipa) if ## wasn't found
if not inner_path:
for ext in ['.zip/', '.rar/', '.7z/', '.tar/', '.tar.gz/', '.tgz/']:
if ext in url.lower():
# Split at the end of the extension
idx = url.lower().find(ext) + len(ext) - 1
base_url = url[:idx]
inner_path = unquote(url[idx+1:])
url = base_url
break
# Handle non-ZIP nested archives (RAR, 7z, etc.)
# RemoteZip does not work on these via the Archive.org bridge.
if inner_path and not url.lower().endswith('.zip'):
direct_inner_url = f"{url}/{quote(inner_path)}"
with tempfile.NamedTemporaryFile(suffix='.ipa') as tmp:
print(f" downloading inner ipa from bridge: {inner_path}")
try:
req = Request(direct_inner_url, headers={'User-Agent': 'Mozilla/5.0'})
with urlopen(req) as response:
data = response.read(1024)
if data.startswith(b'<!DOCTYPE html>') or data.startswith(b'<html>'):
print(f"ERROR: [{uid}] bridge returned HTML instead of file", file=stderr)
return False
with open(tmp.name, 'wb') as f:
f.write(data)
while True:
chunk = response.read(1024*1024)
if not chunk: break
f.write(chunk)
import zipfile
with zipfile.ZipFile(tmp.name) as zip: