Skip to content

armgit / my-yt

Public Imported from GitHub
0

A clean and minimal youtube frontend, without all the ads and whistles

JavaScript

revisit modules

Christian Feib9a4f57e2764
diff --git a/client/components/channels-list.js b/client/components/channels-list.js
index 3bc7cb6..8a207b6 100644
--- a/client/components/channels-list.js
+++ b/client/components/channels-list.js
@@ -54,7 +54,6 @@ class ChannelsList extends HTMLElement {
const $searchInput = document.querySelector('#search')
if (!$searchInput) return
const channel = `@${event.target.innerText || event.target.innerHTML}`
- console.log(event.target)
const channels = this.querySelectorAll('.channel')
if ($searchInput.value === channel) {
diff --git a/client/components/forms/add-channel-form.js b/client/components/forms/add-channel-form.js
index ac68a01..0307044 100644
--- a/client/components/forms/add-channel-form.js
+++ b/client/components/forms/add-channel-form.js
@@ -41,7 +41,7 @@ class AddChannelForm extends HTMLElement {
const loader = form.querySelector('.loader')
const status = form.querySelector('.status')
- const channelName = document.getElementById('channel-name').value
+ const channelName = input.value.trim()
if (!channelName) return alert('empty channel name')
freezeForm()
diff --git a/client/components/video-element.js b/client/components/video-element.js
index 0643b97..cd6cf86 100644
--- a/client/components/video-element.js
+++ b/client/components/video-element.js
@@ -246,6 +246,7 @@ class VideoElement extends HTMLElement {
filterByChannelHandler (event) {
const $searchInput = document.querySelector('#search')
+ if (!$searchInput) return
const channel = `@${this.video.channelName}`
$searchInput.value = ($searchInput && $searchInput.value !== channel) ? channel : ''
$searchInput.dispatchEvent(new Event('input'))
diff --git a/index.js b/index.js
index d772024..74132ee 100644
--- a/index.js
+++ b/index.js
@@ -1,28 +1,28 @@
import os from 'os'
-import Repository from './lib/repository.js'
+import { initRepository } from './server/service-container.js'
import { createServer } from './server/http.js'
import stateFactory from './server/state-factory.js'
import { broadcastSSE } from './server/sse.js'
import { updateAndPersistVideos } from './lib/update-videos.js'
async function main ({ port = 3000 } = {}) {
- const repo = new Repository()
+ initRepository()
const connections = []
const state = stateFactory((updatedState) =>
broadcastSSE(JSON.stringify({ type: 'state', state: updatedState }), connections))
let lastAdded = Date.now()
- runUpdateVideos(repo, connections)
- setInterval(runUpdateVideos, (+process.env.UPDATE_INTERVAL_MINUTES || 30) * 1000 * 60, repo, connections)
+ runUpdateVideos(connections)
+ setInterval(runUpdateVideos, (+process.env.UPDATE_INTERVAL_MINUTES || 30) * 1000 * 60, connections)
- createServer({ repo, state, connections })
+ createServer({ state, connections })
.listen(port, () => {
console.log(`Server running at http://${os.hostname()}:${port} (or http://localhost:${port})`)
})
- function runUpdateVideos (repo, connections) {
+ function runUpdateVideos (connections) {
console.log('update videos')
- updateAndPersistVideos(repo, (err, data) => {
+ updateAndPersistVideos((err, data) => {
if (err) return console.error(err)
const { name, videos } = data
const newVideos = videos.filter(v => v.addedAt > lastAdded).filter(v => !v.ignored)
diff --git a/lib/subtitles-summary.js b/lib/subtitles-summary.js
index aa3c9e7..1ea10cf 100644
--- a/lib/subtitles-summary.js
+++ b/lib/subtitles-summary.js
@@ -3,8 +3,10 @@ import fs from 'fs'
import { getVideoSubtitles } from './youtube.js'
import * as llm from './llm/index.js'
import retry from './retry-promise.js'
+import { getRepository } from '../server/service-container.js'
-export async function summarizeVideo (id, repo, llmSettings = {}, callback = () => {}) {
+export async function summarizeVideo (id, llmSettings = {}, callback = () => {}) {
+ const repo = getRepository()
return retry(() => new Promise(async (resolve, reject) => {
try {
const transcript = await getVideoSubtitles(id, callback)
diff --git a/lib/update-videos.js b/lib/update-videos.js
index b63fc48..e294618 100644
--- a/lib/update-videos.js
+++ b/lib/update-videos.js
@@ -1,13 +1,16 @@
import { getVideosFor } from './youtube.js'
+import { getRepository } from '../server/service-container.js'
-export async function updateAndPersistVideos (repo, callback = () => {}) {
+export async function updateAndPersistVideos (callback = () => {}) {
+ const repo = getRepository()
const channels = repo.getChannels()
for (const channel of channels) {
- await updateAndPersistVideosForChannel(channel.name, repo, callback)
+ await updateAndPersistVideosForChannel(channel.name, callback)
}
}
-export async function updateAndPersistVideosForChannel (name, repo, 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))
diff --git a/lib/youtube.js b/lib/youtube.js
index 7e0e091..1b883db 100644
--- a/lib/youtube.js
+++ b/lib/youtube.js
@@ -2,6 +2,7 @@ import spawn from 'nano-spawn'
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'
export const ytUrlRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/(?:watch\?v=)?)([\w-]+)/
@@ -21,7 +22,8 @@ function parseDuration (durationStr) {
return null
}
-export async function downloadVideo (id, repo, callback = () => {}) {
+export async function downloadVideo (id, callback = () => {}) {
+ const repo = getRepository()
if (isUnsupportedUrl(id)) throw new Error('unsupported url')
const videoId = isYouTubeUrl(id) ? extractIdFromUrl(id) : id
diff --git a/package-lock.json b/package-lock.json
index f57b512..48436c3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,8 +12,10 @@
"nano-spawn": "^2.0.0"
},
"devDependencies": {
+ "@esm-bundle/chai": "^4.3.4-fix.0",
"@open-wc/testing": "^4.0.0",
"@web/test-runner": "^0.20.2",
+ "@web/test-runner-puppeteer": "^0.18.0",
"sinon": "^21.0.3",
"standard": "^17.1.2",
"undici": "^7.24.6"
@@ -108,9 +110,9 @@
}
},
"node_modules/@esm-bundle/chai": {
- "version": "4.3.4",
- "resolved": "https://registry.npmjs.org/@esm-bundle/chai/-/chai-4.3.4.tgz",
- "integrity": "sha512-6Tx35wWiNw7X0nLY9RMx8v3EL8SacCFW+eEZOE9Hc+XxmU5HFE2AFEg+GehUZpiyDGwVvPH75ckGlqC7coIPnA==",
+ "version": "4.3.4-fix.0",
+ "resolved": "https://registry.npmjs.org/@esm-bundle/chai/-/chai-4.3.4-fix.0.tgz",
+ "integrity": "sha512-26SKdM4uvDWlY8/OOOxSB1AqQWeBosCX3wRYUZO7enTAj03CtVxIiCimYVG2WpULcyV51qapK4qTovwkUr5Mlw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -302,18 +304,18 @@
}
},
"node_modules/@puppeteer/browsers": {
- "version": "2.10.5",
- "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.10.5.tgz",
- "integrity": "sha512-eifa0o+i8dERnngJwKrfp3dEq7ia5XFyoqB17S4gK8GhsQE4/P8nxOfQSE0zQHxzzLo/cmF+7+ywEQ7wK7Fb+w==",
+ "version": "2.13.1",
+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.13.1.tgz",
+ "integrity": "sha512-zmS4RTK9fbrc++WlAJhxYbfz3IjDeOmkK/CwwbLmk7ydfS9e2CiEeRJHEPvjDVElO/bwXbidwGA37Bsm6LzCnQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "debug": "^4.4.1",
+ "debug": "^4.4.3",
"extract-zip": "^2.0.1",
"progress": "^2.0.3",
"proxy-agent": "^6.5.0",
- "semver": "^7.7.2",
- "tar-fs": "^3.0.8",
+ "semver": "^7.7.4",
+ "tar-fs": "^3.1.1",
"yargs": "^17.7.2"
},
"bin": {
@@ -1425,6 +1427,21 @@
"node": ">=18.0.0"
}
},
+ "node_modules/@web/test-runner-puppeteer": {
+ "version": "0.18.0",
+ "resolved": "https://registry.npmjs.org/@web/test-runner-puppeteer/-/test-runner-puppeteer-0.18.0.tgz",
+ "integrity": "sha512-pc0gADGjqflSRIZQehwD9INKUY1DZ92eWJwuVwZXzKxr5soniT/Bknv2hT5ttpJ5P7ILuCyjJyq5IjKzPBFUXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@web/test-runner-chrome": "^0.18.0",
+ "@web/test-runner-core": "^0.13.0",
+ "puppeteer": "^24.0.0"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -2118,9 +2135,9 @@
}
},
"node_modules/chromium-bidi": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-5.1.0.tgz",
- "integrity": "sha512-9MSRhWRVoRPDG0TgzkHrshFSJJNZzfY5UFqUMuksg7zL1yoZIZ3jLB0YAgHclbiAxPI86pBnwDX1tbzoiV8aFw==",
+ "version": "14.0.0",
+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-14.0.0.tgz",
+ "integrity": "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
@@ -2338,6 +2355,52 @@
"node": ">= 0.8"
}
},
+ "node_modules/cosmiconfig": {
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.1.tgz",
+ "integrity": "sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "env-paths": "^2.2.1",
+ "import-fresh": "^3.3.0",
+ "js-yaml": "^4.1.0",
+ "parse-json": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/d-fischer"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.9.5"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/cosmiconfig/node_modules/parse-json": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
+ "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.0.0",
+ "error-ex": "^1.3.1",
+ "json-parse-even-better-errors": "^2.3.0",
+ "lines-and-columns": "^1.1.6"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -2425,9 +2488,9 @@
"license": "MIT"
},
"node_modules/debug": {
- "version": "4.4.1",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
- "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==",
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2579,9 +2642,9 @@
}
},
"node_modules/devtools-protocol": {
- "version": "0.0.1439962",
- "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1439962.tgz",
- "integrity": "sha512-jJF48UdryzKiWhJ1bLKr7BFWUQCEIT5uCNbDLqkQJBtkFxYzILJH44WN0PDKMIlGDN7Utb8vyUY85C3w4R/t2g==",
+ "version": "0.0.1608973",
+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1608973.tgz",
+ "integrity": "sha512-Tpm17fxYzt+J7VrGdc1k8YdRqS3YV7se/M6KeemEqvUbq/n7At1rWVuXMxQgpWkdwSdIEKYbU//Bve+Shm4YNQ==",
"dev": true,
"license": "BSD-3-Clause"
},
@@ -2670,6 +2733,16 @@
"once": "^1.4.0"
}
},
+ "node_modules/env-paths": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",
+ "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/error-ex": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",
@@ -4937,6 +5010,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/json-parse-even-better-errors": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
+ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
@@ -5150,6 +5230,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/lines-and-columns": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/lit": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/lit/-/lit-3.3.0.tgz",
@@ -6206,28 +6293,51 @@
"node": ">=6"
}
},
+ "node_modules/puppeteer": {
+ "version": "24.43.0",
+ "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.43.0.tgz",
+ "integrity": "sha512-DRnMFz+J3s4lFUQcjqKl0/7h0jzlCZuUFU9lNjtKrnMl5WI1RwCaIItpHVu9empuPyUreYueN0sUW3/pnfdqsg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@puppeteer/browsers": "2.13.1",
+ "chromium-bidi": "14.0.0",
+ "cosmiconfig": "^9.0.0",
+ "devtools-protocol": "0.0.1608973",
+ "puppeteer-core": "24.43.0",
+ "typed-query-selector": "^2.12.2"
+ },
+ "bin": {
+ "puppeteer": "lib/cjs/puppeteer/node/cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/puppeteer-core": {
- "version": "24.9.0",
- "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.9.0.tgz",
- "integrity": "sha512-HFdCeH/wx6QPz8EncafbCqJBqaCG1ENW75xg3cLFMRUoqZDgByT6HSueiumetT2uClZxwqj0qS4qMVZwLHRHHw==",
+ "version": "24.43.0",
+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.43.0.tgz",
+ "integrity": "sha512-cCRNXsUlhyPoKDz6+TiSpfZpRS3mD6Y1YFKhkdr6ik6TMfuJb7fAtXq9ThUFc4sphxObDk3BuAvdxc1Y6YOnqQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "@puppeteer/browsers": "2.10.5",
- "chromium-bidi": "5.1.0",
- "debug": "^4.4.1",
- "devtools-protocol": "0.0.1439962",
- "typed-query-selector": "^2.12.0",
- "ws": "^8.18.2"
+ "@puppeteer/browsers": "2.13.1",
+ "chromium-bidi": "14.0.0",
+ "debug": "^4.4.3",
+ "devtools-protocol": "0.0.1608973",
+ "typed-query-selector": "^2.12.2",
+ "webdriver-bidi-protocol": "0.4.1",
+ "ws": "^8.20.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/puppeteer-core/node_modules/ws": {
- "version": "8.18.2",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz",
- "integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==",
+ "version": "8.20.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
+ "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -7529,9 +7639,9 @@
}
},
"node_modules/typed-query-selector": {
- "version": "2.12.0",
- "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.0.tgz",
- "integrity": "sha512-SbklCd1F0EiZOyPiW192rrHZzZ5sBijB6xM+cpmrwDqObvdtunOHHIk9fCGsoK5JVIYXoyEp4iEdE3upFH3PAg==",
+ "version": "2.12.2",
+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",
+ "integrity": "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==",
"dev": true,
"license": "MIT"
},
@@ -7636,6 +7746,13 @@
"node": ">=0.10.48"
}
},
+ "node_modules/webdriver-bidi-protocol": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.1.tgz",
+ "integrity": "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/webidl-conversions": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
diff --git a/package.json b/package.json
index d184813..b3653dc 100644
--- a/package.json
+++ b/package.json
@@ -17,8 +17,10 @@
"nano-spawn": "^2.0.0"
},
"devDependencies": {
+ "@esm-bundle/chai": "^4.3.4-fix.0",
"@open-wc/testing": "^4.0.0",
"@web/test-runner": "^0.20.2",
+ "@web/test-runner-puppeteer": "^0.18.0",
"sinon": "^21.0.3",
"standard": "^17.1.2",
"undici": "^7.24.6"
diff --git a/server/http.js b/server/http.js
index 07e8837..6bb4d63 100644
--- a/server/http.js
+++ b/server/http.js
@@ -3,9 +3,7 @@ import { URL } from 'url'
import { handleSSE, broadcastSSE } from './sse.js'
import apiHandler from './router/index.js'
import appHandler from './router/app.js'
-import Repository from '../lib/repository.js'
-
-export function createServer ({ repo = new Repository(), connections = [], state }) {
+export function createServer ({ connections = [], state }) {
return http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host}`)
@@ -15,7 +13,7 @@ export function createServer ({ repo = new Repository(), connections = [], state
return broadcastSSE(JSON.stringify({ type: 'state', state }), connections)
}
- if (url.pathname.startsWith('/api/')) return apiHandler(req, res, repo, connections, state)
+ if (url.pathname.startsWith('/api/')) return apiHandler(req, res, connections, state)
return appHandler(req, res)
} catch (error) {
diff --git a/server/router/handlers/channels.js b/server/router/handlers/channels.js
index 2bff172..7860d9f 100644
--- a/server/router/handlers/channels.js
+++ b/server/router/handlers/channels.js
@@ -1,13 +1,16 @@
import { updateAndPersistVideosForChannel } from '../../../lib/update-videos.js'
import { broadcastMessage, parseBody } from '../_helpers.js'
+import { getRepository } from '../../service-container.js'
-export function getChannelHandler (req, res, repo, connections = [], state = {}) {
+export function getChannelHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const channels = repo.getChannels()
res.writeHead(200, { 'Content-Type': 'application/json' })
return res.end(JSON.stringify(channels))
}
-export async function addChannelHandler (req, res, repo, connections = []) {
+export async function addChannelHandler (req, res, connections = []) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
let { name } = parsed
@@ -19,7 +22,7 @@ export async function addChannelHandler (req, res, repo, connections = []) {
return res.end('Channel already added')
}
- const videos = await updateAndPersistVideosForChannel(name, repo)
+ const videos = await updateAndPersistVideosForChannel(name)
if (Array.isArray(videos)) {
repo.addChannel(name)
broadcastMessage('new-videos', { name, videos }, connections)
@@ -31,7 +34,8 @@ export async function addChannelHandler (req, res, repo, connections = []) {
return res.end('Channel not found')
}
-export async function deleteChannelHandler (req, res, repo, connections = [], state = {}) {
+export async function deleteChannelHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
let { name } = parsed
@@ -47,7 +51,8 @@ export async function deleteChannelHandler (req, res, repo, connections = [], st
return res.end('Channel deleted')
}
-export async function ignoreVideoHandler (req, res, repo, connections = [], state = {}) {
+export async function ignoreVideoHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
const { id, ignore } = parsed
@@ -57,7 +62,8 @@ export async function ignoreVideoHandler (req, res, repo, connections = [], stat
return res.end(JSON.stringify(ignored))
}
-export async function deleteVideoHandler (req, res, repo, connections = [], state = {}) {
+export async function deleteVideoHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
const { id } = parsed
diff --git a/server/router/handlers/disk-space.js b/server/router/handlers/disk-space.js
index 20ef552..5d809d8 100644
--- a/server/router/handlers/disk-space.js
+++ b/server/router/handlers/disk-space.js
@@ -1,7 +1,9 @@
import fs from 'fs'
import { broadcastMessage, parseBody, getQuery } from '../_helpers.js'
+import { getRepository } from '../../service-container.js'
-export function diskUsageHandler (req, res, repo, connections = [], state = {}) {
+export function diskUsageHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const onlyIgnored = getQuery(req).onlyIgnored === 'true'
const videos = repo.getAllVideos()
@@ -21,7 +23,8 @@ export function diskUsageHandler (req, res, repo, connections = [], state = {})
res.end(diskSpaceUsed.toFixed(3) + 'GB')
}
-export async function reclaimDiskSpaceHandler (req, res, repo, connections = [], state = {}) {
+export async function reclaimDiskSpaceHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
const { onlyIgnored } = parsed
diff --git a/server/router/handlers/downloads.js b/server/router/handlers/downloads.js
index b3a4164..733f037 100644
--- a/server/router/handlers/downloads.js
+++ b/server/router/handlers/downloads.js
@@ -1,7 +1,9 @@
import { downloadVideo, isUnsupportedUrl, extractIdFromUrl, isYouTubeUrl } from '../../../lib/youtube.js'
import { broadcastMessage, parseBody } from '../_helpers.js'
+import { getRepository } from '../../service-container.js'
-export async function downloadVideoHandler (req, res, repo, connections = [], state = {}) {
+export async function downloadVideoHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
let { id, external } = parsed
@@ -17,7 +19,7 @@ export async function downloadVideoHandler (req, res, repo, connections = [], st
state.downloading[id] = { lines: [] }
let broadcastNewVideoOnce = false
- downloadVideo(id, repo, (message) => {
+ downloadVideo(id, (message) => {
if (external && !broadcastNewVideoOnce) {
broadcastMessage('new-videos', { videos: [repo.getVideo(id)] }, connections)
broadcastNewVideoOnce = true
diff --git a/server/router/handlers/settings.js b/server/router/handlers/settings.js
index 0e33a0b..a1304c9 100644
--- a/server/router/handlers/settings.js
+++ b/server/router/handlers/settings.js
@@ -1,12 +1,15 @@
import { parseBody } from '../_helpers.js'
+import { getRepository } from '../../service-container.js'
-export function getVideoQualityHandler (req, res, repo, connections = [], state = {}) {
+export function getVideoQualityHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const videoQuality = repo.getVideoQualitySetting()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(videoQuality))
}
-export async function setVideoQualityHandler (req, res, repo, connections = [], state = {}) {
+export async function setVideoQualityHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
const videoQuality = parsed
@@ -20,13 +23,15 @@ export async function setVideoQualityHandler (req, res, repo, connections = [],
res.end(JSON.stringify(newQuality))
}
-export function getTranscodeVideosHandler (req, res, repo) {
+export function getTranscodeVideosHandler (req, res) {
+ const repo = getRepository()
const transcodeVideos = repo.getTranscodeVideosSetting()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(transcodeVideos))
}
-export async function setTranscodeVideosHandler (req, res, repo) {
+export async function setTranscodeVideosHandler (req, res) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
const transcodeVideos = parsed
@@ -36,13 +41,15 @@ export async function setTranscodeVideosHandler (req, res, repo) {
res.end()
}
-export async function getExcludedTermsHandler (req, res, repo, connections = [], state = {}) {
+export async function getExcludedTermsHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const excludedTerms = repo.getExcludedTerms()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(excludedTerms))
}
-export async function addExcludedTermHandler (req, res, repo) {
+export async function addExcludedTermHandler (req, res) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
const term = parsed.term
@@ -51,7 +58,8 @@ export async function addExcludedTermHandler (req, res, repo) {
res.end()
}
-export async function removeExcludedTermHandler (req, res, repo) {
+export async function removeExcludedTermHandler (req, res) {
+ const repo = getRepository()
const parsed = await parseBody(req, res)
if (parsed === null) return
const term = parsed.term
diff --git a/server/router/handlers/summaries.js b/server/router/handlers/summaries.js
index bd6e113..31463fa 100644
--- a/server/router/handlers/summaries.js
+++ b/server/router/handlers/summaries.js
@@ -1,7 +1,6 @@
import { summarizeVideo } from '../../../lib/subtitles-summary.js'
import { broadcastMessage, parseBody, llmSettings } from '../_helpers.js'
-
-export async function summarizeVideoHandler (req, res, repo, connections = [], state = {}) {
+export async function summarizeVideoHandler (req, res, connections = [], state = {}) {
const parsed = await parseBody(req, res)
if (parsed === null) return
const { id } = parsed
@@ -9,7 +8,7 @@ export async function summarizeVideoHandler (req, res, repo, connections = [], s
state.summarizing = state.summarizing || {}
state.summarizing[id] = { lines: [] }
- summarizeVideo(id, repo, llmSettings, (line) => {
+ summarizeVideo(id, llmSettings, (line) => {
broadcastMessage('download-log-line', { line }, connections)
})
.then(({ summary, transcript }) =>
diff --git a/server/router/handlers/videos.js b/server/router/handlers/videos.js
index e792973..19fcd80 100644
--- a/server/router/handlers/videos.js
+++ b/server/router/handlers/videos.js
@@ -1,14 +1,17 @@
import fs from 'fs'
import { broadcastMessage, getQuery } from '../_helpers.js'
+import { getRepository } from '../../service-container.js'
-export function searchVideosHandler (req, res, repo, connections = [], state = {}) {
+export function searchVideosHandler (req, res, connections = [], state = {}) {
+ const repo = getRepository()
const query = getQuery(req)
const videos = repo.getVideos(query)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(videos))
}
-export function watchVideoHandler (req, res, repo, connections = []) {
+export function watchVideoHandler (req, res, connections = []) {
+ const repo = getRepository()
const id = req.url.replace('/api/videos/', '').replace(/\.(webm|mp4)$/, '')
const video = repo.getVideo(id)
const location = video.location || `./data/videos/${id}.mp4`
diff --git a/server/router/index.js b/server/router/index.js
index 90be583..254c588 100644
--- a/server/router/index.js
+++ b/server/router/index.js
@@ -46,18 +46,18 @@ const routeMap = {
'DELETE /api/excluded-terms': settings.removeExcludedTermHandler
}
-export default function apiHandler (req, res, repo, connections = [], state = {}) {
+export default function apiHandler (req, res, connections = [], state = {}) {
const path = req.url.split('?')[0]
// Exact match with method
const key = `${req.method} ${path}`
if (routeMap[key]) {
- return routeMap[key](req, res, repo, connections, state)
+ return routeMap[key](req, res, connections, state)
}
// Regex-style matches (path-based patterns with method check)
if (req.method === 'GET' && path.startsWith('/api/videos/')) {
- return videos.watchVideoHandler(req, res, repo, connections)
+ return videos.watchVideoHandler(req, res, connections)
}
if (req.method === 'GET' && path.startsWith('/api/captions/')) {
return videos.captionsHandler(req, res)
diff --git a/server/service-container.js b/server/service-container.js
new file mode 100644
index 0000000..b56df24
--- /dev/null
+++ b/server/service-container.js
@@ -0,0 +1,28 @@
+import Repository from '../lib/repository.js'
+
+const _instances = new Map()
+
+export function initRepository (dataDir) {
+ const key = dataDir || './data'
+ if (!_instances.has(key)) {
+ _instances.set(key, new Repository(key))
+ }
+ return _instances.get(key)
+}
+
+export function getRepository (dataDir) {
+ const key = dataDir || './data'
+ if (_instances.has(key)) {
+ return _instances.get(key)
+ }
+ // Fallback: if no explicit "./data" key exists, return any initialized instance (useful for tests)
+ if (_instances.size > 0) {
+ return _instances.values().next().value
+ }
+ throw new Error(`Repository not initialized for "${key}". Call initRepository("${key}") first.`)
+}
+
+export function resetForTesting (dataDir) {
+ const key = dataDir || './data'
+ _instances.delete(key)
+}
diff --git a/test/repository.search.test.js b/test/repository.search.test.js
index 2711993..d5425bc 100644
--- a/test/repository.search.test.js
+++ b/test/repository.search.test.js
@@ -1,14 +1,23 @@
+import os from 'os'
+import path from 'path'
import { test, describe } from 'node:test'
import fs from 'fs'
import assert from 'assert'
-import Repository from '../lib/repository.js'
+import { initRepository, resetForTesting } from '../server/service-container.js'
+const testDir = path.join(os.tmpdir(), 'my-yt-repo-search-test')
let repo
+
test.beforeEach(() => {
- if (fs.existsSync('./test/data')) {
- fs.rmSync('./test/data', { recursive: true })
+ resetForTesting(testDir)
+ if (fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true })
}
- repo = new Repository('./test/data')
+ repo = initRepository(testDir)
+})
+
+test.afterEach(() => {
+ resetForTesting(testDir)
})
const video1 = { id: '12345', channelName: 'tester', title: 'The Code', description: 'some description in common' }
@@ -21,12 +30,14 @@ describe('search', () => {
assert.equal(results.length, 1)
assert.deepEqual(results, [video2])
})
+
test('searches videos by channel name', async () => {
repo.upsertVideos([video1, video2])
const results = await repo.getVideos({ filter: '@tester' })
assert.equal(results.length, 1)
assert.deepEqual(results, [video1])
})
+
test('searches videos by description', async () => {
repo.upsertVideos([video1, video2])
const results = await repo.getVideos({ filter: 'some description' })
diff --git a/test/repository.test.js b/test/repository.test.js
index 05e7812..effc835 100644
--- a/test/repository.test.js
+++ b/test/repository.test.js
@@ -1,14 +1,23 @@
+import os from 'os'
+import path from 'path'
import { test, describe } from 'node:test'
import fs from 'fs'
import assert from 'assert'
-import Repository from '../lib/repository.js'
+import { initRepository, resetForTesting } from '../server/service-container.js'
+const testDir = path.join(os.tmpdir(), 'my-yt-repo-test')
let repo
+
test.beforeEach(() => {
- if (fs.existsSync('./test/data')) {
- fs.rmSync('./test/data', { recursive: true })
+ resetForTesting(testDir)
+ if (fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true })
}
- repo = new Repository('./test/data')
+ repo = initRepository(testDir)
+})
+
+test.afterEach(() => {
+ resetForTesting(testDir)
})
const video1 = { id: '12345', channelName: 'tester', title: 'The Code', description: 'some description in common' }
@@ -17,8 +26,8 @@ const video2 = { id: '67890', channelName: 'programmer', title: 'The Error', des
describe('repository', () => {
test('empty repo provisions data folder', () => {
assert.ok(repo)
- assert.equal(repo.paths.videos, './test/data/videos.json')
- assert.equal(repo.paths.channels, './test/data/channels.json')
+ assert.equal(repo.paths.videos, `${testDir}/videos.json`)
+ assert.equal(repo.paths.channels, `${testDir}/channels.json`)
assert.equal(repo.getVideos().length, 0)
assert.ok(fs.existsSync(repo.paths.videos))
assert.ok(fs.existsSync(repo.paths.channels))
@@ -114,13 +123,16 @@ describe('repository', () => {
test('gets video quality', () => {
assert.equal(repo.getVideoQualitySetting(), 720)
})
+
test('sets video quality', () => {
assert.ok(repo.setVideoQualitySetting(1080))
assert.equal(repo.getVideoQualitySetting(), 1080)
})
+
test('gets transcode videos setting', () => {
assert.equal(repo.getTranscodeVideosSetting(), true)
})
+
test('sets transcode videos setting', () => {
repo.setTranscodeVideosSetting(false)
assert.equal(repo.getTranscodeVideosSetting(), false)
diff --git a/test/search.test.js b/test/search.test.js
index 1d0a162..8a71995 100644
--- a/test/search.test.js
+++ b/test/search.test.js
@@ -1,22 +1,25 @@
+import os from 'os'
+import path from 'path'
import { test } from 'node:test'
import fs from 'fs'
import assert from 'assert'
import { searchVideosHandler } from '../server/router/index.js'
-import Repository from '../lib/repository.js'
+import { initRepository, resetForTesting } from '../server/service-container.js'
+const testDir = path.join(os.tmpdir(), 'my-yt-search-test')
const req = {}
const assertRes = (assertionCb) => ({
writeHead: () => {},
end: assertionCb
})
-let repo
test.beforeEach(() => {
- if (fs.existsSync('./test/data')) {
- fs.rmSync('./test/data', { recursive: true })
+ resetForTesting(testDir)
+ if (fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true })
}
- repo = new Repository('./test/data')
- repo.upsertVideos([
+
+ initRepository(testDir).upsertVideos([
{
id: '1',
channelName: 'SomeChannel',
@@ -46,18 +49,25 @@ test.beforeEach(() => {
}
])
})
+
+test.afterEach(() => {
+ resetForTesting(testDir)
+})
+
test('gets all videos without filters, show only not ignored videos', () => {
searchVideosHandler(req, assertRes(data => {
assert.deepEqual(JSON.parse(data).length, 1)
- }), repo)
+ }))
})
+
test('filters videos by channel name', () => {
searchVideosHandler({ url: '?filter=@SomeChannel' }, assertRes(data => {
assert.deepEqual(JSON.parse(data).length, 1)
- }), repo)
+ }))
})
+
test('filters videos by title', () => {
searchVideosHandler({ url: '?filter=A+video+title' }, assertRes(data => {
assert.deepEqual(JSON.parse(data).length, 1)
- }), repo)
+ }))
})
diff --git a/test/server.test.js b/test/server.test.js
index a1f2e57..27514fa 100644
--- a/test/server.test.js
+++ b/test/server.test.js
@@ -1,20 +1,26 @@
+import os from 'os'
+import path from 'path'
import { test, describe } from 'node:test'
import fs from 'fs'
import assert from 'assert'
import { createServer } from '../server/http.js'
-import Repository from '../lib/repository.js'
+import { initRepository, resetForTesting } from '../server/service-container.js'
-let repo
+const serverTestDir = path.join(os.tmpdir(), 'my-yt-server-test')
const state = {}
const connections = []
+
test.beforeEach(() => {
- if (fs.existsSync('./test/data')) {
- fs.rmSync('./test/data', { recursive: true })
+ const topDir = path.join(os.tmpdir(), 'my-yt-top-test')
+ resetForTesting(topDir)
+ if (fs.existsSync(topDir)) {
+ fs.rmSync(topDir, { recursive: true })
}
- repo = new Repository('./test/data')
+ initRepository(topDir)
})
+
test('starts server', async () => {
- const server = createServer({ repo, state, connections })
+ const server = createServer({ state, connections })
await new Promise(resolve => server.listen(3001, resolve))
assert.equal(server.address().port, 3001)
await new Promise(resolve => server.close(resolve))
@@ -23,10 +29,16 @@ test('starts server', async () => {
describe('server - user flow', () => {
let server
test.before((cb) => {
- server = createServer({ repo, state, connections })
+ resetForTesting(serverTestDir)
+ if (fs.existsSync(serverTestDir)) {
+ fs.rmSync(serverTestDir, { recursive: true })
+ }
+ initRepository(serverTestDir)
+ server = createServer({ state, connections })
server.listen(3001, cb)
console.log('listening server')
}, { timeout: 10000 })
+
test.after((cb) => {
server.close(cb)
console.log('closed server')
@@ -38,6 +50,7 @@ describe('server - user flow', () => {
assert.equal(res.status, 200)
assert.deepEqual(data, [])
})
+
test('add channel', { timeout: 10000 }, async () => {
const resAddChannel = await fetch('http://0.0.0.0:3001/api/channels', {
method: 'POST',
@@ -60,12 +73,14 @@ describe('server - user flow', () => {
assert.equal(res.status, 200)
assert.deepEqual(data, [{ name: 'veritasium' }])
})
+
test('get videos', { timeout: 5000 }, async () => {
const res = await fetch('http://0.0.0.0:3001/api/videos')
const data = await res.json()
assert.equal(res.status, 200)
assert.ok(data.length > 0)
})
+
test('delete channel', { timeout: 5000 }, async () => {
const resDeleteChannel = await fetch('http://0.0.0.0:3001/api/channels', {
method: 'DELETE',
@@ -80,6 +95,7 @@ describe('server - user flow', () => {
assert.equal(resGetChannels.status, 200)
assert.deepEqual(dataGetChannels, [])
})
+
test('get videos again', { timeout: 5000 }, async () => {
const res = await fetch('http://0.0.0.0:3001/api/videos')
const data = await res.json()