181 lines
6.4 KiB
TypeScript
181 lines
6.4 KiB
TypeScript
export type YoutubeProChannel = {
|
||
id: string;
|
||
name: string;
|
||
/** 备忘尾码(旧版) */
|
||
streamKeySuffix?: string;
|
||
/** 完整串流密钥或 rtmp(s) URL */
|
||
streamKey?: string;
|
||
/** 本线路 URL_config 草稿(多路本地编排) */
|
||
urlLines?: string;
|
||
/** 建议 PM2 名,如 youtube2__xxx */
|
||
pm2Name?: string;
|
||
notes?: string;
|
||
};
|
||
|
||
const STORAGE_KEY = "live-hub-youtube-pro-v2";
|
||
const YOUTUBE_PRO_PM2_PREFIX = "youtube2__";
|
||
const PM2_SANITIZE_RE = /[^a-zA-Z0-9_.-]+/g;
|
||
const RESERVED_PRO_PM2_NAMES = new Set(["youtube", "douyin_youtube", "tiktok", "obs", "web"]);
|
||
|
||
export function isBrokenYoutubeProLaneName(value: string | undefined): boolean {
|
||
const s = (value || "").trim();
|
||
return (
|
||
!s ||
|
||
/\?{2,}/.test(s) ||
|
||
/?{2,}/.test(s) ||
|
||
/<2F>/.test(s) ||
|
||
/锟|绾胯矾|çº|è·|Â/.test(s) ||
|
||
/^(undefined|null|nan)$/i.test(s)
|
||
);
|
||
}
|
||
|
||
export function cleanYoutubeProLaneName(value: string | undefined, index: number): string {
|
||
const raw = (value || "").trim();
|
||
if (!isBrokenYoutubeProLaneName(raw)) return raw;
|
||
const laneNo = raw.match(/\d+/)?.[0] || String(Math.max(0, index) + 1);
|
||
return `线路 ${laneNo}`;
|
||
}
|
||
|
||
export function cleanYoutubeProChannelNames(channels: YoutubeProChannel[]): YoutubeProChannel[] {
|
||
return channels.map((channel, index) => ({
|
||
...channel,
|
||
name: cleanYoutubeProLaneName(channel.name, index),
|
||
}));
|
||
}
|
||
|
||
export function sanitizeYoutubePm2Name(value: string): string {
|
||
return (value || "").trim().replace(PM2_SANITIZE_RE, "_");
|
||
}
|
||
|
||
export function normalizeYoutubeProPm2Name(value: string, channelId: string): string {
|
||
const raw = sanitizeYoutubePm2Name(value);
|
||
if (!raw || RESERVED_PRO_PM2_NAMES.has(raw) || raw === YOUTUBE_PRO_PM2_PREFIX) {
|
||
return defaultPm2NameForChannel(channelId);
|
||
}
|
||
if (raw.startsWith(YOUTUBE_PRO_PM2_PREFIX)) return raw;
|
||
return defaultPm2NameForChannel(raw);
|
||
}
|
||
|
||
export function resolveYoutubeProChannelPm2(channel: Pick<YoutubeProChannel, "id" | "pm2Name">): string {
|
||
return normalizeYoutubeProPm2Name(String(channel.pm2Name || ""), String(channel.id || ""));
|
||
}
|
||
|
||
export function parseYoutubeProChannelList(raw: unknown): YoutubeProChannel[] {
|
||
if (!Array.isArray(raw)) return [];
|
||
const parsed = raw
|
||
.map((x, index) => migrateRow(x as Record<string, unknown>, index))
|
||
.filter((c): c is YoutubeProChannel => c !== null);
|
||
return cleanYoutubeProChannelNames(parsed);
|
||
}
|
||
|
||
function migrateRow(x: Record<string, unknown>, index = 0): YoutubeProChannel | null {
|
||
if (!x || typeof x !== "object") return null;
|
||
const id = String(x.id || "").trim();
|
||
if (!id) return null;
|
||
const name = cleanYoutubeProLaneName(typeof x.name === "string" ? x.name : "", index);
|
||
return {
|
||
id,
|
||
name,
|
||
streamKeySuffix: typeof x.streamKeySuffix === "string" ? x.streamKeySuffix : undefined,
|
||
streamKey: typeof x.streamKey === "string" ? x.streamKey : undefined,
|
||
urlLines: typeof x.urlLines === "string" ? x.urlLines : undefined,
|
||
pm2Name: normalizeYoutubeProPm2Name(typeof x.pm2Name === "string" ? x.pm2Name : "", id),
|
||
notes: typeof x.notes === "string" ? x.notes : undefined,
|
||
};
|
||
}
|
||
|
||
function safeParse(raw: string | null): YoutubeProChannel[] {
|
||
if (!raw) return [];
|
||
try {
|
||
const v = JSON.parse(raw) as unknown;
|
||
if (!Array.isArray(v)) return [];
|
||
const parsed = v.map((x, index) => migrateRow(x as Record<string, unknown>, index)).filter((c): c is YoutubeProChannel => c !== null);
|
||
return cleanYoutubeProChannelNames(parsed);
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
export function loadYoutubeProChannels(): YoutubeProChannel[] {
|
||
if (typeof window === "undefined") return [];
|
||
let raw = window.localStorage.getItem(STORAGE_KEY);
|
||
if (!raw) {
|
||
raw = window.localStorage.getItem("live-hub-youtube-pro-v1");
|
||
if (raw) {
|
||
const legacy = safeParse(raw);
|
||
if (legacy.length) {
|
||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(legacy));
|
||
return legacy;
|
||
}
|
||
}
|
||
}
|
||
return safeParse(raw);
|
||
}
|
||
|
||
export function saveYoutubeProChannels(channels: YoutubeProChannel[]): void {
|
||
if (typeof window === "undefined") return;
|
||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(cleanYoutubeProChannelNames(channels)));
|
||
}
|
||
|
||
const YOUTUBE_PRO_SYNC_PATHS = ["/hub/youtube_pro_channels", "/youtube_pro_channels"] as const;
|
||
|
||
export type YoutubeProChannelsRemoteResult = {
|
||
fetched: boolean;
|
||
channels: YoutubeProChannel[];
|
||
};
|
||
|
||
export type YoutubeProChannelsSyncOptions = {
|
||
force?: boolean;
|
||
};
|
||
|
||
/** 从服务器拉多频道列表(依次尝试 /hub 与根路径,兼容反代未转发 /hub 的情况) */
|
||
export async function fetchYoutubeProChannelsRemote(
|
||
fetchJson: <T,>(path: string, init?: RequestInit) => Promise<T>,
|
||
): Promise<YoutubeProChannelsRemoteResult> {
|
||
for (const path of YOUTUBE_PRO_SYNC_PATHS) {
|
||
try {
|
||
const data = await fetchJson<{ channels?: unknown }>(path);
|
||
return { fetched: true, channels: parseYoutubeProChannelList(data.channels) };
|
||
} catch {
|
||
/* try next */
|
||
}
|
||
}
|
||
return { fetched: false, channels: [] };
|
||
}
|
||
|
||
export async function pushYoutubeProChannelsRemote(
|
||
fetchJson: <T,>(path: string, init?: RequestInit) => Promise<T>,
|
||
channels: YoutubeProChannel[],
|
||
options: YoutubeProChannelsSyncOptions = {},
|
||
): Promise<void> {
|
||
let last: Error | null = null;
|
||
const cleanChannels = cleanYoutubeProChannelNames(channels);
|
||
for (const path of YOUTUBE_PRO_SYNC_PATHS) {
|
||
try {
|
||
const data = await fetchJson<{ neko?: { ok?: boolean; reason?: string; desired?: number; current?: number | string | null } }>(path, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ channels: cleanChannels, force: !!options.force }),
|
||
});
|
||
if (data.neko?.ok === false) {
|
||
const desired = data.neko.desired ? ` desired=${data.neko.desired}` : "";
|
||
const current = data.neko.current ? ` current=${data.neko.current}` : "";
|
||
last = new Error(`Neko capacity expansion failed:${desired}${current} ${data.neko.reason || "unknown error"}`.trim());
|
||
break;
|
||
}
|
||
return;
|
||
} catch (e) {
|
||
last = e instanceof Error ? e : new Error(String(e));
|
||
}
|
||
}
|
||
throw last ?? new Error("youtube_pro_channels sync failed");
|
||
}
|
||
|
||
export function newChannelId(): string {
|
||
return `ch_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`;
|
||
}
|
||
|
||
export function defaultPm2NameForChannel(channelId: string): string {
|
||
return `${YOUTUBE_PRO_PM2_PREFIX}${sanitizeYoutubePm2Name(channelId) || "channel"}`;
|
||
}
|