feat: lives PeerTube/Rumble, page Admin, TTL par provider, import/export playlists
CI / build-and-test (push) Successful in 14m56s
CI / build-and-test (push) Successful in 14m56s
#1 Live - PeerTube: API native ?isLive=true (recherche sepiasearch + videos de chaine), mapPeertubeItem exporte la regle live (type/kind/isLive, viewers, jamais de duree), caps pt live:true, themes « En direct » branches pt/ru - Rumble: mode 'live' de scrapeRumbleList (rumble.com/browse/live, SSR), items type:live + extraction channelId (/c/<slug>), route GET /api/rumble/live, onglet chaine live filtre par channelId (plafond page 1 = 50 directs) - Odysee: N/A prouve (proxy na-backend sous jeton, probe 2026-10), caps inchangees - Tests: npm run test:live (25 assertions), assertion adapter_contract mise a jour (seuls tw/pt/ru declarent live) #2 Playlists natives - Twitch: NON FAISABLE — probe avec token app valide: GET/POST /helix/playlists et /helix/playlists/{id}/videos -> 404 (controle /helix/users -> 400). Matrice README: Twitch/Odysee/Rumble en N/A avec preuves #3 Quick wins - Page Administration /#/admin (entree sidebar Informations + i18n nav.admin FR/EN): healthz + providers/metrics rendus (statut, yt-dlp, clés actives/ bannies, anti-ban, cache par provider, compteurs 1h, quota du jour) ; healthz sert aussi sous /proxy/api/healthz - TTL par provider: server/env-ttl.mjs (<BASE>_<P> -> <BASE> -> defaut, jamais nul), branche sur les caches details et transcripts ; suggest reste global (cle agregee multi-providers) ; tests npm run test:cache - Import/Export playlists JSON: GET /playlists/export (newtube-playlists-v1, avant /playlists/:id) + POST /playlists/import (dedoublonnage par titre), boutons [Exporter] [Importer] sur la page listes de lecture README: matrice fournisseurs (Live pt/ru OK, od N/A, playlists N/A prouves), roadmap deplace en ✅ (Live, import/export, Admin, TTL) + 🟡 mis a jour.
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* TTL de cache par provider — modèle identique à `SEARCH_CACHE_TTL_MS_<P>`
|
||||
* (server/db.mjs) étendu aux caches mémoire de index.mjs.
|
||||
*
|
||||
* Priorité : `<BASE>_<PROVIDER>` (ex. `DETAILS_CACHE_TTL_MS_YT`) →
|
||||
* `<BASE>` (`DETAILS_CACHE_TTL_MS`) → défaut passé par l'appelant.
|
||||
* Une valeur absente, non numérique ou ≤ 0 est ignorée (jamais de TTL nul
|
||||
* qui viderait le cache à chaque lecture).
|
||||
*
|
||||
* Base volontairement sans suffixe imposé : `TRANSCRIPT_CACHE_TTL` garde son
|
||||
* nom d'env historique, le suffixe `_YT` s'y ajoute tel quel.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} base nom de la variable d'environnement de base
|
||||
* @param {string} provider id provider ('yt', 'dailymotion', …)
|
||||
* @param {number} fallback TTL par défaut (ms)
|
||||
* @returns {number} TTL en ms
|
||||
*/
|
||||
export function perProviderTtl(base, provider, fallback) {
|
||||
const p = String(provider || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
if (p) {
|
||||
const v = Number(process.env[`${base}_${p}`]);
|
||||
if (Number.isFinite(v) && v > 0) return v;
|
||||
}
|
||||
const g = Number(process.env[base]);
|
||||
if (Number.isFinite(g) && g > 0) return g;
|
||||
return fallback;
|
||||
}
|
||||
+89
-3
@@ -19,6 +19,7 @@ import { applyProviderFlags, providerFlag } from './providers/feature-flags.mjs'
|
||||
import { dedupeSuggestGroups } from './suggest.mjs';
|
||||
import { buildDebugPayload, APPLICATION_NDJSON } from './search-transport.mjs';
|
||||
import { parseSearchFilters, activeFilters as activeSearchFilters, applySearchFilters, filtersCacheKey } from './search-filters.mjs';
|
||||
import { perProviderTtl } from './env-ttl.mjs';
|
||||
import { fetchWebSuggest, fetchOdyseeLighthouseSuggest } from './suggest-web.mjs';
|
||||
import { pickTrack, parseTrackText, parseVtt, dedupeTranscriptLines, orderedTracks, translatedFallbacks, firstPerLanguage, normalizeTranscriptProvider, transcriptTrackExt, looksLikeHtmlError, ensureFmtParam, isEmptyTimedTextBody, isBlobTranscript, mergeTranscriptCandidates } from './transcript.mjs';
|
||||
import {
|
||||
@@ -1538,7 +1539,10 @@ function detailsCacheGet(key) {
|
||||
// Récence = LRU naïf (même modèle que `ytCache`).
|
||||
detailsCache.delete(key);
|
||||
detailsCache.set(key, hit);
|
||||
if ((Date.now() - hit.ts) >= DETAILS_CACHE_TTL_MS) { detailsCache.delete(key); return null; }
|
||||
// TTL par provider (`DETAILS_CACHE_TTL_MS_<P>`) puis global, cf. env-ttl.mjs.
|
||||
// La clé est `${provider}:…` : le provider est le premier segment.
|
||||
const ttl = perProviderTtl('DETAILS_CACHE_TTL_MS', String(key).split(':')[0], DETAILS_CACHE_TTL_MS);
|
||||
if ((Date.now() - hit.ts) >= ttl) { detailsCache.delete(key); return null; }
|
||||
return hit.data;
|
||||
}
|
||||
function detailsCacheSet(key, data) {
|
||||
@@ -2855,7 +2859,9 @@ app.use('/api', r);
|
||||
// Health endpoint for container checks
|
||||
app.get('/api/health', (_req, res) => res.json({ status: 'ok' }));
|
||||
// Step 17 : observabilité YouTube (mode, yt-dlp, cache, quota). Aucun secret exposé.
|
||||
app.get(['/healthz', '/api/healthz'], async (_req, res) => {
|
||||
// Trois chemins, comme le router `r` : le front appelle `/proxy/api` en prod
|
||||
// (voir apiBase()), sans quoi healthz tomberait sur le fallback SPA → HTML.
|
||||
app.get(['/healthz', '/api/healthz', '/proxy/api/healthz'], async (_req, res) => {
|
||||
try {
|
||||
const [{ getYoutubeMetricsToday, countYoutubeCacheRows, searchCacheStats, providerMetricsSnapshot, countSearchCacheRows }, common] =
|
||||
await Promise.all([import('./db.mjs'), import('./providers/youtube-common.mjs')]);
|
||||
@@ -3345,7 +3351,10 @@ const transcriptCache = new Map();
|
||||
function transcriptCacheGet(key) {
|
||||
const hit = transcriptCache.get(key);
|
||||
if (!hit) return null;
|
||||
if ((Date.now() - hit.ts) >= TRANSCRIPT_CACHE_TTL_MS) {
|
||||
// TTL par provider (`TRANSCRIPT_CACHE_TTL_<P>`) puis global, cf. env-ttl.mjs.
|
||||
// Clé `transcript:<provider>:…` : le provider est le 2e segment.
|
||||
const ttl = perProviderTtl('TRANSCRIPT_CACHE_TTL', String(key).split(':')[1], TRANSCRIPT_CACHE_TTL_MS);
|
||||
if ((Date.now() - hit.ts) >= ttl) {
|
||||
transcriptCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
@@ -3853,6 +3862,83 @@ r.get('/playlists', authMiddlewareCookieAware, (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Export JSON des playlists de l'utilisateur (+ items).
|
||||
// DÉCLARÉ AVANT `/playlists/:id` : sinon « export » est avalé par le paramètre
|
||||
// :id et répond 404 not_found (matching Express séquentiel).
|
||||
r.get('/playlists/export', authMiddlewareCookieAware, (req, res) => {
|
||||
try {
|
||||
const rows = listPlaylists({ userId: req.user.id, limit: 1000, offset: 0 });
|
||||
const playlists = (rows || []).map((pl) => ({
|
||||
title: pl.title,
|
||||
description: pl.description || undefined,
|
||||
thumbnail: pl.thumbnail || undefined,
|
||||
isPrivate: !!pl.isPrivate,
|
||||
items: (listPlaylistItems({ playlistId: pl.id, limit: 5000, offset: 0 }) || []).map((it) => ({
|
||||
provider: it.provider,
|
||||
videoId: it.videoId,
|
||||
title: it.title || undefined,
|
||||
thumbnail: it.thumbnail || undefined,
|
||||
})),
|
||||
}));
|
||||
return res.json({
|
||||
app: 'newtube',
|
||||
format: 'newtube-playlists-v1',
|
||||
exportedAt: new Date().toISOString(),
|
||||
playlists,
|
||||
});
|
||||
} catch (e) {
|
||||
return res.status(500).json({ error: 'export_failed', details: String(e?.message || e) });
|
||||
}
|
||||
});
|
||||
|
||||
// Import JSON : crée les listes manquantes (même titre = déjà importée, non
|
||||
// recréée — réimporter le même fichier ne duplique rien), ajoute les vidéos.
|
||||
r.post('/playlists/import', authMiddlewareCookieAware, (req, res) => {
|
||||
try {
|
||||
const list = req.body?.playlists;
|
||||
if (!Array.isArray(list)) return res.status(400).json({ error: 'playlists_required' });
|
||||
if (list.length > 200) return res.status(400).json({ error: 'too_many_playlists' });
|
||||
const existing = new Set(listPlaylists({ userId: req.user.id, limit: 1000, offset: 0 }).map((p) => String(p.title || '').trim()));
|
||||
let created = 0, skippedLists = 0, itemsAdded = 0, itemsSkipped = 0;
|
||||
for (const raw of list) {
|
||||
const title = String(raw?.title || '').trim();
|
||||
if (!title) { skippedLists++; continue; }
|
||||
if (existing.has(title)) { skippedLists++; continue; } // déjà présente : pas de doublon au réimport
|
||||
let pl;
|
||||
try {
|
||||
pl = createPlaylist({
|
||||
userId: req.user.id,
|
||||
title,
|
||||
description: typeof raw?.description === 'string' ? raw.description : undefined,
|
||||
thumbnail: typeof raw?.thumbnail === 'string' ? raw.thumbnail : undefined,
|
||||
isPrivate: raw?.isPrivate !== false, // défaut privé (comme l'UI)
|
||||
});
|
||||
} catch { skippedLists++; continue; }
|
||||
existing.add(title);
|
||||
created++;
|
||||
const items = Array.isArray(raw?.items) ? raw.items.slice(0, 5000) : [];
|
||||
for (const it of items) {
|
||||
const provider = String(it?.provider || '').trim();
|
||||
const videoId = String(it?.videoId || '').trim();
|
||||
if (!provider || !videoId) { itemsSkipped++; continue; }
|
||||
const row = addPlaylistVideo({
|
||||
userId: req.user.id,
|
||||
playlistId: pl.id,
|
||||
provider,
|
||||
videoId,
|
||||
title: typeof it?.title === 'string' ? it.title : undefined,
|
||||
thumbnail: typeof it?.thumbnail === 'string' ? it.thumbnail : undefined,
|
||||
});
|
||||
if (row === 'not_found' || row === 'forbidden') itemsSkipped++;
|
||||
else itemsAdded++;
|
||||
}
|
||||
}
|
||||
return res.status(201).json({ created, skippedLists, itemsAdded, itemsSkipped });
|
||||
} catch (e) {
|
||||
return res.status(500).json({ error: 'import_failed', details: String(e?.message || e) });
|
||||
}
|
||||
});
|
||||
|
||||
// Get playlist details (owner only for now)
|
||||
r.get('/playlists/:id', authMiddlewareCookieAware, (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -397,18 +397,29 @@ async function ptContent(externalId, { type, page, limit, sort, q }) {
|
||||
nextPage: (data?.data || []).length >= perPage ? (page || 1) + 1 : null, total: data?.total ?? null,
|
||||
};
|
||||
}
|
||||
if (type === 'live' || type === 'shorts') return { items: [], nextPage: null };
|
||||
if (type === 'shorts') return { items: [], nextPage: null };
|
||||
// Live : l'API accepte `?isLive=true` sur les vidéos de chaîne (probe
|
||||
// 2026-10 : reconnu — isLive=false → 35 vidéos, true → 0 sur une chaîne
|
||||
// hors direct). Sans ce paramètre l'onglet Live retournait toujours [].
|
||||
const isLive = type === 'live';
|
||||
const qs = new URLSearchParams({ start: String(start), count: String(perPage), sort: sort === 'popular' ? '-views' : '-publishedAt' });
|
||||
if (isLive) qs.set('isLive', 'true');
|
||||
if (q) qs.set('search', q);
|
||||
const data = await readJson(await fetchWithTimeout(`https://${instance}/api/v1/video-channels/${encodeURIComponent(channel)}/videos?${qs}`));
|
||||
const items = (data?.data || []).map((v) => ({
|
||||
id: String(v.uuid || v.id), title: v.name, thumbnail: v?.thumbnailPath ? `https://${instance}${v.thumbnailPath}` : undefined,
|
||||
url: v?.url, uploaderName: v?.channel?.displayName || channel,
|
||||
channelId: externalId, channelExternalId: externalId,
|
||||
// Phase 2.2 - idem : jamais de 0 pour une durée/vues inconnues.
|
||||
...(Number(v.duration) > 0 ? { duration: Number(v.duration) } : {}),
|
||||
...(Number(v.views) > 0 ? { views: Number(v.views) } : {}), publishedAt: v.publishedAt, type: 'video',
|
||||
}));
|
||||
const items = (data?.data || []).map((v) => {
|
||||
const live = v.isLive === true;
|
||||
return {
|
||||
id: String(v.uuid || v.id), title: v.name, thumbnail: v?.thumbnailPath ? `https://${instance}${v.thumbnailPath}` : undefined,
|
||||
url: v?.url, uploaderName: v?.channel?.displayName || channel,
|
||||
channelId: externalId, channelExternalId: externalId,
|
||||
// Phase 2.2 - idem : jamais de 0 pour une durée/vues inconnues.
|
||||
// Direct : durée non émise (temps écoulé), spectateurs via `viewers`.
|
||||
...(!live && Number(v.duration) > 0 ? { duration: Number(v.duration) } : {}),
|
||||
...(Number(v.views) > 0 ? { views: Number(v.views) } : {}),
|
||||
publishedAt: v.publishedAt, type: live ? 'live' : 'video',
|
||||
...(live ? { kind: 'live', isLive: true, ...(Number(v.viewers) > 0 ? { viewers: Number(v.viewers) } : {}) } : {}),
|
||||
};
|
||||
});
|
||||
return { items, nextPage: items.length >= perPage ? (page || 1) + 1 : null, total: data?.total ?? null };
|
||||
}
|
||||
|
||||
@@ -445,20 +456,33 @@ async function odContent(externalId, { type, page, limit, sort, q }) {
|
||||
|
||||
// ---- Rumble : pas d'API publique -> recherche unifiée filtrée par chaîne ----
|
||||
async function ruContent(externalId, { type, page, limit, q }, ctx) {
|
||||
const needle = String(externalId || '').replace(/^@/, '').toLowerCase();
|
||||
// Predicate partagé vidéos / live : channelId (slug /c/<slug>) en priorité,
|
||||
// sinon acheminement large sur nom + chaîne + URL.
|
||||
const matchChannel = (r) => {
|
||||
if (r?.channelId && needle && String(r.channelId).toLowerCase() === needle) return true;
|
||||
const hay = `${r?.uploaderName || ''} ${r?.channelId || ''} ${r?.url || ''}`.toLowerCase();
|
||||
return !needle || hay.includes(needle);
|
||||
};
|
||||
if (type === 'live') {
|
||||
// Directs Rumble : la seule source publique est la page SSR
|
||||
// rumble.com/browse/live (le fetch /live de rumble.com est muré login).
|
||||
// ponytail: plafond — page 1 bornée à 50 directs ; une chaîne live mais
|
||||
// hors des 50 premières n'apparaît pas, monter la pagination si ça compte.
|
||||
const { scrapeRumbleList } = await import('./rumble.mjs');
|
||||
const list = await scrapeRumbleList({ page: 1, limit: 50, mode: 'live' });
|
||||
const items = (list?.items || []).filter(matchChannel).slice(0, Number(limit || 24));
|
||||
return { items, nextPage: null };
|
||||
}
|
||||
if (type !== 'videos') return { items: [], nextPage: null };
|
||||
const searchRegistry = ctx?.searchRegistry || ctx;
|
||||
const mod = searchRegistry?.ru;
|
||||
if (!mod || typeof mod.search !== 'function') return { items: [], nextPage: null };
|
||||
const needle = String(externalId || '').replace(/^@/, '').toLowerCase();
|
||||
// Phase 3.5 - filtre sur `channelId` en priorité : c'est l'identifiant
|
||||
// canonique extrait en phase 1.5, donc plus fiable qu'une comparaison de
|
||||
// sous-chaîne sur le nom ou l'URL.
|
||||
const results = await mod.search(q || needle || 'videos', { limit: 50, page: 1 });
|
||||
const items = (results || []).filter((r) => {
|
||||
if (r?.channelId && needle && String(r.channelId).toLowerCase() === needle) return true;
|
||||
const hay = `${r?.uploaderName || ''} ${r?.channelId || ''} ${r?.url || ''}`.toLowerCase();
|
||||
return !needle || hay.includes(needle);
|
||||
}).slice(0, Number(limit || 24));
|
||||
const items = (results || []).filter(matchChannel).slice(0, Number(limit || 24));
|
||||
return { items, nextPage: null };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,112 @@
|
||||
/**
|
||||
* Minimal PeerTube provider handler
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mapping d'une vidéo PeerTube vers le contrat `Suggestion`.
|
||||
* Exporté pour les tests : la règle « `isLive` → `type:'live'` + `kind:'live'` »
|
||||
* est le cœur de la capacité Live du provider ; sur un direct la durée (temps
|
||||
* écoulé, pas une longueur) n'est jamais émise, doctrine « jamais de 0 ».
|
||||
*
|
||||
* @param {any} item réponse brute de l'API PeerTube / sepiasearch
|
||||
* @returns {any} suggestion normalisée
|
||||
*/
|
||||
export function mapPeertubeItem(item) {
|
||||
const rawThumb = item.thumbnailUrl || item.thumbnailPath || '';
|
||||
const thumbnail = rawThumb
|
||||
? rawThumb.startsWith('http')
|
||||
? rawThumb
|
||||
: rawThumb.startsWith('//')
|
||||
? `https:${rawThumb}`
|
||||
: new URL(rawThumb, item.url || 'https://sepiasearch.org').toString()
|
||||
: undefined;
|
||||
// Dimensions max des fichiers (signal d'orientation pour isShortItem).
|
||||
// Défensif : sepiasearch n'expose pas toujours `files`.
|
||||
let fw = 0;
|
||||
let fh = 0;
|
||||
try {
|
||||
for (const f of (Array.isArray(item.files) ? item.files : [])) {
|
||||
const w = Number(f?.width);
|
||||
const h = Number(f?.height);
|
||||
if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 && w * h >= fw * fh) {
|
||||
fw = w;
|
||||
fh = h;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
const live = item.isLive === true;
|
||||
return {
|
||||
title: item.name,
|
||||
id: item.uuid,
|
||||
url: item.url,
|
||||
thumbnail,
|
||||
uploaderName: (item.account && (item.account.displayName || item.account.name)) || undefined,
|
||||
// Phase 1.8 - les avatars de compte ET de chaine sont exposes par
|
||||
// l'API sepiasearch mais n'etaient jamais mappes : la page chaine
|
||||
// affichait un avatar generique sur toutes les chaines PeerTube.
|
||||
uploaderAvatar: item.account?.avatars?.[0]?.path || item.account?.avatarUrl || undefined,
|
||||
channelAvatarUrl: item.channel?.avatars?.[0]?.path || item.channel?.avatarUrl || undefined,
|
||||
channelId: (item.channel && (item.channel.name || item.channel.uuid)) || (item.account && item.account.name) || undefined,
|
||||
// Phase 1.7 - champs deja presents dans la reponse, jamais mappes.
|
||||
// `views` est le nom canonique du contrat (les 5 autres adaptateurs
|
||||
// l'emettaient) ; `viewCount` reste en alias pour ne pas casser un
|
||||
// consommateur existant. Trouve en gelant la sortie reelle (phase 8.4) :
|
||||
// le front lisait `views`, le serveur n'envoyait que `viewCount`, et les
|
||||
// compteurs PeerTube n'atteignaient donc jamais l'UI.
|
||||
views: Number.isFinite(Number(item.views)) ? Number(item.views) : undefined,
|
||||
viewCount: Number.isFinite(Number(item.views)) ? Number(item.views) : undefined,
|
||||
likes: Number.isFinite(Number(item.likes)) ? Number(item.likes) : undefined,
|
||||
publishedAt: item.publishedAt || item.createdAt || undefined,
|
||||
// L'API PeerTube renvoie `language` comme OBJET `{ id, label }` (et non
|
||||
// `{ code }` comme le laissait croire l'ancienne garde) : sans ce
|
||||
// tri, l'objet entier partait dans le contrat, où `language` est
|
||||
// déclaré `string`. Le front recevait `{id: null, label: 'Unknown'}` au
|
||||
// lieu d'un code ISO. Vu en gelant la sortie réelle (phase 8.4).
|
||||
// `label` est volontairement exclu : c'est une étiquette lisible
|
||||
// ("Unknown") et non un code — la publier produirait une langue
|
||||
// inventée, que la règle « absent = undefined » interdit.
|
||||
language: typeof item.language === 'string' ? item.language
|
||||
: (item.language?.code || item.language?.id || undefined),
|
||||
hasSubtitles: Array.isArray(item.subtitleFiles) ? item.subtitleFiles.length > 0 : undefined,
|
||||
// Direct : `type`/`kind`/'isLive' posés ensemble (doctrine Twitch phase
|
||||
// 3.2 — un des trois seul ne passe ni `isLiveItem()` ni la classification).
|
||||
type: live ? 'live' : 'video',
|
||||
kind: live ? 'live' : 'vod',
|
||||
...(live ? {
|
||||
isLive: true,
|
||||
// `viewers` = spectateurs en direct (V2 du contrat), jamais des vues.
|
||||
...(Number(item.viewers) > 0 ? { viewers: Number(item.viewers) } : {}),
|
||||
} : {}),
|
||||
duration: !live && typeof item.duration === 'number' && item.duration > 0 ? Math.round(item.duration) : undefined,
|
||||
...(fw > 0 ? { width: fw } : {}),
|
||||
...(fh > 0 ? { height: fh } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const handler = {
|
||||
id: 'pt',
|
||||
label: 'PeerTube',
|
||||
/**
|
||||
* @param {string} q
|
||||
* @param {{ limit: number, page?: number }} opts
|
||||
* @param {{ limit: number, page?: number, filters?: { type?: string } }} opts
|
||||
* @returns {Promise<Array<any>>}
|
||||
*/
|
||||
async search(q, opts) {
|
||||
const { limit = 10, page = 1 } = opts || {};
|
||||
const { limit = 10, page = 1, filters } = opts || {};
|
||||
try {
|
||||
// Use PeerTube API search
|
||||
const params = new URLSearchParams({
|
||||
count: Math.min(limit, 50).toString(),
|
||||
start: Math.max(0, (Math.max(1, Number(page || 1)) - 1) * Math.min(limit, 50)).toString(),
|
||||
});
|
||||
// Filtre Live : `isLive` est un paramètre natif de l'API PeerTube
|
||||
// (openapi, /videos + /search/videos) ; sepiasearch l'applique aussi
|
||||
// (probe 2026-10 : `search=news&isLive=true` → 0, sans texte → 113 directs).
|
||||
if (filters?.type === 'live') params.set('isLive', 'true');
|
||||
if (q) params.set('search', q);
|
||||
const response = await fetch(
|
||||
`https://sepiasearch.org/api/v1/search/videos?` +
|
||||
new URLSearchParams({
|
||||
search: q,
|
||||
count: Math.min(limit, 50).toString(),
|
||||
start: Math.max(0, (Math.max(1, Number(page || 1)) - 1) * Math.min(limit, 50)).toString()
|
||||
})
|
||||
`https://sepiasearch.org/api/v1/search/videos?${params}`
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -28,70 +115,7 @@ const handler = {
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
return (data.data || []).map(item => {
|
||||
const rawThumb = item.thumbnailUrl || item.thumbnailPath || '';
|
||||
const thumbnail = rawThumb
|
||||
? rawThumb.startsWith('http')
|
||||
? rawThumb
|
||||
: rawThumb.startsWith('//')
|
||||
? `https:${rawThumb}`
|
||||
: new URL(rawThumb, item.url || 'https://sepiasearch.org').toString()
|
||||
: undefined;
|
||||
// Dimensions max des fichiers (signal d'orientation pour isShortItem).
|
||||
// Défensif : sepiasearch n'expose pas toujours `files`.
|
||||
let fw = 0;
|
||||
let fh = 0;
|
||||
try {
|
||||
for (const f of (Array.isArray(item.files) ? item.files : [])) {
|
||||
const w = Number(f?.width);
|
||||
const h = Number(f?.height);
|
||||
if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 && w * h >= fw * fh) {
|
||||
fw = w;
|
||||
fh = h;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
return {
|
||||
title: item.name,
|
||||
id: item.uuid,
|
||||
url: item.url,
|
||||
thumbnail,
|
||||
uploaderName: (item.account && (item.account.displayName || item.account.name)) || undefined,
|
||||
// Phase 1.8 - les avatars de compte ET de chaine sont exposes par
|
||||
// l'API sepiasearch mais n'etaient jamais mappes : la page chaine
|
||||
// affichait un avatar generique sur toutes les chaines PeerTube.
|
||||
uploaderAvatar: item.account?.avatars?.[0]?.path || item.account?.avatarUrl || undefined,
|
||||
channelAvatarUrl: item.channel?.avatars?.[0]?.path || item.channel?.avatarUrl || undefined,
|
||||
channelId: (item.channel && (item.channel.name || item.channel.uuid)) || (item.account && item.account.name) || undefined,
|
||||
// Phase 1.7 - champs deja presents dans la reponse, jamais mappes.
|
||||
// `views` est le nom canonique du contrat (les 5 autres adaptateurs
|
||||
// l'emettaient) ; `viewCount` reste en alias pour ne pas casser un
|
||||
// consommateur existant. Trouve en gelant la sortie reelle (phase 8.4) :
|
||||
// le front lisait `views`, le serveur n'envoyait que `viewCount`, et les
|
||||
// compteurs PeerTube n'atteignaient donc jamais l'UI.
|
||||
views: Number.isFinite(Number(item.views)) ? Number(item.views) : undefined,
|
||||
viewCount: Number.isFinite(Number(item.views)) ? Number(item.views) : undefined,
|
||||
likes: Number.isFinite(Number(item.likes)) ? Number(item.likes) : undefined,
|
||||
publishedAt: item.publishedAt || item.createdAt || undefined,
|
||||
// L'API PeerTube renvoie `language` comme OBJET `{ id, label }` (et non
|
||||
// `{ code }` comme le laissait croire l'ancienne garde) : sans ce
|
||||
// tri, l'objet entier partait dans le contrat, où `language` est
|
||||
// déclaré `string`. Le front recevait `{id: null, label: 'Unknown'}`
|
||||
// au lieu d'un code ISO. Vu en gelant la sortie réelle (phase 8.4).
|
||||
// `label` est volontairement exclu : c'est une étiquette lisible
|
||||
// ("Unknown") et non un code — la publier produirait une langue
|
||||
// inventée, ce que la règle « absent = undefined » interdit.
|
||||
language: typeof item.language === 'string' ? item.language
|
||||
: (item.language?.code || item.language?.id || undefined),
|
||||
hasSubtitles: Array.isArray(item.subtitleFiles) ? item.subtitleFiles.length > 0 : undefined,
|
||||
type: 'video',
|
||||
kind: 'vod',
|
||||
duration: typeof item.duration === 'number' && item.duration > 0 ? Math.round(item.duration) : undefined,
|
||||
...(fw > 0 ? { width: fw } : {}),
|
||||
...(fh > 0 ? { height: fh } : {}),
|
||||
};
|
||||
});
|
||||
return (data.data || []).map(mapPeertubeItem);
|
||||
} catch (error) {
|
||||
console.error('PeerTube search error:', error);
|
||||
return [];
|
||||
|
||||
@@ -102,9 +102,9 @@ export const PROVIDER_CAPABILITIES = {
|
||||
yt: { suggest: true, live: false, channelMeta: true, channelContent: ['videos', 'shorts', 'playlists', 'live'] },
|
||||
dm: { suggest: true, live: false, channelMeta: true, channelContent: ['videos', 'playlists'] },
|
||||
tw: { suggest: false, live: true, channelMeta: true, channelContent: ['videos', 'live'] },
|
||||
pt: { suggest: false, live: false, channelMeta: true, channelContent: ['videos', 'playlists'] },
|
||||
pt: { suggest: false, live: true, channelMeta: true, channelContent: ['videos', 'playlists', 'live'] },
|
||||
od: { suggest: false, live: false, channelMeta: true, channelContent: ['videos'] },
|
||||
ru: { suggest: false, live: false, channelMeta: true, channelContent: ['videos'] },
|
||||
ru: { suggest: false, live: true, channelMeta: true, channelContent: ['videos', 'live'] },
|
||||
};
|
||||
|
||||
/** Ordre canonique des providers (un unique endroit, hors route). */
|
||||
|
||||
@@ -612,13 +612,14 @@ export async function scrapeRumbleVideo(videoIdOrUrl) {
|
||||
* `parseSearchHtml` (structurel + JSON-LD), via le registre.
|
||||
*
|
||||
* @param {string} html
|
||||
* @param {{ mode?: 'browse'|'shorts' }} [opts]
|
||||
* @param {{ mode?: 'browse'|'shorts'|'live' }} [opts]
|
||||
* @returns {Array<any>} items non bornés (le dédoublonnage et la limite sont
|
||||
* appliqués par `scrapeRumbleList`, pour ne jamais couper avant dédup).
|
||||
*/
|
||||
export function parseCardsHtml(html, { mode = 'browse' } = {}) {
|
||||
const $ = load(html);
|
||||
const isShortsMode = mode === 'shorts';
|
||||
const isLiveMode = mode === 'live';
|
||||
const found = [];
|
||||
const linkSelector = isShortsMode
|
||||
? 'a[href*="/shorts/v"], a[href^="/v"], a[href^="/video/"]'
|
||||
@@ -695,6 +696,11 @@ export function parseCardsHtml(html, { mode = 'browse' } = {}) {
|
||||
const views = parseRumbleViews(viewsText);
|
||||
|
||||
const uploaderName = card.find('.video-item--channel, .channel-name, a[href^="/c/"], a[href^="/user/"]').first().text().replace(/\s+/g, ' ').trim() || undefined;
|
||||
// Slug de chaîne (`/c/<slug>`) : même extraction que `parseSearchHtml`
|
||||
// (ligne auteurUrl) — indispensable au filtre par chaîne du branch
|
||||
// « live » de channel-content, les cartes n'ayant pas de channelId sinon.
|
||||
const channelHref = (card.find('a[href^="/c/"], a[href^="/user/"]').first().attr('href') || '').split('?')[0];
|
||||
const channelId = (channelHref.match(/\/c\/([^/?#]+)/i)?.[1] || '').trim() || undefined;
|
||||
|
||||
// On renvoie TOUJOURS une URL canonique cohérente.
|
||||
let videoId = null;
|
||||
@@ -719,9 +725,15 @@ export function parseCardsHtml(html, { mode = 'browse' } = {}) {
|
||||
// de durée est absent du HTML (la durée reste la source de vérité).
|
||||
// `== null` : une durée absente vaut undefined (contrat « jamais 0 ») et
|
||||
// doit rester acceptée par le flux Shorts, comme l'ancien 0 le faisait.
|
||||
isShort: isShortsMode ? (durationSeconds == null || durationSeconds <= 90) : (durationSeconds > 0 && durationSeconds <= 75),
|
||||
// Mode "live" (rumble.com/browse/live) : tout ce qui sort de cette page
|
||||
// EST en direct — `type/isLive` posés ici, jamais un Short (durée du
|
||||
// direct = temps écoulé, pas une longueur de vidéo).
|
||||
isShort: isLiveMode ? false
|
||||
: isShortsMode ? (durationSeconds == null || durationSeconds <= 90) : (durationSeconds > 0 && durationSeconds <= 75),
|
||||
url,
|
||||
type: 'video',
|
||||
type: isLiveMode ? 'live' : 'video',
|
||||
...(isLiveMode ? { kind: 'live', isLive: true } : {}),
|
||||
...(channelId ? { channelId } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -743,7 +755,8 @@ export function parseCardsHtml(html, { mode = 'browse' } = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pages liste hors recherche : /videos?sort=… (browse) et /shorts.
|
||||
* Pages liste hors recherche : /videos?sort=… (browse), /shorts et
|
||||
* /browse/live (directs — SSR, liens /vXXXX identiques au browse).
|
||||
* Envelope { items, total, page, limit, nextCursor } identique à l'ancien
|
||||
* routeur. Un blocage CF → throw 503 (le front dégrade en `items: []`,
|
||||
* le bandeau « bloqué temporairement » vient de /api/search).
|
||||
@@ -753,7 +766,9 @@ export async function scrapeRumbleList({ page = 1, limit = 24, sort = 'viral', m
|
||||
const limitNum = Math.min(50, Math.max(1, Number(limit) || 24));
|
||||
const url = mode === 'shorts'
|
||||
? `https://rumble.com/shorts?page=${pageNum}`
|
||||
: `https://rumble.com/videos?sort=${encodeURIComponent(String(sort))}&page=${pageNum}`;
|
||||
: mode === 'live'
|
||||
? `https://rumble.com/browse/live?page=${pageNum}`
|
||||
: `https://rumble.com/videos?sort=${encodeURIComponent(String(sort))}&page=${pageNum}`;
|
||||
const r = await fetchHtml(url);
|
||||
if (!r || isChallenge(r.html)) throw rumbleFail('rumble_cloudflare_challenge', 503);
|
||||
if (r.status !== 200) throw rumbleFailureForStatus(r.status);
|
||||
|
||||
@@ -107,6 +107,28 @@ router.get('/shorts', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/rumble/live?page=&limit=
|
||||
* Directs en cours (rumble.com/browse/live, SSR) : IDs /vXXXX propres,
|
||||
* items marqués `type:'live'` par `parseCardsHtml` (mode live).
|
||||
*/
|
||||
router.get('/live', async (req, res) => {
|
||||
const page = Math.max(1, parseInt(String(req.query.page || '1'), 10) || 1);
|
||||
const limit = Math.min(50, Math.max(1, parseInt(String(req.query.limit || '24'), 10) || 24));
|
||||
|
||||
const key = cacheKey('/live', { page, limit });
|
||||
const cached = getCache(key);
|
||||
if (cached) return res.json(cached);
|
||||
|
||||
try {
|
||||
const data = await scrapeRumbleList({ page, limit, mode: 'live' });
|
||||
setCache(key, data);
|
||||
return res.json(data);
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
// Recherche : même adaptateur (et donc même cache SQLite, negative cache et
|
||||
// channelRef) que le groupe `ru` de la recherche unifiée.
|
||||
router.get('/search', async (req, res) => {
|
||||
|
||||
@@ -62,7 +62,12 @@ describe('Phase 8.1 — contrat unique ProviderAdapter', () => {
|
||||
assert.ok(caps.channelContent.every((t) => ['videos', 'shorts', 'playlists', 'live'].includes(t)),
|
||||
'types de contenu dans le vocabulaire connu');
|
||||
assert.equal(caps.suggest, typeof a.suggest === 'function', 'suggest déclaré ⟺ suggest fourni');
|
||||
assert.equal(caps.live, pid === 'tw', 'seul Twitch est live (fait observable)');
|
||||
// Sources live réelles : Twitch (Helix /streams), PeerTube (?isLive=true,
|
||||
// channel-content + recherche), Rumble (rumble.com/browse/live). YouTube
|
||||
// sert ses lives via channelContent eventType mais garde live:false
|
||||
// (historique : le flag n'a jamais servi yt) — on ne bouge pas un fait
|
||||
// observable hors périmètre.
|
||||
assert.equal(caps.live, ['tw', 'pt', 'ru'].includes(pid), 'seuls tw/pt/ru déclarent live');
|
||||
});
|
||||
|
||||
it(`${pid}: search du contrat EST la recherche enveloppée (cache → ref → provenance)`, () => {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// TTL de cache par provider (server/env-ttl.mjs) — priorité
|
||||
// `<BASE>_<PROVIDER>` → `<BASE>` → défaut, valeurs invalides ignorées.
|
||||
import { perProviderTtl } from '../env-ttl.mjs';
|
||||
|
||||
let pass = 0;
|
||||
const eq = (a, b, m) => {
|
||||
const x = JSON.stringify(a), y = JSON.stringify(b);
|
||||
if (x !== y) throw new Error(`${m}\n expected ${y}\n got ${x}`);
|
||||
pass++; console.log(` V ${m}`);
|
||||
};
|
||||
|
||||
const BASE = 'TESTCACHE_TTL_MS';
|
||||
const cleanup = () => {
|
||||
delete process.env[BASE];
|
||||
delete process.env[`${BASE}_YT`];
|
||||
delete process.env[`${BASE}_ODYSEE`];
|
||||
delete process.env[`${BASE}_BAD`];
|
||||
};
|
||||
|
||||
// 1. Défaut seul
|
||||
cleanup();
|
||||
eq(perProviderTtl(BASE, 'yt', 60000), 60000, 'sans env -> défaut');
|
||||
|
||||
// 2. Base globale
|
||||
process.env[BASE] = '30000';
|
||||
eq(perProviderTtl(BASE, 'yt', 60000), 30000, 'base globale prise');
|
||||
eq(perProviderTtl(BASE, 'ru', 60000), 30000, 'base globale valable pour tout provider');
|
||||
|
||||
// 3. Provider l'emporte sur la base
|
||||
process.env[`${BASE}_YT`] = '1000';
|
||||
eq(perProviderTtl(BASE, 'yt', 60000), 1000, 'spécifique provider prioritaire');
|
||||
eq(perProviderTtl(BASE, 'ru', 60000), 30000, 'les autres providers gardent la base');
|
||||
|
||||
// 4. id long normalisé (ODYSEE depuis 'odysee')
|
||||
process.env[`${BASE}_ODYSEE`] = '500';
|
||||
eq(perProviderTtl(BASE, 'odysee', 60000), 500, 'id long -> suffixe MAJUSCULE');
|
||||
|
||||
// 5. Valeurs invalides ignorées (jamais de TTL négatif/nul/NaN)
|
||||
process.env[`${BASE}_BAD`] = 'abc';
|
||||
eq(perProviderTtl(BASE, 'bad', 60000), 30000, 'suffixe non numérique ignore -> base');
|
||||
process.env[`${BASE}_YT`] = '0';
|
||||
eq(perProviderTtl(BASE, 'yt', 60000), 30000, 'suffixe 0 ignore (TTL nul interdit)');
|
||||
delete process.env[BASE];
|
||||
process.env[`${BASE}_YT`] = 'garbage';
|
||||
eq(perProviderTtl(BASE, 'yt', 60000), 60000, 'base invalide -> défaut');
|
||||
|
||||
// 6. Provider absent / vide
|
||||
delete process.env[`${BASE}_YT`];
|
||||
eq(perProviderTtl(BASE, '', 60000), 60000, 'provider vide -> défaut');
|
||||
|
||||
cleanup();
|
||||
console.log(`\nOK ${pass} assertions`);
|
||||
@@ -0,0 +1,73 @@
|
||||
// Live PeerTube + Rumble — capacité « direct » testée hors réseau.
|
||||
// - mapPeertubeItem : règle `isLive` → type/kind/isLive (doctrine phase 3.2),
|
||||
// durée jamais émise sur un direct, viewers = spectateurs.
|
||||
// - parseCardsHtml mode 'live' : items de rumble.com/browse/live typés live,
|
||||
// jamais des Shorts, slug de chaîne extrait (filtre channel-content).
|
||||
import { mapPeertubeItem } from '../providers/peertube.mjs';
|
||||
import { parseCardsHtml } from '../providers/rumble.mjs';
|
||||
import { isLiveItem, isShortItem } from '../search-filters.mjs';
|
||||
|
||||
let pass = 0;
|
||||
const eq = (a, b, m) => {
|
||||
const x = JSON.stringify(a), y = JSON.stringify(b);
|
||||
if (x !== y) throw new Error(`${m}\n expected ${y}\n got ${x}`);
|
||||
pass++; console.log(` V ${m}`);
|
||||
};
|
||||
|
||||
// --- PeerTube : item en direct ---
|
||||
const live = mapPeertubeItem({
|
||||
uuid: 'u1', name: 'Direct', url: 'https://instance/w/u1',
|
||||
isLive: true, viewers: 42, duration: 123, views: 5,
|
||||
account: { displayName: 'A' }, channel: { name: 'ch' },
|
||||
});
|
||||
eq(live.type, 'live', 'PT live: type live');
|
||||
eq(live.kind, 'live', 'PT live: kind live');
|
||||
eq(live.isLive, true, 'PT live: isLive posé');
|
||||
eq(live.duration, undefined, 'PT live: durée jamais émise (temps écoulé)');
|
||||
eq(live.viewers, 42, 'PT live: viewers = spectateurs');
|
||||
eq(live.views, 5, 'PT live: vues conservées (live a les deux compteurs)');
|
||||
eq(isLiveItem(live), true, 'isLiveItem serveur le classe live');
|
||||
eq(isShortItem(live, 'peertube'), false, 'un direct n’est jamais un Short');
|
||||
|
||||
// --- PeerTube : VOD classique inchangée ---
|
||||
const vod = mapPeertubeItem({ uuid: 'u2', name: 'Vid', duration: 123, isLive: false });
|
||||
eq(vod.type, 'video', 'PT vod: type video');
|
||||
eq(vod.kind, 'vod', 'PT vod: kind vod');
|
||||
eq(vod.duration, 123, 'PT vod: durée conservée');
|
||||
eq(vod.isLive, undefined, 'PT vod: pas de champ isLive inventé');
|
||||
eq(isLiveItem(vod), false, 'PT vod n’est pas live');
|
||||
|
||||
// --- Rumble : mode live sur une carte type browse ---
|
||||
const html = `<html><body><ul>
|
||||
<li class="video-listing-entry">
|
||||
<a class="video-item--a" href="/v9z1live-title.html?e9s=track"></a>
|
||||
<h3 class="video-item--title">Live title</h3>
|
||||
<a href="/c/WarRoom">War Room</a>
|
||||
<img data-src="https://cdn.example/t.jpg" />
|
||||
</li>
|
||||
<li class="video-listing-entry">
|
||||
<a class="video-item--a" href="/v8y2other.html"></a>
|
||||
<h3 class="video-item--title">Autre titre</h3>
|
||||
<a href="/c/OtherChan">Other</a>
|
||||
</li>
|
||||
</ul></body></html>`;
|
||||
|
||||
const items = parseCardsHtml(html, { mode: 'live' });
|
||||
eq(items.length, 2, 'mode live: 2 cartes parsées');
|
||||
const [i1] = items;
|
||||
eq(i1.videoId, 'v9z1live', 'mode live: id extrait au slug');
|
||||
eq(i1.type, 'live', 'mode live: type live');
|
||||
eq(i1.kind, 'live', 'mode live: kind live');
|
||||
eq(i1.isLive, true, 'mode live: isLive posé');
|
||||
eq(i1.isShort, false, 'mode live: jamais un Short');
|
||||
eq(i1.channelId, 'WarRoom', 'mode live: slug de chaîne extrait');
|
||||
eq(isLiveItem(i1), true, 'mode live passe isLiveItem');
|
||||
|
||||
// --- Même HTML en mode browse : tout reste une VOD (pas de régression) ---
|
||||
const browse = parseCardsHtml(html, { mode: 'browse' });
|
||||
eq(browse[0].type, 'video', 'mode browse: type video (pas de fuite live)');
|
||||
eq(browse[0].isLive, undefined, 'mode browse: pas de isLive inventé');
|
||||
eq(browse[0].isShort, false, 'mode browse: durée inconnue => pas short');
|
||||
eq(browse[0].channelId, 'WarRoom', 'mode browse: channelId extrait (additif)');
|
||||
|
||||
console.log(`\nOK ${pass} assertions`);
|
||||
Reference in New Issue
Block a user