Files
UHD_Media_Tool/packages/domain/src/classification.ts
T
rootandClaude Opus 5.5 ceb66f8c77 feat: v0.3.8–v0.3.14 工作区汇总(依赖升级、整理来源、手动入库、原地入库等)
生产 v0.3.8~v0.3.13 均由 8013196 加工作区修改构建部署,此前未提交;本提交补齐源码,
并含未部署的 v0.3.14 原地入库。中间各版本源码状态未保存,无法逐版拆分,详见
docs/plan/17-full-upgrade.md 与 docs/plan/18-organize-release.md。

- v0.3.8 全面升级:Deno workspace 依赖、Router 8 / Vite 8、camofox 1.18.0 / Node 24、
  PostgreSQL 18.6、备份客户端 18.6、演示 qB 5.2.4
- v0.3.9 媒体整理:分类规则、整理来源与目录快照(0059)、文件管理整理入口
- v0.3.10 手动下载与入库:独立手动下载、详情页资源下载、TMDB / Local 元数据兜底
  (metadata.resolve_organize)、正常多版本 / 一次性洗版(0060)
- v0.3.11 搜索详情与桌面黑边修复
- v0.3.12 列表分页、搜索历史、首页概况
- v0.3.13 统一整理弹窗与队列
- v0.3.14 原地入库(0061,未部署)

同批审计修复:
- 刮削入队:确认原记录存在后才删重放产生的新记录;写回 run 关联失败时保持 queued,
  由处理器补关联(对齐 MP 先登记、只在入队失败时记失败)
- 识别升级链只在结果更确定时采用,不再用 no_match 顶替原有歧义候选
- bluray_dir 资产以原盘目录本身为刮削根(MP 同做法)
- metadata.resolve_organize 登记到入库排障 Skill 与能力地图
- db/src/types.ts 按迁移重新生成;contracts 整理动作枚举顺序与数据库对齐
- 测试:原地入库用例改为直接查记录表;domain 测试模板补 version
- 前端:通知铃铛弹层与用户菜单统一样式;站点卡片共用卡头、底栏贴底、分页间距

依赖升级证据只提交摘要文件,registry-snapshot.json 移至 .local/(SHA-256 记于文档)。

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 15:47:17 +08:00

133 lines
5.4 KiB
TypeScript

import { parseDocument } from "yaml";
/** Ordered TMDB rules; first matching category wins. */
export interface ClassificationRule {
category: string;
conditions: { field: string; values: string[] }[];
}
export interface ClassificationConfig {
movie: ClassificationRule[];
tv: ClassificationRule[];
}
export interface ClassificationResult {
category: string | null;
matchedFields: string[];
fallback: boolean;
}
export { DEFAULT_CLASSIFICATION_YAML } from "@umt/contracts";
const scalar = (v: unknown): v is string | number | boolean =>
typeof v === "string" || typeof v === "boolean" || (typeof v === "number" && Number.isFinite(v));
export function parseClassificationYaml(yaml: string): ClassificationConfig {
const doc = parseDocument(yaml, { uniqueKeys: true, schema: "core" });
if (doc.errors.length) throw new Error(doc.errors.map((e) => e.message).join("; "));
const raw: unknown = doc.toJS({ mapAsMap: true, maxAliasCount: 0 });
if (!(raw instanceof Map) || [...raw.keys()].some((k) => k !== "movie" && k !== "tv"))
throw new Error("分类配置的一级名称只能是 movie、tv");
const config: ClassificationConfig = { movie: [], tv: [] };
for (const type of ["movie", "tv"] as const) {
const categories: unknown = raw.get(type);
if (!(categories instanceof Map)) throw new Error(`${type} 必须是分类名称映射`);
for (const [category, fields] of categories) {
if (
typeof category !== "string" ||
!category.trim() ||
category.trim() !== category ||
/[\\/<>:"|?*]/.test(category) ||
Array.from(category).some((ch) => ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127) ||
category === "." ||
category === ".." ||
/[. ]$/.test(category) ||
/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(category)
)
throw new Error(`${type} 分类名称必须是安全的单层目录名`);
if (fields !== null && !(fields instanceof Map)) throw new Error(`${type}.${category} 必须是条件映射或 null`);
const conditions: ClassificationRule["conditions"] = [];
for (const [field, input] of fields ?? []) {
if (typeof field !== "string" || !field.trim()) throw new Error(`${category} 的条件字段必须是非空字符串`);
const list: unknown[] = Array.isArray(input) ? input : [input];
if (!list.length || !list.every(scalar)) throw new Error(`${category}.${field} 条件必须是标量或标量列表`);
const values = list.flatMap((v) =>
String(v)
.split(",")
.map((s) => s.trim()),
);
if (values.some((v) => !v || v === "!")) throw new Error(`${category}.${field} 条件值不能为空`);
if (field === "release_year") {
for (const value of values) {
const year = value.replace(/^!/, "");
if (!/^\d{4}(?:-\d{4})?$/.test(year) || (year.includes("-") && year.slice(0, 4) > year.slice(5)))
throw new Error(`${category}.release_year 请使用 YYYY 或 YYYY-YYYY`);
}
}
conditions.push({ field, values });
}
config[type].push({ category, conditions });
}
if (config[type].some((r, i) => !r.conditions.length && i !== config[type].length - 1))
throw new Error(`${type} 无条件兜底分类必须放在最后`);
}
return config;
}
function actualValues(raw: Record<string, unknown>, type: "movie" | "tv", field: string): string[] {
let input = field === "release_year" ? raw[type === "movie" ? "release_date" : "first_air_date"] : raw[field];
if (field === "genre_ids" && input === undefined) input = raw.genres;
const list = Array.isArray(input) ? input : [input];
return list.flatMap((item) => {
let value = item;
if (value && typeof value === "object") {
const o = value as Record<string, unknown>;
value =
field === "production_countries"
? o.iso_3166_1
: field === "genre_ids" || field === "genres"
? o.id
: undefined;
}
if (!scalar(value) || String(value).trim() === "") return [];
if (field === "release_year") {
const year = String(value)
.match(/^\d{4}(?:-|$)/)?.[0]
.slice(0, 4);
return year ? [year] : [];
}
return [String(value)];
});
}
function matches(actual: string[], values: string[], field: string): boolean {
if (!actual.length) return false;
const hit = (value: string) =>
actual.some((a) => {
if (field === "release_year" && value.includes("-")) {
const [start, end] = value.split("-");
return a >= start! && a <= end!;
}
return a === value;
});
const excluded = values.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
const included = values.filter((v) => !v.startsWith("!"));
return !excluded.some(hit) && (!included.length || included.some(hit));
}
export function classifyTmdb(
config: ClassificationConfig,
type: "movie" | "tv",
raw: Record<string, unknown> | null | undefined,
): ClassificationResult {
const none: ClassificationResult = { category: null, matchedFields: [], fallback: false };
if (!raw || !Object.keys(raw).length) return none;
for (const rule of config[type]) {
if (rule.conditions.every(({ field, values }) => matches(actualValues(raw, type, field), values, field)))
return {
category: rule.category,
matchedFields: rule.conditions.map((c) => c.field),
fallback: !rule.conditions.length,
};
}
return none;
}