Skip to content

armgit / my-yt

Public Imported from GitHub
0

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

JavaScript

feat: state change based on proxy

Christian Fei64fd22cddfba
diff --git a/lib/router/api.js b/lib/router/api.js
index ae0879f..d328db3 100644
--- a/lib/router/api.js
+++ b/lib/router/api.js
@@ -133,7 +133,6 @@ async function downloadVideoHandler(req, res, repo, connections = [], state = {}
broadcastNewVideoOnce = true
}
broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections)
- state.changed = true
})
.then(() => {
const video = repo.getVideo(id)
@@ -144,7 +143,6 @@ async function downloadVideoHandler(req, res, repo, connections = [], state = {}
})
.finally(() => {
delete state.downloading[id]
- state.changed = true
})
res.writeHead(200, { 'Content-Type': 'text/plain' })
@@ -160,7 +158,6 @@ async function summarizeVideoHandler(req, res, repo, connections = [], state = {
summarizeVideo(id, repo, llmSettings, (line) => {
broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections)
- state.changed = true
})
.then(({summary, transcript}) =>
broadcastSSE(JSON.stringify({type: 'summary', summary, transcript, videoId: id}), connections))
@@ -170,7 +167,6 @@ async function summarizeVideoHandler(req, res, repo, connections = [], state = {
})
.finally(() => {
delete state.summarizing[id]
- state.changed = true
})
res.writeHead(200, { 'Content-Type': 'text/plain' })
diff --git a/lib/server.js b/lib/server.js
index 9da5634..c96b663 100644
--- a/lib/server.js
+++ b/lib/server.js
@@ -7,11 +7,26 @@ import appHandler from './router/app.js'
import Repository from './repository.js'
export function createServer (repo = new Repository()) {
- const state = {
+ const stateChangeHandler = {
+ get(target, key) {
+ if (typeof target[key] === 'object' && target[key] !== null) {
+ return new Proxy(target[key], stateChangeHandler);
+ }
+ return target[key];
+ },
+ set(target, prop, value) {
+ if (target[prop] !== value) broadcastSSE(JSON.stringify({type: 'state', state: target}), connections)
+ target[prop] = value;
+ return true
+ },
+ };
+
+ const state = new Proxy({
downloading: {},
summarizing: {},
- }
- const connections = []
+ }, stateChangeHandler);
+
+ const connections = []
let lastAdded = Date.now()
runUpdateVideos(repo, connections)
@@ -30,11 +45,6 @@ export function createServer (repo = new Repository()) {
})
}
- setInterval(() => {
- if (state.changed) broadcastSSE(JSON.stringify({type: 'state', state}), connections)
- state.changed = false
- }, 2000)
-
return http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host}`)