Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
feat(v1.8.0): Audio Studio EQ, A-B loop, smart transcripts/chapters, play queue, background import, continue shelf, command palette & portal focus rescue
This commit is contained in:
@@ -2999,6 +2999,286 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana
|
||||
|
||||
const videoOriginCache = new Map();
|
||||
const VIDEO_ORIGIN_CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
const transcriptMemoryCache = new Map();
|
||||
const inFlightTranscriptRequests = new Map();
|
||||
const TRANSCRIPT_OK_TTL_MS = 12 * 60 * 60 * 1000;
|
||||
const TRANSCRIPT_EMPTY_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
function resolveTranscriptStorageRoot() {
|
||||
try {
|
||||
if (
|
||||
peertubeHelpers &&
|
||||
peertubeHelpers.plugin &&
|
||||
typeof peertubeHelpers.plugin.getDataDirectoryPath === 'function'
|
||||
) {
|
||||
const dataDir = peertubeHelpers.plugin.getDataDirectoryPath();
|
||||
const candidate = path.resolve(dataDir, '..', '..', '..');
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
}
|
||||
} catch (e) {}
|
||||
if (fs.existsSync('D:\\yaktube_storage')) return 'D:\\yaktube_storage';
|
||||
return process.cwd();
|
||||
}
|
||||
|
||||
function extractYouTubeIdFromText(str) {
|
||||
if (!str || typeof str !== 'string') return null;
|
||||
const match =
|
||||
str.match(/[?&]v=([a-zA-Z0-9_-]{11})/) ||
|
||||
str.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/) ||
|
||||
str.match(/shorts\/([a-zA-Z0-9_-]{11})/) ||
|
||||
str.match(/embed\/([a-zA-Z0-9_-]{11})/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
function extractYouTubeIdFromRow(row) {
|
||||
if (!row) return null;
|
||||
return extractYouTubeIdFromText(row.targetUrl) || extractYouTubeIdFromText(row.description);
|
||||
}
|
||||
|
||||
function fetchRemoteTextWithLimit(targetUrl, timeoutMs = 9000, maxRedirects = 4, maxBytes = 4 * 1024 * 1024) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (maxRedirects <= 0) return reject(new Error('Too many redirects'));
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(targetUrl);
|
||||
} catch (e) {
|
||||
return reject(e);
|
||||
}
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
return reject(new Error('Unsupported protocol'));
|
||||
}
|
||||
const lib = parsed.protocol === 'https:' ? https : http;
|
||||
const req = lib.get(
|
||||
targetUrl,
|
||||
{
|
||||
timeout: timeoutMs,
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36',
|
||||
Accept: 'application/json, text/vtt, text/plain, */*'
|
||||
}
|
||||
},
|
||||
res => {
|
||||
if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
|
||||
res.resume();
|
||||
const nextUrl = new URL(res.headers.location, targetUrl).toString();
|
||||
return resolve(fetchRemoteTextWithLimit(nextUrl, timeoutMs, maxRedirects - 1, maxBytes));
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
res.resume();
|
||||
return reject(new Error('HTTP ' + res.statusCode));
|
||||
}
|
||||
const chunks = [];
|
||||
let received = 0;
|
||||
res.on('data', chunk => {
|
||||
received += chunk.length;
|
||||
if (received > maxBytes) {
|
||||
req.destroy(new Error('Response too large'));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||
res.on('error', reject);
|
||||
}
|
||||
);
|
||||
req.on('timeout', () => req.destroy(new Error('Timeout')));
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function parseTimeTokenToSeconds(token) {
|
||||
if (!token || typeof token !== 'string') return NaN;
|
||||
const parts = token.trim().replace(',', '.').split(':');
|
||||
if (parts.length === 2) {
|
||||
const m = parseInt(parts[0], 10);
|
||||
const s = parseFloat(parts[1]);
|
||||
if (isNaN(m) || isNaN(s)) return NaN;
|
||||
return m * 60 + s;
|
||||
}
|
||||
if (parts.length === 3) {
|
||||
const h = parseInt(parts[0], 10);
|
||||
const m = parseInt(parts[1], 10);
|
||||
const s = parseFloat(parts[2]);
|
||||
if (isNaN(h) || isNaN(m) || isNaN(s)) return NaN;
|
||||
return h * 3600 + m * 60 + s;
|
||||
}
|
||||
return NaN;
|
||||
}
|
||||
|
||||
function decodeSubtitleEntities(str) {
|
||||
return String(str || '')
|
||||
.replace(/<\d{2}:\d{2}(?::\d{2})?\.\d+>/g, '')
|
||||
.replace(/<\/?[^>]+(>|$)/g, ' ')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'|'/g, "'")
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function parseChaptersFromDescription(description, maxDurationSec) {
|
||||
if (!description || typeof description !== 'string') return [];
|
||||
const lines = description.split(/\r?\n/);
|
||||
const seenStarts = new Set();
|
||||
const chapters = [];
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.length > 220) continue;
|
||||
const mPrefix = line.match(/^[\[\(\*•\-–—\s]*((?:\d{1,2}:)?\d{1,2}:\d{2})[\]\)\*:\-\s–—]+(.+)$/);
|
||||
const mSuffix = !mPrefix ? line.match(/^(.+?)[\s\-\–—:\(\[]+((?:\d{1,2}:)?\d{1,2}:\d{2})[\)\]\s]*$/) : null;
|
||||
const timeStr = mPrefix ? mPrefix[1] : mSuffix ? mSuffix[2] : null;
|
||||
let title = mPrefix ? mPrefix[2] : mSuffix ? mSuffix[1] : '';
|
||||
if (!timeStr) continue;
|
||||
const startSec = Math.floor(parseTimeTokenToSeconds(timeStr));
|
||||
if (isNaN(startSec) || startSec < 0) continue;
|
||||
if (maxDurationSec > 0 && startSec > maxDurationSec + 5) continue;
|
||||
title = title.replace(/^[\-\–—:\s•]+|[\-\–—:\s•]+$/g, '').trim();
|
||||
if (!title || title.length < 2) continue;
|
||||
if (seenStarts.has(startSec)) continue;
|
||||
seenStarts.add(startSec);
|
||||
chapters.push({ title, start: startSec });
|
||||
}
|
||||
chapters.sort((a, b) => a.start - b.start);
|
||||
return chapters.length >= 2 ? chapters : [];
|
||||
}
|
||||
|
||||
function parseJson3Subtitles(rawText) {
|
||||
const parsed = JSON.parse(rawText);
|
||||
const events = Array.isArray(parsed && parsed.events) ? parsed.events : [];
|
||||
const cues = [];
|
||||
for (const ev of events) {
|
||||
if (!ev || !Array.isArray(ev.segs)) continue;
|
||||
const text = ev.segs
|
||||
.map(s => (s && s.utf8 ? s.utf8 : ''))
|
||||
.join('')
|
||||
.replace(/\n+/g, ' ');
|
||||
const clean = decodeSubtitleEntities(text);
|
||||
if (!clean || clean === '[Müzik]' || clean === '[Music]') {
|
||||
if (!clean) continue;
|
||||
}
|
||||
const start = Number(((ev.tStartMs || 0) / 1000).toFixed(2));
|
||||
const dur = ev.dDurationMs ? ev.dDurationMs / 1000 : 3;
|
||||
const end = Number((start + Math.max(0.5, dur)).toFixed(2));
|
||||
if (
|
||||
cues.length > 0 &&
|
||||
cues[cues.length - 1].text === clean &&
|
||||
Math.abs(start - cues[cues.length - 1].start) < 2
|
||||
) {
|
||||
cues[cues.length - 1].end = Math.max(cues[cues.length - 1].end, end);
|
||||
continue;
|
||||
}
|
||||
cues.push({ start, end, text: clean });
|
||||
}
|
||||
return cues;
|
||||
}
|
||||
|
||||
function parseVttOrSrtSubtitles(rawText) {
|
||||
const normalized = String(rawText || '')
|
||||
.replace(/^\uFEFF/, '')
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/\r/g, '\n');
|
||||
const blocks = normalized.split(/\n{2,}/);
|
||||
const cues = [];
|
||||
for (const block of blocks) {
|
||||
const lines = block
|
||||
.split('\n')
|
||||
.map(l => l.trim())
|
||||
.filter(Boolean);
|
||||
if (!lines.length) continue;
|
||||
if (/^(WEBVTT|Kind:|Language:|NOTE\b|STYLE\b)/i.test(lines[0])) continue;
|
||||
const timeIdx = lines.findIndex(l => l.includes('-->'));
|
||||
if (timeIdx === -1) continue;
|
||||
const parts = lines[timeIdx].split('-->');
|
||||
if (parts.length < 2) continue;
|
||||
const start = parseTimeTokenToSeconds(parts[0].trim().split(/\s+/)[0]);
|
||||
const end = parseTimeTokenToSeconds(parts[1].trim().split(/\s+/)[0]);
|
||||
if (isNaN(start)) continue;
|
||||
const rawBody = lines.slice(timeIdx + 1).join(' ');
|
||||
const clean = decodeSubtitleEntities(rawBody);
|
||||
if (!clean) continue;
|
||||
const safeStart = Number(start.toFixed(2));
|
||||
const safeEnd = Number((!isNaN(end) && end > start ? end : start + 3).toFixed(2));
|
||||
if (cues.length > 0 && cues[cues.length - 1].text === clean) {
|
||||
cues[cues.length - 1].end = Math.max(cues[cues.length - 1].end, safeEnd);
|
||||
continue;
|
||||
}
|
||||
cues.push({ start: safeStart, end: safeEnd, text: clean });
|
||||
}
|
||||
return cues;
|
||||
}
|
||||
|
||||
function parseSubtitlePayload(rawText) {
|
||||
if (!rawText || typeof rawText !== 'string') return [];
|
||||
const trimmed = rawText.trim();
|
||||
if (!trimmed) return [];
|
||||
if (trimmed.startsWith('{')) {
|
||||
try {
|
||||
return parseJson3Subtitles(trimmed);
|
||||
} catch (e) {}
|
||||
}
|
||||
return parseVttOrSrtSubtitles(trimmed);
|
||||
}
|
||||
|
||||
function pickPreferredCaptionTrack(ytInfo, preferredLang, videoLang) {
|
||||
const manual = ytInfo && ytInfo.subtitles && typeof ytInfo.subtitles === 'object' ? ytInfo.subtitles : {};
|
||||
const auto =
|
||||
ytInfo && ytInfo.automatic_captions && typeof ytInfo.automatic_captions === 'object'
|
||||
? ytInfo.automatic_captions
|
||||
: {};
|
||||
const availableLanguages = [];
|
||||
const collectLangs = (mapObj, isAuto) => {
|
||||
for (const code of Object.keys(mapObj)) {
|
||||
if (!code || code === 'live_chat') continue;
|
||||
const tracks = mapObj[code];
|
||||
if (!Array.isArray(tracks) || tracks.length === 0) continue;
|
||||
availableLanguages.push({
|
||||
code,
|
||||
name: tracks[0].name || code,
|
||||
auto: isAuto
|
||||
});
|
||||
}
|
||||
};
|
||||
collectLangs(manual, false);
|
||||
collectLangs(auto, true);
|
||||
|
||||
const priorityLangs = [];
|
||||
for (const candidate of [preferredLang, 'tr', videoLang, 'en', 'en-US', 'en-GB']) {
|
||||
const c = candidate ? String(candidate).trim().toLowerCase() : '';
|
||||
if (c && !priorityLangs.includes(c)) priorityLangs.push(c);
|
||||
}
|
||||
|
||||
const pickFormat = tracks => {
|
||||
for (const ext of ['json3', 'vtt', 'srt']) {
|
||||
const hit = tracks.find(t => t && t.ext === ext && t.url);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return tracks.find(t => t && t.url) || null;
|
||||
};
|
||||
|
||||
const pickFromMap = (mapObj, isAuto) => {
|
||||
const keys = Object.keys(mapObj).filter(
|
||||
k => k && k !== 'live_chat' && Array.isArray(mapObj[k]) && mapObj[k].length
|
||||
);
|
||||
if (keys.length === 0) return null;
|
||||
for (const p of priorityLangs) {
|
||||
const exact = keys.find(k => k.toLowerCase() === p) || keys.find(k => k.toLowerCase().startsWith(p + '-'));
|
||||
if (exact) {
|
||||
const track = pickFormat(mapObj[exact]);
|
||||
if (track) return { code: exact, isAuto, track };
|
||||
}
|
||||
}
|
||||
// Also match *-orig auto-captions (video's native language) or first available
|
||||
const origKey = keys.find(k => k.endsWith('-orig')) || keys[0];
|
||||
const fallbackTrack = pickFormat(mapObj[origKey]);
|
||||
return fallbackTrack ? { code: origKey, isAuto, track: fallbackTrack } : null;
|
||||
};
|
||||
|
||||
const chosen = pickFromMap(manual, false) || pickFromMap(auto, true);
|
||||
return { chosen, availableLanguages: availableLanguages.slice(0, 12) };
|
||||
}
|
||||
|
||||
router.get('/video-origin/:uuid', async (req, res) => {
|
||||
if (isCrawlerBotRequest(req)) {
|
||||
@@ -3042,23 +3322,7 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana
|
||||
}
|
||||
|
||||
const row = rows[0];
|
||||
let youtubeId = null;
|
||||
|
||||
if (row.targetUrl) {
|
||||
const match =
|
||||
row.targetUrl.match(/[?&]v=([^&]+)/) ||
|
||||
row.targetUrl.match(/youtu\.be\/([^?]+)/) ||
|
||||
row.targetUrl.match(/shorts\/([^?]+)/);
|
||||
if (match) youtubeId = match[1];
|
||||
}
|
||||
|
||||
if (!youtubeId && row.description) {
|
||||
const match =
|
||||
row.description.match(/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/) ||
|
||||
row.description.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/) ||
|
||||
row.description.match(/shorts\/([a-zA-Z0-9_-]{11})/);
|
||||
if (match) youtubeId = match[1];
|
||||
}
|
||||
const youtubeId = extractYouTubeIdFromRow(row);
|
||||
|
||||
const payload = {
|
||||
ok: true,
|
||||
@@ -3076,6 +3340,254 @@ async function register({ registerHook, getRouter, registerSetting, settingsMana
|
||||
}
|
||||
});
|
||||
|
||||
// 6b. Akıllı Transkript & Bölüm (Chapters) Çekici
|
||||
router.get('/video-transcript/:uuid', async (req, res) => {
|
||||
if (isCrawlerBotRequest(req)) {
|
||||
return res.json({ ok: false, botIgnored: true, cues: [], chapters: [] });
|
||||
}
|
||||
const rawParam = (req.params.uuid || '').trim();
|
||||
if (!rawParam) return res.status(400).json({ ok: false, error: 'UUID required' });
|
||||
const resolvedUuid = shortToUuid(rawParam);
|
||||
const reqLang = String(req.query.lang || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const forceRefresh = req.query.refresh === '1' || req.query.refresh === 'true';
|
||||
const queryYtId =
|
||||
req.query.youtubeId && /^[a-zA-Z0-9_-]{11}$/.test(String(req.query.youtubeId).trim())
|
||||
? String(req.query.youtubeId).trim()
|
||||
: null;
|
||||
const cacheKey = `${resolvedUuid}__${reqLang || 'auto'}__${queryYtId || 'db'}`;
|
||||
|
||||
if (!forceRefresh) {
|
||||
const memHit = transcriptMemoryCache.get(cacheKey);
|
||||
if (memHit) {
|
||||
const ttl = memHit.hasContent ? TRANSCRIPT_OK_TTL_MS : TRANSCRIPT_EMPTY_TTL_MS;
|
||||
if (Date.now() - memHit.time < ttl) {
|
||||
return res.json(memHit.payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const storageRoot = resolveTranscriptStorageRoot();
|
||||
const transcriptCacheDir = path.join(storageRoot, 'cache', 'transcripts');
|
||||
const diskCachePath = path.join(
|
||||
transcriptCacheDir,
|
||||
`${resolvedUuid.replace(/[^a-zA-Z0-9_-]/g, '_')}_${reqLang || 'auto'}.json`
|
||||
);
|
||||
|
||||
if (!forceRefresh && fs.existsSync(diskCachePath)) {
|
||||
try {
|
||||
const st = await fs.promises.stat(diskCachePath);
|
||||
if (Date.now() - st.mtimeMs < 7 * 24 * 60 * 60 * 1000) {
|
||||
const diskPayload = JSON.parse(await fs.promises.readFile(diskCachePath, 'utf8'));
|
||||
if (diskPayload && diskPayload.ok) {
|
||||
transcriptMemoryCache.set(cacheKey, {
|
||||
time: Date.now(),
|
||||
hasContent:
|
||||
(diskPayload.cues && diskPayload.cues.length > 0) ||
|
||||
(diskPayload.chapters && diskPayload.chapters.length > 0),
|
||||
payload: diskPayload
|
||||
});
|
||||
return res.json(diskPayload);
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
if (inFlightTranscriptRequests.has(cacheKey)) {
|
||||
try {
|
||||
const shared = await inFlightTranscriptRequests.get(cacheKey);
|
||||
return res.json(shared);
|
||||
} catch (err) {
|
||||
return res.status(500).json({ ok: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
const workPromise = (async () => {
|
||||
let row = null;
|
||||
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(resolvedUuid)) {
|
||||
const rows = await dbQuery(
|
||||
`SELECT v.id, v.uuid, v.name, v.description, v.duration, v.language, vi."targetUrl"
|
||||
FROM "video" v
|
||||
LEFT JOIN "videoImport" vi ON vi."videoId" = v.id
|
||||
WHERE v.uuid = $1::uuid
|
||||
LIMIT 1`,
|
||||
[resolvedUuid]
|
||||
);
|
||||
if (rows[0]) row = rows[0];
|
||||
} else if (/^\d+$/.test(rawParam)) {
|
||||
const rows = await dbQuery(
|
||||
`SELECT v.id, v.uuid, v.name, v.description, v.duration, v.language, vi."targetUrl"
|
||||
FROM "video" v
|
||||
LEFT JOIN "videoImport" vi ON vi."videoId" = v.id
|
||||
WHERE v.id = $1::int
|
||||
LIMIT 1`,
|
||||
[parseInt(rawParam, 10)]
|
||||
);
|
||||
if (rows[0]) row = rows[0];
|
||||
}
|
||||
|
||||
if (!row && !queryYtId) {
|
||||
return { ok: false, error: 'Video not found', cues: [], chapters: [] };
|
||||
}
|
||||
|
||||
let cues = [];
|
||||
let chapters = row ? parseChaptersFromDescription(row.description, Number(row.duration || 0)) : [];
|
||||
let language = row && row.language ? row.language : null;
|
||||
let languageName = language || '';
|
||||
let isAutoGenerated = false;
|
||||
let source = chapters.length > 0 ? 'description' : 'none';
|
||||
let availableLanguages = [];
|
||||
const youtubeId = queryYtId || extractYouTubeIdFromRow(row);
|
||||
|
||||
// 1. Try local/remote PeerTube videoCaption rows if not requesting a different language
|
||||
if (row && row.id) {
|
||||
try {
|
||||
const capRows = await dbQuery(
|
||||
`SELECT id, language, filename, "fileUrl", "automaticallyGenerated"
|
||||
FROM "videoCaption"
|
||||
WHERE "videoId" = $1
|
||||
ORDER BY CASE WHEN language = $2 THEN 0 WHEN language = 'tr' THEN 1 WHEN language = 'en' THEN 2 ELSE 3 END, "automaticallyGenerated" ASC, id ASC
|
||||
LIMIT 6`,
|
||||
[row.id, reqLang || 'tr']
|
||||
);
|
||||
for (const cap of capRows) {
|
||||
availableLanguages.push({
|
||||
code: cap.language,
|
||||
name: cap.language,
|
||||
auto: Boolean(cap.automaticallyGenerated)
|
||||
});
|
||||
}
|
||||
const matchedCap = reqLang
|
||||
? capRows.find(c => String(c.language || '').toLowerCase() === reqLang)
|
||||
: capRows[0];
|
||||
if (matchedCap) {
|
||||
let capText = '';
|
||||
const localCapPath = matchedCap.filename
|
||||
? path.join(storageRoot, 'captions', path.basename(matchedCap.filename))
|
||||
: '';
|
||||
const cachedCapPath = matchedCap.filename
|
||||
? path.join(storageRoot, 'cache', 'video-captions', path.basename(matchedCap.filename))
|
||||
: '';
|
||||
if (localCapPath && fs.existsSync(localCapPath)) {
|
||||
capText = await fs.promises.readFile(localCapPath, 'utf8');
|
||||
} else if (cachedCapPath && fs.existsSync(cachedCapPath)) {
|
||||
capText = await fs.promises.readFile(cachedCapPath, 'utf8');
|
||||
} else if (matchedCap.fileUrl) {
|
||||
capText = await fetchRemoteTextWithLimit(matchedCap.fileUrl, 7000);
|
||||
}
|
||||
const parsedLocalCues = parseSubtitlePayload(capText);
|
||||
if (parsedLocalCues.length > 0) {
|
||||
cues = parsedLocalCues;
|
||||
language = matchedCap.language;
|
||||
languageName = matchedCap.language;
|
||||
isAutoGenerated = Boolean(matchedCap.automaticallyGenerated);
|
||||
source = 'peertube-caption';
|
||||
}
|
||||
}
|
||||
} catch (capErr) {}
|
||||
}
|
||||
|
||||
// 2. Fallback to live YouTube subtitle & chapter extraction via yt-dlp when cues or chapters are still needed
|
||||
if (youtubeId && (cues.length === 0 || chapters.length === 0 || reqLang)) {
|
||||
try {
|
||||
const ytdlpPath = resolveYtDlpPath(logger, customYtDlpPath, peertubeHelpers);
|
||||
const ytUrl = `https://www.youtube.com/watch?v=${youtubeId}`;
|
||||
const rawJsonStr = await new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
ytdlpPath,
|
||||
['--dump-single-json', '--skip-download', '--no-warnings', '--socket-timeout', '8', ytUrl],
|
||||
{ maxBuffer: 14 * 1024 * 1024, timeout: 15000 },
|
||||
(err, stdout) => {
|
||||
if (err || !stdout) return reject(err || new Error('Empty yt-dlp output'));
|
||||
resolve(stdout);
|
||||
}
|
||||
);
|
||||
});
|
||||
const startIdx = rawJsonStr.indexOf('{');
|
||||
const endIdx = rawJsonStr.lastIndexOf('}');
|
||||
if (startIdx !== -1 && endIdx !== -1) {
|
||||
const ytInfo = JSON.parse(rawJsonStr.substring(startIdx, endIdx + 1));
|
||||
if (Array.isArray(ytInfo.chapters) && ytInfo.chapters.length > 0) {
|
||||
chapters = ytInfo.chapters
|
||||
.filter(c => c && c.title && c.start_time !== undefined)
|
||||
.map(c => ({
|
||||
title: String(c.title).trim(),
|
||||
start: Math.max(0, Math.floor(Number(c.start_time || 0))),
|
||||
end: c.end_time !== undefined ? Math.floor(Number(c.end_time)) : null
|
||||
}));
|
||||
} else if (chapters.length === 0 && ytInfo.description) {
|
||||
chapters = parseChaptersFromDescription(ytInfo.description, Number(ytInfo.duration || 0));
|
||||
}
|
||||
|
||||
if (cues.length === 0 || reqLang) {
|
||||
const picked = pickPreferredCaptionTrack(ytInfo, reqLang, row && row.language);
|
||||
if (picked.availableLanguages.length > 0) {
|
||||
availableLanguages = picked.availableLanguages;
|
||||
}
|
||||
if (picked.chosen && picked.chosen.track && picked.chosen.track.url) {
|
||||
const subText = await fetchRemoteTextWithLimit(picked.chosen.track.url, 9000);
|
||||
const ytCues = parseSubtitlePayload(subText);
|
||||
if (ytCues.length > 0) {
|
||||
cues = ytCues;
|
||||
language = picked.chosen.code;
|
||||
languageName = (picked.chosen.track && picked.chosen.track.name) || picked.chosen.code;
|
||||
isAutoGenerated = picked.chosen.isAuto;
|
||||
source = picked.chosen.isAuto ? 'youtube-auto' : 'youtube-manual';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ytErr) {
|
||||
if (logger) {
|
||||
logger.warn(`[YakTube Transcript] Extract warning for ${resolvedUuid}: ${ytErr.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const payload = {
|
||||
ok: true,
|
||||
uuid: (row && row.uuid) || resolvedUuid,
|
||||
title: (row && row.name) || '',
|
||||
youtubeId: youtubeId || null,
|
||||
language,
|
||||
languageName,
|
||||
isAutoGenerated,
|
||||
source,
|
||||
cues,
|
||||
chapters,
|
||||
availableLanguages
|
||||
};
|
||||
|
||||
const hasContent = cues.length > 0 || chapters.length > 0;
|
||||
if (transcriptMemoryCache.size > 400) transcriptMemoryCache.clear();
|
||||
transcriptMemoryCache.set(cacheKey, {
|
||||
time: Date.now(),
|
||||
hasContent,
|
||||
payload
|
||||
});
|
||||
|
||||
if (hasContent) {
|
||||
try {
|
||||
await fs.promises.mkdir(transcriptCacheDir, { recursive: true });
|
||||
await fs.promises.writeFile(diskCachePath, JSON.stringify(payload), 'utf8');
|
||||
} catch (diskErr) {}
|
||||
}
|
||||
|
||||
return payload;
|
||||
})().finally(() => {
|
||||
inFlightTranscriptRequests.delete(cacheKey);
|
||||
});
|
||||
|
||||
inFlightTranscriptRequests.set(cacheKey, workPromise);
|
||||
try {
|
||||
const result = await workPromise;
|
||||
return res.json(result);
|
||||
} catch (err) {
|
||||
return res.status(500).json({ ok: false, error: err.message, cues: [], chapters: [] });
|
||||
}
|
||||
});
|
||||
|
||||
// 7. YouTube Original Comments Route
|
||||
router.get('/youtube-comments', async (req, res) => {
|
||||
const videoId = (req.query.id || req.query.v || '').trim();
|
||||
|
||||
Reference in New Issue
Block a user