Files
d2r-mobile/dm/ios/Sources/asset_dl.m
T
2026-10-12 16:51:08 +08:00

263 lines
31 KiB
Objective-C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 直装包的游戏资源下载(直装包没有苹果托管资源包,也用不了开发者账号的 iCloud)。
// 从我们自己的下载站把资源文件逐个拉到 Documents/D2R Mobile Resources/data,全部到齐后由 main.m 的 romfs_locate 照常校验、就地进游戏。
// 下载站目录:<根>/manifest.json({"files":[{"name","size","sha256"}…]},tools/asset_manifest.py 生成)+ <根>/data/<文件名>。
// 根地址怎么定(隧道换域名时不用重出包):环境变量 DM_ASSET_BASE(测试)→ 包内 dm/asset_pointers.txt 里的每个「地址文件」网址
// (取回的正文第一行就是根地址)→ 上次成功用过的根地址 → 包内 dm/asset_base.txt(出包时写进去的缺省根地址)。逐个试,谁的清单取得到用谁。
// 传输:后台会话(URLSession background),一次一个任务,每个任务取一个文件的一段(≤16 MB,Range),取完追加到 <文件名>.part;
// .part 的长度就是这个文件已到手的字节数——杀进程重开 / 断网重连都从这里接着取,不重头。整个文件到齐后核字节数与 SHA-256,
// 对了才改成正式文件名;不对就删掉重下(同一文件最多 3 次)。网络出错自动重试(间隔 2 → 30 秒),不用玩家点。
// 已经在目录里且字节数对的文件不重下(玩家用「文件」拷进来的那些)。
// 老机型补充包(显卡不支持 BC 的机型)走同一套:DmAssetDL.astcPack 下到 Documents/Legacy Device Pack/data,根地址只认
// 环境变量 DM_ASTC_PACK_BASE(测试)→ 上次用过的 → 包内 dm/astc_pack_base.txt(出包时写进去;空 = 没配自动下载,只能玩家用「文件」拷),后台会话标识另起一个。
// Game asset download for the direct-install build (a direct-install build has no Apple-hosted asset packs and cannot use the developer account's iCloud).
// Pull the asset files one by one from our own download site into Documents/D2R Mobile Resources/data; once all have arrived, romfs_locate in main.m verifies them as usual and enters the game in place.
// Download site layout: <root>/manifest.json ({"files":[{"name","size","sha256"}…]}, generated by tools/asset_manifest.py) + <root>/data/<file name>.
// How the root address is determined (no need to rebuild the package when the tunnel changes domain): environment variable DM_ASSET_BASE (test) → each "address file" URL in the bundled dm/asset_pointers.txt
// (the first line of the fetched body is the root address) → the last root address that worked → the bundled dm/asset_base.txt (default root address written at packaging time). Try them one by one; use whichever one's manifest can be fetched.
// Transfer: background session (URLSession background), one task at a time, each task fetches one range of one file (≤16 MB, Range) and appends it to <file name>.part when done;
// the length of .part is the number of bytes of this file already received -- killing and relaunching the process / reconnecting after a network drop both resume from here, not from the start. Once the whole file has arrived, verify the byte count and SHA-256,
// rename to the final file name only if they match; if not, delete and re-download (at most 3 times per file). Network errors retry automatically (interval 2 → 30 s), no player tap needed.
// Files already in the directory with the right byte count are not re-downloaded (those the player copied in with the Files app).
// The Legacy Device Pack (models whose GPU does not support BC) uses the same mechanism: DmAssetDL.astcPack downloads to Documents/Legacy Device Pack/data; the root address only accepts
// environment variable DM_ASTC_PACK_BASE (test) → the last one used → the bundled dm/astc_pack_base.txt (written at packaging time; empty = auto-download not configured, the player can only copy it in with the Files app); it gets a separate background session identifier.
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <Network/Network.h>
#import "asset_dl.h"
#include "../../host/dm_i18n.h"
void plog(const char *fmt, ...);
#define DL_CHUNK (16ll << 20)
static NSString *dm_dl_sid(NSString *suffix) { return [NSBundle.mainBundle.bundleIdentifier stringByAppendingString:suffix]; } // 后台会话标识 = 包名 + 后缀 | Background session identifier = bundle ID + suffix
@interface DmAssetDL () <NSURLSessionDownloadDelegate>
@property (strong) NSURLSession *session; @property (strong) dispatch_queue_t q;
@property (copy) NSString *base, *dir; @property (strong) NSArray<NSDictionary *> *files;
@property (assign) int64_t total, settled; // 清单总字节数;已落盘的字节数(正式文件 + 各 .part) | Total bytes in the manifest; bytes already on disk (final files + all .part)
@property (assign) int running, retry, cellular; @property (strong) NSMutableDictionary<NSString *, NSNumber *> *redo;
@property (copy) void (^onProgress)(int64_t, int64_t, NSString *); @property (copy) void (^onDone)(NSString *);
@property (copy) NSString *sid, *envBase, *ptrFile, *baseFile, *defKey; // 后台会话标识、测试用环境变量、包内地址文件 / 缺省根地址文件、记住上次根地址的键 | Background session identifier, test environment variable, bundled address file / default root address file, key that remembers the last root address
@property (copy) void (^bgDone)(void); // 系统为后台会话唤醒 App 时给的收尾回调 | Completion callback given by the system when it wakes the App for the background session
// 卡住自救:盯当前这一片的吞吐,明显掉速就取消它、换一个全新的进程内会话(= 全新连接)从 .part 的长度接着取。
// 起因:系统的后台会话会一直复用同一条连接,那条连接塌了(丢包 / 被限速)之后每一片都慢,结束 App 重开也接回同一条。
// Stall self-healing: watch the throughput of the current chunk; on a clear slowdown, cancel it and continue from the length of the .part file on a brand-new in-process session (= a brand-new connection).
// Why: the system background session keeps reusing the same connection; once that connection degrades (packet loss / throttling) every chunk is slow, and quitting and reopening the app re-attaches to the same one.
@property (strong) NSURLSession *fg; // 自救用的进程内会话;每次自救新建一个 | In-process session used for self-healing; a new one is created each time
@property (assign) int useFg, heal, skipWin; // 现在是否走进程内会话;本轮已自救几次;自救后先放过几个窗口再判(给新连接起速的时间,也防来回折腾) | Whether the in-process session is in use now; how many times this round has self-healed; how many windows to skip after a self-heal before judging again (gives the new connection time to ramp up and avoids flapping)
@property (assign) int64_t curBytes, winBytes; // 当前这一片已收字节;本窗口起点时的已收字节 | Bytes received for the current chunk; bytes received at the start of this window
@property (assign) CFAbsoluteTime winT; @property (assign) double best; // 本窗口起点时刻;本轮见过的最高窗口吞吐(字节 / 秒) | Start time of this window; best window throughput seen this round (bytes / second)
@property (strong) dispatch_source_t watch;
- (NSURLSession *)bg;
@end
@implementation DmAssetDL
+ (instancetype)shared { static DmAssetDL *s; static dispatch_once_t once; dispatch_once(&once, ^{ s = [[DmAssetDL alloc] initDir:@"D2R Mobile Resources/data" sid:dm_dl_sid(@".assets") env:@"DM_ASSET_BASE" ptr:@"asset_pointers.txt" base:@"asset_base.txt" key:@"dm_asset_base"]; }); return s; }
+ (instancetype)astcPack { static DmAssetDL *s; static dispatch_once_t once; dispatch_once(&once, ^{ s = [[DmAssetDL alloc] initDir:@"Legacy Device Pack/data" sid:dm_dl_sid(@".astcpack") env:@"DM_ASTC_PACK_BASE" ptr:nil base:@"astc_pack_base.txt" key:@"dm_astc_pack_base"]; }); return s; }
- (instancetype)initDir:(NSString *)dir sid:(NSString *)sid env:(NSString *)env ptr:(NSString *)ptr base:(NSString *)base key:(NSString *)key {
if ((self = [super init])) {
self.q = dispatch_queue_create("dm.assetdl", DISPATCH_QUEUE_SERIAL); self.redo = [NSMutableDictionary new];
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
{ const char *td = getenv("DM_ROMFS_TEST_DOC"); if (td && *td && !strchr(td, '/')) doc = [doc stringByAppendingPathComponent:@(td)]; } // 只测试用:与 main.m romfs_locate 同一个开关,下到被当成「D2R Mobile」的那个文件夹里 | test only: the same switch as romfs_locate in main.m; downloads into the folder that is treated as "D2R Mobile"
__weak DmAssetDL *w = self; // 切到后台:进程内会话在后台不保活,把在途这一片交还给系统的后台会话接着取 | Going to the background: an in-process session is not kept alive there, so hand the chunk in flight back to the system background session to carry on
[NSNotificationCenter.defaultCenter addObserverForName:@"UIApplicationDidEnterBackgroundNotification" object:nil queue:nil usingBlock:^(NSNotification *n) { DmAssetDL *d = w; if (d) dispatch_async(d.q, ^{
if (d.running && d.useFg) { plog("assets: 进后台,在途这一片交还给系统的后台会话"); d.useFg = 0; [d.fg invalidateAndCancel]; d.fg = nil; [d pump]; } }); }];
self.dir = [doc stringByAppendingPathComponent:dir]; self.sid = sid; self.envBase = env; self.ptrFile = ptr; self.baseFile = base; self.defKey = key;
}
return self;
}
void dm_asset_dl_bg_events(NSString *ident, void (^done)(void)) { DmAssetDL *d = [ident isEqualToString:dm_dl_sid(@".astcpack")] ? DmAssetDL.astcPack : DmAssetDL.shared; d.bgDone = done; dispatch_async(d.q, ^{ (void)[d bg]; }); } // 接回同标识的后台会话,事件才送得到 | Reattach the background session with the same identifier, otherwise the events cannot be delivered
- (NSURLSession *)bg { // 后台会话:同一个标识全进程只建一次;杀进程后重开用同一标识接回系统手里没做完的任务 | Background session: one identifier is created only once per process; after the process is killed and relaunched, the same identifier reattaches the unfinished tasks held by the system
if (!self.session) {
NSURLSessionConfiguration *c = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:self.sid];
c.sessionSendsLaunchEvents = YES; c.discretionary = NO; c.allowsCellularAccess = YES; c.HTTPMaximumConnectionsPerHost = 2;
c.timeoutIntervalForRequest = 60; c.timeoutIntervalForResource = 7 * 24 * 3600;
NSOperationQueue *oq = [NSOperationQueue new]; oq.underlyingQueue = self.q; oq.maxConcurrentOperationCount = 1;
self.session = [NSURLSession sessionWithConfiguration:c delegate:self delegateQueue:oq];
}
return self.session;
}
- (NSURLSession *)fgNew { // 新建一个进程内会话:不沿用任何已有连接 | Create a new in-process session: reuses no existing connection
[self.fg invalidateAndCancel];
NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.allowsCellularAccess = YES; c.HTTPMaximumConnectionsPerHost = 2;
c.timeoutIntervalForRequest = 30; c.timeoutIntervalForResource = 3600; c.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSOperationQueue *oq = [NSOperationQueue new]; oq.underlyingQueue = self.q; oq.maxConcurrentOperationCount = 1;
self.fg = [NSURLSession sessionWithConfiguration:c delegate:self delegateQueue:oq]; return self.fg;
}
// 每 5 秒看一次当前这一片的吞吐(只在 self.q 上跑)。判掉速:一个窗口(缺省 20 秒)的平均吞吐低于 24 KB/s,
// 或低于本轮见过的最高窗口吞吐的四分之一且低于 512 KB/s。测试开关:DM_ASSET_STALL_MIN=<字节/秒>(低于它就算掉速)、DM_ASSET_STALL_WIN=<秒>
// Every 5 seconds, look at the throughput of the current chunk (runs only on self.q). Slowdown rule: the average throughput over one window (20 seconds by default) is below 24 KB/s,
// or below a quarter of the best window throughput seen this round and below 512 KB/s. Test switches: DM_ASSET_STALL_MIN=<bytes/second> (anything below counts as a slowdown), DM_ASSET_STALL_WIN=<seconds>
- (void)watchTick {
if (!self.running) return;
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); const char *ew = getenv("DM_ASSET_STALL_WIN"), *em = getenv("DM_ASSET_STALL_MIN"); double win = ew ? atof(ew) : 20;
if (!self.winT) { self.winT = now; self.winBytes = self.curBytes; return; }
if (now - self.winT < win) return;
double rate = MAX(0, self.curBytes - self.winBytes) / (now - self.winT); self.winT = now; self.winBytes = self.curBytes;
if (self.skipWin > 0) { self.skipWin--; if (rate > self.best) self.best = rate; return; }
BOOL slow = em ? rate < atof(em) : (rate < 24 * 1024 || (rate * 4 < self.best && rate < 512 * 1024));
if (rate > self.best) self.best = rate;
if (!slow) return;
self.heal++; self.skipWin = MIN(self.heal, 6); self.useFg = 1; self.winT = 0; self.curBytes = 0;
plog("assets: 这一片掉速(%.0f KB/s,本轮最高 %.0f KB/s):取消、换新连接从已下的地方接着取(第 %d 次)", rate / 1024, self.best / 1024, self.heal);
(void)[self fgNew];
[[self bg] getTasksWithCompletionHandler:^(NSArray *d0, NSArray *u0, NSArray<NSURLSessionDownloadTask *> *tasks) { for (NSURLSessionTask *t in tasks) if (t.state != NSURLSessionTaskStateCompleted) [t cancel];
[self report:[self scan] note:[NSString stringWithFormat:@(dm_ui("dmDlReconnect")), self.heal]]; [self pump]; }];
}
static NSData *dl_get(NSString *url, NSTimeInterval timeout) { // 小文件(地址文件、清单)同步取,不走缓存 | Small files (address file, manifest) are fetched synchronously, bypassing the cache
NSURL *u = [NSURL URLWithString:url]; if (!u) return nil;
NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.timeoutIntervalForRequest = timeout; c.timeoutIntervalForResource = timeout * 2;
c.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSession *s = [NSURLSession sessionWithConfiguration:c]; dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block NSData *out = nil;
[[s dataTaskWithURL:u completionHandler:^(NSData *d, NSURLResponse *r, NSError *e) {
if (!e && [(NSHTTPURLResponse *)r statusCode] == 200) out = d; else plog("assets: 取 %s 失败:%s", url.UTF8String, e ? e.localizedDescription.UTF8String : [NSString stringWithFormat:@"HTTP %ld", (long)[(NSHTTPURLResponse *)r statusCode]].UTF8String);
dispatch_semaphore_signal(sem); }] resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); [s finishTasksAndInvalidate]; return out;
}
static NSString *dl_trim(NSString *s) { s = [s stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; while ([s hasSuffix:@"/"]) s = [s substringToIndex:s.length - 1]; return s; }
static NSArray<NSString *> *dl_lines(NSString *path) { // 包内文本:一行一项,# 开头是注释 | Bundled text: one item per line; lines starting with # are comments
NSMutableArray *a = [NSMutableArray new]; NSString *t = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
for (NSString *l in [t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { NSString *v = dl_trim(l); if (v.length && ![v hasPrefix:@"#"]) [a addObject:v]; }
return a;
}
// 定根地址并取清单。成功返回 nil,失败返回原因
// Determine the root address and fetch the manifest. Returns nil on success, the reason on failure
- (NSString *)resolve {
NSString *res = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"dm"]; NSMutableArray<NSString *> *cand = [NSMutableArray new];
if (getenv("DM_TEST_NO_DL_BASE")) return @(dm_ui("dmDlNoBase")); // 只测试用:同 main.m res_dl_configured | Test only: same as res_dl_configured in main.m
const char *e = getenv(self.envBase.UTF8String); if (e && *e) [cand addObject:dl_trim(@(e))];
else {
for (NSString *p in self.ptrFile ? dl_lines([res stringByAppendingPathComponent:self.ptrFile]) : @[]) {
NSData *d = dl_get(p, 8); NSString *t = d ? [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding] : nil;
NSString *first = dl_trim([t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet].firstObject ?: @"");
if ([first hasPrefix:@"https://"]) { plog("assets: 地址文件 %s → %s", p.UTF8String, first.UTF8String); [cand addObject:first]; }
}
NSString *last = [NSUserDefaults.standardUserDefaults stringForKey:self.defKey]; if (last.length) [cand addObject:last];
[cand addObjectsFromArray:dl_lines([res stringByAppendingPathComponent:self.baseFile])];
}
if (!cand.count) return @(dm_ui("dmDlNoBase"));
for (NSString *b in cand) {
NSData *d = dl_get([b stringByAppendingString:@"/manifest.json"], 15); if (!d) continue;
NSDictionary *j = [NSJSONSerialization JSONObjectWithData:d options:0 error:nil]; NSArray *fs = [j isKindOfClass:NSDictionary.class] ? j[@"files"] : nil;
int64_t tot = 0; BOOL ok = [fs isKindOfClass:NSArray.class] && fs.count;
for (NSDictionary *f in (ok ? fs : @[])) {
NSString *nm = [f isKindOfClass:NSDictionary.class] ? f[@"name"] : nil, *sha = [f isKindOfClass:NSDictionary.class] ? f[@"sha256"] : nil; NSNumber *sz = [f isKindOfClass:NSDictionary.class] ? f[@"size"] : nil;
if (![nm isKindOfClass:NSString.class] || !nm.length || [nm containsString:@"/"] || [nm hasPrefix:@"."] || ![sha isKindOfClass:NSString.class] || sha.length != 64 || ![sz isKindOfClass:NSNumber.class] || sz.longLongValue < 0) { ok = NO; break; }
}
if (!ok) { plog("assets: %s 的清单格式不对,换下一个地址", b.UTF8String); continue; }
// 只下档案文件与它的区段表:清单里别的(配置、密钥、提取工具的各张清单)游戏用不着(见 host/romfs_validate.c),不下、也就不会因为它们下不动
// Download only the archive files and their extent tables: the rest of the manifest (config, key, the extraction tool's manifests) is not needed by the
// game (see host/romfs_validate.c), so it is not downloaded and the download cannot get stuck on it
fs = [fs filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary *f, id _) { return [f[@"name"] hasSuffix:@".data"] || [f[@"name"] hasSuffix:@".data.holes"]; }]];
for (NSDictionary *f in fs) tot += [f[@"size"] longLongValue];
if (!fs.count) { plog("assets: %s 的清单里没有档案文件,换下一个地址", b.UTF8String); continue; }
self.base = b; self.files = fs; self.total = tot; [NSUserDefaults.standardUserDefaults setObject:b forKey:self.defKey];
plog("assets: 下载地址 %s,清单 %lu 个文件共 %lld 字节", b.UTF8String, (unsigned long)fs.count, tot); return nil;
}
return @(dm_ui("dmDlNoServer"));
}
static int64_t dl_size(NSString *p) { NSDictionary *a = [NSFileManager.defaultManager attributesOfItemAtPath:p error:nil]; return a ? (int64_t)[a fileSize] : -1; }
- (NSString *)final:(NSString *)nm { return [self.dir stringByAppendingPathComponent:nm]; }
- (NSString *)part:(NSString *)nm { return [self.dir stringByAppendingPathComponent:[nm stringByAppendingString:@".part"]]; }
- (BOOL)have:(NSDictionary *)f { return dl_size([self final:f[@"name"]]) == [f[@"size"] longLongValue]; } // 正式文件在且字节数对 | The final file exists and its byte count is right
- (int64_t)scan { int64_t n = 0; for (NSDictionary *f in self.files) { if ([self have:f]) n += [f[@"size"] longLongValue]; else { int64_t p = dl_size([self part:f[@"name"]]); if (p > 0) n += MIN(p, [f[@"size"] longLongValue]); } } return n; }
static NSString *dl_sha256(NSString *path) {
NSFileHandle *h = [NSFileHandle fileHandleForReadingAtPath:path]; if (!h) return nil; CC_SHA256_CTX c; CC_SHA256_Init(&c);
for (;;) { @autoreleasepool { NSData *d = [h readDataOfLength:1 << 20]; if (!d.length) break; CC_SHA256_Update(&c, d.bytes, (CC_LONG)d.length); } }
unsigned char dg[32]; CC_SHA256_Final(dg, &c); NSMutableString *s = [NSMutableString new]; for (int i = 0; i < 32; i++) [s appendFormat:@"%02x", dg[i]]; return s;
}
- (void)prepare:(void (^)(NSString *err, int64_t remain, int64_t total, BOOL cellular))done {
self.shortBytes = 0; self.freeBytes = 0; // 每次先清:更早一步失败(取清单断网等)时不留上一轮「空间不够」 | Clear first every time: when an earlier step fails (manifest fetch with no network, etc.), do not keep the previous round's "not enough space"
dispatch_async(self.q, ^{
NSString *err = getenv("DM_ASSET_DL_OFF") ? @"测试开关 DM_ASSET_DL_OFF:下载站当作走不通" : [self resolve]; if (err) { dispatch_async(dispatch_get_main_queue(), ^{ done(err, 0, 0, NO); }); return; }
NSFileManager *fm = NSFileManager.defaultManager; [fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil];
[[NSURL fileURLWithPath:self.dir.stringByDeletingLastPathComponent] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; // 4 GB 资源不进 iCloud 备份 | The 4 GB of assets do not go into iCloud backup
self.settled = [self scan]; int64_t remain = self.total - self.settled;
NSNumber *freeb = nil; [[NSURL fileURLWithPath:self.dir] getResourceValue:&freeb forKey:NSURLVolumeAvailableCapacityForImportantUsageKey error:nil];
{ const char *ft = getenv("DM_ASSET_FREE_TEST"); if (ft) freeb = @((long long)(atof(ft) * 1e9)); } // 测试开关:把手机可用空间当成这么多 GB(造「空间不够」现场) | Test switch: treat the phone's free space as this many GB (reproduces the "not enough space" scenario)
self.freeBytes = freeb ? freeb.longLongValue : 0;
if (freeb && freeb.longLongValue < remain + (200ll << 20)) { self.shortBytes = remain + (200ll << 20) - freeb.longLongValue; NSString *m = [NSString stringWithFormat:@"手机剩余空间不够:还要下 %.2f GB,可用 %.2f GB", remain / 1e9, freeb.longLongValue / 1e9]; dispatch_async(dispatch_get_main_queue(), ^{ done(m, remain, self.total, NO); }); return; }
// 当前网络是不是按流量计费的(蜂窝 / 个人热点):是的话由界面先问玩家
// Whether the current network is metered (cellular / personal hotspot): if so, the UI asks the player first
nw_path_monitor_t mon = nw_path_monitor_create(); dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block BOOL exp = NO; __block int got = 0;
nw_path_monitor_set_queue(mon, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
nw_path_monitor_set_update_handler(mon, ^(nw_path_t p) { if (!got) { got = 1; exp = nw_path_is_expensive(p); dispatch_semaphore_signal(sem); } });
nw_path_monitor_start(mon); dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC)); nw_path_monitor_cancel(mon);
if (getenv("DM_ASSET_CELL_TEST")) exp = YES;
plog("assets: 已有 %lld / %lld 字节,还要下 %lld;%s", self.settled, self.total, remain, exp ? "当前是按流量计费的网络" : "当前不是按流量计费的网络");
dispatch_async(dispatch_get_main_queue(), ^{ done(nil, remain, self.total, exp); });
});
}
- (void)run:(void (^)(int64_t, int64_t, NSString *))progress done:(void (^)(NSString *))done {
dispatch_async(self.q, ^{ self.onProgress = progress; self.onDone = done; self.running = 1; self.retry = 0; self.heal = 0; self.skipWin = 0; self.best = 0; self.winT = 0; self.curBytes = 0;
if (!self.watch) { self.watch = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.q); dispatch_source_set_timer(self.watch, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), 5 * NSEC_PER_SEC, NSEC_PER_SEC);
__weak DmAssetDL *w = self; dispatch_source_set_event_handler(self.watch, ^{ [w watchTick]; }); dispatch_resume(self.watch); }
[self pump]; });
}
- (void)report:(int64_t)done note:(NSString *)note { void (^p)(int64_t, int64_t, NSString *) = self.onProgress; int64_t t = self.total; if (p) dispatch_async(dispatch_get_main_queue(), ^{ p(done, t, note); }); }
- (void)finish:(NSString *)err { self.running = 0; void (^d)(NSString *) = self.onDone; self.onDone = nil; plog("assets: 直接下载结束:%s", err ? err.UTF8String : "全部到齐"); if (d) dispatch_async(dispatch_get_main_queue(), ^{ d(err); }); }
// 找到第一个没到齐的文件,给它起(或接回)一个分段任务。只在 self.q 上跑
// Find the first incomplete file and start (or reattach) a ranged task for it. Runs only on self.q
- (void)pump {
if (!self.running) return;
self.settled = [self scan];
for (NSDictionary *f in self.files) {
if ([self have:f]) continue;
NSString *nm = f[@"name"], *part = [self part:nm]; int64_t size = [f[@"size"] longLongValue], p = MAX(dl_size(part), 0);
if (p > size) { [NSFileManager.defaultManager removeItemAtPath:part error:nil]; p = 0; }
if (p == size) { // 到齐:核校验值,对了才改成正式名 | All received: verify the checksum; rename to the final name only if it matches
[self report:self.settled note:[NSString stringWithFormat:@(dm_ui("dmDlVerifying")), nm]];
if (!size) [NSFileManager.defaultManager createFileAtPath:part contents:NSData.data attributes:nil];
NSString *sha = dl_sha256(part);
if ([sha isEqualToString:f[@"sha256"]]) { NSError *e = nil; [NSFileManager.defaultManager removeItemAtPath:[self final:nm] error:nil];
if (![NSFileManager.defaultManager moveItemAtPath:part toPath:[self final:nm] error:&e]) { [self finish:[NSString stringWithFormat:@(dm_ui("dmDlWriteFail")), nm, e.localizedDescription]]; return; }
plog("assets: %s 到齐(%lld 字节,校验值对)", nm.UTF8String, size); continue; }
int n = self.redo[nm].intValue + 1; self.redo[nm] = @(n); [NSFileManager.defaultManager removeItemAtPath:part error:nil];
plog("assets: 🔴 %s 校验值不对(得 %s,应 %s),删掉重下(第 %d 次)", nm.UTF8String, sha.UTF8String, [f[@"sha256"] UTF8String], n);
if (n >= 3) { [self finish:[NSString stringWithFormat:@(dm_ui("dmDlBad3")), nm]]; return; }
p = 0; self.settled = [self scan];
}
int64_t end = MIN(p + DL_CHUNK, size) - 1; NSString *desc = [NSString stringWithFormat:@"%@\t%lld\t%lld", nm, p, end];
[[self bg] getTasksWithCompletionHandler:^(NSArray *d0, NSArray *u0, NSArray<NSURLSessionDownloadTask *> *tasks) {
BOOL alive = NO;
for (NSURLSessionTask *t in tasks) { if (t.state == NSURLSessionTaskStateCompleted) continue; if (!self.useFg && !alive && [t.taskDescription isEqualToString:desc]) { alive = YES; if (t.state == NSURLSessionTaskStateSuspended) [t resume]; } else [t cancel]; }
self.winT = 0; self.curBytes = 0; // 新的一片(或刚接回的一片):吞吐窗口从头量。接回的旧任务若是僵死的,一个窗口后照掉速处理 | A new chunk (or one just re-attached): measure the throughput window from scratch. If a re-attached old task is dead, it is treated as a slowdown after one window
if (alive) { plog("assets: 接回系统手里没做完的任务:%s 字节 %lld–%lld", nm.UTF8String, p, end); return; }
NSString *enc = [nm stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/data/%@", self.base, enc]]];
[rq setValue:[NSString stringWithFormat:@"bytes=%lld-%lld", p, end] forHTTPHeaderField:@"Range"]; rq.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSessionDownloadTask *t = [(self.useFg ? (self.fg ?: [self fgNew]) : [self bg]) downloadTaskWithRequest:rq]; t.taskDescription = desc; [t resume];
}];
[self report:self.settled note:nil];
return;
}
[self finish:nil];
}
- (void)URLSession:(NSURLSession *)s downloadTask:(NSURLSessionDownloadTask *)t didWriteData:(int64_t)n totalBytesWritten:(int64_t)w totalBytesExpectedToWrite:(int64_t)x {
self.curBytes = w;
if (self.running) [self report:self.settled + w note:nil];
}
- (void)URLSession:(NSURLSession *)s downloadTask:(NSURLSessionDownloadTask *)t didFinishDownloadingToURL:(NSURL *)loc {
NSArray<NSString *> *d = [t.taskDescription componentsSeparatedByString:@"\t"]; if (d.count != 3) return;
NSString *nm = d[0], *part = [self part:nm]; int64_t off = d[1].longLongValue, end = d[2].longLongValue, got = dl_size(loc.path), have = MAX(dl_size(part), 0);
NSHTTPURLResponse *r = (NSHTTPURLResponse *)t.response; NSString *cr = [r valueForHTTPHeaderField:@"Content-Range"]; NSString *wantcr = [NSString stringWithFormat:@"bytes %lld-%lld/", off, end];
if (r.statusCode != 206 || ![cr hasPrefix:wantcr] || got != end - off + 1 || have != off) { // 不是要的那一段(服务器不认 Range / 中间页 / 重复送达):丢掉,pump 会按 .part 的实际长度重新要 | Not the range we asked for (server ignores Range / interstitial page / duplicate delivery): discard; pump will ask again based on the actual length of .part
plog("assets: 丢弃一段 %s 字节 %lld–%lld:HTTP %ld,Content-Range %s,收到 %lld 字节,.part 现有 %lld", nm.UTF8String, off, end, (long)r.statusCode, cr.UTF8String ?: "无", got, have); return; }
NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:loc.path]; if (![NSFileManager.defaultManager fileExistsAtPath:part]) [NSFileManager.defaultManager createFileAtPath:part contents:nil attributes:nil];
NSFileHandle *out = [NSFileHandle fileHandleForWritingAtPath:part]; if (!in || !out) { plog("assets: 🔴 打不开 %s", part.UTF8String); return; }
@try { [out seekToEndOfFile]; for (;;) { @autoreleasepool { NSData *b = [in readDataOfLength:1 << 20]; if (!b.length) break; [out writeData:b]; } } [out synchronizeFile]; }
@catch (NSException *ex) { plog("assets: 🔴 写 %s 出错:%s", part.UTF8String, ex.reason.UTF8String); [out truncateFileAtOffset:(unsigned long long)off]; }
[out closeFile]; [in closeFile];
}
- (void)URLSession:(NSURLSession *)s task:(NSURLSessionTask *)t didCompleteWithError:(NSError *)e {
if (e && e.code == NSURLErrorCancelled) return; // 我们自己取消的多余任务 | Surplus tasks that we cancelled ourselves
if (!self.running) return; // 进程刚被系统唤醒、界面还没来要:落盘已在上面做完,等 run 时再接着 | The process was just woken by the system and the UI has not asked yet: writing to disk is already done above; resume when run is called
if (e) { int wait = MIN(30, 2 << MIN(self.retry, 4)); self.retry++;
plog("assets: 一段没取成(%s),%d 秒后自动重试(第 %d 次)", e.localizedDescription.UTF8String, wait, self.retry);
[self report:[self scan] note:[NSString stringWithFormat:@(dm_ui("dmDlNetRetry")), wait]];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, wait * NSEC_PER_SEC), self.q, ^{ [self pump]; }); return; }
self.retry = 0; [self pump];
}
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)s { void (^d)(void) = self.bgDone; self.bgDone = nil; if (d) dispatch_async(dispatch_get_main_queue(), d); }
@end