331 lines
12 KiB
JavaScript
331 lines
12 KiB
JavaScript
/*
|
||
Copyright (C) 2025 QuantumNous
|
||
|
||
This program is free software: you can redistribute it and/or modify
|
||
it under the terms of the GNU Affero General Public License as
|
||
published by the Free Software Foundation, either version 3 of the
|
||
License, or (at your option) any later version.
|
||
|
||
This program is distributed in the hope that it will be useful,
|
||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
GNU Affero General Public License for more details.
|
||
|
||
You should have received a copy of the GNU Affero General Public License
|
||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||
|
||
For commercial licensing, please contact support@quantumnous.com
|
||
*/
|
||
|
||
// WeyAi 桌面端下载页的纯函数:整理 GET /api/weyai/desktop/release 的返回、识别访问者系统。
|
||
// 安装包命名沿用 electron-builder 的 artifactName:WeyAi-<version>-<os>-<arch>.<ext>
|
||
// (os 为 win / mac / linux;deb 的 arch 为 amd64 / arm64)。
|
||
// 发布布局:<base_url>/latest*.yml + <base_url>/<version>/<安装包>;后端已按清单来源
|
||
// 给出 arch 和绝对地址,这里只做兜底解析和协议过滤。
|
||
|
||
import { toSafeHttpUrl } from '../../helpers/safeUrl.js';
|
||
|
||
export const PLATFORMS = ['windows', 'mac', 'linux'];
|
||
|
||
const PLATFORM_ALIASES = {
|
||
windows: 'windows',
|
||
win: 'windows',
|
||
win32: 'windows',
|
||
mac: 'mac',
|
||
macos: 'mac',
|
||
darwin: 'mac',
|
||
osx: 'mac',
|
||
linux: 'linux',
|
||
};
|
||
|
||
// 每个平台内安装包的推荐顺序(越靠前越推荐)
|
||
const KIND_RANK = {
|
||
windows: ['exe', 'msi', 'zip'],
|
||
mac: ['dmg', 'pkg', 'zip'],
|
||
linux: ['deb', 'AppImage', 'rpm', 'tar.gz'],
|
||
};
|
||
|
||
export function normalizePlatform(value) {
|
||
if (!value) return '';
|
||
return PLATFORM_ALIASES[`${value}`.toLowerCase()] || '';
|
||
}
|
||
|
||
export function normalizeArch(value) {
|
||
const v = `${value || ''}`.toLowerCase();
|
||
if (['x64', 'amd64', 'x86_64', 'x86-64'].includes(v)) return 'x64';
|
||
// armv7l 要排在 arm 之前:后端 guessArch 会原样给出 armv7l,落到 arm64 分支
|
||
// 或返回空都不对——返回空会让它在推荐排序里被当成"架构未知"而优于"架构不符"
|
||
if (['armv7l', 'armv7', 'armhf'].includes(v)) return 'armv7l';
|
||
if (['arm64', 'aarch64', 'arm'].includes(v)) return 'arm64';
|
||
if (v === 'universal') return 'universal';
|
||
if (['ia32', 'x86', 'i386'].includes(v)) return 'ia32';
|
||
return '';
|
||
}
|
||
|
||
function fileNameOf(url) {
|
||
const clean = `${url || ''}`.split(/[?#]/)[0];
|
||
const parts = clean.split('/');
|
||
try {
|
||
return decodeURIComponent(parts[parts.length - 1] || '');
|
||
} catch (_e) {
|
||
return parts[parts.length - 1] || '';
|
||
}
|
||
}
|
||
|
||
export function inferKind(name) {
|
||
const lower = `${name || ''}`.toLowerCase();
|
||
if (lower.endsWith('.tar.gz')) return 'tar.gz';
|
||
if (lower.endsWith('.appimage')) return 'AppImage';
|
||
const match = lower.match(/\.([a-z0-9]+)$/);
|
||
return match ? match[1] : '';
|
||
}
|
||
|
||
export function inferPlatform(name) {
|
||
const lower = `${name || ''}`.toLowerCase();
|
||
if (/[-_.](win|windows|win32)[-_.]/.test(lower)) return 'windows';
|
||
if (/[-_.](mac|macos|darwin|osx)[-_.]/.test(lower)) return 'mac';
|
||
if (/[-_.]linux[-_.]/.test(lower)) return 'linux';
|
||
const kind = inferKind(lower);
|
||
if (kind === 'exe' || kind === 'msi') return 'windows';
|
||
if (kind === 'dmg' || kind === 'pkg') return 'mac';
|
||
if (['deb', 'rpm', 'appimage', 'AppImage'].includes(kind)) return 'linux';
|
||
return '';
|
||
}
|
||
|
||
export function inferArch(name) {
|
||
const lower = `${name || ''}`.toLowerCase();
|
||
if (/(armv7l|armv7|armhf)/.test(lower)) return 'armv7l';
|
||
if (/(arm64|aarch64)/.test(lower)) return 'arm64';
|
||
if (/universal/.test(lower)) return 'universal';
|
||
if (/(x64|amd64|x86_64)/.test(lower)) return 'x64';
|
||
if (/(ia32|i386)/.test(lower)) return 'ia32';
|
||
return '';
|
||
}
|
||
|
||
// 只产出 http(s) 地址:带协议的必须是 http(s),相对地址按 <base_url>/<version>/ 补全,
|
||
// 补不全(没有合法 base_url)或协议不对的文件直接丢弃。
|
||
function resolveUrl(url, baseUrl, version) {
|
||
if (!url) return '';
|
||
if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) {
|
||
return toSafeHttpUrl(url);
|
||
}
|
||
const base = toSafeHttpUrl(baseUrl).replace(/\/+$/, '');
|
||
if (!base) return '';
|
||
const dir = version ? `${encodeURIComponent(version)}/` : '';
|
||
return `${base}/${dir}${url.replace(/^\/+/, '')}`;
|
||
}
|
||
|
||
function normalizeFile(raw, fallback) {
|
||
if (!raw) return null;
|
||
const rawUrl = raw.url || raw.path || '';
|
||
const name = raw.name || fileNameOf(rawUrl);
|
||
const kind = raw.ext || raw.kind || raw.type || inferKind(name);
|
||
// 差分更新用的 blockmap 等文件不给用户下载
|
||
if (!rawUrl || kind === 'blockmap' || kind === 'yml') return null;
|
||
const platform =
|
||
normalizePlatform(raw.platform || raw.os) ||
|
||
fallback.platform ||
|
||
inferPlatform(name);
|
||
if (!platform) return null;
|
||
const version = raw.version || fallback.version || '';
|
||
const url = resolveUrl(rawUrl, fallback.baseUrl, version);
|
||
if (!url) return null;
|
||
return {
|
||
platform,
|
||
arch: normalizeArch(raw.arch) || inferArch(name),
|
||
kind,
|
||
name,
|
||
url,
|
||
size: Number(raw.size) || 0,
|
||
version,
|
||
releaseDate: raw.release_date || fallback.releaseDate || '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 把接口返回整理成 { enabled, version, releaseDate, files }。兼容两种形态:
|
||
* 1. { enabled?, version, base_url?, platforms: { windows|mac|linux: { version, release_date,
|
||
* files: [{ name, url, size, sha512, arch, ext }] } } }(后端当前实现)
|
||
* 2. { version, release_date, base_url?, files: [{ platform?, arch?, url, name?, size? }] }
|
||
* 缺 platform / arch 时按安装包文件名推断,相对地址按 base_url 补全。
|
||
*/
|
||
export function normalizeRelease(data) {
|
||
if (!data || typeof data !== 'object') {
|
||
return { enabled: true, version: '', releaseDate: '', files: [] };
|
||
}
|
||
const baseUrl = data.base_url || data.baseUrl || '';
|
||
const files = [];
|
||
const push = (list, fallback) => {
|
||
(Array.isArray(list) ? list : []).forEach((raw) => {
|
||
const file = normalizeFile(raw, { baseUrl, ...fallback });
|
||
if (file) files.push(file);
|
||
});
|
||
};
|
||
|
||
push(data.files, {
|
||
version: data.version,
|
||
releaseDate: data.release_date,
|
||
});
|
||
if (data.platforms && typeof data.platforms === 'object') {
|
||
Object.entries(data.platforms).forEach(([key, value]) => {
|
||
if (!value) return;
|
||
push(value.files, {
|
||
platform: normalizePlatform(key),
|
||
version: value.version || data.version,
|
||
releaseDate: value.release_date || data.release_date,
|
||
});
|
||
});
|
||
}
|
||
|
||
// 同一个地址只保留一次
|
||
const seen = new Set();
|
||
const unique = files.filter((file) => {
|
||
if (seen.has(file.url)) return false;
|
||
seen.add(file.url);
|
||
return true;
|
||
});
|
||
|
||
const versions = unique.map((file) => file.version).filter(Boolean);
|
||
// 后端只在各平台里给 release_date,顶层没有这个字段:取各平台里最新的一个
|
||
// (ISO 日期串按字典序比较即按时间先后),data.release_date 仅为兼容扁平形态。
|
||
const latestReleaseDate = unique.reduce(
|
||
(latest, file) =>
|
||
file.releaseDate && file.releaseDate > latest ? file.releaseDate : latest,
|
||
'',
|
||
);
|
||
return {
|
||
// 后端在关闭下载页时返回 enabled: false
|
||
enabled: data.enabled !== false,
|
||
version: data.version || versions[0] || '',
|
||
releaseDate: latestReleaseDate || data.release_date || '',
|
||
files: unique,
|
||
mobile: normalizeMobile(data.mobile),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 整理接口里的手机端发布信息(后端读的是 <base_url>/mobile/manifest.json):
|
||
* { version, release_date, android: { name, url, size, sha256 } } →
|
||
* { version, releaseDate, android: { name, url, size } | null }。
|
||
* 没有发布手机端、或地址不是 http(s) 时返回 null,页面就不显示手机端。
|
||
*/
|
||
export function normalizeMobile(data) {
|
||
if (!data || typeof data !== 'object') return null;
|
||
const raw = data.android;
|
||
const url = raw ? toSafeHttpUrl(raw.url || '') : '';
|
||
if (!url) return null;
|
||
return {
|
||
version: `${data.version || ''}`,
|
||
releaseDate: `${data.release_date || ''}`,
|
||
android: {
|
||
name: raw.name || fileNameOf(url),
|
||
url,
|
||
size: Number(raw.size) || 0,
|
||
},
|
||
};
|
||
}
|
||
|
||
/** 手机系统:android | ios | ''(iPadOS 的 Safari 自称 Macintosh,识别不出来,按电脑处理)。 */
|
||
export function detectMobileOS(userAgent) {
|
||
const ua = `${userAgent || ''}`;
|
||
if (/android/i.test(ua)) return 'android';
|
||
if (/iphone|ipad|ipod/i.test(ua)) return 'ios';
|
||
return '';
|
||
}
|
||
|
||
function kindRank(file) {
|
||
const rank = (KIND_RANK[file.platform] || []).indexOf(file.kind);
|
||
return rank === -1 ? 99 : rank;
|
||
}
|
||
|
||
/**
|
||
* 按平台分组,组内按安装包类型、架构排序。
|
||
*/
|
||
export function groupByPlatform(files) {
|
||
const groups = {};
|
||
PLATFORMS.forEach((platform) => {
|
||
groups[platform] = files
|
||
.filter((file) => file.platform === platform)
|
||
.sort(
|
||
(a, b) => kindRank(a) - kindRank(b) || a.arch.localeCompare(b.arch),
|
||
);
|
||
});
|
||
return groups;
|
||
}
|
||
|
||
/**
|
||
* 为访问者挑选推荐安装包:同平台、优先匹配架构(mac 的 universal 包视为匹配),
|
||
* 再按安装包类型排序。架构未知时 Windows、Linux 取 x64,mac 取 arm64。
|
||
*/
|
||
export function pickRecommended(files, client) {
|
||
if (!client || !PLATFORMS.includes(client.os)) return null;
|
||
const candidates = files.filter((file) => file.platform === client.os);
|
||
if (candidates.length === 0) return null;
|
||
const wantArch = client.arch || (client.os === 'mac' ? 'arm64' : 'x64');
|
||
const archScore = (file) => {
|
||
if (file.arch === wantArch) return 0;
|
||
if (file.arch === 'universal') return 1;
|
||
if (!file.arch) return 2;
|
||
return 3;
|
||
};
|
||
return [...candidates].sort(
|
||
(a, b) => archScore(a) - archScore(b) || kindRank(a) - kindRank(b),
|
||
)[0];
|
||
}
|
||
|
||
/**
|
||
* 从 userAgent / platform 字符串识别系统和架构(同步部分)。
|
||
* os:windows | mac | linux | mobile | '';arch:x64 | arm64 | ''。
|
||
* 手机另带 mobile:android | ios | ''(用来推荐手机端安装包)。
|
||
*/
|
||
export function detectClientFromUA(userAgent, platform) {
|
||
const ua = `${userAgent || ''}`;
|
||
const plat = `${platform || ''}`;
|
||
if (/android|iphone|ipad|ipod|mobile/i.test(ua)) {
|
||
return { os: 'mobile', arch: '', mobile: detectMobileOS(ua) };
|
||
}
|
||
let os = '';
|
||
if (/windows/i.test(ua) || /^win/i.test(plat)) os = 'windows';
|
||
else if (/macintosh|mac os x/i.test(ua) || /^mac/i.test(plat)) os = 'mac';
|
||
else if (/linux|x11|cros/i.test(ua) || /linux/i.test(plat)) os = 'linux';
|
||
|
||
let arch = '';
|
||
if (/arm64|aarch64/i.test(ua) || /arm|aarch64/i.test(plat)) arch = 'arm64';
|
||
else if (/win64|x64|wow64|x86_64|amd64/i.test(ua) || /x86_64/i.test(plat)) {
|
||
arch = 'x64';
|
||
}
|
||
// Safari 在 Apple 芯片上仍报 Intel,UA 里的 Intel 不可信,交给高熵接口或默认值
|
||
if (os === 'mac') arch = '';
|
||
return { os, arch };
|
||
}
|
||
|
||
/**
|
||
* 识别访问者系统和架构:先用 UA,再用 Chromium 的 userAgentData 高熵值修正架构。
|
||
*/
|
||
export async function detectClient(nav) {
|
||
const n = nav || (typeof navigator !== 'undefined' ? navigator : {});
|
||
const result = detectClientFromUA(n.userAgent, n.platform);
|
||
try {
|
||
if (n.userAgentData?.getHighEntropyValues) {
|
||
const info = await n.userAgentData.getHighEntropyValues([
|
||
'architecture',
|
||
'bitness',
|
||
]);
|
||
if (info?.architecture === 'arm') result.arch = 'arm64';
|
||
else if (info?.architecture === 'x86' && info?.bitness === '64') {
|
||
result.arch = 'x64';
|
||
}
|
||
}
|
||
} catch (_e) {
|
||
// 浏览器不支持时保留 UA 的判断
|
||
}
|
||
return result;
|
||
}
|
||
|
||
export function formatSize(bytes) {
|
||
if (!bytes) return '';
|
||
const mb = bytes / 1024 / 1024;
|
||
if (mb >= 1024) return `${(mb / 1024).toFixed(2)} GB`;
|
||
return `${mb.toFixed(1)} MB`;
|
||
}
|