feat(update): App laedt Updates per HTTP mit Fortschrittsanzeige statt als 65-MB-WebSocket-Block

Bisher kam die APK als EINE WebSocket-Nachricht (~65 MB Base64) mit starrem
60-s-Timeout — ueber den externen Proxy (Heim-Upload → Hetzner → Handy) zu
knapp, Abbruch ohne Fortschritt.

RVS: GET/HEAD /update/latest.apk — nur mit gueltigem Raum-Token im Header
X-RVS-Token (sonst 403), Content-Length, Range/206 zum Fortsetzen. Version
im Dateinamen wird ohne angehaengten Punkt erkannt.

App: Download per HTTP (react-native-fs) mit Fortschritt in % und MB,
Abbrechen-Knopf, Abbruch nur bei 30 s ohne Daten statt fester Gesamtzeit,
3 Versuche, Groessen-Check gegen Content-Length. Alter RVS (404): Fallback
auf den WebSocket-Weg mit 5 min Timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-25 13:10:07 +01:00
co-authored by Claude Opus 5.5
parent baf9e93c2a
commit a00199c121
5 changed files with 247 additions and 36 deletions
+139 -34
View File
@@ -17,6 +17,26 @@ const APP_VERSION = packageJson.version || '0.0.0.0';
type UpdateCallback = (info: UpdateInfo) => void;
/** Fortschritt fuer die Anzeige (UpdateProgress-Komponente) */
export interface UpdateProgress {
active: boolean;
version: string;
/** 0..1, -1 = unbekannt */
fraction: number;
receivedMB: number;
totalMB: number;
/** z.B. "Lade herunter …", "Neuer Versuch (2/3) …", "Installiere …" */
status: string;
}
type ProgressCallback = (p: UpdateProgress) => void;
const HTTP_ATTEMPTS = 3;
// Abbruch nur, wenn der Download HAENGT (so lange kommt kein Byte) — nicht
// nach einer festen Gesamtzeit wie frueher (60 s fuer 65 MB war zu knapp).
const READ_STALL_MS = 30_000;
const WS_TIMEOUT_MS = 5 * 60_000;
export interface UpdateInfo {
version: string;
downloadUrl: string;
@@ -27,6 +47,10 @@ class UpdateService {
private listeners: UpdateCallback[] = [];
private checking = false;
private downloading = false;
private progressListeners: ProgressCallback[] = [];
private progress: UpdateProgress = { active: false, version: '', fraction: -1, receivedMB: 0, totalMB: 0, status: '' };
private jobId: number | null = null;
private cancelled = false;
constructor() {
// Beim Start alte APK-Reste aus dem Cache wegraeumen — wenn diese App
@@ -150,46 +174,125 @@ class UpdateService {
);
}
/** APK ueber WebSocket herunterladen und installieren */
onProgress(callback: ProgressCallback): () => void {
this.progressListeners.push(callback);
callback(this.progress);
return () => {
this.progressListeners = this.progressListeners.filter(cb => cb !== callback);
};
}
private setProgress(p: Partial<UpdateProgress>): void {
this.progress = { ...this.progress, ...p };
this.progressListeners.forEach(cb => cb(this.progress));
}
/** Laufenden Download abbrechen (Knopf in der Fortschrittsanzeige) */
cancelDownload(): void {
this.cancelled = true;
if (this.jobId !== null) {
try { RNFS.stopDownload(this.jobId); } catch (_) {}
}
}
/**
* APK per HTTP vom RVS laden (/update/latest.apk, Token im Header).
* Gibt false zurueck, wenn der RVS den Weg noch nicht kennt (alter RVS) —
* dann nimmt downloadAndInstall den alten WebSocket-Weg.
*/
private async downloadViaHttp(info: UpdateInfo, destPath: string): Promise<boolean> {
const cfg = rvs.getConfig();
if (!cfg) return false;
const url = `${cfg.useTLS ? 'https' : 'http'}://${cfg.host}:${cfg.port}/update/latest.apk`;
let lastErr = '';
for (let attempt = 1; attempt <= HTTP_ATTEMPTS; attempt++) {
if (this.cancelled) throw new Error('Abgebrochen');
this.setProgress({ status: attempt === 1 ? 'Lade herunter …' : `Neuer Versuch (${attempt}/${HTTP_ATTEMPTS}) …`,
fraction: -1, receivedMB: 0 });
let expected = 0;
try {
const job = RNFS.downloadFile({
fromUrl: url,
toFile: destPath,
headers: { 'X-RVS-Token': cfg.token },
connectionTimeout: 15_000,
readTimeout: READ_STALL_MS,
progressInterval: 300,
begin: (r) => { expected = r.contentLength > 0 ? r.contentLength : 0; },
progress: (r) => {
const total = r.contentLength > 0 ? r.contentLength : info.size;
this.setProgress({
fraction: total > 0 ? Math.min(1, r.bytesWritten / total) : -1,
receivedMB: r.bytesWritten / 1048576,
totalMB: total / 1048576,
});
},
});
this.jobId = job.jobId;
const res = await job.promise;
this.jobId = null;
if (res.statusCode === 403 || res.statusCode === 404) {
// Alter RVS ohne HTTP-Download (404) bzw. Token unbekannt (403)
console.warn(`[Update] HTTP-Download nicht verfuegbar (${res.statusCode}) — nehme WebSocket`);
return false;
}
if (res.statusCode !== 200) throw new Error(`HTTP ${res.statusCode}`);
const st = await RNFS.stat(destPath);
if (expected && Number(st.size) !== expected) {
throw new Error(`Datei unvollstaendig (${st.size} von ${expected} Bytes)`);
}
return true;
} catch (err: any) {
this.jobId = null;
if (this.cancelled) throw new Error('Abgebrochen');
lastErr = err?.message || String(err);
console.warn(`[Update] HTTP-Download Versuch ${attempt} fehlgeschlagen: ${lastErr}`);
await new Promise<void>(r => setTimeout(r, 2000 * attempt));
}
}
throw new Error(`Download fehlgeschlagen: ${lastErr}`);
}
/** Alter Weg: APK als ein grosser Block ueber die WebSocket-Verbindung */
private async downloadViaWebSocket(info: UpdateInfo, destPath: string): Promise<void> {
this.setProgress({ status: 'Lade herunter (ohne Fortschritt) …', fraction: -1 });
rvs.send('update_download' as any, {});
const base64 = await new Promise<string>((resolve, reject) => {
const timeout = setTimeout(() => { unsub(); reject(new Error('Download-Timeout (5 min)')); }, WS_TIMEOUT_MS);
const unsub = rvs.onMessage((msg: RVSMessage) => {
if ((msg.type as string) === 'update_data') {
clearTimeout(timeout);
unsub();
if (msg.payload.error) reject(new Error(msg.payload.error as string));
else resolve(msg.payload.base64 as string);
}
});
});
if (this.cancelled) throw new Error('Abgebrochen');
await RNFS.writeFile(destPath, base64, 'base64');
}
/** APK herunterladen (HTTP mit Fortschritt, sonst WebSocket) und installieren */
async downloadAndInstall(info: UpdateInfo): Promise<void> {
if (this.downloading) return;
this.downloading = true;
this.cancelled = false;
this.setProgress({ active: true, version: info.version, fraction: -1, receivedMB: 0,
totalMB: info.size / 1048576, status: 'Starte …' });
const fileName = `ARIA-v${info.version}.apk`;
const destPath = `${RNFS.CachesDirectoryPath}/${fileName}`;
try {
console.log(`[Update] Fordere APK v${info.version} an...`);
Alert.alert('Download gestartet', `Version ${info.version} wird ueber RVS heruntergeladen...`);
// APK ueber WebSocket anfordern
rvs.send('update_download' as any, {});
// Auf update_data warten (einmalig)
const apkData = await new Promise<{base64: string, fileName: string}>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('Download-Timeout (60s)')), 60000);
const unsub = rvs.onMessage((msg: RVSMessage) => {
if ((msg.type as string) === 'update_data') {
clearTimeout(timeout);
unsub();
if (msg.payload.error) {
reject(new Error(msg.payload.error as string));
} else {
resolve({
base64: msg.payload.base64 as string,
fileName: msg.payload.fileName as string || `ARIA-${info.version}.apk`,
});
}
}
});
});
// Vor dem Schreiben alte APKs im Cache wegraeumen — falls mehrere
// Updates in einer Session gezogen werden
console.log(`[Update] Lade APK v${info.version} …`);
// Vor dem Download alte APKs im Cache wegraeumen
await this.cleanupOldApks();
// Base64 als APK-Datei speichern
const destPath = `${RNFS.CachesDirectoryPath}/${apkData.fileName}`;
await RNFS.writeFile(destPath, apkData.base64, 'base64');
const viaHttp = await this.downloadViaHttp(info, destPath);
if (!viaHttp) await this.downloadViaWebSocket(info, destPath);
const fileSize = await RNFS.stat(destPath);
console.log(`[Update] APK gespeichert: ${destPath} (${(Number(fileSize.size) / 1024 / 1024).toFixed(1)}MB)`);
console.log(`[Update] APK gespeichert: ${destPath} (${(Number(fileSize.size) / 1024 / 1024).toFixed(1)}MB, ${viaHttp ? 'HTTP' : 'WebSocket'})`);
this.setProgress({ fraction: 1, status: 'Installiere …' });
// APK installieren via natives ApkInstaller Module (FileProvider + Intent)
if (Platform.OS === 'android') {
@@ -199,15 +302,17 @@ class UpdateService {
} catch (installErr: any) {
Alert.alert(
'APK heruntergeladen',
`Version ${info.version} gespeichert.\n\nBitte manuell installieren:\nDateimanager → ${apkData.fileName} antippen.\n\n(${installErr.message})`,
`Version ${info.version} gespeichert.\n\nBitte manuell installieren:\nDateimanager → ${fileName} antippen.\n\n(${installErr.message})`,
);
}
}
} catch (err: any) {
console.error(`[Update] Fehler: ${err.message}`);
Alert.alert('Update fehlgeschlagen', err.message);
try { await RNFS.unlink(destPath); } catch (_) {}
if (!this.cancelled) Alert.alert('Update fehlgeschlagen', err.message);
} finally {
this.downloading = false;
this.setProgress({ active: false });
}
}