1688 lines
63 KiB
JavaScript
1688 lines
63 KiB
JavaScript
/**
|
||
* 用酷安产品库补充 / 覆盖本项目的手机参数。
|
||
*
|
||
* 流程:
|
||
* 1. 拉取酷安机型目录并按品牌 + 型号匹配本地设备;
|
||
* 2. 查询每个产品的版本与配置 ID,取基础版本;
|
||
* 3. 每 4 个配置请求一次配置对比页,解析完整参数表;
|
||
* 4. 按信息度合并酷安参数覆盖本地数据,本地缺失的机型自动创建;
|
||
* 5. 只保留酷安评分与同步时间,原始参数表不再入库。
|
||
*
|
||
* 示例:
|
||
* pnpm sync:coolapk
|
||
* pnpm sync:coolapk -- --write
|
||
* pnpm sync:coolapk -- --limit 10 --write
|
||
*/
|
||
import { existsSync } from 'node:fs';
|
||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||
import { dirname } from 'node:path';
|
||
import * as cheerio from 'cheerio';
|
||
import { pinyin } from 'pinyin-pro';
|
||
import { deviceSchema } from '../src/lib/schema';
|
||
import { importEntities, listDevices } from '../src/lib/repo';
|
||
|
||
const BASE = 'https://m.coolapk.com';
|
||
const HEADERS = {
|
||
'User-Agent':
|
||
'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Mobile Safari/537.36',
|
||
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||
Referer: `${BASE}/mp/productSelector/configSearch?callFunction=addProduct&drawNav=1&isHidden=0`,
|
||
};
|
||
const CATALOG_CACHE = 'data/cache/coolapk-products.json';
|
||
|
||
const BRAND_ALIASES = {
|
||
Xiaomi: ['小米', 'xiaomi'],
|
||
Redmi: ['redmi', '红米'],
|
||
Huawei: ['华为', 'huawei'],
|
||
Honor: ['荣耀', 'honor'],
|
||
OPPO: ['oppo'],
|
||
vivo: ['vivo'],
|
||
iQOO: ['iqoo'],
|
||
OnePlus: ['一加', 'oneplus'],
|
||
realme: ['真我', 'realme'],
|
||
nubia: ['努比亚', 'nubia', '红魔'],
|
||
ZTE: ['中兴', 'zte'],
|
||
Samsung: ['三星', 'samsung'],
|
||
Apple: ['apple', '苹果'],
|
||
Meizu: ['魅族', 'meizu', '魅蓝'],
|
||
Motorola: ['moto', 'motorola', '摩托罗拉'],
|
||
ROG: ['rog', '玩家国度'],
|
||
'NIO Phone': ['蔚来', 'nio'],
|
||
'Lenovo Legion': ['联想拯救者', '拯救者手机', '拯救者', 'lenovo'],
|
||
Maimang: ['麦芒'],
|
||
WIKO: ['wiko'],
|
||
'Moondrop MIAD': ['水月雨', 'moondrop'],
|
||
Philips: ['飞利浦', 'philips'],
|
||
Gionee: ['金立', 'gionee'],
|
||
Coolpad: ['酷派', 'coolpad'],
|
||
Sony: ['索尼', 'sony'],
|
||
Nothing: ['nothing'],
|
||
POCO: ['poco'],
|
||
Google: ['谷歌', 'google', 'nexus'],
|
||
BlackShark: ['黑鲨', 'blackshark'],
|
||
Smartisan: ['坚果', 'smartisan', '锤子'],
|
||
Nokia: ['诺基亚', 'nokia'],
|
||
Lenovo: ['联想', 'lenovo'],
|
||
BlackBerry: ['黑莓', 'blackberry'],
|
||
Sharp: ['夏普', 'sharp'],
|
||
Meitu: ['美图', 'meitu'],
|
||
Hisense: ['海信', 'hisense'],
|
||
RayNeo: ['雷鸟', 'rayneo'],
|
||
Royole: ['柔宇', 'royole'],
|
||
ASUS: ['华硕', 'asus'],
|
||
TCL: ['tcl'],
|
||
Unihertz: ['unihertz'],
|
||
AGM: ['agm'],
|
||
CMF: ['cmf', 'nothing'],
|
||
Qin: ['多亲', 'qin'],
|
||
Tianyi: ['天翼', 'tianyi'],
|
||
BlueFox: ['蓝狐', 'bluefox'],
|
||
STEPX: ['stepx'],
|
||
Essential: ['essential'],
|
||
LG: ['lg'],
|
||
HTC: ['htc'],
|
||
ZUK: ['zuk'],
|
||
'360': ['360'],
|
||
};
|
||
|
||
/** 新机型:从酷安产品名推断品牌与型号 */
|
||
const PRODUCT_PREFIXES = [
|
||
['腾讯红魔', 'nubia', false],
|
||
['红魔', 'nubia', false],
|
||
['努比亚', 'nubia', true],
|
||
['联想拯救者', 'Lenovo Legion', true],
|
||
['拯救者电竞手机', 'Lenovo Legion', true],
|
||
['拯救者手机', 'Lenovo Legion', true],
|
||
['Redmi', 'Redmi', true],
|
||
['红米', 'Redmi', true],
|
||
['小米', 'Xiaomi', true],
|
||
['华为', 'Huawei', true],
|
||
['荣耀', 'Honor', true],
|
||
['OPPO', 'OPPO', true],
|
||
['vivo', 'vivo', true],
|
||
['iQOO', 'iQOO', true],
|
||
['一加', 'OnePlus', true],
|
||
['真我', 'realme', true],
|
||
['realme', 'realme', true],
|
||
['中兴', 'ZTE', true],
|
||
['ZTE', 'ZTE', true],
|
||
['三星', 'Samsung', true],
|
||
['iPhone', 'Apple', false],
|
||
['苹果', 'Apple', true],
|
||
['魅族', 'Meizu', true],
|
||
['魅蓝', 'Meizu', true],
|
||
['moto', 'Motorola', true],
|
||
['摩托罗拉', 'Motorola', true],
|
||
['ROG', 'ROG', true],
|
||
['蔚来', 'NIO Phone', true],
|
||
['NIO', 'NIO Phone', true],
|
||
['麦芒', 'Maimang', true],
|
||
['WIKO', 'WIKO', true],
|
||
['水月雨', 'Moondrop MIAD', true],
|
||
['飞利浦', 'Philips', true],
|
||
['金立', 'Gionee', true],
|
||
['酷派', 'Coolpad', true],
|
||
['索尼', 'Sony', true],
|
||
['Nothing', 'Nothing', true],
|
||
['多亲', 'Qin', true],
|
||
['谷歌', 'Google', true],
|
||
['Google', 'Google', true],
|
||
['黑鲨', 'BlackShark', true],
|
||
['坚果', 'Smartisan', true],
|
||
['诺基亚', 'Nokia', true],
|
||
['LG', 'LG', true],
|
||
['HTC', 'HTC', true],
|
||
['ZUK', 'ZUK', true],
|
||
['360', '360', true],
|
||
['POCO', 'POCO', true],
|
||
['Unihertz', 'Unihertz', true],
|
||
['AGM', 'AGM', true],
|
||
['CMF', 'CMF', true],
|
||
['美图', 'Meitu', true],
|
||
['海信', 'Hisense', true],
|
||
['雷鸟', 'RayNeo', true],
|
||
['柔宇', 'Royole', true],
|
||
['TCL', 'TCL', true],
|
||
['华硕', 'ASUS', true],
|
||
['蓝狐', 'BlueFox', true],
|
||
['天翼', 'Tianyi', true],
|
||
['STEPX', 'STEPX', true],
|
||
['联想', 'Lenovo', true],
|
||
['黑莓', 'BlackBerry', true],
|
||
['夏普', 'Sharp', true],
|
||
['Galaxy', 'Samsung', false],
|
||
['Nexus', 'Google', false],
|
||
['Nokia', 'Nokia', false],
|
||
['畅享', 'Huawei', false],
|
||
['Essential', 'Essential', false],
|
||
];
|
||
|
||
function inferIdentity(name) {
|
||
const text = clean(name);
|
||
for (const [prefix, brand, strip] of PRODUCT_PREFIXES) {
|
||
if (text.toLowerCase().startsWith(prefix.toLowerCase())) {
|
||
const model = strip ? text.slice(prefix.length).trim() : text;
|
||
if (model) return { brand, model };
|
||
}
|
||
}
|
||
return { brand: 'Other', model: text };
|
||
}
|
||
|
||
function slugify(value) {
|
||
const syllables = pinyin(value, { toneType: 'none', type: 'array', nonZh: 'consecutive' });
|
||
return syllables
|
||
.join('-')
|
||
.toLowerCase()
|
||
.replace(/\+/g, '-plus')
|
||
.replace(/&/g, '-and')
|
||
.replace(/[^a-z0-9]+/g, '-')
|
||
.replace(/^-+|-+$/g, '')
|
||
.replace(/-{2,}/g, '-');
|
||
}
|
||
|
||
function makeBlankSpecs() {
|
||
return {
|
||
body: {},
|
||
display: {},
|
||
platform: {},
|
||
memory: {},
|
||
rearCamera: [],
|
||
frontCamera: [],
|
||
vibration: {},
|
||
speakers: { units: [] },
|
||
connectivity: { bands: [], satelliteBands: [] },
|
||
battery: {},
|
||
sensors: { list: [] },
|
||
software: { updateTimeline: [] },
|
||
features: [],
|
||
cameraFeatures: [],
|
||
benchmarks: [],
|
||
pricing: [],
|
||
extra: {},
|
||
};
|
||
}
|
||
|
||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||
|
||
function clean(value) {
|
||
if (typeof value === 'string') return value.replace(/\u00a0/g, ' ').replace(/\s+/g, ' ').trim();
|
||
if (typeof value === 'number') return String(value);
|
||
return '';
|
||
}
|
||
|
||
function lines(value) {
|
||
return String(value ?? '')
|
||
.replace(/\u00a0/g, ' ')
|
||
.split(/\n+/)
|
||
.map((line) => line.replace(/\s+/g, ' ').trim())
|
||
.filter((line) => line && line !== '-');
|
||
}
|
||
|
||
function firstLine(value) {
|
||
return lines(value)[0] ?? '';
|
||
}
|
||
|
||
/** 第一行有效文本;'-' / 空白返回 undefined,避免覆盖成空值 */
|
||
function line(value) {
|
||
return firstLine(value) || undefined;
|
||
}
|
||
|
||
/** 多行文本用分号连接 */
|
||
function semicolon(value) {
|
||
const valueLines = lines(value);
|
||
return valueLines.length > 0 ? valueLines.join(';') : undefined;
|
||
}
|
||
|
||
function unique(values) {
|
||
return [...new Set(values.map(clean).filter(Boolean))];
|
||
}
|
||
|
||
function normalize(value) {
|
||
return String(value ?? '')
|
||
.toLowerCase()
|
||
.replace(/[®™©]/g, '')
|
||
.replace(/+/g, '+')
|
||
.replace(/[\s\-_/·,,.。()()[\]【】::]/g, '');
|
||
}
|
||
|
||
function splitList(value) {
|
||
return unique(String(value ?? '').split(/[,,、;;||]/)).filter((item) => item !== '-');
|
||
}
|
||
|
||
function numericTokens(value) {
|
||
return String(value ?? '').match(/\d+(?:\.\d+)?/g) ?? [];
|
||
}
|
||
|
||
function infoScore(value) {
|
||
const text = clean(value);
|
||
if (!text) return 0;
|
||
const numbers = numericTokens(text).length;
|
||
const units = (
|
||
text.match(
|
||
/(?:mm|cm|g|克|寸|英寸|hz|nit|nits|mah|w|gb|tb|mp|ppi|gbps|nm|ghz|mhz|fps|核|台|个)/gi,
|
||
) ?? []
|
||
).length;
|
||
const vague = (text.match(/大电池|快充|超大|高性能|旗舰|优秀|支持|其他/g) ?? []).length;
|
||
return numbers * 6 + units * 3 + Math.min(text.length, 100) / 50 - vague * 2;
|
||
}
|
||
|
||
function numericConflict(a, b) {
|
||
const left = new Set(numericTokens(a));
|
||
const right = new Set(numericTokens(b));
|
||
if (left.size === 0 || right.size === 0) return false;
|
||
const leftInRight = [...left].every((value) => right.has(value));
|
||
const rightInLeft = [...right].every((value) => left.has(value));
|
||
return !(leftInRight || rightInLeft);
|
||
}
|
||
|
||
/**
|
||
* 合并文本:酷安为准,但不让低信息度内容覆盖高信息度内容;
|
||
* 若两边数值明显冲突,则视为不一致,采用酷安值。
|
||
*/
|
||
function pickText(existing, incoming) {
|
||
if (!incoming) return existing;
|
||
if (!existing) return incoming;
|
||
if (clean(existing).toLowerCase() === clean(incoming).toLowerCase()) return existing;
|
||
const oldScore = infoScore(existing);
|
||
const newScore = infoScore(incoming);
|
||
if (newScore >= oldScore) return incoming;
|
||
if (numericConflict(existing, incoming)) return incoming;
|
||
return existing;
|
||
}
|
||
|
||
function pickList(existing, incoming, options = {}) {
|
||
const oldList = existing ?? [];
|
||
const newList = incoming ?? [];
|
||
if (newList.length === 0) return oldList;
|
||
if (oldList.length === 0) return newList;
|
||
if (newList.length >= oldList.length) return newList;
|
||
if (options.union) return unique([...newList, ...oldList]);
|
||
return oldList;
|
||
}
|
||
|
||
function pickResolution(existing, incoming) {
|
||
if (!incoming) return existing;
|
||
if (!existing) return incoming;
|
||
const newHasPixels = /\d+\s*[x×*]\s*\d+/i.test(incoming);
|
||
const oldHasPixels = /\d+\s*[x×*]\s*\d+/i.test(existing);
|
||
if (newHasPixels && !oldHasPixels) return incoming;
|
||
if (!newHasPixels && oldHasPixels) return existing;
|
||
return pickText(existing, incoming);
|
||
}
|
||
|
||
function resolutionMegapixels(value) {
|
||
const match = String(value ?? '').match(/(\d+(?:\.\d+)?)\s*(亿|万)?像素/);
|
||
if (!match) return undefined;
|
||
const number = Number(match[1]);
|
||
return match[2] === '亿' ? number * 10000 : number;
|
||
}
|
||
|
||
function pickResolutionField(existing, incoming) {
|
||
if (!incoming) return existing;
|
||
if (!existing) return incoming;
|
||
const oldScore = resolutionMegapixels(existing);
|
||
const newScore = resolutionMegapixels(incoming);
|
||
if (oldScore !== undefined && newScore !== undefined) return newScore >= oldScore ? incoming : existing;
|
||
return pickText(existing, incoming);
|
||
}
|
||
|
||
function pickFocal(existing, incoming) {
|
||
if (!incoming) return existing;
|
||
if (!existing) return incoming;
|
||
const oldNumber = Number(numericTokens(existing)[0]);
|
||
const newNumber = Number(numericTokens(incoming)[0]);
|
||
if (Number.isFinite(oldNumber) && Number.isFinite(newNumber)) {
|
||
return Math.abs(oldNumber - newNumber) <= 1 ? existing : incoming;
|
||
}
|
||
return pickText(existing, incoming);
|
||
}
|
||
|
||
function pickSensor(existing, incoming) {
|
||
if (!incoming) return existing;
|
||
if (!existing) return incoming;
|
||
const trim = (value) => clean(value).replace(/[、,,;;\s]+$/g, '');
|
||
if (trim(existing) === trim(incoming)) return trim(incoming);
|
||
const score = (value) => {
|
||
const text = clean(value);
|
||
let total = Math.min(text.length, 20) / 10;
|
||
if (/思特威|索尼|三星|豪威|格科微|SK|OV|IMX|SC\d|HP\d|JN\d|LYT|HPE|HPC/i.test(text)) total += 6;
|
||
if (/^(RYYB|传感器|未知|主摄|镜头|CMOS)/i.test(text)) total -= 4;
|
||
return total;
|
||
};
|
||
return score(incoming) >= score(existing) ? incoming : existing;
|
||
}
|
||
|
||
function pickVideo(existing, incoming) {
|
||
if (!incoming) return existing;
|
||
if (!existing) return incoming;
|
||
const score = (value) => {
|
||
const text = String(value ?? '').toUpperCase();
|
||
const resolution = text.includes('8K') ? 3 : text.includes('4K') ? 2 : text.includes('1080') ? 1 : 0;
|
||
const fps = Number((text.match(/(\d+)\s*FPS/) ?? [])[1] ?? 0);
|
||
return resolution * 1000 + fps;
|
||
};
|
||
return score(incoming) >= score(existing) ? incoming : existing;
|
||
}
|
||
|
||
function toNit(value) {
|
||
const match = clean(value).match(/(\d+(?:\.\d+)?)\s*(?:nits?|尼特)/i);
|
||
return match ? `${match[1]} nit` : undefined;
|
||
}
|
||
|
||
function measure(value) {
|
||
const match = clean(value).match(/(\d+(?:\.\d+)?)\s*(mm|毫米|g|克|寸|英寸)/i);
|
||
if (!match) return undefined;
|
||
const unit = match[2].toLowerCase();
|
||
return `${match[1]}${unit === '毫米' ? 'mm' : unit === '克' ? 'g' : unit === '英寸' ? '英寸' : unit}`;
|
||
}
|
||
|
||
/** 保留「(玻璃蓝/透明)」这类版本说明,同时补全省略的单位 */
|
||
function measureVariant(value, fallbackUnit) {
|
||
const text = clean(value);
|
||
const match = text.match(/(\d+(?:\.\d+)?)\s*(mm|毫米|g|克)?(.*)$/i);
|
||
if (!match) return text;
|
||
const unit = match[2]
|
||
? match[2].toLowerCase() === '毫米'
|
||
? 'mm'
|
||
: match[2].toLowerCase() === '克'
|
||
? 'g'
|
||
: match[2]
|
||
: fallbackUnit;
|
||
return `${match[1]}${unit}${match[3] ?? ''}`.trim();
|
||
}
|
||
|
||
async function request(url, attempt = 1, ajax = false) {
|
||
try {
|
||
await sleep(120);
|
||
const response = await fetch(url, {
|
||
headers: ajax ? { ...HEADERS, 'X-Requested-With': 'XMLHttpRequest' } : HEADERS,
|
||
signal: AbortSignal.timeout(25000),
|
||
});
|
||
if (!response.ok) {
|
||
const error = new Error(`HTTP ${response.status}`);
|
||
error.status = response.status;
|
||
throw error;
|
||
}
|
||
return await response.text();
|
||
} catch (error) {
|
||
if (attempt >= 5) throw error;
|
||
const limited = error?.status === 429 || error?.status === 403;
|
||
await sleep((limited ? 1500 : 500) * attempt);
|
||
return request(url, attempt + 1, ajax);
|
||
}
|
||
}
|
||
|
||
function parseProductList(html) {
|
||
const $ = cheerio.load(html);
|
||
const items = [];
|
||
$('.phone-item[data-product-id]').each((_, element) => {
|
||
const $item = $(element);
|
||
const id = clean($item.attr('data-product-id'));
|
||
const name = clean($item.find('.phone-name').first().text());
|
||
if (id && name) items.push({ id, name });
|
||
});
|
||
return items;
|
||
}
|
||
|
||
async function fetchCatalog(refresh) {
|
||
if (!refresh && existsSync(CATALOG_CACHE)) {
|
||
try {
|
||
const cached = JSON.parse(await readFile(CATALOG_CACHE, 'utf8'));
|
||
if (Array.isArray(cached.items) && cached.items.length > 0) {
|
||
console.log(`使用机型目录缓存(${cached.items.length} 款)`);
|
||
return cached.items;
|
||
}
|
||
} catch {}
|
||
}
|
||
|
||
const items = [];
|
||
const seen = new Set();
|
||
for (let page = 1; page <= 120; page += 1) {
|
||
const html = await request(
|
||
`${BASE}/mp/productSelector/configSearch?callFunction=addProduct&drawNav=1&isHidden=0&page=${page}`,
|
||
);
|
||
const pageItems = parseProductList(html);
|
||
if (pageItems.length === 0) break;
|
||
for (const item of pageItems) {
|
||
if (seen.has(item.id)) continue;
|
||
seen.add(item.id);
|
||
items.push(item);
|
||
}
|
||
if (page % 10 === 0) console.log(` 机型目录 ${page} 页,累计 ${items.length} 款`);
|
||
}
|
||
|
||
await mkdir(dirname(CATALOG_CACHE), { recursive: true });
|
||
await writeFile(
|
||
CATALOG_CACHE,
|
||
`${JSON.stringify({ fetchedAt: new Date().toISOString(), items }, null, 2)}\n`,
|
||
'utf8',
|
||
);
|
||
console.log(`机型目录已缓存:${items.length} 款`);
|
||
return items;
|
||
}
|
||
|
||
function matchProducts(devices, products) {
|
||
const byName = new Map();
|
||
for (const product of products) {
|
||
const key = normalize(product.name);
|
||
if (!byName.has(key)) byName.set(key, []);
|
||
byName.get(key).push(product);
|
||
}
|
||
|
||
const matches = [];
|
||
const misses = [];
|
||
for (const device of devices) {
|
||
const aliases = BRAND_ALIASES[device.brand] ?? [];
|
||
const model = device.model.trim();
|
||
const candidates = [];
|
||
for (const alias of aliases) {
|
||
if (model.toLowerCase().startsWith(alias.toLowerCase())) {
|
||
const rest = model.slice(alias.length).trim();
|
||
if (rest) candidates.push(`${alias}${rest}`, rest);
|
||
} else {
|
||
candidates.push(`${alias}${model}`);
|
||
}
|
||
}
|
||
candidates.push(model);
|
||
|
||
let product;
|
||
for (const candidate of candidates) {
|
||
const found = byName.get(normalize(candidate));
|
||
if (!found) continue;
|
||
if (found.length > 1 && candidate === model) continue;
|
||
product = found[0];
|
||
break;
|
||
}
|
||
if (product) matches.push({ device, product, name: product.name });
|
||
else misses.push(device);
|
||
}
|
||
return { matches, misses };
|
||
}
|
||
|
||
/** 酷安目录偶尔有同名重复机型,保留较新的产品 ID,避免重复建页 */
|
||
function dedupeProducts(products) {
|
||
const byName = new Map();
|
||
for (const product of products) {
|
||
const key = normalize(product.name);
|
||
const current = byName.get(key);
|
||
if (!current || Number(product.id) > Number(current.id)) byName.set(key, product);
|
||
}
|
||
return [...byName.values()];
|
||
}
|
||
|
||
async function fetchVersions(product) {
|
||
const text = await request(
|
||
`${BASE}/mp/productSelector/getProductVersion?callFunction=addProduct&productId=${product.id}`,
|
||
1,
|
||
true,
|
||
);
|
||
let json;
|
||
try {
|
||
json = JSON.parse(text);
|
||
} catch {
|
||
return { product, versions: [] };
|
||
}
|
||
if (!json.data) return { product, versions: [] };
|
||
|
||
const $ = cheerio.load(json.data);
|
||
const versions = [];
|
||
$('.version-item').each((_, element) => {
|
||
const info = clean($(element).find('.version-info').text());
|
||
const configId = clean($(element).find('[data-config-id]').attr('data-config-id'));
|
||
if (!configId) return;
|
||
const match = info.match(/(.+?)\s*[¥¥]\s*(\d+)/);
|
||
versions.push({
|
||
configId,
|
||
name: match ? match[1].trim() : info,
|
||
price: match ? match[2] : undefined,
|
||
});
|
||
});
|
||
return { product, versions };
|
||
}
|
||
|
||
function parseValue(element, $) {
|
||
const $value = $(element).clone();
|
||
$value.find('br').replaceWith('\n');
|
||
const text = $value.text().replace(/\u00a0/g, ' ');
|
||
return text
|
||
.split('\n')
|
||
.map((line) => line.replace(/\s+/g, ' ').trim())
|
||
.filter(Boolean)
|
||
.join('\n');
|
||
}
|
||
|
||
function parseComparePage(html) {
|
||
const $ = cheerio.load(html);
|
||
const products = [];
|
||
$('.products-row .product-card[data-config_id]').each((_, element) => {
|
||
const $card = $(element);
|
||
const configId = clean($card.attr('data-config_id'));
|
||
if (!configId) return;
|
||
products.push({
|
||
configId,
|
||
name:
|
||
clean($card.find('.product-name').attr('data-original_title')) ||
|
||
clean($card.find('.product-name').text()),
|
||
price: clean($card.find('.price-value').text()),
|
||
});
|
||
});
|
||
|
||
const groups = [];
|
||
$('.specs-section').each((_, section) => {
|
||
const $section = $(section);
|
||
const groupName = clean($section.children('.section-title').find('.col-text').text());
|
||
if (!groupName) return;
|
||
const rows = [];
|
||
let subgroup = '';
|
||
$section.children('.section-title-small, .specs-row').each((__, node) => {
|
||
const $node = $(node);
|
||
if ($node.hasClass('section-title-small')) {
|
||
subgroup = clean($node.find('.col-text').text());
|
||
return;
|
||
}
|
||
const label = clean($node.find('.fixed-column .spec-label').first().text());
|
||
if (!label) return;
|
||
const values = [];
|
||
$node.find('.column.flex-column').each((___, column) => {
|
||
values.push(parseValue($(column).find('.spec-value').first(), $));
|
||
});
|
||
rows.push({ subgroup: subgroup || undefined, label, values });
|
||
});
|
||
groups.push({ name: groupName, rows });
|
||
});
|
||
return { products, groups };
|
||
}
|
||
|
||
async function fetchCompare(configIds) {
|
||
const html = await request(
|
||
`${BASE}/mp/productSelector/configCompare?share_key=${configIds.join(',')}`,
|
||
);
|
||
return parseComparePage(html);
|
||
}
|
||
|
||
function rowsOf(groups, groupName) {
|
||
return groups
|
||
.filter((group) => group.name === groupName)
|
||
.flatMap((group) => group.rows.map((row) => ({ ...row, groupName })));
|
||
}
|
||
|
||
function makeLookup(groupRows) {
|
||
return (label, subgroup) => {
|
||
const found = groupRows.find(
|
||
(row) =>
|
||
row.label === label && (subgroup === undefined || row.subgroup === subgroup),
|
||
);
|
||
return found?.value;
|
||
};
|
||
}
|
||
|
||
function mergeCamera(list, module, used) {
|
||
const index = list.findIndex(
|
||
(item, itemIndex) => item.position === module.position && !used.has(itemIndex),
|
||
);
|
||
if (index >= 0) {
|
||
const current = list[index];
|
||
list[index] = {
|
||
...current,
|
||
...(module.sensorModel
|
||
? { sensorModel: pickSensor(current.sensorModel, module.sensorModel) }
|
||
: {}),
|
||
...(module.sensorSize ? { sensorSize: pickText(current.sensorSize, module.sensorSize) } : {}),
|
||
...(module.resolution
|
||
? { resolution: pickResolutionField(current.resolution, module.resolution) }
|
||
: {}),
|
||
...(module.aperture ? { aperture: pickText(current.aperture, module.aperture) } : {}),
|
||
...(module.lensElements ? { lensElements: pickText(current.lensElements, module.lensElements) } : {}),
|
||
...(module.pixelSize ? { pixelSize: pickText(current.pixelSize, module.pixelSize) } : {}),
|
||
...(module.zoom ? { zoom: pickText(current.zoom, module.zoom) } : {}),
|
||
...(module.focalLength ? { focalLength: pickFocal(current.focalLength, module.focalLength) } : {}),
|
||
...(module.fov ? { fov: pickText(current.fov, module.fov) } : {}),
|
||
...(module.ois ? { ois: true } : {}),
|
||
...(module.eis ? { eis: true } : {}),
|
||
...(module.cipa ? { cipa: pickText(current.cipa, module.cipa) } : {}),
|
||
...(module.telephotoStructure
|
||
? { telephotoStructure: pickText(current.telephotoStructure, module.telephotoStructure) }
|
||
: {}),
|
||
...(module.telephotoMacro !== undefined
|
||
? { telephotoMacro: current.telephotoMacro ?? module.telephotoMacro }
|
||
: {}),
|
||
...(module.telephotoMacroDistance
|
||
? { telephotoMacroDistance: pickText(current.telephotoMacroDistance, module.telephotoMacroDistance) }
|
||
: {}),
|
||
...(module.autofocusType
|
||
? { autofocusType: pickText(current.autofocusType, module.autofocusType) }
|
||
: {}),
|
||
};
|
||
used.add(index);
|
||
return list;
|
||
}
|
||
list.push(module);
|
||
used.add(list.length - 1);
|
||
return list;
|
||
}
|
||
|
||
function applyCoolapk(device, payload) {
|
||
const specs = device.specs;
|
||
const { groups, product, configId, price } = payload;
|
||
|
||
const body = (specs.body ??= {});
|
||
const display = (specs.display ??= {});
|
||
const platform = (specs.platform ??= {});
|
||
const memory = (specs.memory ??= {});
|
||
const battery = (specs.battery ??= {});
|
||
const connectivity = (specs.connectivity ??= {});
|
||
const sensors = (specs.sensors ??= {});
|
||
const software = (specs.software ??= {});
|
||
|
||
const basic = rowsOf(groups, '基本信息');
|
||
const appearance = rowsOf(groups, '外观');
|
||
const screen = rowsOf(groups, '屏幕');
|
||
const performance = rowsOf(groups, '性能');
|
||
const network = rowsOf(groups, '网络与连接');
|
||
const charging = rowsOf(groups, '充电与电池');
|
||
const other = rowsOf(groups, '其他配置');
|
||
const cameraRows = rowsOf(groups, '影像');
|
||
const cameraSummary = rowsOf(groups, '重要参数');
|
||
const accessories = rowsOf(groups, '手机附件');
|
||
const secondary = rowsOf(groups, '副屏');
|
||
const afterSales = rowsOf(groups, '售后信息');
|
||
|
||
const fromBasic = makeLookup(basic);
|
||
const fromAppearance = makeLookup(appearance);
|
||
const fromScreen = makeLookup(screen);
|
||
const fromPerformance = makeLookup(performance);
|
||
const fromNetwork = makeLookup(network);
|
||
const fromCharging = makeLookup(charging);
|
||
const fromOther = makeLookup(other);
|
||
const fromCamera = makeLookup(cameraRows);
|
||
const fromSummary = makeLookup(cameraSummary);
|
||
const fromAccessories = makeLookup(accessories);
|
||
const fromSecondary = makeLookup(secondary);
|
||
const fromAfterSales = makeLookup(afterSales);
|
||
|
||
const length = measure(fromAppearance('长度'));
|
||
const width = measure(fromAppearance('宽度'));
|
||
const thicknessLines = lines(fromAppearance('厚度'));
|
||
const thickness = measure(thicknessLines[0]);
|
||
if (length && width && thickness) {
|
||
body.dimensions = pickText(
|
||
body.dimensions,
|
||
`${length.replace(/mm$/, '')} x ${width.replace(/mm$/, '')} x ${thickness.replace(/mm$/, '')} mm`,
|
||
);
|
||
}
|
||
const thicknessVariants = thicknessLines.slice(1).map((item) => measureVariant(item, 'mm'));
|
||
if (thicknessVariants.length > 0) {
|
||
body.thicknessVariants = pickList(body.thicknessVariants, thicknessVariants, { union: true });
|
||
}
|
||
const weightLines = lines(fromAppearance('重量'));
|
||
const weight = measure(weightLines[0]);
|
||
if (weight) body.weight = pickText(body.weight, weight);
|
||
const weightVariants = weightLines.slice(1).map((item) => measureVariant(item, 'g'));
|
||
if (weightVariants.length > 0) {
|
||
body.weightVariants = pickList(body.weightVariants, weightVariants, { union: true });
|
||
}
|
||
const buttons = semicolon(fromAppearance('按键'));
|
||
if (buttons) body.buttons = pickText(body.buttons, buttons);
|
||
|
||
const colors = lines(fromAppearance('机身颜色') ?? '');
|
||
if (colors.length > 0) {
|
||
const nextColors = pickList(body.colors, colors);
|
||
if (nextColors === colors) {
|
||
body.colors = colors;
|
||
body.colorHexes = [];
|
||
}
|
||
}
|
||
const frontMaterial = semicolon(fromAppearance('正面材质') ?? fromAppearance('屏幕盖板'));
|
||
const frame = semicolon(fromAppearance('中框材质'));
|
||
const back = semicolon(fromAppearance('背壳材质'));
|
||
if (frontMaterial || frame || back) {
|
||
body.build = {
|
||
...(body.build ?? {}),
|
||
...(frontMaterial ? { front: pickText(body.build?.front, frontMaterial) } : {}),
|
||
...(frame ? { frame: pickText(body.build?.frame, frame) } : {}),
|
||
...(back ? { back: pickText(body.build?.back, back) } : {}),
|
||
};
|
||
}
|
||
const ipRating = line(fromOther('三防功能') ?? fromSummary('三防功能'));
|
||
if (ipRating) body.ipRating = pickText(body.ipRating, ipRating);
|
||
|
||
const sim = line(fromNetwork('SIM卡类型'));
|
||
if (sim) body.sim = pickText(body.sim, sim);
|
||
|
||
const size = line(fromScreen('屏幕尺寸'));
|
||
if (size) display.size = pickText(display.size, size);
|
||
const resolutionLines = lines(fromScreen('屏幕分辨率'));
|
||
if (resolutionLines.length > 0) {
|
||
display.resolution = pickResolution(display.resolution, resolutionLines[0]);
|
||
// 酷安常把 PPI 放在分辨率第二行,例如「2772x1280px / 447 PPI」
|
||
const ppi = resolutionLines.find((item) => /PPI/i.test(item));
|
||
if (ppi) display.pixelDensity = pickText(display.pixelDensity, ppi);
|
||
}
|
||
const panelLines = lines(fromScreen('屏幕材质'));
|
||
if (panelLines.length > 0) {
|
||
display.panel = pickText(display.panel, panelLines[0]);
|
||
if (panelLines.length > 1) {
|
||
display.features = pickList(display.features, panelLines.slice(1), { union: true });
|
||
}
|
||
}
|
||
const vendor = line(fromScreen('屏幕厂商'));
|
||
if (vendor) display.vendor = pickText(display.vendor, vendor);
|
||
const technology = line(fromScreen('屏幕发光材质'));
|
||
if (technology) display.technology = pickText(display.technology, technology);
|
||
const cutout = line(fromScreen('屏幕形态'));
|
||
if (cutout) display.cutout = pickText(display.cutout, cutout);
|
||
const refreshLines = lines(fromScreen('屏幕刷新率'));
|
||
if (refreshLines.length > 0) {
|
||
display.refreshRate = pickText(display.refreshRate, refreshLines[0]);
|
||
// 第二行常是 LTPO / LTPS 等背板说明
|
||
const refreshNote = refreshLines.slice(1).join(';');
|
||
if (refreshNote) display.refreshNote = pickText(display.refreshNote, refreshNote);
|
||
}
|
||
const pixelDensity = line(fromScreen('像素密度'));
|
||
if (pixelDensity) display.pixelDensity = pickText(display.pixelDensity, pixelDensity);
|
||
const touch = semicolon(fromScreen('触控采样率'));
|
||
if (touch) display.touchSampling = pickText(display.touchSampling, touch);
|
||
const instant = semicolon(fromScreen('瞬时触控采样率'));
|
||
if (instant) display.touchSamplingInstant = pickText(display.touchSamplingInstant, instant);
|
||
const colorDepth = line(fromScreen('屏幕色深'));
|
||
if (colorDepth) display.colorDepth = pickText(display.colorDepth, colorDepth);
|
||
const colorGamut = line(fromScreen('屏幕色域'));
|
||
if (colorGamut) display.colorGamut = pickText(display.colorGamut, colorGamut);
|
||
const hdr = semicolon(fromScreen('HDR支持'));
|
||
if (hdr) display.hdr = pickText(display.hdr, hdr);
|
||
const protection = line(fromScreen('盖板玻璃'));
|
||
if (protection) display.protection = pickText(display.protection, protection);
|
||
const dimming = line(fromScreen('屏幕调光'));
|
||
if (dimming) display.pwmDimming = pickText(display.pwmDimming, dimming);
|
||
const extraTech = fromScreen('其他技术');
|
||
if (extraTech) {
|
||
const techValues = lines(extraTech);
|
||
if (techValues.length > 0) {
|
||
display.features = pickList(display.features, techValues, { union: true });
|
||
}
|
||
}
|
||
const aspectRatio = line(fromScreen('屏幕比例') ?? fromScreen('宽高比'));
|
||
if (aspectRatio) display.aspectRatio = pickText(display.aspectRatio, aspectRatio);
|
||
const screenBodyRatio = line(fromScreen('屏占比'));
|
||
if (screenBodyRatio) display.screenBodyRatio = pickText(display.screenBodyRatio, screenBodyRatio);
|
||
const bezel = line(fromScreen('边框') ?? fromScreen('边框宽度'));
|
||
if (bezel) display.bezel = pickText(display.bezel, bezel);
|
||
const width16x9 = line(fromScreen('16:9等效宽度') ?? fromScreen('16:9等效尺寸'));
|
||
if (width16x9) display.width16x9 = pickText(display.width16x9, width16x9);
|
||
const equivalentPpi = line(fromScreen('等效PPI') ?? fromScreen('等效像素密度'));
|
||
if (equivalentPpi) display.equivalentPpi = pickText(display.equivalentPpi, equivalentPpi);
|
||
const refreshRange = line(fromScreen('刷新范围') ?? fromScreen('刷新率范围'));
|
||
if (refreshRange) display.refreshRange = pickText(display.refreshRange, refreshRange);
|
||
const refreshRangeFromRate = lines(fromScreen('屏幕刷新率'))
|
||
.join(';')
|
||
.match(/(\d+\s*-\s*\d+\s*Hz)/i)?.[1];
|
||
if (refreshRangeFromRate) display.refreshRange = pickText(display.refreshRange, refreshRangeFromRate);
|
||
const alwaysOn = fromScreen('息屏显示');
|
||
if (alwaysOn) {
|
||
if (/支持|是/.test(alwaysOn) && !/不支持/.test(alwaysOn)) display.alwaysOn = true;
|
||
else if (/不支持|否/.test(alwaysOn)) display.alwaysOn = false;
|
||
}
|
||
|
||
for (const row of screen) {
|
||
if (!/亮度/.test(row.label)) continue;
|
||
// 同一行可能有多档亮度,例如「8000nits / 全屏峰值亮度2600nits、手动峰值亮度1000nit」
|
||
for (const segment of lines(row.value).flatMap((item) => item.split(/[、,,;;]/))) {
|
||
const nit = toNit(segment);
|
||
if (!nit) continue;
|
||
const context = `${row.label} ${segment}`;
|
||
if (/全屏|全局/.test(context)) display.brightnessGlobalPeak = pickText(display.brightnessGlobalPeak, nit);
|
||
else if (/典型|默认|手动/.test(context)) display.brightnessTypical = pickText(display.brightnessTypical, nit);
|
||
else if (/HDR|峰值|最高|激发/.test(context)) display.brightnessPeak = pickText(display.brightnessPeak, nit);
|
||
}
|
||
}
|
||
|
||
if (secondary.length > 0) {
|
||
const target = { ...(display.secondary ?? {}) };
|
||
const secondarySize = line(fromSecondary('屏幕尺寸'));
|
||
if (secondarySize) target.size = pickText(target.size, secondarySize);
|
||
const secondaryResolutionLines = lines(fromSecondary('屏幕分辨率'));
|
||
if (secondaryResolutionLines.length > 0) {
|
||
target.resolution = pickResolution(target.resolution, secondaryResolutionLines[0]);
|
||
const ppi = secondaryResolutionLines.find((item) => /PPI/i.test(item));
|
||
if (ppi) target.pixelDensity = pickText(target.pixelDensity, ppi);
|
||
}
|
||
const secondaryPanelLines = lines(fromSecondary('屏幕材质'));
|
||
if (secondaryPanelLines.length > 0) {
|
||
target.panel = pickText(target.panel, secondaryPanelLines[0]);
|
||
if (secondaryPanelLines.length > 1) {
|
||
target.features = pickList(target.features, secondaryPanelLines.slice(1), { union: true });
|
||
}
|
||
}
|
||
const secondaryVendor = line(fromSecondary('屏幕厂商'));
|
||
if (secondaryVendor) target.vendor = pickText(target.vendor, secondaryVendor);
|
||
const secondaryTechnology = line(fromSecondary('屏幕发光材质'));
|
||
if (secondaryTechnology) target.technology = pickText(target.technology, secondaryTechnology);
|
||
const secondaryCutout = line(fromSecondary('屏幕形态'));
|
||
if (secondaryCutout) target.cutout = pickText(target.cutout, secondaryCutout);
|
||
const secondaryRefreshLines = lines(fromSecondary('屏幕刷新率'));
|
||
if (secondaryRefreshLines.length > 0) {
|
||
target.refreshRate = pickText(target.refreshRate, secondaryRefreshLines[0]);
|
||
const note = secondaryRefreshLines.slice(1).join(';');
|
||
if (note) target.refreshNote = pickText(target.refreshNote, note);
|
||
}
|
||
const secondaryDimming = line(fromSecondary('屏幕调光'));
|
||
if (secondaryDimming) target.pwmDimming = pickText(target.pwmDimming, secondaryDimming);
|
||
const secondaryTouch = semicolon(fromSecondary('瞬时触控采样率'));
|
||
if (secondaryTouch) target.touchSamplingInstant = pickText(target.touchSamplingInstant, secondaryTouch);
|
||
const secondaryDepth = line(fromSecondary('屏幕色深'));
|
||
if (secondaryDepth) target.colorDepth = pickText(target.colorDepth, secondaryDepth);
|
||
const secondaryGamut = line(fromSecondary('屏幕色域'));
|
||
if (secondaryGamut) target.colorGamut = pickText(target.colorGamut, secondaryGamut);
|
||
const secondaryHdr = semicolon(fromSecondary('HDR支持'));
|
||
if (secondaryHdr) target.hdr = pickText(target.hdr, secondaryHdr);
|
||
const secondaryProtection = line(fromSecondary('盖板玻璃'));
|
||
if (secondaryProtection) target.protection = pickText(target.protection, secondaryProtection);
|
||
const secondaryTech = fromSecondary('其他技术');
|
||
if (secondaryTech) {
|
||
const techValues = lines(secondaryTech);
|
||
if (techValues.length > 0) {
|
||
target.features = pickList(target.features, techValues, { union: true });
|
||
}
|
||
}
|
||
for (const row of secondary) {
|
||
if (!/亮度/.test(row.label)) continue;
|
||
for (const segment of lines(row.value).flatMap((item) => item.split(/[、,,;;]/))) {
|
||
const nit = toNit(segment);
|
||
if (!nit) continue;
|
||
const context = `${row.label} ${segment}`;
|
||
if (/全屏|全局/.test(context)) target.brightnessGlobalPeak = pickText(target.brightnessGlobalPeak, nit);
|
||
else if (/典型|默认|手动/.test(context)) target.brightnessTypical = pickText(target.brightnessTypical, nit);
|
||
else if (/HDR|峰值|最高|激发/.test(context)) target.brightnessPeak = pickText(target.brightnessPeak, nit);
|
||
}
|
||
}
|
||
const hasSecondaryData = Object.entries(target).some(([key, value]) =>
|
||
key === 'features' ? Array.isArray(value) && value.length > 0 : Boolean(value),
|
||
);
|
||
if (hasSecondaryData) display.secondary = target;
|
||
else delete display.secondary;
|
||
}
|
||
|
||
const chipset = firstLine(fromPerformance('SoC型号') ?? fromSummary('芯片') ?? '');
|
||
if (chipset) platform.chipset = pickText(platform.chipset, chipset);
|
||
const socBrand = line(fromPerformance('SoC品牌'));
|
||
if (socBrand) platform.socBrand = pickText(platform.socBrand, socBrand);
|
||
const gpu = line(fromPerformance('GPU型号') ?? fromPerformance('GPU'));
|
||
if (gpu) platform.gpu = pickText(platform.gpu, gpu);
|
||
const coprocessor = ['协处理器', '辅助芯片', '独显芯片']
|
||
.map((label) => semicolon(fromPerformance(label)))
|
||
.filter(Boolean)
|
||
.join(';');
|
||
if (coprocessor) platform.coprocessor = pickText(platform.coprocessor, coprocessor);
|
||
const os = line(fromBasic('操作系统'));
|
||
if (os) platform.os = pickText(platform.os, os);
|
||
const skin = line(fromBasic('出厂系统版本'));
|
||
if (skin) {
|
||
platform.skin = pickText(platform.skin, skin);
|
||
software.launchVersion = pickText(software.launchVersion, skin);
|
||
}
|
||
const regulatory = line(fromBasic('入网型号'));
|
||
if (regulatory) specs.regulatoryModel = pickText(specs.regulatoryModel, regulatory);
|
||
const serviceLines = lines(fromAfterSales('售后服务'));
|
||
if (serviceLines.length > 0) {
|
||
const hotline = serviceLines.find((item) => /^\d{3,6}$/.test(item));
|
||
const policy = serviceLines.filter((item) => !/^\d{3,6}$/.test(item)).join(';');
|
||
const service = hotline
|
||
? policy
|
||
? `服务热线 ${hotline};${policy}`
|
||
: `服务热线 ${hotline}`
|
||
: policy;
|
||
if (service) specs.service = pickText(specs.service, service);
|
||
}
|
||
|
||
const ram = line(fromPerformance('RAM容量'));
|
||
if (ram) memory.ram = pickText(memory.ram, ram);
|
||
const ramType = semicolon(fromPerformance('RAM存储类型'));
|
||
if (ramType) memory.ramType = pickText(memory.ramType, ramType);
|
||
const storage = line(fromPerformance('ROM容量'));
|
||
if (storage) memory.storage = pickText(memory.storage, storage);
|
||
const storageType = semicolon(fromPerformance('ROM存储类型'));
|
||
if (storageType) memory.storageType = pickText(memory.storageType, storageType);
|
||
const cardSlotLines = lines(fromPerformance('存储卡'));
|
||
if (cardSlotLines.length > 0) {
|
||
// 「支持 / NM卡(最大512GB)」这类第二行才是真正规格
|
||
const detail = cardSlotLines.filter((item) => item !== '支持').join(';') || cardSlotLines[0];
|
||
memory.cardSlot = pickText(memory.cardSlot, detail);
|
||
}
|
||
const cooling = semicolon(fromPerformance('主动散热'));
|
||
if (cooling) body.cooling = pickText(body.cooling, cooling);
|
||
|
||
const capacity = line(fromCharging('电池容量'));
|
||
if (capacity) battery.capacity = pickText(battery.capacity, capacity);
|
||
const batteryType = line(fromCharging('电池类型'));
|
||
if (batteryType) battery.type = pickText(battery.type, batteryType);
|
||
const wiredLines = lines(fromCharging('有线充电'));
|
||
if (wiredLines.length > 0) {
|
||
const primary = wiredLines[0];
|
||
const existing = battery.wired;
|
||
// 旧数据曾把「100W / 100W PPS」合并进 wired,这里拆回主功率与协议
|
||
battery.wired =
|
||
existing && existing.includes(';') && clean(existing.split(';')[0]) === clean(primary)
|
||
? primary
|
||
: pickText(existing, primary);
|
||
const protocol = wiredLines.slice(1).join(';');
|
||
if (protocol) battery.chargingProtocol = pickText(battery.chargingProtocol, protocol);
|
||
}
|
||
const wireless = semicolon(fromCharging('无线充电'));
|
||
if (wireless) battery.wireless = pickText(battery.wireless, wireless);
|
||
const reverse = semicolon(fromCharging('反向充电'));
|
||
if (reverse) battery.reverse = pickText(battery.reverse, reverse);
|
||
|
||
const networkType = line(fromNetwork('网络类型'));
|
||
if (networkType) connectivity.cellular = pickText(connectivity.cellular, networkType);
|
||
|
||
const fiveG = String(fromNetwork('5G网络频段') ?? '').match(/(n\d+)/gi) ?? [];
|
||
const fourG = String(fromNetwork('4G网络频段') ?? '').match(/(B\d+)/gi) ?? [];
|
||
const bands = unique(
|
||
[...fiveG, ...fourG].map((band) =>
|
||
band[0].toLowerCase() === 'n' ? `n${band.slice(1)}` : `B${band.slice(1).toUpperCase()}`,
|
||
),
|
||
);
|
||
if (bands.length > 0) connectivity.bands = pickList(connectivity.bands, bands, { union: true });
|
||
|
||
const wifi = fromNetwork('WLAN协议');
|
||
const wifiText = lines(wifi).join(',');
|
||
if (wifiText) connectivity.wifi = pickText(connectivity.wifi, wifiText);
|
||
const bluetooth = semicolon(fromNetwork('蓝牙'));
|
||
const bluetoothAudio = semicolon(fromNetwork('蓝牙音频规格'));
|
||
if (bluetooth || bluetoothAudio) {
|
||
const bluetoothText = [bluetooth, bluetoothAudio].filter(Boolean).join(';');
|
||
connectivity.bluetooth = pickText(connectivity.bluetooth, bluetoothText);
|
||
}
|
||
const satelliteLocation = semicolon(fromNetwork('卫星定位'));
|
||
const locationTech = semicolon(fromNetwork('定位技术'));
|
||
const gpsParts = [satelliteLocation, locationTech].filter(Boolean);
|
||
if (gpsParts.length > 0) {
|
||
connectivity.gps = pickText(connectivity.gps, gpsParts.join(';'));
|
||
}
|
||
if (/支持/.test(fromNetwork('NFC') ?? '')) connectivity.nfc = true;
|
||
if (/支持/.test(fromNetwork('红外功能') ?? '')) connectivity.ir = true;
|
||
if (/支持/.test(fromNetwork('UWB') ?? '')) connectivity.uwb = true;
|
||
const usb = semicolon(fromNetwork('机身接口'));
|
||
if (usb) {
|
||
connectivity.usb = pickText(connectivity.usb, usb);
|
||
const speed = usb.match(/(\d+(?:\.\d+)?\s*Gbps)/i);
|
||
if (speed) connectivity.usbSpeed = pickText(connectivity.usbSpeed, speed[1].replace(/\s+/g, ''));
|
||
if (/DP|DisplayPort|视频输出/i.test(usb)) connectivity.usbVideoOut = true;
|
||
}
|
||
const satelliteText = [
|
||
fromNetwork('卫星通讯'),
|
||
fromNetwork('卫星通话'),
|
||
fromNetwork('卫星通信'),
|
||
]
|
||
.filter(Boolean)
|
||
.join(';');
|
||
if (/支持|天通|北斗/.test(satelliteText)) {
|
||
connectivity.satellite = true;
|
||
if (/天通/.test(satelliteText)) connectivity.satelliteProvider = '天通';
|
||
else if (/北斗/.test(satelliteText)) connectivity.satelliteProvider = '北斗';
|
||
}
|
||
|
||
// 酷安详情把规格写在第二行,例如「X轴马达 / 0815规格」,不能只取首行
|
||
const motorDetail = fromOther('震动马达');
|
||
const motorRaw = lines(motorDetail).length > 0 ? motorDetail : fromSummary('震动马达');
|
||
const motorLines = lines(motorRaw);
|
||
if (motorLines.length > 0) {
|
||
const vibration = (specs.vibration ??= {});
|
||
vibration.type = pickText(vibration.type, motorLines[0]);
|
||
if (motorLines.length === 1) {
|
||
// 少数机型把型号直接写在类型里:「0815超线性马达」
|
||
const typeCode = motorLines[0].match(/([A-Za-z]*\d{3,6}[A-Za-z]*)/)?.[1];
|
||
if (typeCode) vibration.model = pickText(vibration.model, typeCode);
|
||
}
|
||
for (const item of motorLines.slice(1)) {
|
||
const detail = clean(item);
|
||
// 酷安第二行是马达型号:0815规格、东磁0809规格、瑞声科技ELA8282规格、0916C 等
|
||
const codeMatch = detail.match(/^(.*?)([A-Za-z]*\d{3,6}[A-Za-z]*)(?:\s*规格)?(.*)$/);
|
||
if (codeMatch) {
|
||
const vendor = clean(codeMatch[1]);
|
||
const code = codeMatch[2];
|
||
const model = `${vendor}${code}`.trim();
|
||
if (model) vibration.model = pickText(vibration.model, model);
|
||
// 旧数据曾把型号写入 size,迁移时清理重复值(如 7514A / ESA7514A)
|
||
const sizeText = vibration.size ? clean(vibration.size) : '';
|
||
if (
|
||
sizeText &&
|
||
(sizeText === code || model.includes(sizeText) || sizeText.includes(code))
|
||
) {
|
||
delete vibration.size;
|
||
}
|
||
continue;
|
||
}
|
||
const volume = detail.match(/([\d.]+\s*(?:cm³|mm³))/i)?.[1];
|
||
if (volume) vibration.volume = pickText(vibration.volume, volume);
|
||
}
|
||
if (vibration.model && vibration.size) {
|
||
const modelText = clean(vibration.model);
|
||
const sizeText = clean(vibration.size);
|
||
if (modelText.includes(sizeText) || sizeText.includes(modelText)) delete vibration.size;
|
||
}
|
||
}
|
||
|
||
const speakerDetail = fromOther('扬声器');
|
||
const speakerRaw = lines(speakerDetail).length > 0 ? speakerDetail : fromSummary('扬声器');
|
||
const speakerLines = lines(speakerRaw);
|
||
if (speakerLines.length > 0) {
|
||
const text = speakerLines[0];
|
||
const countMatch = text.match(/(\d+)\s*扬声器/);
|
||
const chineseMatch = text.match(/(单|双|二|三|四|五)/);
|
||
const chineseCount = { 单: 1, 双: 2, 二: 2, 三: 3, 四: 4, 五: 5 };
|
||
const count = countMatch
|
||
? Number(countMatch[1])
|
||
: chineseMatch
|
||
? chineseCount[chineseMatch[1]]
|
||
: undefined;
|
||
const speakers = (specs.speakers ??= {});
|
||
if (count) {
|
||
speakers.count = count;
|
||
speakers.stereo = count >= 2;
|
||
}
|
||
|
||
// 第二行起是单元规格:如「双1115X规格」「2.1立体声、双1115F扬声器+1620低音单元」
|
||
const detailUnits = [];
|
||
for (const part of speakerLines.slice(1).join(';').split(/[、,,;;++]/)) {
|
||
const trimmed = clean(part);
|
||
const model = trimmed.match(/(\d{3,4}[A-Za-z]*)/)?.[1];
|
||
if (!model) continue;
|
||
const multiplier = /^双|^二/.test(trimmed) ? 2 : /^三/.test(trimmed) ? 3 : /^四/.test(trimmed) ? 4 : 1;
|
||
const label = /低音|重低音/.test(trimmed) ? '低音单元' : undefined;
|
||
for (let index = 0; index < multiplier; index += 1) detailUnits.push({ label, model });
|
||
}
|
||
const audioText = ['扬声器认证', '音频认证', '音质认证']
|
||
.map((label) => fromOther(label))
|
||
.filter(Boolean)
|
||
.join(';');
|
||
if (audioText) {
|
||
if (/杜比|Dolby/i.test(audioText)) speakers.dolbyAtmos = true;
|
||
if (/Hi-?Res|金标/i.test(audioText)) speakers.hiRes = true;
|
||
const loudness = audioText.match(/(\d+(?:\.\d+)?\s*dB(?:A)?)/i)?.[1];
|
||
if (loudness) speakers.loudnessDba = pickText(speakers.loudnessDba, loudness);
|
||
}
|
||
const headphone = line(fromOther('耳机孔') ?? fromNetwork('耳机孔'));
|
||
if (headphone) {
|
||
if (/支持|有|3\.5/i.test(headphone) && !/不支持|无/.test(headphone)) speakers.headphoneJack = true;
|
||
else if (/不支持|无/.test(headphone)) speakers.headphoneJack = false;
|
||
}
|
||
|
||
if (detailUnits.length > 0) {
|
||
const existingUnits = speakers.units ?? [];
|
||
if (existingUnits.length === 0) {
|
||
speakers.units = detailUnits.map((unit, index) => ({
|
||
label: unit.label ?? `单元${index + 1}`,
|
||
model: unit.model,
|
||
}));
|
||
} else {
|
||
speakers.units = existingUnits.map((unit, index) => {
|
||
const incoming = detailUnits[index];
|
||
return incoming
|
||
? { ...unit, model: incoming.model, ...(incoming.label ? { label: unit.label ?? incoming.label } : {}) }
|
||
: unit;
|
||
});
|
||
for (let index = existingUnits.length; index < detailUnits.length; index += 1) {
|
||
const unit = detailUnits[index];
|
||
speakers.units.push({ label: unit.label ?? `单元${index + 1}`, model: unit.model });
|
||
}
|
||
}
|
||
if (!count) {
|
||
speakers.count = detailUnits.length;
|
||
speakers.stereo = detailUnits.length >= 2;
|
||
}
|
||
}
|
||
}
|
||
|
||
const unlock = fromOther('解锁方式') ?? fromSummary('解锁方式');
|
||
const unlockText = line(unlock);
|
||
if (unlockText) {
|
||
sensors.fingerprint = pickText(sensors.fingerprint, unlockText);
|
||
const fingerprint = sensors.fingerprint ?? '';
|
||
if (/超声波/.test(fingerprint)) sensors.fingerprintType = '超声波';
|
||
else if (/光学|短焦|超薄/.test(fingerprint)) sensors.fingerprintType = '光学';
|
||
else if (/侧边/.test(fingerprint)) sensors.fingerprintType = '侧面';
|
||
else if (/屏幕/.test(fingerprint)) sensors.fingerprintType = '屏下';
|
||
}
|
||
const fingerprintPosition = line(fromOther('指纹位置'));
|
||
if (fingerprintPosition) sensors.fingerprintPosition = pickText(sensors.fingerprintPosition, fingerprintPosition);
|
||
const sensorList = fromOther('传感器');
|
||
if (sensorList) {
|
||
const list = splitList(sensorList);
|
||
if (list.length > 0) {
|
||
sensors.list = pickList(sensors.list, list, { union: true });
|
||
const joined = list.join(',');
|
||
if (/陀螺仪/.test(joined)) sensors.gyro = true;
|
||
if (/气压/.test(joined)) sensors.barometer = true;
|
||
if (/色温/.test(joined)) sensors.colorSensor = true;
|
||
if (/flicker/i.test(joined)) sensors.flickerSensor = true;
|
||
}
|
||
}
|
||
|
||
const cameraSubgroups = unique(cameraRows.map((row) => row.subgroup));
|
||
const rearModules = [];
|
||
const frontModules = [];
|
||
const positionForSubgroup = (subgroup) => {
|
||
if (/前置/.test(subgroup)) return 'front';
|
||
if (/超广角/.test(subgroup)) return 'ultrawide';
|
||
if (/微距/.test(subgroup)) return 'macro';
|
||
if (/景深/.test(subgroup)) return 'depth';
|
||
if (/黑白/.test(subgroup)) return 'mono';
|
||
if (/色彩/.test(subgroup)) return 'color';
|
||
if (/长焦/.test(subgroup)) {
|
||
const structure = fromCamera('长焦结构', subgroup) ?? '';
|
||
return /潜望/.test(structure) ? 'periscope' : 'tele';
|
||
}
|
||
if (/主摄/.test(subgroup)) return 'wide';
|
||
if (/其他摄像头/.test(subgroup)) {
|
||
const type = fromCamera('类型', subgroup) ?? '';
|
||
if (/微距/.test(type)) return 'macro';
|
||
if (/景深/.test(type)) return 'depth';
|
||
if (/黑白|单色/.test(type)) return 'mono';
|
||
if (/色彩/.test(type)) return 'color';
|
||
}
|
||
return undefined;
|
||
};
|
||
|
||
for (const subgroup of cameraSubgroups) {
|
||
if (!/参数|其他摄像头/.test(subgroup)) continue;
|
||
const position = positionForSubgroup(subgroup);
|
||
if (!position) continue;
|
||
const get = (label) => line(fromCamera(label, subgroup));
|
||
// 型号行常有两行:第一行传感器型号,第二行尺寸/镜片,例如「索尼LYT808 / 1/1.4英寸、七镜式镜头」
|
||
const modelLines = lines(fromCamera('型号', subgroup));
|
||
const modelRaw = modelLines.join(' ');
|
||
const sizeMatch = modelRaw.match(/(1\/\d+(?:\.\d+)?)\s*(?:英寸|")/);
|
||
const lensMatch = modelRaw.match(/(?:[一二三四五六七八九十\d]+镜式镜头|\d+G\d+P)/);
|
||
const pixelSize = modelRaw.match(/(\d+(?:\.\d+)?)\s*(?:μm|µm|um)/i)?.[0]?.replace(/\s+/g, '');
|
||
const cleanedModel = clean(
|
||
modelLines
|
||
.map((item) =>
|
||
item
|
||
.replace(/(1\/\d+(?:\.\d+)?)\s*(?:英寸|")/g, '')
|
||
.replace(/(?:[一二三四五六七八九十\d]+镜式镜头|\d+G\d+P)/g, '')
|
||
.replace(/(\d+(?:\.\d+)?)\s*(?:μm|µm|um)/gi, ''),
|
||
)
|
||
.join(' '),
|
||
).replace(/[、,,;;\s]+$/g, '');
|
||
const sensorModel = /^(?:RYYB|RGGB|RCCB|未知)$/i.test(cleanedModel) ? '' : cleanedModel;
|
||
const resolution = get('像素');
|
||
const focalLines = lines(fromCamera('等效焦距', subgroup));
|
||
const focalLength = focalLines.find((item) => /(?:mm|毫米)/i.test(item));
|
||
const zoom = focalLines.filter((item) => /变焦/.test(item)).join(';');
|
||
// 防抖模式可能有两行:「光学防抖 / CIPA 7.0」
|
||
const stabilizationText = lines(fromCamera('防抖模式', subgroup)).join(';');
|
||
const cipa = stabilizationText.match(/CIPA\s*[\d.]+/i)?.[0]?.replace(/\s+/g, ' ');
|
||
const teleLines = lines(fromCamera('长焦微距', subgroup));
|
||
const isTeleModule = position === 'tele' || position === 'periscope';
|
||
const telephotoStructure = isTeleModule ? line(fromCamera('长焦结构', subgroup)) : undefined;
|
||
const telephotoMacro = isTeleModule && teleLines.length > 0 ? /支持|是/.test(teleLines[0]) : undefined;
|
||
const telephotoMacroDistance = isTeleModule
|
||
? teleLines.join(';').match(/(\d+(?:\.\d+)?\s*(?:cm|厘米))/i)?.[1]
|
||
: undefined;
|
||
const module = {
|
||
position,
|
||
...(sensorModel ? { sensorModel } : {}),
|
||
...(sizeMatch ? { sensorSize: `${sizeMatch[1]}"` } : {}),
|
||
...(lensMatch ? { lensElements: lensMatch[0] } : {}),
|
||
...(pixelSize ? { pixelSize } : {}),
|
||
...(resolution ? { resolution } : {}),
|
||
...(get('光圈') ? { aperture: get('光圈') } : {}),
|
||
...(focalLength ? { focalLength } : {}),
|
||
...(zoom ? { zoom } : {}),
|
||
...(get('视场') ? { fov: get('视场') } : {}),
|
||
...(stabilizationText && /光学防抖|OIS/i.test(stabilizationText) ? { ois: true } : {}),
|
||
...(stabilizationText && /电子防抖|EIS/i.test(stabilizationText) ? { eis: true } : {}),
|
||
...(cipa ? { cipa } : {}),
|
||
...(telephotoStructure ? { telephotoStructure } : {}),
|
||
...(telephotoMacro !== undefined ? { telephotoMacro } : {}),
|
||
...(telephotoMacroDistance ? { telephotoMacroDistance } : {}),
|
||
...(get('自动对焦') ? { autofocusType: get('自动对焦') } : {}),
|
||
};
|
||
const hasData =
|
||
module.sensorModel ||
|
||
module.sensorSize ||
|
||
module.lensElements ||
|
||
module.pixelSize ||
|
||
module.resolution ||
|
||
module.aperture ||
|
||
module.focalLength ||
|
||
module.zoom ||
|
||
module.fov ||
|
||
module.ois ||
|
||
module.cipa ||
|
||
module.telephotoStructure ||
|
||
module.telephotoMacro !== undefined;
|
||
if (!hasData) continue;
|
||
if (position === 'front') frontModules.push(module);
|
||
else rearModules.push(module);
|
||
}
|
||
|
||
// 旧数据可能把同一颗潜望长焦记成 tele,酷安记成 periscope;
|
||
// 酷安偶尔也会把同一颗长焦拆成「长焦① / 长焦②」,用等效焦距去重
|
||
const focalKey = (value) => String(value ?? '').match(/(\d+(?:\.\d+)?)/)?.[1];
|
||
const uniqueRearModules = [];
|
||
for (const module of rearModules) {
|
||
if (
|
||
(module.position === 'tele' || module.position === 'periscope') &&
|
||
module.focalLength &&
|
||
uniqueRearModules.some(
|
||
(existing) =>
|
||
(existing.position === 'tele' || existing.position === 'periscope') &&
|
||
focalKey(existing.focalLength) === focalKey(module.focalLength),
|
||
)
|
||
) {
|
||
continue;
|
||
}
|
||
uniqueRearModules.push(module);
|
||
}
|
||
const newTeleFocals = new Set(
|
||
uniqueRearModules
|
||
.filter((module) => module.position === 'tele' || module.position === 'periscope')
|
||
.map((module) => focalKey(module.focalLength))
|
||
.filter(Boolean),
|
||
);
|
||
if (newTeleFocals.size > 0) {
|
||
specs.rearCamera = specs.rearCamera.filter(
|
||
(camera) =>
|
||
!(
|
||
(camera.position === 'tele' || camera.position === 'periscope') &&
|
||
newTeleFocals.has(focalKey(camera.focalLength))
|
||
),
|
||
);
|
||
}
|
||
|
||
const usedRear = new Set();
|
||
const usedFront = new Set();
|
||
for (const module of uniqueRearModules) {
|
||
specs.rearCamera = mergeCamera(specs.rearCamera, module, usedRear);
|
||
}
|
||
for (const module of frontModules) {
|
||
specs.frontCamera = mergeCamera(specs.frontCamera, module, usedFront);
|
||
}
|
||
|
||
const videoMax = (subgroup) => {
|
||
const rows = cameraRows.filter((row) => row.subgroup === subgroup);
|
||
const candidates = rows
|
||
.filter((row) => /视频拍摄/.test(row.label))
|
||
.map((row) => {
|
||
const resolution = row.label.startsWith('8K')
|
||
? '8K'
|
||
: row.label.startsWith('4K')
|
||
? '4K'
|
||
: row.label.startsWith('1080')
|
||
? '1080P'
|
||
: undefined;
|
||
const fps = [...String(row.value).matchAll(/(\d+)\s*FPS/gi)].map((match) => Number(match[1]));
|
||
return resolution ? { resolution, fps: fps.length ? Math.max(...fps) : 0 } : undefined;
|
||
})
|
||
.filter(Boolean)
|
||
.sort((a, b) => (a.resolution === b.resolution ? b.fps - a.fps : ['8K', '4K', '1080P'].indexOf(a.resolution) - ['8K', '4K', '1080P'].indexOf(b.resolution)));
|
||
const best = candidates[0];
|
||
if (!best) return undefined;
|
||
return best.fps > 0 ? `${best.resolution}@${best.fps}fps` : best.resolution;
|
||
};
|
||
|
||
const videoModes = (subgroup) =>
|
||
cameraRows
|
||
.filter((row) => row.subgroup === subgroup && /视频拍摄/.test(row.label))
|
||
.map((row) => {
|
||
const value = clean(row.value);
|
||
return /^支持$/.test(value) ? row.label : `${row.label}:${value}`;
|
||
});
|
||
const rearVideo = videoMax('后置视频拍摄');
|
||
const rearModes = videoModes('后置视频拍摄');
|
||
if (rearVideo || rearModes.length > 0) {
|
||
const main = specs.rearCamera.find((camera) => camera.position === 'wide');
|
||
if (main) {
|
||
main.video = {
|
||
...(main.video ?? {}),
|
||
...(rearVideo ? { max: pickVideo(main.video?.max, rearVideo) } : {}),
|
||
...(rearModes.length > 0
|
||
? { modes: pickList(main.video?.modes, rearModes, { union: true }) }
|
||
: {}),
|
||
};
|
||
}
|
||
}
|
||
const frontVideo = videoMax('前置视频拍摄');
|
||
const frontModes = videoModes('前置视频拍摄');
|
||
if (frontVideo || frontModes.length > 0) {
|
||
const front = specs.frontCamera.find((camera) => camera.position === 'front');
|
||
if (front) {
|
||
front.video = {
|
||
...(front.video ?? {}),
|
||
...(frontVideo ? { max: pickVideo(front.video?.max, frontVideo) } : {}),
|
||
...(frontModes.length > 0
|
||
? { modes: pickList(front.video?.modes, frontModes, { union: true }) }
|
||
: {}),
|
||
};
|
||
}
|
||
}
|
||
|
||
// 功能列表可能在页面里折行,先拼回一整段再按分隔符拆分
|
||
const cameraFeatureRaw = lines(cameraRows.find((row) => row.label === '后置摄像头功能')?.value).join('');
|
||
const cameraFeatureList = splitList(cameraFeatureRaw);
|
||
const coBrand = line(fromCamera('影像联名品牌') ?? fromSummary('影像联名'));
|
||
if (cameraFeatureList.length > 0 || coBrand) {
|
||
specs.cameraFeatures = pickList(specs.cameraFeatures, unique([coBrand, ...cameraFeatureList]));
|
||
}
|
||
|
||
const ramValues = unique(
|
||
payload.versions.map((version) => version.name.match(/(\d+GB|\d+TB)\s*\+\s*/i)?.[1]),
|
||
);
|
||
const storageValues = unique(
|
||
payload.versions.map((version) => version.name.match(/\+\s*(\d+GB|\d+TB)/i)?.[1]),
|
||
);
|
||
if (ramValues.length > 0) {
|
||
const ramList = pickList(
|
||
memory.ram ? splitList(memory.ram.replace(/\s*\/\s*/g, ',')) : [],
|
||
ramValues,
|
||
);
|
||
memory.ram = ramList.join(' / ');
|
||
}
|
||
if (storageValues.length > 0) {
|
||
const storageList = pickList(
|
||
memory.storage ? splitList(memory.storage.replace(/\s*\/\s*/g, ',')) : [],
|
||
storageValues,
|
||
);
|
||
memory.storage = storageList.join(' / ');
|
||
}
|
||
const priced = payload.versions.filter((version) => version.price);
|
||
if (priced.length > 0) {
|
||
specs.pricing = pickList(specs.pricing, priced.map((version) => `${version.name} ${version.price} 元`));
|
||
}
|
||
const boxRaw = semicolon(fromAccessories('包装清单'));
|
||
if (boxRaw) {
|
||
const boxList = splitList(boxRaw);
|
||
if (boxList.length > 0) specs.boxContents = pickList(specs.boxContents, boxList);
|
||
}
|
||
|
||
const ratingRows = groups.find((group) => group.name === '酷安评分')?.rows ?? [];
|
||
const ratingNumber = (label) => {
|
||
const value = Number(ratingRows.find((row) => row.label === label)?.value);
|
||
return Number.isFinite(value) ? value : undefined;
|
||
};
|
||
|
||
specs.coolapk = {
|
||
productId: product.id,
|
||
configId,
|
||
name: product.name,
|
||
price: price || undefined,
|
||
syncedAt: new Date().toISOString(),
|
||
rating: {
|
||
overall: ratingNumber('所有人评分'),
|
||
owner: ratingNumber('机主评分'),
|
||
battery: ratingNumber('续航'),
|
||
camera: ratingNumber('影像'),
|
||
performance: ratingNumber('性能'),
|
||
display: ratingNumber('屏幕'),
|
||
design: ratingNumber('外观质感'),
|
||
value: ratingNumber('性价比'),
|
||
},
|
||
};
|
||
}
|
||
|
||
function allocateSlug(identity, product, usedSlugs) {
|
||
const base = slugify(`${identity.brand} ${identity.model}`).slice(0, 80).replace(/-+$/g, '');
|
||
let slug = base || `coolapk-${product.id}`;
|
||
if (usedSlugs.has(slug)) {
|
||
let suffix = 2;
|
||
slug = `${base || `coolapk-${product.id}`}-${suffix}`;
|
||
while (usedSlugs.has(slug)) {
|
||
suffix += 1;
|
||
slug = `${base || `coolapk-${product.id}`}-${suffix}`;
|
||
}
|
||
}
|
||
usedSlugs.add(slug);
|
||
return slug;
|
||
}
|
||
|
||
function parseCoolapkDate(value) {
|
||
const match = String(value ?? '').match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
|
||
if (!match) return undefined;
|
||
return `${match[1]}-${String(match[2]).padStart(2, '0')}-${String(match[3]).padStart(2, '0')}`;
|
||
}
|
||
|
||
function createDevice(target, payload) {
|
||
const specs = makeBlankSpecs();
|
||
const detailRows = payload.groups.find((group) => group.name === '基本信息')?.rows ?? [];
|
||
const releasedAt = parseCoolapkDate(
|
||
detailRows.find((row) => row.label === '发布时间')?.value,
|
||
);
|
||
const today = new Date().toISOString().slice(0, 10);
|
||
const device = {
|
||
slug: target.slug,
|
||
category: 'phone',
|
||
brand: target.identity.brand,
|
||
model: target.identity.model,
|
||
aliases: unique([payload.product.name, `${target.identity.brand} ${target.identity.model}`]),
|
||
announceDate: releasedAt,
|
||
releaseDate: releasedAt,
|
||
lifecycle: releasedAt && releasedAt > today ? 'announced' : 'released',
|
||
gallery: [],
|
||
tags: [],
|
||
chipRefs: {},
|
||
specs,
|
||
meta: [],
|
||
};
|
||
applyCoolapk(device, payload);
|
||
const summaryParts = [
|
||
specs.display?.size,
|
||
specs.display?.panel,
|
||
specs.platform?.chipset,
|
||
specs.battery?.capacity,
|
||
].filter(Boolean);
|
||
device.summary = summaryParts.join(',').slice(0, 120) || undefined;
|
||
return device;
|
||
}
|
||
|
||
function parseArgs(argv) {
|
||
const options = { write: false, limit: 0, out: '', refreshCatalog: false, concurrency: 2, slugs: [] };
|
||
for (let index = 0; index < argv.length; index += 1) {
|
||
const arg = argv[index];
|
||
if (arg === '--write') options.write = true;
|
||
else if (arg === '--limit') options.limit = Number(argv[(index += 1)] ?? 0);
|
||
else if (arg === '--out') options.out = argv[(index += 1)] ?? '';
|
||
else if (arg === '--slug') options.slugs.push(argv[(index += 1)] ?? '');
|
||
else if (arg === '--refresh-catalog') options.refreshCatalog = true;
|
||
else if (arg === '--concurrency') options.concurrency = Number(argv[(index += 1)] ?? 2);
|
||
else throw new Error(`未知参数:${arg}`);
|
||
}
|
||
return options;
|
||
}
|
||
|
||
async function main() {
|
||
const options = parseArgs(process.argv.slice(2));
|
||
console.log('拉取酷安机型目录 ...');
|
||
const products = dedupeProducts(await fetchCatalog(options.refreshCatalog));
|
||
|
||
const devices = listDevices({ category: 'phone' });
|
||
const { matches, misses } = matchProducts(devices, products);
|
||
console.log(`本地 ${devices.length} 款,匹配酷安 ${matches.length} 款,未匹配 ${misses.length} 款`);
|
||
if (misses.length > 0) {
|
||
console.log('未匹配示例:', misses.slice(0, 12).map((device) => `${device.brand} ${device.model}`));
|
||
}
|
||
|
||
const matchedIds = new Set(matches.map((match) => match.product.id));
|
||
const matchedSlugs = new Set(matches.map((match) => match.device.slug));
|
||
const usedSlugs = new Set(devices.map((device) => device.slug));
|
||
const targets = matches.map((match) => ({
|
||
kind: 'merge',
|
||
device: match.device,
|
||
product: match.product,
|
||
}));
|
||
|
||
// 名称拼接没对上时,再按「推断品牌 + 型号」精确匹配一次,避免给已有设备重复建页
|
||
let extraMatches = 0;
|
||
for (const product of products) {
|
||
if (matchedIds.has(product.id)) continue;
|
||
const identity = inferIdentity(product.name);
|
||
const existing = devices.find(
|
||
(device) =>
|
||
!matchedSlugs.has(device.slug) &&
|
||
device.brand === identity.brand &&
|
||
normalize(device.model) === normalize(identity.model),
|
||
);
|
||
if (!existing) continue;
|
||
matchedIds.add(product.id);
|
||
matchedSlugs.add(existing.slug);
|
||
extraMatches += 1;
|
||
targets.push({ kind: 'merge', device: existing, product });
|
||
}
|
||
|
||
const newProducts = products.filter((product) => !matchedIds.has(product.id));
|
||
for (const product of newProducts) {
|
||
const identity = inferIdentity(product.name);
|
||
const slug = allocateSlug(identity, product, usedSlugs);
|
||
targets.push({ kind: 'create', product, identity, slug });
|
||
}
|
||
console.log(
|
||
`本地 ${devices.length} 款,匹配 ${matches.length + extraMatches} 款,将新建 ${newProducts.length} 款酷安机型`,
|
||
);
|
||
|
||
const selected = options.slugs.length
|
||
? targets.filter((target) =>
|
||
options.slugs.includes(target.kind === 'merge' ? target.device.slug : target.slug),
|
||
)
|
||
: options.limit > 0
|
||
? targets.slice(0, options.limit)
|
||
: targets;
|
||
if (selected.length === 0) throw new Error('没有匹配到指定 slug 的机型');
|
||
console.log(`开始获取 ${selected.length} 款机型的版本信息 ...`);
|
||
|
||
const withVersions = [];
|
||
let cursor = 0;
|
||
let done = 0;
|
||
async function versionWorker() {
|
||
while (cursor < selected.length) {
|
||
const index = cursor;
|
||
cursor += 1;
|
||
const target = selected[index];
|
||
try {
|
||
const result = await fetchVersions(target.product);
|
||
if (result.versions.length > 0) withVersions.push({ ...target, versions: result.versions });
|
||
else console.log(` 无版本信息:${target.product.name}`);
|
||
} catch (error) {
|
||
console.warn(` 版本失败 ${target.product.name}:${error instanceof Error ? error.message : error}`);
|
||
}
|
||
done += 1;
|
||
if (done % 50 === 0) console.log(` 版本进度 ${done}/${selected.length}`);
|
||
}
|
||
}
|
||
await Promise.all(
|
||
Array.from({ length: Math.min(options.concurrency, selected.length) }, () => versionWorker()),
|
||
);
|
||
|
||
console.log(`拿到 ${withVersions.length} 款机型的版本列表,开始批量对比 ...`);
|
||
const chunks = [];
|
||
for (let index = 0; index < withVersions.length; index += 4) {
|
||
chunks.push(withVersions.slice(index, index + 4));
|
||
}
|
||
|
||
const results = [];
|
||
for (let index = 0; index < chunks.length; index += 1) {
|
||
const chunk = chunks[index];
|
||
const configIds = chunk.map((item) => item.versions[0].configId);
|
||
try {
|
||
const parsed = await fetchCompare(configIds);
|
||
const productMap = new Map(parsed.products.map((product) => [product.configId, product]));
|
||
for (const item of chunk) {
|
||
const product = productMap.get(item.versions[0].configId);
|
||
if (!product) continue;
|
||
const column = parsed.products.findIndex((entry) => entry.configId === item.versions[0].configId);
|
||
if (column < 0) continue;
|
||
const groups = parsed.groups.map((group) => ({
|
||
name: group.name,
|
||
rows: group.rows.map((row) => ({
|
||
subgroup: row.subgroup,
|
||
label: row.label,
|
||
value: row.values[column] ?? '',
|
||
})),
|
||
}));
|
||
results.push({
|
||
kind: item.kind,
|
||
device: item.device,
|
||
identity: item.identity,
|
||
slug: item.slug,
|
||
product: item.product,
|
||
versions: item.versions,
|
||
configId: item.versions[0].configId,
|
||
price: product.price,
|
||
groups,
|
||
});
|
||
}
|
||
} catch (error) {
|
||
console.warn(` 对比失败(${configIds.join(',')}):${error instanceof Error ? error.message : error}`);
|
||
}
|
||
if ((index + 1) % 20 === 0 || index + 1 === chunks.length) {
|
||
console.log(` 对比进度 ${index + 1}/${chunks.length}`);
|
||
}
|
||
}
|
||
|
||
const merged = [];
|
||
const issues = [];
|
||
const enriched = [];
|
||
let created = 0;
|
||
for (const item of results) {
|
||
try {
|
||
const device =
|
||
item.kind === 'create'
|
||
? createDevice(item, item)
|
||
: (() => {
|
||
const next = structuredClone(item.device);
|
||
applyCoolapk(next, item);
|
||
return next;
|
||
})();
|
||
const parsed = deviceSchema.safeParse(device);
|
||
if (!parsed.success) {
|
||
issues.push({
|
||
name: device.slug,
|
||
issues: parsed.error.issues.slice(0, 8).map((issue) => `${issue.path.join('.')}: ${issue.message}`),
|
||
});
|
||
continue;
|
||
}
|
||
if (item.kind === 'create') created += 1;
|
||
merged.push(parsed.data);
|
||
enriched.push({ slug: device.slug, coolapk: parsed.data.specs.coolapk?.name });
|
||
} catch (error) {
|
||
issues.push({ name: item.slug ?? item.device?.slug ?? item.product?.name, issues: [String(error)] });
|
||
}
|
||
}
|
||
|
||
if (issues.length > 0) {
|
||
console.error(`\n有 ${issues.length} 款合并失败:`);
|
||
for (const issue of issues.slice(0, 20)) {
|
||
console.error(`- ${issue.name}`);
|
||
for (const line of issue.issues) console.error(` ${line}`);
|
||
}
|
||
throw new Error('合并失败,已中止,未写入任何数据');
|
||
}
|
||
console.log(`成功合并 ${merged.length} 款(其中新建 ${created} 款)`);
|
||
|
||
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
||
const outPath = options.out || `data/import/coolapk-${stamp}.json`;
|
||
const payload = {
|
||
formatVersion: 1,
|
||
generator: 'LFSpecs / sync-coolapk',
|
||
exportedAt: new Date().toISOString(),
|
||
devices: merged,
|
||
chips: [],
|
||
};
|
||
await mkdir(dirname(outPath), { recursive: true });
|
||
await writeFile(outPath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
|
||
console.log(`JSON 已写入 ${outPath}(${merged.length} 款)`);
|
||
|
||
if (!options.write) {
|
||
console.log('未指定 --write,本次只产出 JSON。');
|
||
return;
|
||
}
|
||
console.log('写入数据库 ...');
|
||
const counts = importEntities(merged, []);
|
||
console.log(`数据库写入完成:devices ${counts.devices} / chips ${counts.chips}`);
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error);
|
||
process.exit(1);
|
||
});
|