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:
@@ -36,16 +36,19 @@ Agrégez, explorez et regardez des vidéos depuis
|
||||
| ----------------------------- | :-------: | :-----: | :----: | :--: | :---------: |
|
||||
| YouTube 🔴 | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| Dailymotion 🔵 | ✅ | ✅ | ✅ | ✅ | ⏳ |
|
||||
| Twitch 🟣 | ✅ | ✅ | Clips ✅ | ✅ | ⏳ |
|
||||
| PeerTube 🟢 (multi-instances) | ✅ | ✅ | ✅ | ⏳ | ⏳ |
|
||||
| Odysee 🟡 | ✅ | ✅ | ✅ | ⏳ | ⏳ |
|
||||
| Rumble 🟠 | ✅ | ✅ | ✅ | ⏳ | ⏳ |
|
||||
| Twitch 🟣 | ✅ | ✅ | Clips ✅ | ✅ | N/A |
|
||||
| PeerTube 🟢 (multi-instances) | ✅ | ✅ | ✅ | ✅ | ⏳ |
|
||||
| Odysee 🟡 | ✅ | ✅ | ✅ | N/A | N/A |
|
||||
| Rumble 🟠 | ✅ | ✅ | ✅ | ✅ | N/A |
|
||||
|
||||
\* Playlists = intégration locale NewTube (création/gestion) ; la synchro native (ajout/suppression côté fournisseur) dépend de l’API publique de chaque fournisseur → ⏳ pour tous sauf YouTube.
|
||||
\* Playlists = intégration locale NewTube (création/gestion) ; la synchro native (ajout/suppression côté fournisseur) exige l’API d’écriture du fournisseur :
|
||||
* **YouTube ✅** (Data API) ; **Dailymotion / PeerTube ⏳** : APIs d’écriture existantes mais coûteuses (inscription d’app OAuth pour l’un, JWT par instance pour l’autre).
|
||||
* **Twitch N/A** — API playlists **supprimée** : probe 2026-10 avec token app valide, `GET/POST /helix/playlists` et `/helix/playlists/{id}/videos` répondent tous **404** (contrôle `/helix/users` → 400 = route existante).
|
||||
* **Odysee N/A** — proxy `na-backend` en lecture seule (méthodes d’écriture : « authentication token missing ») ; **Rumble N/A** — aucune API publique.
|
||||
|
||||
Notes sur les colonnes :
|
||||
* **Shorts** : le flux `/#/shorts` tourne sur les 6 fournisseurs — catalogue `/api/search?type=shorts` (lot affiché s’il compte ≥ 3 résultats), sinon repli recherche avec requêtes dédiées (`SHORTS_QUERIES`). Filtre de durée côté serveur : YouTube (`videoDuration=short`), Dailymotion (`shorter_than`), PeerTube (`durationMax`) ; filtre client pour Odysee et Rumble ; **Rumble** : flux natif `rumble.com/shorts` ; **Twitch** : pas de format vertical natif, le flux sert les **clips**.
|
||||
* **Live** : lecture des streams live prouvée pour YouTube, Dailymotion et Twitch ; PeerTube / Odysee / Rumble ⏳ (voir « Fournisseurs existants — lacunes à combler »).
|
||||
* **Live** : sources câblées — YouTube (`search.list eventType=live`), Twitch (top streams Helix), PeerTube (API `?isLive=true` : thème « En direct » + onglet Live de la chaîne), Rumble (`rumble.com/browse/live` : thème + onglet chaîne filtré par `channelId`). **Dailymotion** : lecture possible mais `live:false` côté capacités (le thème y affiche « Ce fournisseur ne propose pas de directs »). **Odysee N/A** — aucune API publique de lives (proxy na-backend sous jeton, probe 2026-10).
|
||||
|
||||
* **Rumble 🟠** : scraping maison derrière Cloudflare (fetch navigateur + helper `curl_cffi`). Si le réseau du serveur est challengé, l’API répond `503 { error: "rumble_cloudflare_challenge" }` (« bloqué temporairement ») au lieu d’un résultat vide : Rumble peut donc être temporairement absent selon le réseau — voir `server/providers/rumble.mjs`.
|
||||
|
||||
@@ -267,23 +270,26 @@ Légende : **✅ livré** (câblé de bout en bout) · **🟡 partiellement livr
|
||||
* ✅ **Sous-titres & transcripts** — `GET /api/transcript/:provider/:videoId` (yt-dlp `subtitles`/`automatic_captions`, parsing `json3`/`vtt`, cache 24 h, rate-limit), panneau **Transcript** sur la page Watch (sélecteur de langue, dégradation propre si indisponible)
|
||||
* ✅ **YouTube sans quota (InnerTube façon SmartTube)** — `youtubei.js` pinné, chaîne `innertube → scrape yt-dlp → API officielle` (`YT_SEARCH_MODE`, défaut `innertube-first`), **pagination illimitée** via continuations (scroll infini, `page=2,3…`), **vidéos connexes** watch-next dans `GET /api/details/youtube/:videoId` → sidebar Watch, `GET /api/trending?provider=yt`, cache mémoire + SQLite, anti-ban (`YT_COOKIES_FILE`, `YT_PO_TOKEN`, `YT_EGRESS_PROXY`), observabilité `/healthz` (mode, binaire `binOk`, cache, quota jour, clés)
|
||||
* ✅ **OAuth** (Google/Twitch) pour import favoris/abonnements — `/library/import` : abonnements + likes YouTube (lecture seule), follows Twitch → abonnements, preview + import, `GET /api/oauth/status|connections|preview`, `POST /api/oauth/:provider/import`
|
||||
* ✅ **Live sur PeerTube & Rumble** — thème « En direct » + onglet Live de la chaîne : PeerTube via l'API native `?isLive=true` (recherche sepiasearch + vidéos de chaîne, items `type:'live'` + spectateurs), Rumble via la page SSR `rumble.com/browse/live` (route `/api/rumble/live`, items typés live ; onglet chaîne filtré par `channelId` — plafond : page 1 bornée à 50 directs). Odysee : **N/A** (aucune API publique de lives, probe 2026-10). Tests : `npm run test:live`
|
||||
* ✅ **Import/Export playlists (JSON)** — `GET /playlists/export` (dump complet + items, format `newtube-playlists-v1`), `POST /playlists/import` (création des listes manquantes, dédoublonnage par titre au réimport, compteurs détaillés ; bornes 200 listes / 5 000 vidéos par liste) ; boutons **[Exporter] [Importer]** sur `/#/library/playlists`.
|
||||
* ✅ **Page Administration** (`/#/admin`, entrée « Administration » de la section Informations dans la barre latérale) — `/healthz` + `/api/providers/metrics` rendus lisibles : statut API, mode YouTube, version et santé yt-dlp, clés actives / bannies (+ suffixes), anti-ban (cookies / PO token / proxy), cache de recherche par provider, compteurs 1 h par provider, quota YouTube du jour. Au passage : `healthz` servi aussi sous `/proxy/api/healthz` (le chemin que le front utilise en prod). *Journaux (logs) et exposition Prometheus restent à faire — voir Observabilité.*
|
||||
* ✅ **Cache TTL par provider** — `server/env-ttl.mjs` (`<BASE>_<PROVIDER>` → `<BASE>` → défaut, valeurs invalides ignorées, jamais de TTL nul) branché sur les caches **details** (`DETAILS_CACHE_TTL_MS_<P>`) et **transcripts** (`TRANSCRIPT_CACHE_TTL_<P>`) en plus de la recherche (`SEARCH_CACHE_TTL_MS_<P>`). 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_<PROVIDER>` / `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
|
||||
|
||||
+2
-1
@@ -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",
|
||||
|
||||
@@ -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`);
|
||||
@@ -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: '' }
|
||||
];
|
||||
|
||||
@@ -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<Record<ProviderId, ProviderCapabilities>> = {
|
||||
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). */
|
||||
|
||||
@@ -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: `
|
||||
<div class="container mx-auto p-4 sm:p-6 max-w-5xl">
|
||||
<div class="mb-6 flex flex-col flex-wrap gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h2 class="border-l-4 border-red-500 pl-4 text-2xl font-bold text-slate-100">Administration</h2>
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-xs text-slate-400" *ngIf="refreshAt()">Actualisé {{ refreshAt() }}</span>
|
||||
<button type="button" (click)="load()" class="chip bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-600 px-4 py-2 rounded">Actualiser</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div *ngIf="error()" class="bg-red-900/40 border border-red-700 text-red-300 p-4 rounded mb-4">{{ error() }}</div>
|
||||
|
||||
<div *ngIf="loading()" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div *ngFor="let i of [1,2,3,4]" class="animate-pulse bg-slate-800 rounded-lg h-40 border border-slate-700"></div>
|
||||
</div>
|
||||
|
||||
<div *ngIf="!loading()" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<!-- Général -->
|
||||
<section class="bg-slate-800/70 border border-slate-700 rounded-lg p-4">
|
||||
<h3 class="font-semibold text-slate-100 mb-3">Général</h3>
|
||||
<dl class="text-sm space-y-1.5">
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">Statut API</dt>
|
||||
<dd class="text-slate-200">{{ health()?.status || '—' }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">Mode YouTube</dt>
|
||||
<dd class="text-slate-200">{{ health()?.youtube?.effectiveMode || health()?.youtube?.mode || '—' }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">yt-dlp</dt>
|
||||
<dd class="text-slate-200" [class.text-red-400]="health()?.youtube?.ytdlp && !health()?.youtube?.ytdlp?.binOk">
|
||||
{{ ytDlpLabel() }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">Cache YouTube (SQLite)</dt>
|
||||
<dd class="text-slate-200">{{ health()?.youtube?.cache?.sqliteRows ?? '—' }} lignes</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">Cache de recherche</dt>
|
||||
<dd class="text-slate-200">{{ health()?.providers?.cache?.rows ?? '—' }} lignes</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<!-- Clés API -->
|
||||
<section class="bg-slate-800/70 border border-slate-700 rounded-lg p-4">
|
||||
<h3 class="font-semibold text-slate-100 mb-3">Clés & anti-ban YouTube</h3>
|
||||
<dl class="text-sm space-y-1.5">
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">Clés actives</dt>
|
||||
<dd class="text-emerald-400">{{ keysOk() }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">Clés bannies</dt>
|
||||
<dd [class.text-red-400]="bannedKeys().length > 0" [class.text-slate-200]="bannedKeys().length === 0">{{ bannedKeys().length }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3" *ngFor="let b of bannedKeys()">
|
||||
<dt class="text-slate-500">Bannie</dt>
|
||||
<dd class="text-red-300 font-mono text-xs">{{ b }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt class="text-slate-400">Cookies / PO token / proxy</dt>
|
||||
<dd class="text-slate-200">{{ antibanLabel() }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<!-- Fournisseurs (1 h) -->
|
||||
<section class="bg-slate-800/70 border border-slate-700 rounded-lg p-4">
|
||||
<h3 class="font-semibold text-slate-100 mb-3">Fournisseurs (1 h)</h3>
|
||||
<p *ngIf="!providerRows().length" class="text-sm text-slate-400">Aucun appel récent.</p>
|
||||
<table *ngIf="providerRows().length" class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="text-left text-slate-400 border-b border-slate-700">
|
||||
<th class="py-1 font-medium">Provider</th>
|
||||
<th class="py-1 font-medium text-right">Appels</th>
|
||||
<th class="py-1 font-medium text-right">OK</th>
|
||||
<th class="py-1 font-medium text-right">Erreurs</th>
|
||||
<th class="py-1 font-medium text-right">Latence</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let row of providerRows()" class="border-b border-slate-700/50">
|
||||
<td class="py-1 text-slate-200 font-mono">{{ row.provider }}</td>
|
||||
<td class="py-1 text-right text-slate-200">{{ row.calls }}</td>
|
||||
<td class="py-1 text-right text-slate-200">{{ row.ok }}</td>
|
||||
<td class="py-1 text-right" [class.text-red-400]="row.errors > 0" [class.text-slate-200]="row.errors === 0">{{ row.errors }}</td>
|
||||
<td class="py-1 text-right text-slate-200">{{ row.avgLatencyMs }} ms</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<!-- Cache de recherche par provider + quota YouTube -->
|
||||
<section class="bg-slate-800/70 border border-slate-700 rounded-lg p-4">
|
||||
<h3 class="font-semibold text-slate-100 mb-3">Cache de recherche par provider</h3>
|
||||
<p *ngIf="!cacheRows().length" class="text-sm text-slate-400">Cache vide.</p>
|
||||
<table *ngIf="cacheRows().length" class="w-full text-sm mb-4">
|
||||
<thead>
|
||||
<tr class="text-left text-slate-400 border-b border-slate-700">
|
||||
<th class="py-1 font-medium">Provider</th>
|
||||
<th class="py-1 font-medium text-right">Entrées</th>
|
||||
<th class="py-1 font-medium text-right">Hits</th>
|
||||
<th class="py-1 font-medium text-right">Taux</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let row of cacheRows()" class="border-b border-slate-700/50">
|
||||
<td class="py-1 text-slate-200 font-mono">{{ row.provider }}</td>
|
||||
<td class="py-1 text-right text-slate-200">{{ row.entries }}</td>
|
||||
<td class="py-1 text-right text-slate-200">{{ row.hits }}</td>
|
||||
<td class="py-1 text-right text-slate-200">{{ (row.hitRate * 100) | number:'1.0-0' }} %</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h4 class="text-sm font-semibold text-slate-300 mb-1">YouTube aujourd'hui</h4>
|
||||
<p class="text-sm text-slate-400">
|
||||
{{ ytToday()?.scrape_calls ?? 0 }} scrapes · {{ ytToday()?.api_calls ?? 0 }} appels API ·
|
||||
{{ ytToday()?.quota_units ?? 0 }} unités de quota
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class AdminComponent {
|
||||
private http = inject(HttpClient);
|
||||
|
||||
loading = signal(true);
|
||||
error = signal<string | null>(null);
|
||||
health = signal<any>(null);
|
||||
metrics = signal<any>(null);
|
||||
refreshAt = signal<string>('');
|
||||
|
||||
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<any>(`${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<any>(`${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;
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,21 @@
|
||||
<button (click)="openCreate()" class="chip bg-red-600 hover:bg-red-500 text-white font-semibold px-4 py-3 rounded sm:py-2">
|
||||
Nouvelle playlist
|
||||
</button>
|
||||
<button type="button" (click)="exportPlaylists()" class="chip bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-600 font-semibold px-4 py-3 rounded sm:py-2">
|
||||
Exporter
|
||||
</button>
|
||||
<label class="chip bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-600 font-semibold px-4 py-3 rounded sm:py-2 cursor-pointer"
|
||||
[class.opacity-50]="busyImport()" [class.pointer-events-none]="busyImport()">
|
||||
{{ busyImport() ? 'Import…' : 'Importer' }}
|
||||
<input type="file" accept="application/json,.json" class="hidden" (change)="onImportFile($event)" [disabled]="busyImport()" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (importMsg()) {
|
||||
<div class="mb-4 bg-emerald-900/30 border border-emerald-700 text-emerald-300 p-3 rounded text-sm">{{ importMsg() }}</div>
|
||||
}
|
||||
|
||||
@if (loading()) {
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
|
||||
@for (i of [1,2,3,4,5,6,7,8]; track i) {
|
||||
|
||||
@@ -36,6 +36,9 @@ export class PlaylistsComponent {
|
||||
formThumbnail = signal<string>('');
|
||||
formPrivate = signal<boolean>(true);
|
||||
busySave = signal<boolean>(false);
|
||||
// Import / export JSON
|
||||
busyImport = signal<boolean>(false);
|
||||
importMsg = signal<string | null>(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('');
|
||||
|
||||
@@ -232,6 +232,12 @@
|
||||
<span [class.hidden]="collapsed" class="truncate">{{ 'nav.usage' | t }}</span>
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a routerLink="/admin" routerLinkActive="bg-slate-800" class="flex items-center px-3 py-2 rounded hover:bg-slate-800 transition" [ngClass]="{ 'gap-0 justify-center': collapsed, 'gap-3': !collapsed }" [attr.title]="collapsed ? ('nav.admin' | t) : null">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="currentColor"><path d="M3 5h18v4H3V5zm0 6h18v4H3v-4zm0 6h18v2H3v-2z"/></svg>
|
||||
<span [class.hidden]="collapsed" class="truncate">{{ 'nav.admin' | t }}</span>
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://git.dracodev.net/Projets/NewTube" target="_blank" rel="noopener noreferrer" class="flex items-center px-3 py-2 rounded hover:bg-slate-800 transition" [ngClass]="{ 'gap-0 justify-center': collapsed, 'gap-3': !collapsed }" [attr.title]="collapsed ? 'Gitea' : null">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2zm1 14.59V20h-2v-3.41a4.994 4.994 0 0 1-4-4.9V7h2v4.69A3 3 0 0 0 12 14a3 3 0 0 0 3-2.31V7h2v4.69a4.994 4.994 0 0 1-4 4.9z"/></svg>
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -68,6 +68,7 @@ const EN: Record<string, string> = {
|
||||
'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<string, string> = {
|
||||
'nav.providers': 'Fournisseurs',
|
||||
'nav.info': 'Informations',
|
||||
'nav.usage': 'Utilisation',
|
||||
'nav.admin': 'Administration',
|
||||
'explore.music': 'Musique',
|
||||
'explore.gaming': 'Jeux vidéo',
|
||||
'explore.news': 'Actualités',
|
||||
|
||||
@@ -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<PagedResult<Video>> {
|
||||
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<any>(primary).pipe(
|
||||
catchError(() => this.http.get<any>(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<Video>;
|
||||
}),
|
||||
catchError((e) => { console.error(`PeerTube (${instance}) live error`, e); return of({ items: [], nextCursor: null }); })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Directs Rumble en cours — page SSR `rumble.com/browse/live` via la route
|
||||
* serveur `/api/rumble/live` (le cœur parse en mode live : items déjà
|
||||
* `type:'live'`, ids /vXXXX). Re-mappés au format classification Twitch.
|
||||
*/
|
||||
public getRumbleLivePage(cursor?: string | null, limit = 24): Observable<PagedResult<Video>> {
|
||||
const page = cursor ? Math.max(1, Number(cursor) || 1) : 1;
|
||||
const params = new URLSearchParams({ limit: String(limit), page: String(page) });
|
||||
return this.fetchRumble('/live', params).pipe(
|
||||
map((res: any) => ({
|
||||
items: (res?.items || []).map((i: any) => ({
|
||||
...this.mapRumbleItemToVideo(i),
|
||||
type: 'live',
|
||||
isLive: true,
|
||||
isShort: false,
|
||||
duration: 0,
|
||||
})),
|
||||
nextCursor: res?.nextCursor || null,
|
||||
} as PagedResult<Video>)),
|
||||
catchError((e) => { console.error('Rumble live error', e); return of({ items: [], nextCursor: null }); })
|
||||
);
|
||||
}
|
||||
|
||||
// Dailymotion mapper.
|
||||
// allow_embed=false (embed désactivé par le propriétaire) => le player
|
||||
// répond "Forbidden" : propagé via `raw.allowEmbed` pour que les Shorts
|
||||
|
||||
Reference in New Issue
Block a user