Repository navigation
Expand file tree
/
Copy pathupdateService.ts
More file actions
1598 lines (1389 loc) · 47.2 KB
/
Copy pathupdateService.ts
File metadata and controls
1598 lines (1389 loc) · 47.2 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
import { check, type Update } from "@tauri-apps/plugin-updater";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import i18n from "@/i18n";
import { addMessage, updateMessage, removeMessage, removeMessagesByTag, type AppMessage } from "./messageStore";
import { pushGlobalAlert } from "@/components/ui/global-alert";
import { getConfig, setConfig } from "./configService";
import logger from "./logger";
import { isAndroidApp, isWindowsPlatform, isMobileApp } from "./platform";
// ============================================================================
// Types
// ============================================================================
export type UpdateChannel = "stable" | "preview";
export type UpdateSource = "github" | "mirror";
export type UpdateStatus =
| "idle"
| "checking"
| "available"
| "not-available"
| "error";
export type ChangelogStatus =
| "idle"
| "loading"
| "success"
| "failed"
| "unavailable";
export type UpdateErrorCode =
| "UPDATE_CHECK_FAILED"
| "CHANGELOG_FETCH_FAILED"
| "DOWNLOAD_FAILED"
| "INSTALL_FAILED";
export interface UpdateInfo {
currentVersion: string;
newVersion: string;
date?: string;
body?: string;
apkUrl?: string;
}
export interface ManualUpdate {
currentVersion: string;
version: string;
date?: string;
body?: string;
}
export interface AndroidUpdate extends ManualUpdate {
apkUrl: string;
}
/**
* Result of handing a downloaded APK to Android's package installer.
*
* `permissionRequired` means the app is not yet allowed to install unknown apps; the
* plugin has already opened the system settings screen for the user to grant it.
*/
export type AndroidInstallStatus = "opened" | "permissionRequired";
export interface AndroidInstallResult {
status: AndroidInstallStatus;
}
/** Narrow an update to the Android manual-update shape (which always has an APK URL). */
function isAndroidUpdate(
update: Update | ManualUpdate,
): update is AndroidUpdate {
return "apkUrl" in update && typeof update.apkUrl === "string";
}
export interface UpdateCheckResult {
available: boolean;
update: UpdateInfo | null;
changelog: string | null;
changelogStatus: ChangelogStatus;
status: UpdateStatus;
errorCode?: UpdateErrorCode;
errorMessage?: string;
}
interface GitHubRelease {
tag_name: string;
prerelease: boolean;
draft: boolean;
body: string;
published_at: string;
assets: Array<{ name: string; browser_download_url: string }>;
}
interface ChangelogCacheEntry {
changelog: string;
timestamp: number;
}
// ============================================================================
// Constants
// ============================================================================
const REPO_OWNER = "mon3tr-dev";
const REPO_NAME = "endprotocol";
const GITHUB_API_BASE = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}`;
const MIRROR_BASE = "https://updates.msk-network.cn";
const CHANGELOG_CACHE_TTL = 30 * 1000;
const CHANGELOG_CACHE_KEY_PREFIX = "changelog_cache_";
// ============================================================================
// State
// ============================================================================
let currentUpdate: Update | ManualUpdate | AndroidUpdate | null = null;
let currentUpdateInfo: UpdateInfo | null = null;
let isDownloading = false;
let downloadProgress = 0;
let downloadTotal = 0;
let downloadAbortController: AbortController | null = null;
let currentChannel: UpdateChannel = "stable";
let currentSource: UpdateSource = "github";
let previousChannel: UpdateChannel | null = null;
let channelSwitchDetected = false;
let changelogCache: Map<string, ChangelogCacheEntry> = new Map();
let status: UpdateStatus = "idle";
let listeners: Array<() => void> = [];
// Android: path of the APK downloaded during the current update attempt. Retained so a
// user who had to grant "install unknown apps" can retry the install without
// re-downloading the package.
let lastAndroidApkPath: string | null = null;
// The updater plugin installs manual channel updates from this manifest endpoint.
let manualUpdaterEndpoint: string | null = null;
// ============================================================================
// SemVer Helpers
// ============================================================================
interface SemVer {
major: number;
minor: number;
patch: number;
prerelease: string[];
}
function parseSemVer(version: string): SemVer | null {
const match = version.match(
/^v?(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.]+))?$/,
);
if (!match) return null;
const prerelease = match[4]
? match[4].split(".").map((p) => p.toLowerCase())
: [];
return {
major: parseInt(match[1], 10),
minor: parseInt(match[2], 10),
patch: parseInt(match[3], 10),
prerelease,
};
}
function compareSemVer(a: SemVer, b: SemVer): number {
if (a.major !== b.major) return a.major - b.major;
if (a.minor !== b.minor) return a.minor - b.minor;
if (a.patch !== b.patch) return a.patch - b.patch;
if (a.prerelease.length === 0 && b.prerelease.length > 0) return 1;
if (a.prerelease.length > 0 && b.prerelease.length === 0) return -1;
const maxLen = Math.max(a.prerelease.length, b.prerelease.length);
for (let i = 0; i < maxLen; i++) {
const aId = a.prerelease[i];
const bId = b.prerelease[i];
if (aId === undefined) return -1;
if (bId === undefined) return 1;
const aNum = /^\d+$/.test(aId) ? parseInt(aId, 10) : null;
const bNum = /^\d+$/.test(bId) ? parseInt(bId, 10) : null;
if (aNum !== null && bNum !== null) {
if (aNum !== bNum) return aNum - bNum;
} else {
if (aId !== bId) return aId < bId ? -1 : 1;
}
}
return 0;
}
function isPreviewChannel(version: string): boolean {
const semver = parseSemVer(version);
return semver !== null && semver.prerelease.length > 0;
}
function stripVPrefix(tag: string): string {
return tag.startsWith("v") ? tag.slice(1) : tag;
}
function channelFromVersion(version: string): UpdateChannel {
return isPreviewChannel(version) ? "preview" : "stable";
}
// ============================================================================
// GitHub API
// ============================================================================
async function fetchGitHubReleases(): Promise<GitHubRelease[]> {
const response = await fetch(`${GITHUB_API_BASE}/releases?per_page=100`);
if (!response.ok) {
throw new Error(`GitHub API ${response.status}: ${response.statusText}`);
}
return response.json();
}
async function fetchGitHubReleaseByTag(
tag: string,
): Promise<GitHubRelease | null> {
try {
const response = await fetch(
`${GITHUB_API_BASE}/releases/tags/${encodeURIComponent(tag)}`,
);
if (!response.ok) return null;
return response.json();
} catch {
return null;
}
}
async function getLatestPreviewEndpoint(): Promise<string | null> {
const releases = await fetchGitHubReleases();
const latest = releases
.filter((release) => release.prerelease && !release.draft)
.map((release) => ({
release,
version: parseSemVer(stripVPrefix(release.tag_name)),
}))
.filter(
(item): item is { release: GitHubRelease; version: SemVer } =>
item.version !== null,
)
.sort((a, b) => compareSemVer(b.version, a.version))[0]?.release;
if (!latest) return null;
return `https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/download/${encodeURIComponent(latest.tag_name)}/latest.json`;
}
// ============================================================================
// Changelog Cache
// ============================================================================
function getCacheKey(channel: UpdateChannel, version: string): string {
return `${CHANGELOG_CACHE_KEY_PREFIX}${channel}_${version}`;
}
function getChangelogFromCache(
channel: UpdateChannel,
version: string,
): string | null {
const key = getCacheKey(channel, version);
const entry = changelogCache.get(key);
if (!entry) return null;
if (Date.now() - entry.timestamp > CHANGELOG_CACHE_TTL) {
changelogCache.delete(key);
return null;
}
return entry.changelog;
}
function setChangelogCache(
channel: UpdateChannel,
version: string,
changelog: string,
): void {
const key = getCacheKey(channel, version);
changelogCache.set(key, { changelog, timestamp: Date.now() });
}
// ============================================================================
// Channel Switch Detection
// ============================================================================
function isChannelSwitchUpdateRequired(
localVersion: string,
remoteVersion: string,
targetChannel: UpdateChannel,
): boolean {
const localChannel = channelFromVersion(localVersion);
const remoteChannel = channelFromVersion(remoteVersion);
if (localChannel === remoteChannel) return false;
if (remoteChannel !== targetChannel) return false;
return localVersion !== remoteVersion;
}
// ============================================================================
// Get Mirror Changelog URL
// ============================================================================
async function fetchMirrorChangelogUrl(channel: UpdateChannel): Promise<string | null> {
const endpoint = channel === "stable"
? `${MIRROR_BASE}/stable/latest.json`
: `${MIRROR_BASE}/preview/latest.json`;
try {
const text = await invoke<string>("fetch_url", { url: endpoint });
const json: { notes?: string } = JSON.parse(text);
if (json.notes?.startsWith("http")) {
return json.notes;
}
} catch {
// Ignore
}
return null;
}
// ============================================================================
// Resolve Release (Unified)
// ============================================================================
async function resolveRelease(): Promise<Update | ManualUpdate | null> {
const channel = currentChannel;
logger.info(`Resolving ${channel} release (source: ${currentSource})...`, "Updater");
if (isAndroidApp()) {
return await resolveAndroidRelease();
}
// Preview channel: bypass Tauri plugin, fetch preview endpoint directly.
// The plugin tries endpoints in order and returns the first newer version,
// so on preview channel it always returns the stable update (listed first),
// which our filter then discards.
if (channel === "preview") {
return await resolvePreviewRelease();
}
// Stable channel: use Tauri updater plugin (reads endpoints from tauri.conf.json)
const update = await check();
if (!update) {
logger.info(`No ${channel} update available via Tauri updater`, "Updater");
if (channelSwitchDetected) {
logger.info(`Channel switch detected, performing manual ${channel} check...`, "Updater");
return await resolveChannelSwitchRelease();
}
return null;
}
if (isPreviewChannel(update.version)) {
logger.info(`Skipping preview version ${update.version} on stable channel`, "Updater");
return null;
}
return update;
}
// ============================================================================
// Android APK Selection
// ============================================================================
/** Android ABI of the running app, reported by the backend (`get_android_abi`). */
let androidAbi: string | null = null;
/**
* Resolve the ABI of the installed APK once.
*
* Releases are split per ABI (`endprotocol-android-<arch>-release.apk`), so the
* update check must not just take "an APK" from the release: picking the wrong
* split means downloading ~30 MB for a foreign architecture and then failing to
* install. Any failure leaves `androidAbi` null, which makes selection fall back
* to the old "whatever single APK exists" behaviour.
*/
async function resolveAndroidAbi(): Promise<string | null> {
if (androidAbi !== null) return androidAbi;
try {
androidAbi = await invoke<string | null>("get_android_abi");
} catch (error) {
logger.warn("Failed to resolve the Android ABI: " + error, "Updater");
androidAbi = null;
}
return androidAbi;
}
/** Map an `endprotocol-android-<part>-release.apk` asset name to its ABI. */
const ANDROID_APK_ARCHES: Record<string, string> = {
arm64: "arm64-v8a",
x86_64: "x86_64",
armeabi: "armeabi-v7a",
armv7: "armeabi-v7a",
x86: "x86",
universal: "universal",
};
/** `endprotocol-android-<arch>-release.apk` → arch token, or null if not a split. */
function androidApkArch(name: string): string | null {
const match = /android-([a-z0-9_]+?)(?:-release)?\.apk$/i.exec(name);
return match ? match[1].toLowerCase() : null;
}
/**
* Pick the APK in `names` that belongs on `abi`, or null when none does.
*
* Correctness matters more than finding *an* APK: installing a foreign-ABI split
* fails, so a release that ships splits without one for this device must yield
* "no update" rather than fall back to another architecture. Only releases
* without any split at all (a single universal APK, i.e. `v0.1.7-pre3` and
* earlier) may use that universal asset.
*/
function selectAndroidApkName(
names: string[],
abi: string | null,
): string | null {
const splitArchs = names
.map((name) => androidApkArch(name))
.filter((arch): arch is string => arch !== null && arch !== "universal");
if (splitArchs.length > 0) {
if (!abi) return null;
return (
names.find((name) => {
const arch = androidApkArch(name);
return arch !== null && ANDROID_APK_ARCHES[arch] === abi;
}) ?? null
);
}
// No per-ABI splits: a universal APK runs on every ABI.
return names.find((name) => /universal|all-abi/i.test(name)) ?? null;
}
function getAndroidApkAsset(
release: GitHubRelease,
abi: string | null,
): string | null {
const apkAssets = release.assets.filter((asset) =>
asset.name.toLowerCase().endsWith(".apk"),
);
if (apkAssets.length === 0) return null;
const chosen = selectAndroidApkName(
apkAssets.map((asset) => asset.name),
abi,
);
if (!chosen) return null;
const selected = apkAssets.find((asset) => asset.name === chosen);
if (!selected) return null;
try {
const url = new URL(selected.browser_download_url);
if (
url.protocol === "https:" &&
url.hostname === "github.com" &&
url.pathname.startsWith(`/${REPO_OWNER}/${REPO_NAME}/releases/download/`) &&
url.pathname.toLowerCase().endsWith(".apk")
) {
return url.toString();
}
} catch {
return null;
}
return null;
}
/**
* Rewrite a GitHub Release APK URL onto the mirror, when the mirror source is
* selected.
*
* The mirror serves the same release assets under
* `<base>/<channel>/<tag>/<asset>`, which is exactly what its `latest.json`
* references for desktop builds — Android was the only platform still pinned to
* GitHub. Returns the URL untouched when the asset is not a release download of
* this repository or the source is GitHub.
*/
function mirrorAndroidApkUrl(githubUrl: string, tag: string): string {
if (currentSource !== "mirror") return githubUrl;
try {
const url = new URL(githubUrl);
const prefix = `/${REPO_OWNER}/${REPO_NAME}/releases/download/${encodeURIComponent(tag)}/`;
if (!url.pathname.startsWith(prefix)) return githubUrl;
const asset = decodeURIComponent(url.pathname.slice(prefix.length));
if (!asset.toLowerCase().endsWith(".apk")) return githubUrl;
return `${MIRROR_BASE}/${currentChannel}/${encodeURIComponent(tag)}/${encodeURIComponent(asset)}`;
} catch {
return githubUrl;
}
}
/** Shape of the `android` entry in a release `latest.json` (see release.yml). */
interface AndroidManifestEntry {
url: string;
assetName?: string;
}
interface AndroidManifest extends AndroidManifestEntry {
apks?: Record<string, AndroidManifestEntry>;
}
interface ReleaseManifest {
version?: string;
pub_date?: string;
notes?: string;
android?: AndroidManifest;
}
/**
* Pick the manifest entry matching `abi`, falling back to the legacy single APK.
*
* The mirror's manifest is regenerated by a Worker that may not preserve the
* nested `apks` map, so the top-level `url` cannot be trusted blindly: on a
* per-ABI release it points at the arm64 split, which would install-fail on an
* x86_64 device. Fall back to it only when it is a universal asset.
*/
function pickAndroidManifestEntry(
android: AndroidManifest | undefined,
abi: string | null,
): string | null {
if (!android) return null;
const candidates: string[] = [];
if (abi && android.apks?.[abi]?.url) candidates.push(android.apks[abi].url);
// Names available via `assetName` on the top-level entry and the `apks` map.
const named = new Map<string, string>();
for (const entry of [android, ...Object.values(android.apks ?? {})]) {
if (entry.assetName && entry.url) named.set(entry.assetName, entry.url);
}
if (named.size > 0) {
const chosen = selectAndroidApkName([...named.keys()], abi);
if (chosen && named.has(chosen)) candidates.push(named.get(chosen)!);
}
// Legacy manifests carry a bare `url` with no ABIs at all.
if (android.url && named.size === 0) candidates.push(android.url);
return candidates[0] ?? null;
}
/**
* Resolve an Android update from the mirror manifest.
*
* Only the channel manifest is fetched (no GitHub API round-trip), which is the
* point of selecting the mirror: GitHub API and `objects.githubusercontent.com`
* are regularly unreachable exactly where the mirror is needed. Returns null on
* any failure so the caller can fall back to the GitHub path.
*/
async function resolveAndroidReleaseFromMirror(
localParsed: SemVer,
localVersion: string,
): Promise<AndroidUpdate | null> {
const abi = await resolveAndroidAbi();
const endpoint = `${MIRROR_BASE}/${currentChannel}/latest.json`;
let manifest: ReleaseManifest;
try {
const text = await invoke<string>("fetch_url", { url: endpoint });
manifest = JSON.parse(text);
} catch (error) {
logger.warn(`Mirror manifest unavailable (${endpoint}): ${error}`, "Updater");
return null;
}
const remoteParsed = manifest.version ? parseSemVer(manifest.version) : null;
if (!remoteParsed) {
logger.warn("Mirror manifest carries no parseable version", "Updater");
return null;
}
if (currentChannel === "stable" && remoteParsed.prerelease.length > 0) {
return null;
}
if (compareSemVer(remoteParsed, localParsed) <= 0) {
logger.info(
`No mirror Android update: ${localVersion} >= ${manifest.version}`,
"Updater",
);
return null;
}
const apkUrl = pickAndroidManifestEntry(manifest.android, abi);
if (!apkUrl) {
// A manifest without an `android` entry predates Android releases; fall
// back to GitHub so an installable build is still found.
logger.info("Mirror manifest has no Android APK entry", "Updater");
return null;
}
logger.info(
`Mirror Android update available: ${localVersion} → ${manifest.version} (ABI ${abi ?? "unknown"})`,
"Updater",
);
return {
currentVersion: localVersion,
version: stripVPrefix(manifest.version),
date: manifest.pub_date,
body: manifest.notes,
apkUrl,
};
}
async function resolveAndroidRelease(): Promise<AndroidUpdate | null> {
currentUpdate = null;
currentUpdateInfo = null;
manualUpdaterEndpoint = null;
const { getVersion } = await import("@tauri-apps/api/app");
const localVersion = await getVersion();
const localParsed = parseSemVer(localVersion);
if (!localParsed) return null;
if (currentSource === "mirror") {
const mirrored = await resolveAndroidReleaseFromMirror(localParsed, localVersion);
if (mirrored) return mirrored;
logger.info("Falling back to GitHub Releases for the Android update", "Updater");
}
const abi = await resolveAndroidAbi();
const releases = (await fetchGitHubReleases())
.filter((release) => !release.draft && release.tag_name.startsWith("v"))
.map((release) => ({
release,
version: parseSemVer(stripVPrefix(release.tag_name)),
}))
.filter(
(item): item is { release: GitHubRelease; version: SemVer } =>
item.version !== null &&
(currentChannel === "preview"
? true
: item.version.prerelease.length === 0),
)
.sort((a, b) => compareSemVer(b.version, a.version));
// Releases published before the Android pipeline existed (v0.1.6 and older)
// carry no APK. Picking one of those would resolve to "no update" and the UI
// would claim the app is up to date even though a newer installable build
// exists, so only consider releases that actually ship an APK for this ABI.
const installable = releases
.map((item) => ({
...item,
apkUrl: getAndroidApkAsset(item.release, abi),
}))
.filter(
(item): item is { release: GitHubRelease; version: SemVer; apkUrl: string } =>
item.apkUrl !== null,
);
if (installable.length === 0) {
logger.info(
"No release with an Android APK asset was found",
"Updater",
);
return null;
}
const newestStable = installable.find(
(item) => item.version.prerelease.length === 0,
);
const candidate = currentChannel === "preview"
? (newestStable && compareSemVer(newestStable.version, localParsed) > 0
? newestStable
: installable.find((item) => item.version.prerelease.length > 0))
: newestStable;
if (!candidate || compareSemVer(candidate.version, localParsed) <= 0) {
return null;
}
const apkUrl = candidate.apkUrl;
if (!apkUrl) {
logger.info(
`Release ${candidate.release.tag_name} has no supported Android APK asset`,
"Updater",
);
return null;
}
const tag = candidate.release.tag_name;
const downloadUrl = mirrorAndroidApkUrl(apkUrl, tag);
logger.info(
`Resolved Android APK for ${tag} (ABI ${abi ?? "unknown"}, source ${currentSource}): ${downloadUrl}`,
"Updater",
);
return {
currentVersion: localVersion,
version: stripVPrefix(tag),
date: candidate.release.published_at,
body: candidate.release.body,
apkUrl: downloadUrl,
};
}
async function resolvePreviewRelease(): Promise<Update | ManualUpdate | null> {
const { getVersion } = await import("@tauri-apps/api/app");
const localVersion = await getVersion();
const localParsed = parseSemVer(localVersion);
manualUpdaterEndpoint = null;
if (!localParsed) {
logger.error(`Failed to parse local version: ${localVersion}`, "Updater");
return null;
}
// Stable releases also supersede previews with the same major/minor/patch.
const stableEndpoint = currentSource === "mirror"
? `${MIRROR_BASE}/stable/latest.json`
: `https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/latest/download/latest.json`;
try {
const text = await invoke<string>("fetch_url", { url: stableEndpoint });
const stableJson: {
version: string;
pub_date?: string;
notes?: string;
} = JSON.parse(text);
const stableVersion = parseSemVer(stableJson.version);
if (
stableVersion &&
stableVersion.prerelease.length === 0 &&
compareSemVer(stableVersion, localParsed) > 0
) {
const stableUpdate = await invoke<{
version: string;
date?: string;
body?: string;
} | null>("check_update_endpoint", { endpoint: stableEndpoint });
if (stableUpdate) {
logger.info(
`Stable update available on preview channel: ${localVersion} → ${stableJson.version}`,
"Updater",
);
manualUpdaterEndpoint = stableEndpoint;
return {
version: stableUpdate.version,
currentVersion: localVersion,
date: stableUpdate.date ?? stableJson.pub_date,
body: stableUpdate.body ?? stableJson.notes,
};
}
}
} catch (error) {
logger.info(
`Stable release check failed on preview channel: ${error}`,
"Updater",
);
}
// Determine preview endpoint based on source
const endpoint = currentSource === "mirror"
? `${MIRROR_BASE}/preview/latest.json`
: await getLatestPreviewEndpoint();
if (!endpoint) {
logger.info("No published preview release was found", "Updater");
return null;
}
logger.info(`Fetching preview endpoint: ${endpoint}`, "Updater");
let latestJson: {
version: string;
pub_date?: string;
notes?: string;
};
try {
const text = await invoke<string>("fetch_url", { url: endpoint });
latestJson = JSON.parse(text);
} catch (error) {
logger.error("Failed to fetch preview endpoint: " + error, "Updater");
// Channel-switch fallback
if (channelSwitchDetected) {
logger.info("Channel switch detected, performing manual preview check...", "Updater");
return await resolveChannelSwitchRelease();
}
return null;
}
const remoteVersion = latestJson.version;
if (!remoteVersion) {
logger.error("Preview endpoint returned no version", "Updater");
return null;
}
// Must be a prerelease version
if (!isPreviewChannel(remoteVersion)) {
logger.info(`Remote version ${remoteVersion} is not a prerelease, skipping`, "Updater");
return null;
}
// Compare versions
const remoteParsed = parseSemVer(remoteVersion);
if (!remoteParsed) {
logger.error(`Failed to parse remote version: ${remoteVersion}`, "Updater");
return null;
}
if (compareSemVer(remoteParsed, localParsed) <= 0) {
logger.info(`No preview update: ${localVersion} >= ${remoteVersion}`, "Updater");
return null;
}
const endpointUpdate = await invoke<{
version: string;
date?: string;
body?: string;
} | null>("check_update_endpoint", { endpoint });
if (!endpointUpdate) {
logger.info(
`No compatible ${remoteVersion} update is available for this platform`,
"Updater",
);
return null;
}
logger.info(`Preview update available: ${localVersion} → ${remoteVersion}`, "Updater");
manualUpdaterEndpoint = endpoint;
// Return an Update-like object
return {
version: endpointUpdate.version,
currentVersion: localVersion,
date: endpointUpdate.date ?? latestJson.pub_date,
body: endpointUpdate.body ?? latestJson.notes,
};
}
async function resolveChannelSwitchRelease(): Promise<Update | ManualUpdate | null> {
const { getVersion } = await import("@tauri-apps/api/app");
const localVersion = await getVersion();
const channel = currentChannel;
let releases: GitHubRelease[];
try {
releases = await fetchGitHubReleases();
} catch (error) {
logger.error("Failed to fetch GitHub releases: " + error, "Updater");
return null;
}
const filtered = releases.filter((r) => {
if (r.draft) return false;
if (!r.tag_name.startsWith("v")) return false;
return channel === "stable" ? !r.prerelease : r.prerelease;
});
if (filtered.length === 0) return null;
filtered.sort((a, b) => {
const aVer = parseSemVer(stripVPrefix(a.tag_name));
const bVer = parseSemVer(stripVPrefix(b.tag_name));
if (!aVer || !bVer) return 0;
return compareSemVer(bVer, aVer);
});
const latest = filtered[0];
const remoteVersion = stripVPrefix(latest.tag_name);
if (!isChannelSwitchUpdateRequired(localVersion, remoteVersion, channel)) {
return null;
}
logger.info(`Channel switch update: ${localVersion} → ${remoteVersion}`, "Updater");
const latestJsonUrl = `https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/download/${latest.tag_name}/latest.json`;
try {
const response = await fetch(latestJsonUrl);
if (!response.ok) return null;
const latestJson: { version: string; pub_date: string; notes: string } = await response.json();
const endpointUpdate = await invoke<{
version: string;
date?: string;
body?: string;
} | null>("check_update_endpoint", { endpoint: latestJsonUrl });
if (!endpointUpdate) return null;
manualUpdaterEndpoint = latestJsonUrl;
return {
version: endpointUpdate.version,
currentVersion: localVersion,
date: endpointUpdate.date ?? latestJson.pub_date,
body: endpointUpdate.body ?? latestJson.notes,
};
} catch (error) {
logger.error("Failed to fetch latest.json for channel switch: " + error, "Updater");
return null;
}
}
// ============================================================================
// Changelog Fetching
// ============================================================================
async function fetchChangelog(
channel: UpdateChannel,
version: string,
tag: string,
): Promise<{ changelog: string | null; status: ChangelogStatus }> {
const cached = getChangelogFromCache(channel, version);
if (cached !== null) {
logger.debug(`Changelog cache hit for ${tag}`, "Updater");
return { changelog: cached, status: "success" };
}
logger.info(`Fetching changelog for ${tag}...`, "Updater");
// Strategy 1: Mirror source - fetch notes URL from mirror's latest.json
if (currentSource === "mirror") {
try {
const notesUrl = await fetchMirrorChangelogUrl(channel);
if (notesUrl) {
const text = await invoke<string>("fetch_url", { url: notesUrl });
if (text.trim().length > 0) {
logger.info("Changelog fetched from mirror notes URL", "Updater");
setChangelogCache(channel, version, text);
return { changelog: text, status: "success" };
}
}
} catch (error) {
logger.warn("Failed to fetch changelog from mirror: " + error, "Updater");
}
}
// Strategy 2: GitHub Release body
try {
const release = await fetchGitHubReleaseByTag(tag);
if (release?.body && release.body.trim().length > 0) {
logger.info("Changelog fetched from Release body", "Updater");
setChangelogCache(channel, version, release.body);
return { changelog: release.body, status: "success" };
}
} catch (error) {
logger.warn("Failed to fetch changelog from Release body: " + error, "Updater");
}
// Strategy 3: CHANGELOG.md release asset
try {
const assetUrl = `https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/download/${tag}/CHANGELOG.md`;
const response = await fetch(assetUrl);
if (response.ok) {
const text = await response.text();
if (text.trim().length > 0) {
logger.info("Changelog fetched from Release asset", "Updater");
setChangelogCache(channel, version, text);
return { changelog: text, status: "success" };
}
}
} catch (error) {
logger.warn("Failed to fetch changelog from Release asset: " + error, "Updater");
}
logger.warn(`Changelog not available for ${tag}`, "Updater");
return { changelog: null, status: "failed" };
}
// ============================================================================
// Core Update Logic
// ============================================================================
async function performUpdateCheck(): Promise<UpdateCheckResult> {
const channel = currentChannel;
logger.info(`Checking for updates on ${channel} channel (source: ${currentSource})...`, "Updater");
let update: Update | ManualUpdate | null;
try {
update = await resolveRelease();
} catch (error) {
logger.error("Update check failed: " + error, "Updater");
return {
available: false,
update: null,
changelog: null,
changelogStatus: "unavailable",
status: "error",
errorCode: "UPDATE_CHECK_FAILED",
errorMessage: String(error),
};
}
if (!update) {
return {
available: false,
update: null,
changelog: null,
changelogStatus: "unavailable",
status: "not-available",
};
}