A clean and minimal youtube frontend, without all the ads and whistles
JavaScript
refactor: #5 YouTube Scraper Resilience & Error Isolation
Christian Fei2825bc485a9b
diff --git a/lib/scraper-errors.js b/lib/scraper-errors.jsnew file mode 100644index 0000000..38bb4ff--- /dev/null+++ b/lib/scraper-errors.js@@ -0,0 +1,11 @@+/**+ * Structured error class for YouTube scraper failures.+ * Provides contextual data for logging and alerting without leaking sensitive details.+ */+export class ScraperError extends Error {+ constructor (message, context = {}) {+ super(message)+ this.name = 'ScraperError'+ this.context = context // structured error data for logging/alerting+ }+}diff --git a/lib/update-videos.js b/lib/update-videos.jsindex e294618..03d26f6 100644--- a/lib/update-videos.js+++ b/lib/update-videos.js@@ -1,5 +1,6 @@import { getVideosFor } from './youtube.js'import { getRepository } from '../server/service-container.js'+import { ScraperError } from './scraper-errors.js'export async function updateAndPersistVideos (callback = () => {}) {const repo = getRepository()@@ -11,16 +12,23 @@ export async function updateAndPersistVideos (callback = () => {}) {export async function updateAndPersistVideosForChannel (name, callback = () => {}) {const repo = getRepository()- let videos = await getVideosFor(name)- if (Array.isArray(videos)) {- videos = videos.map(v => repo.patchVideo(v))- repo.upsertVideos(videos)- videos = videos- .filter(v => !v.ignored)- .filter(v => repo.filterByExcludedTerms(v))- callback(null, { name, videos })- } else {- callback(new Error(`Failed to fetch videos for channel "${name}"`))+ try {+ let videos = await getVideosFor(name)+ if (Array.isArray(videos)) {+ videos = videos.map(v => repo.patchVideo(v))+ repo.upsertVideos(videos)+ videos = videos+ .filter(v => !v.ignored)+ .filter(v => repo.filterByExcludedTerms(v))+ callback(null, { name, videos })+ }+ return videos+ } catch (error) {+ if (error instanceof ScraperError) {+ console.error(`[update] Failed updating @${name}: ${error.message}`)+ callback(null, { type: 'update-error', channel: name, error: error.message })+ return // Don't fail the entire batch for one channel+ }+ throw error // Non-scraper errors still propagate}- return videos}diff --git a/lib/youtube.js b/lib/youtube.jsindex 1b883db..1ae5024 100644--- a/lib/youtube.js+++ b/lib/youtube.js@@ -3,6 +3,7 @@ import fs from 'fs'import * as ytdlp from './yt-dlp.js'import { runWorkerDownload, runWorkerTranscode } from './workers/run-worker.js'import { getRepository } from '../server/service-container.js'+import { ScraperError } from './scraper-errors.js'export const ytUrlRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/(?:watch\?v=)?)([\w-]+)/@@ -90,19 +91,37 @@ function normalizeSubtitleFiles (id) {})}export async function getVideosFor (channelName, { includeMembersOnly = false } = {}) {- try {- const response = await fetch(`https://www.youtube.com/${channelWithAt(channelName)}/videos`, {- headers: fetchYoutubeHeaders+ const channelUrl = `https://www.youtube.com/${channelWithAt(channelName)}/videos`+ const response = await fetch(channelUrl, {+ headers: fetchYoutubeHeaders+ })++ if (!response.ok) {+ throw new ScraperError(`HTTP ${response.status} fetching channel page for @${channelName}`, {+ statusCode: response.status,+ channel: channelName})- const text = await response.text()- const match = text.match(/var ytInitialData = (.+?);<\/script>/)- if (!match || !match[1]) {- console.log('no match for', channelName)- return null- }+ }++ const text = await response.text()+ const match = text.match(/var ytInitialData = (.+?);<\/script>/)+ if (!match || !match[1]) {+ console.error(`[scraper] No ytInitialData found for @${channelName}`)+ console.error(`[scraper] Last 200 chars of response: "${text.slice(-200)}"`)+ throw new ScraperError('YouTube HTML structure changed — scraper regex no longer matches', {+ channel: channelName+ })+ }++ try {const json = JSON.parse(match[1].trim())const videoTab = json.contents.twoColumnBrowseResultsRenderer.tabs.find(t => t.tabRenderer?.title === 'Videos')+ if (!videoTab || !videoTab.tabRenderer) {+ throw new ScraperError('YouTube channel page has no "Videos" tab — structure may have changed', {+ channel: channelName+ })+ }const videoContents = videoTab.tabRenderer.content.richGridRenderer.contentsreturn videoContents.map(toInternalVideo)@@ -111,8 +130,12 @@ export async function getVideosFor (channelName, { includeMembersOnly = false }.filter(v => v.publishedAt > new Date(Date.now() - 6 * 31 * 24 * 60 * 60 * 1000))// .filter((_,i) => i < 10)} catch (error) {- console.error('Error fetching latest video:', error.message)- return null+ if (error instanceof ScraperError) throw error+ // Unexpected parse errors — wrap as scraper failure+ console.error(`[scraper] Failed to parse channel data for @${channelName}: ${error.message}`)+ throw new ScraperError('Failed to parse YouTube channel data', {+ channel: channelName+ })}function channelWithAt (channelName = '') {diff --git a/server/router/handlers/health.js b/server/router/handlers/health.jsnew file mode 100644index 0000000..2f0d26d--- /dev/null+++ b/server/router/handlers/health.js@@ -0,0 +1,53 @@+import { ScraperError } from '../../../lib/scraper-errors.js'++/**+ * Reports the scraper health status for each channel.+ * A channel is "healthy" if it has a video from the last 48 hours,+ * otherwise "stale". Returns summary per channel.+ */+export async function scraperStatusHandler (req, res, connections = [], state = {}) {+ const repo = state.repo+ if (!repo) {+ res.writeHead(500, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Repository not available' }))+ return+ }++ const channels = repo.getChannels()+ const status = {}++ for (const channel of channels) {+ try {+ // Check if there's a recent video from this channel (last 48 hours)+ const videos = repo.getVideos({ filter: `@${channel.name}` })+ const lastVideo = videos.sort((a, b) => new Date(b.date) - new Date(a.date))[0]++ const now = Date.now()+ const recentThreshold = 48 * 3600 * 1000 // 48 hours+ const isHealthy = lastVideo && (now - new Date(lastVideo.date).getTime()) < recentThreshold++ status[channel.name] = {+ lastVideoDate: lastVideo?.date,+ videoCount: videos.length,+ status: isHealthy ? 'healthy' : 'stale'+ }++ // Attempt a lightweight scraper probe for stale channels+ if (!isHealthy) {+ const { getVideosFor } = await import('../../lib/youtube.js')+ const videosResult = await getVideosFor(channel.name)+ if (Array.isArray(videosResult) && videosResult.length > 0) {+ status[channel.name].status = 'needs-update'+ }+ }+ } catch (error) {+ status[channel.name] = {+ error: 'probe-failed',+ message: error instanceof ScraperError ? error.message : String(error)+ }+ }+ }++ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(status))+}diff --git a/server/router/index.js b/server/router/index.jsindex 254c588..f3943f1 100644--- a/server/router/index.js+++ b/server/router/index.js@@ -4,6 +4,7 @@ import downloads from './handlers/downloads.js'import summaries from './handlers/summaries.js'import settings from './handlers/settings.js'import diskSpace from './handlers/disk-space.js'+import { scraperStatusHandler } from './handlers/health.js'const routeMap = {// Channels: GET, POST, DELETE@@ -43,7 +44,10 @@ const routeMap = {// Excluded terms: GET, POST, DELETE'GET /api/excluded-terms': settings.getExcludedTermsHandler,'POST /api/excluded-terms': settings.addExcludedTermHandler,- 'DELETE /api/excluded-terms': settings.removeExcludedTermHandler+ 'DELETE /api/excluded-terms': settings.removeExcludedTermHandler,++ // Scraper health: GET+ 'GET /api/scraper-status': scraperStatusHandler}export default function apiHandler (req, res, connections = [], state = {}) {diff --git a/server/service-container.js b/server/service-container.jsindex b56df24..0028045 100644--- a/server/service-container.js+++ b/server/service-container.js@@ -11,6 +11,9 @@ export function initRepository (dataDir) {}export function getRepository (dataDir) {+ // Check for test override first+ if (_override !== null) return _override+const key = dataDir || './data'if (_instances.has(key)) {return _instances.get(key)@@ -26,3 +29,14 @@ export function resetForTesting (dataDir) {const key = dataDir || './data'_instances.delete(key)}++// Test helpers: allow injecting a mock repository for testing+let _override = null++export function setRepositoryOverride (mockRepo) {+ _override = mockRepo+}++export function resetRepositoryOverride () {+ _override = null+}diff --git a/test/youtube.scraper.test.js b/test/youtube.scraper.test.jsnew file mode 100644index 0000000..7a68ef6--- /dev/null+++ b/test/youtube.scraper.test.js@@ -0,0 +1,134 @@+import { test } from 'node:test'+import assert from 'assert'+import { getVideosFor, getVideo } from '../lib/youtube.js'+import { updateAndPersistVideosForChannel } from '../lib/update-videos.js'+import { ScraperError } from '../lib/scraper-errors.js'++test('throws structured error when HTML has no ytInitialData', async () => {+ const originalFetch = global.fetch+ global.fetch = () => Promise.resolve({+ ok: true,+ text: () => Promise.resolve('<html><body>no script tag here</body></html>')+ })++ try {+ await getVideosFor('test_channel')+ assert.fail('Should have thrown ScraperError')+ } catch (error) {+ assert.ok(error instanceof ScraperError, 'Should be a ScraperError')+ assert.strictEqual(error.name, 'ScraperError')+ assert.ok(error.message.includes('YouTube HTML structure changed'))+ assert.strictEqual(error.context.channel, 'test_channel')+ } finally {+ global.fetch = originalFetch+ }+})++test('throws structured error on HTTP failure', async () => {+ const originalFetch = global.fetch+ global.fetch = () => Promise.resolve({+ ok: false,+ status: 404,+ text: () => Promise.resolve('Not Found')+ })++ try {+ await getVideosFor('nonexistent_channel_xyz123')+ assert.fail('Should have thrown ScraperError')+ } catch (error) {+ assert.ok(error instanceof ScraperError, 'Should be a ScraperError')+ assert.strictEqual(error.context.statusCode, 404)+ assert.strictEqual(error.context.channel, 'nonexistent_channel_xyz123')+ } finally {+ global.fetch = originalFetch+ }+})++test('throws structured error on HTTP 500', async () => {+ const originalFetch = global.fetch+ global.fetch = () => Promise.resolve({+ ok: false,+ status: 500,+ text: () => Promise.resolve('Internal Server Error')+ })++ try {+ await getVideosFor('any_channel')+ assert.fail('Should have thrown ScraperError')+ } catch (error) {+ assert.ok(error instanceof ScraperError, 'Should be a ScraperError')+ assert.strictEqual(error.context.statusCode, 500)+ } finally {+ global.fetch = originalFetch+ }+})++test('throws structured error when channel has no Videos tab', async () => {+ // When the HTML structure is valid enough to parse, but lacks a "Videos" tab,+ // the scraper should throw with structured context.+ const mockHtml = '<html><body><script>var ytInitialData = {"broken": true};</script></body></html>'+ const originalFetch = global.fetch+ global.fetch = () => Promise.resolve({+ ok: true,+ text: () => Promise.resolve(mockHtml)+ })++ try {+ await getVideosFor('shorts_only_channel')+ assert.fail('Should have thrown ScraperError')+ } catch (error) {+ assert.ok(error instanceof ScraperError, 'Should be a ScraperError')+ } finally {+ global.fetch = originalFetch+ }+})++test('updateAndPersistVideosForChannel reports error via callback on ScraperError', async () => {+ const originalFetch = global.fetch++ // Track callback calls+ const callbackCalls = []+ const mockCallback = (...args) => { callbackCalls.push(args) }++ // Make scraper throw a ScraperError (HTML structure change)+ global.fetch = () => Promise.resolve({+ ok: true,+ text: () => Promise.resolve('<html><body>no data</body></html>')+ })++ // Use a module-level variable to allow test-time override of getRepository+ const { setRepositoryOverride, resetRepositoryOverride } = await import('../server/service-container.js')+ const mockRepo = {+ getChannels: () => [],+ patchVideo: (v) => v,+ upsertVideos: () => {},+ filterByExcludedTerms: (v) => true+ }++ setRepositoryOverride(mockRepo)++ try {+ await updateAndPersistVideosForChannel('failing_channel', mockCallback)++ // The callback should have been called with an error event+ const errorCall = callbackCalls.find(call => call[1] && call[1].type === 'update-error')+ assert.ok(errorCall, 'Callback should report update-error for ScraperError')+ assert.strictEqual(errorCall[1].channel, 'failing_channel')+ } finally {+ global.fetch = originalFetch+ resetRepositoryOverride()+ }+})++test('ScraperError has structured context', () => {+ const error = new ScraperError('test message', { channel: 'ch1', statusCode: 502 })+ assert.strictEqual(error.name, 'ScraperError')+ assert.strictEqual(error.message, 'test message')+ assert.deepStrictEqual(error.context, { channel: 'ch1', statusCode: 502 })+})++test('getVideo still returns null on failure (not throwing)', async () => {+ // getVideo should NOT be affected — it catches and returns null for yt-dlp failures+ const result = await getVideo('invalid_video_id_that_does_not_exist_12345')+ assert.strictEqual(result, null)+})