` → `` → défaut, valeurs invalides ignorées, jamais de TTL nul) branché sur les caches **details** (`DETAILS_CACHE_TTL_MS_`) et **transcripts** (`TRANSCRIPT_CACHE_TTL_
`) en plus de la recherche (`SEARCH_CACHE_TTL_MS_
`). Le cache **suggest** reste global par conception : sa clé agrégée couvre plusieurs providers d'un coup, un TTL par provider demanderait de scinder le cache. Tests : `npm run test:cache`
### 🟡 Partiellement livré
* 🟡 **Tags** — ✅ tables `tags` / `video_tags` (stockage des listes « Aimés » et « À regarder plus tard », recherche serveur dans ces listes) ; ⏳ tags **libres** créés par l'utilisateur sur n'importe quelle vidéo + recherche de vidéos par tag
-* 🟡 **Observabilité** — ✅ `GET /healthz` (mode `YT_SEARCH_MODE`, binaire yt-dlp, cache, quota du jour, clés masquées — testé par `test:api`) + `GET /api/providers/metrics` ; ⏳ page **Admin** (clés OK/KO, logs, versions) + exposition métriques au format Prometheus
-* 🟡 **Cache serveur configurable** — ✅ TTL réglable par variable d'environnement sur **tous** les caches, la recherche étant déjà **par provider** (`SEARCH_CACHE_TTL_MS_` / `SEARCH_CACHE_TTL_MS_DEFAULT`), plus `YT_CACHE_TTL_MS`, `YT_RELATED_TTL_MS`, `DETAILS_CACHE_TTL_MS`, `TRANSCRIPT_CACHE_TTL`, `SUGGEST_CACHE_TTL_MS`, `CHANNEL_TTL_MS` ; ⏳ étendre le TTL **par provider** aux caches details / transcripts / suggest (aujourd'hui un seul TTL global chacun)
+* 🟡 **Observabilité** — ✅ `GET /healthz` (mode `YT_SEARCH_MODE`, binaire yt-dlp, cache, quota du jour, clés masquées — testé par `test:api`), `GET /api/providers/metrics` et la **page Admin** qui les rend (voir ✅) ; ⏳ journaux (aucun endpoint de logs aujourd'hui) + exposition métriques au format Prometheus
* 🟡 **Qualité vidéo** — ✅ sélecteur de qualité sur `/#/watch` (formats yt-dlp, tri décroissant `1080p → 144p`, reprise de la lecture sur le flux choisi) ; ⏳ mode **« auto » intelligent** (choix automatique du flux selon la bande passante)
* 🟡 **Traduction UI (i18n)** — ✅ socle FR/EN (`src/services/i18n.service.ts`, chaque clé déclarée des deux côtés) couvrant barre de recherche, barre de filtres, pages thèmes ; ⏳ couverture **élargie** aux écrans encore en texte FR hardcodé (`/watch`, `/shorts`, bibliothèque)
### ⏳ Pas encore démarré
-* ⏳ **Import/Export** playlists (JSON / OPML-like)
* ⏳ **PWA** (installable, offline cache des métadonnées)
* ⏳ **Chromecast / AirPlay**
* ⏳ Mode **« TV »**
* ⏳ **Theming avancé** (polices, densité, accents)
-* ⏳ **Fournisseurs existants — lacunes à combler** (détail dans la matrice en haut) : lecture **Live** sur PeerTube, Odysee, Rumble ; **playlists natives** (synchro côté fournisseur) pour Dailymotion, Twitch, PeerTube, Odysee, Rumble
+* ⏳ **Playlists natives Dailymotion & PeerTube** (les 3 autres fournisseurs sont en **N/A** — voir la matrice : API Twitch supprimée, Odysee/Rumble sans API d'écriture) : inscription d'app OAuth Dailymotion, JWT par instance PeerTube
+* ⏳ **Logs & Prometheus** (volet restant de l'Observabilité — la page Admin est livrée)
* ⏳ **Nouveaux fournisseurs** — plan détaillé ci-dessous
### 🆕 Nouveaux fournisseurs — plan d'implémentation
diff --git a/package.json b/package.json
index 55eed04..10c86b3 100644
--- a/package.json
+++ b/package.json
@@ -27,8 +27,9 @@
"fixtures:record": "node ./server/tests/record_provider_shapes.mjs",
"doc:providers": "node ./server/tests/generate-provider-doc.mjs",
"test:rumble": "node ./server/tests/rumble-ld.test.mjs",
+ "test:live": "node ./server/tests/live_providers.test.mjs",
"test:odysee": "node ./server/tests/odysee-resolve.test.mjs",
- "test:cache": "node ./server/tests/search-cache.test.mjs",
+ "test:cache": "node ./server/tests/search-cache.test.mjs && node ./server/tests/env_ttl.test.mjs",
"test:videos": "node ./server/tests/videos_catalog.test.mjs",
"test:channelref": "node ./server/tests/channel_ref.test.mjs",
"test:flags": "node --test ./server/tests/contract_version.test.mjs ./server/tests/feature_flags_http.test.mjs",
diff --git a/server/env-ttl.mjs b/server/env-ttl.mjs
new file mode 100644
index 0000000..aeb98b2
--- /dev/null
+++ b/server/env-ttl.mjs
@@ -0,0 +1,29 @@
+/**
+ * TTL de cache par provider — modèle identique à `SEARCH_CACHE_TTL_MS_`
+ * (server/db.mjs) étendu aux caches mémoire de index.mjs.
+ *
+ * Priorité : `_` (ex. `DETAILS_CACHE_TTL_MS_YT`) →
+ * `` (`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;
+}
diff --git a/server/index.mjs b/server/index.mjs
index 9ca4cc0..51085f5 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -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_`) 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_
`) puis global, cf. env-ttl.mjs.
+ // Clé `transcript::…` : 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 {
diff --git a/server/providers/channel-content.mjs b/server/providers/channel-content.mjs
index ff1c8d8..3121254 100644
--- a/server/providers/channel-content.mjs
+++ b/server/providers/channel-content.mjs
@@ -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/) 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 };
}
diff --git a/server/providers/peertube.mjs b/server/providers/peertube.mjs
index 6f3dbcb..728f458 100644
--- a/server/providers/peertube.mjs
+++ b/server/providers/peertube.mjs
@@ -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>}
*/
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 [];
diff --git a/server/providers/registry.mjs b/server/providers/registry.mjs
index cbf68e9..6d3453d 100644
--- a/server/providers/registry.mjs
+++ b/server/providers/registry.mjs
@@ -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). */
diff --git a/server/providers/rumble.mjs b/server/providers/rumble.mjs
index ae48459..77a8e0d 100644
--- a/server/providers/rumble.mjs
+++ b/server/providers/rumble.mjs
@@ -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} 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/`) : 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);
diff --git a/server/rumble.mjs b/server/rumble.mjs
index faf25a1..19a77d6 100644
--- a/server/rumble.mjs
+++ b/server/rumble.mjs
@@ -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) => {
diff --git a/server/tests/adapter_contract.test.mjs b/server/tests/adapter_contract.test.mjs
index 45423fb..2dafe72 100644
--- a/server/tests/adapter_contract.test.mjs
+++ b/server/tests/adapter_contract.test.mjs
@@ -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)`, () => {
diff --git a/server/tests/env_ttl.test.mjs b/server/tests/env_ttl.test.mjs
new file mode 100644
index 0000000..61c220f
--- /dev/null
+++ b/server/tests/env_ttl.test.mjs
@@ -0,0 +1,52 @@
+// TTL de cache par provider (server/env-ttl.mjs) — priorité
+// `_` → `` → 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`);
diff --git a/server/tests/live_providers.test.mjs b/server/tests/live_providers.test.mjs
new file mode 100644
index 0000000..ba45fa4
--- /dev/null
+++ b/server/tests/live_providers.test.mjs
@@ -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 = ``;
+
+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`);
diff --git a/src/app.routes.ts b/src/app.routes.ts
index f977d43..0a8f226 100644
--- a/src/app.routes.ts
+++ b/src/app.routes.ts
@@ -136,5 +136,10 @@ export const APP_ROUTES: Routes = [
loadComponent: () => import('./components/info/utilisation/utilisation.component').then(m => m.UtilisationComponent),
title: 'NewTube - Utilisation'
},
+ {
+ path: 'admin',
+ loadComponent: () => import('./components/admin/admin.component').then(m => m.AdminComponent),
+ title: 'NewTube - Administration'
+ },
{ path: '**', redirectTo: '' }
];
diff --git a/src/app/shared/providers/provider-capabilities.ts b/src/app/shared/providers/provider-capabilities.ts
index 52b7f60..cee7fb6 100644
--- a/src/app/shared/providers/provider-capabilities.ts
+++ b/src/app/shared/providers/provider-capabilities.ts
@@ -44,18 +44,21 @@ export interface ProviderCapabilities {
* yt : 4 onglets (scrape yt-dlp + Data API v3)
* dm : vidéos + playlists (`/user/{u}/playlists`) — PAS de shorts ni live
* tw : vidéos (VOD) + live (`/streams`) — PAS de playlists ni shorts
- * pt : vidéos + playlists (`/video-playlists`) — PAS DE live (l'API l'expose
- * via `?isLive=true` mais ce n'est pas câblé : cf. anomalie #5 du doc)
- * od : vidéos uniquement (le handler ne traite que `type === 'videos'`)
- * ru : vidéos uniquement (délégation à la recherche globale + filtre client)
+ * pt : vidéos + playlists (`/video-playlists`) + live (`?isLive=true`, API
+ * native sur les vidéos de chaîne ET sur la recherche sepiasearch)
+ * od : vidéos uniquement (le handler ne traite que `type === 'videos'` ;
+ * pas de direct non plus : les lives Odysee ne sont exposés par aucune
+ * API publique — proxy na-backend requiert un jeton, probe 2026-10)
+ * ru : vidéos (délégation à la recherche globale + filtre client) + live
+ * (page SSR rumble.com/browse/live — /live direct est muré login)
*/
export const PROVIDER_CAPABILITIES: Readonly> = {
yt: { search: true, videos: true, shorts: true, live: true, playlists: true, about: true, searchInChannel: true },
dm: { search: true, videos: true, shorts: false, live: false, playlists: true, about: true, searchInChannel: true },
tw: { search: true, videos: true, shorts: false, live: true, playlists: false, about: true, searchInChannel: true },
- pt: { search: true, videos: true, shorts: false, live: false, playlists: true, about: true, searchInChannel: true },
+ pt: { search: true, videos: true, shorts: false, live: true, playlists: true, about: true, searchInChannel: true },
od: { search: true, videos: true, shorts: false, live: false, playlists: false, about: true, searchInChannel: true },
- ru: { search: true, videos: true, shorts: false, live: false, playlists: false, about: true, searchInChannel: true },
+ ru: { search: true, videos: true, shorts: false, live: true, playlists: false, about: true, searchInChannel: true },
};
/** Projection vers l'ancienne forme `supports` du registre front (compat). */
diff --git a/src/components/admin/admin.component.ts b/src/components/admin/admin.component.ts
new file mode 100644
index 0000000..fc1b3e6
--- /dev/null
+++ b/src/components/admin/admin.component.ts
@@ -0,0 +1,218 @@
+import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { HttpClient } from '@angular/common/http';
+
+/**
+ * Page Administration — /admin.
+ *
+ * Aucune logique métier : deux lectures (déjà publiques côté API) rendues
+ * lisibles. `/healthz` fournit statut / mode YouTube / yt-dlp / clés ;
+ * `/providers/metrics` le cache de recherche et les compteurs 1 h par
+ * fournisseur. Pas de journaux ici (aucun endpoint de logs) : c'est le
+ * volet restant de « Observabilité » côté README.
+ */
+@Component({
+ selector: 'app-admin',
+ standalone: true,
+ imports: [CommonModule],
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ template: `
+
+
+
Administration
+
+ Actualisé {{ refreshAt() }}
+
+
+
+
+
{{ error() }}
+
+
+
+
+
+
+ Général
+
+
+
- Statut API
+ - {{ health()?.status || '—' }}
+
+
+
- Mode YouTube
+ - {{ health()?.youtube?.effectiveMode || health()?.youtube?.mode || '—' }}
+
+
+
- yt-dlp
+ -
+ {{ ytDlpLabel() }}
+
+
+
+
- Cache YouTube (SQLite)
+ - {{ health()?.youtube?.cache?.sqliteRows ?? '—' }} lignes
+
+
+
- Cache de recherche
+ - {{ health()?.providers?.cache?.rows ?? '—' }} lignes
+
+
+
+
+
+
+ Clés & anti-ban YouTube
+
+
+
- Clés actives
+ - {{ keysOk() }}
+
+
+
- Clés bannies
+ - 0" [class.text-slate-200]="bannedKeys().length === 0">{{ bannedKeys().length }}
+
+
+
- Bannie
+ - {{ b }}
+
+
+
- Cookies / PO token / proxy
+ - {{ antibanLabel() }}
+
+
+
+
+
+
+ Fournisseurs (1 h)
+ Aucun appel récent.
+
+
+
+ | Provider |
+ Appels |
+ OK |
+ Erreurs |
+ Latence |
+
+
+
+
+ | {{ row.provider }} |
+ {{ row.calls }} |
+ {{ row.ok }} |
+ 0" [class.text-slate-200]="row.errors === 0">{{ row.errors }} |
+ {{ row.avgLatencyMs }} ms |
+
+
+
+
+
+
+
+ Cache de recherche par provider
+ Cache vide.
+
+
+
+ | Provider |
+ Entrées |
+ Hits |
+ Taux |
+
+
+
+
+ | {{ row.provider }} |
+ {{ row.entries }} |
+ {{ row.hits }} |
+ {{ (row.hitRate * 100) | number:'1.0-0' }} % |
+
+
+
+ YouTube aujourd'hui
+
+ {{ ytToday()?.scrape_calls ?? 0 }} scrapes · {{ ytToday()?.api_calls ?? 0 }} appels API ·
+ {{ ytToday()?.quota_units ?? 0 }} unités de quota
+
+
+
+
+ `,
+})
+export class AdminComponent {
+ private http = inject(HttpClient);
+
+ loading = signal(true);
+ error = signal(null);
+ health = signal(null);
+ metrics = signal(null);
+ refreshAt = signal('');
+
+ constructor() {
+ this.load();
+ }
+
+ private apiBase(): string {
+ try {
+ const port = window?.location?.port || '';
+ return port && port !== '4000' ? '/proxy/api' : '/api';
+ } catch { return '/api'; }
+ }
+
+ load(): void {
+ this.loading.set(true);
+ this.error.set(null);
+ let pending = 2;
+ const done = () => {
+ if (--pending > 0) return;
+ this.loading.set(false);
+ this.refreshAt.set(new Date().toLocaleTimeString());
+ };
+ this.http.get(`${this.apiBase()}/healthz`, { withCredentials: true }).subscribe({
+ next: (v) => { this.health.set(v); done(); },
+ error: (e) => { this.error.set(`healthz : ${e?.error?.error || e?.message || 'erreur'}`); done(); },
+ });
+ this.http.get(`${this.apiBase()}/providers/metrics`, { withCredentials: true }).subscribe({
+ next: (v) => { this.metrics.set(v); done(); },
+ error: (e) => { this.error.set(`metrics : ${e?.error?.error || e?.message || 'erreur'}`); done(); },
+ });
+ }
+
+ ytDlpLabel(): string {
+ const y = this.health()?.youtube?.ytdlp;
+ if (!y) return '—';
+ return `${y.version || 'version inconnue'}${y.binOk === false ? ' (binaire KO)' : ''}`;
+ }
+
+ keysOk(): number {
+ const k = this.health()?.youtube?.keys;
+ if (!k) return 0;
+ return Math.max(0, Number(k.count || 0) - (k.banned || []).length);
+ }
+
+ bannedKeys(): string[] {
+ return this.health()?.youtube?.keys?.banned || [];
+ }
+
+ antibanLabel(): string {
+ const a = this.health()?.youtube?.antiban;
+ if (!a) return '—';
+ return `${a.cookiesFile ? 'cookies' : 'sans cookies'} / ${a.poToken ? 'po-token' : 'sans po-token'} / ${a.egressProxy ? 'proxy' : 'sans proxy'}`;
+ }
+
+ providerRows(): any[] {
+ return this.metrics()?.providers || [];
+ }
+
+ cacheRows(): any[] {
+ return this.metrics()?.cache || [];
+ }
+
+ ytToday(): any {
+ return this.metrics()?.youtube?.today || null;
+ }
+}
diff --git a/src/components/library/playlists/playlists.component.html b/src/components/library/playlists/playlists.component.html
index 9d11acf..b446839 100644
--- a/src/components/library/playlists/playlists.component.html
+++ b/src/components/library/playlists/playlists.component.html
@@ -12,9 +12,21 @@
+
+
+ @if (importMsg()) {
+ {{ importMsg() }}
+ }
+
@if (loading()) {
@for (i of [1,2,3,4,5,6,7,8]; track i) {
diff --git a/src/components/library/playlists/playlists.component.ts b/src/components/library/playlists/playlists.component.ts
index a82f825..fc377bd 100644
--- a/src/components/library/playlists/playlists.component.ts
+++ b/src/components/library/playlists/playlists.component.ts
@@ -36,6 +36,9 @@ export class PlaylistsComponent {
formThumbnail = signal
('');
formPrivate = signal(true);
busySave = signal(false);
+ // Import / export JSON
+ busyImport = signal(false);
+ importMsg = signal(null);
constructor() {
this.reload();
@@ -108,6 +111,67 @@ export class PlaylistsComponent {
this.formPrivate.set(input.checked);
}
+ // --- Import / export JSON (routes /playlists/export et /playlists/import) ---
+ exportPlaylists(): void {
+ this.error.set(null);
+ this.http.get(`${this.apiBase()}/playlists/export`, { withCredentials: true, responseType: 'blob' }).subscribe({
+ next: (blob) => {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `newtube-playlists-${new Date().toISOString().slice(0, 10)}.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ },
+ error: () => this.error.set('Export impossible (connexion ?)'),
+ });
+ }
+
+ onImportFile(event: Event): void {
+ const input = event.target as HTMLInputElement;
+ const file = input.files?.[0];
+ input.value = ''; // permet de re-sélectionner le même fichier
+ if (!file) return;
+ this.busyImport.set(true);
+ this.importMsg.set(null);
+ this.error.set(null);
+ const reader = new FileReader();
+ reader.onload = () => {
+ let payload: any;
+ try {
+ payload = JSON.parse(String(reader.result || ''));
+ } catch {
+ this.busyImport.set(false);
+ this.error.set('Fichier JSON invalide');
+ return;
+ }
+ // Accepte le format complet ({ playlists: [...] }) et une simple liste.
+ const playlists = Array.isArray(payload) ? payload : payload?.playlists;
+ if (!Array.isArray(playlists)) {
+ this.busyImport.set(false);
+ this.error.set('Format non reconnu (cle "playlists" absente)');
+ return;
+ }
+ this.http.post(`${this.apiBase()}/playlists/import`, { playlists }, { withCredentials: true }).subscribe({
+ next: (res: any) => {
+ this.busyImport.set(false);
+ this.importMsg.set(`Import : ${res?.created ?? 0} liste(s) créée(s), ${res?.itemsAdded ?? 0} vidéo(s) ajoutée(s)`
+ + (res?.skippedLists ? `, ${res.skippedLists} liste(s) déjà présente(s)` : ''));
+ this.reload();
+ },
+ error: (err) => {
+ this.busyImport.set(false);
+ this.error.set(err?.error?.error || 'Import impossible');
+ },
+ });
+ };
+ reader.onerror = () => {
+ this.busyImport.set(false);
+ this.error.set('Lecture du fichier impossible');
+ };
+ reader.readAsText(file);
+ }
+
openCreate() {
this.editId.set(null);
this.formTitle.set('');
diff --git a/src/components/sidebar/sidebar.component.html b/src/components/sidebar/sidebar.component.html
index 7cebed4..b1f585c 100644
--- a/src/components/sidebar/sidebar.component.html
+++ b/src/components/sidebar/sidebar.component.html
@@ -232,6 +232,12 @@
{{ 'nav.usage' | t }}
+
+
+
+ {{ 'nav.admin' | t }}
+
+
diff --git a/src/components/themes/provider-theme-page.component.ts b/src/components/themes/provider-theme-page.component.ts
index cfb0c56..ab7486a 100644
--- a/src/components/themes/provider-theme-page.component.ts
+++ b/src/components/themes/provider-theme-page.component.ts
@@ -231,6 +231,12 @@ export class ProviderThemePageComponent implements OnDestroy {
} else if (provider === 'twitch') {
// Thème live : top streams (jamais vide quand Twitch est configuré).
apiCall = this.api.getTwitchTopStreamsPage(cursor || undefined);
+ } else if (isLiveTheme && provider === 'peertube') {
+ // Directs PeerTube : API native `?isLive=true` (instance active).
+ apiCall = this.api.searchPeerTubeLivePage(cursor || undefined);
+ } else if (isLiveTheme && provider === 'rumble') {
+ // Directs Rumble : page SSR rumble.com/browse/live via /api/rumble/live.
+ apiCall = this.api.getRumbleLivePage(cursor || undefined);
} else {
apiCall = query
? this.api.searchVideosPage(query, cursor, provider)
diff --git a/src/components/themes/theme-page.component.ts b/src/components/themes/theme-page.component.ts
index e7f37fd..5653dbe 100644
--- a/src/components/themes/theme-page.component.ts
+++ b/src/components/themes/theme-page.component.ts
@@ -261,11 +261,27 @@ export class ThemePageComponent {
// Thème "En direct" : vrais lives uniquement.
// - YouTube : search.list eventType=live (pas une recherche textuelle "live").
// - Twitch : top streams Helix (la recherche de chaînes "live" est trop restrictive).
+ // - PeerTube : API native `?isLive=true` (instance active).
+ // - Rumble : page SSR rumble.com/browse/live (route /api/rumble/live).
if (slug === 'live') {
+ const mode = block.provider === 'youtube' ? 'youtube_eventType_live'
+ : block.provider === 'twitch' ? 'twitch_top_streams'
+ : block.provider === 'peertube' ? 'peertube_islive'
+ : 'rumble_browse_live';
+ // La porte `providerSupportsLive` n'autorise que yt/tw/pt/ru : tout
+ // autre provider ne doit PAS retomber sur la source Rumble par défaut.
+ if (!['youtube', 'twitch', 'peertube', 'rumble'].includes(block.provider)) {
+ block.loading = false; block.error = null; block.items = [];
+ this.blocks.update(a => [...a]);
+ return;
+ }
const liveCall = block.provider === 'youtube'
? this.api.searchYouTubeLivePage('', null)
- : this.api.getTwitchTopStreamsPage(null);
- const mode = block.provider === 'youtube' ? 'youtube_eventType_live' : 'twitch_top_streams';
+ : block.provider === 'twitch'
+ ? this.api.getTwitchTopStreamsPage(null)
+ : block.provider === 'peertube'
+ ? this.api.searchPeerTubeLivePage(null)
+ : this.api.getRumbleLivePage(null);
liveCall.subscribe({
next: res => {
block.items = this.enrich(res.items || [], block.provider)
diff --git a/src/services/i18n.service.ts b/src/services/i18n.service.ts
index e37c148..c3f0162 100644
--- a/src/services/i18n.service.ts
+++ b/src/services/i18n.service.ts
@@ -68,6 +68,7 @@ const EN: Record = {
'nav.providers': 'Providers',
'nav.info': 'Information',
'nav.usage': 'Usage',
+ 'nav.admin': 'Administration',
'explore.music': 'Music',
'explore.gaming': 'Gaming',
'explore.news': 'News',
@@ -263,6 +264,7 @@ const FR: Record = {
'nav.providers': 'Fournisseurs',
'nav.info': 'Informations',
'nav.usage': 'Utilisation',
+ 'nav.admin': 'Administration',
'explore.music': 'Musique',
'explore.gaming': 'Jeux vidéo',
'explore.news': 'Actualités',
diff --git a/src/services/youtube-api.service.ts b/src/services/youtube-api.service.ts
index e339280..911f435 100644
--- a/src/services/youtube-api.service.ts
+++ b/src/services/youtube-api.service.ts
@@ -1231,6 +1231,70 @@ export class YoutubeApiService {
);
}
+ /**
+ * Directs PeerTube de l'instance active — paramètre natif `?isLive=true`
+ * (openapi PeerTube, probe 2026-10). Source du thème « En direct » pour
+ * PeerTube. Items repassés au format Twitch de la classification
+ * (`type:'live'` + `isLive` + durée 0) : c'est ce que le filtre
+ * `_kind === 'live'` des pages thèmes attend.
+ */
+ public searchPeerTubeLivePage(cursor?: string | null): Observable> {
+ const instance = this.instances.activePeerTubeInstance();
+ const start = cursor ? Number(cursor) : 0;
+ const params = new URLSearchParams({
+ count: '24',
+ start: String(start),
+ sort: '-publishedAt',
+ nsfw: 'false',
+ isLive: 'true',
+ });
+ const primary = `/api/peertube/${instance}/api/v1/videos?${params.toString()}`;
+ const fallback = `/proxy/api/peertube/${instance}/api/v1/videos?${params.toString()}`;
+ return this.http.get(primary).pipe(
+ catchError(() => this.http.get(fallback)),
+ map(res => {
+ const list = (res?.data || res?.result || []) as any[];
+ return {
+ items: (list || []).map((i: any) => ({
+ ...this.mapPeerTubeItemToVideo(i, instance),
+ type: 'live',
+ isLive: true,
+ isShort: false,
+ duration: 0,
+ // `viewers` = spectateurs du direct (comme Helix sur Twitch),
+ // seulement s'il est réellement exposé.
+ ...(Number(i?.viewers) > 0 ? { views: Number(i.viewers) } : {}),
+ })),
+ nextCursor: list.length > 0 ? String(start + 24) : null,
+ } as PagedResult