Skip to content

armgit / my-yt

Public Imported from GitHub
0

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

JavaScript

sse experiment

Christian Fei5d0523df8757
diff --git a/index.html b/index.html
index d8cc046..126e0b4 100644
--- a/index.html
+++ b/index.html
@@ -184,13 +184,42 @@
$videoPlayer.querySelector('video')?.pause()
})
+ const eventSource = new window.EventSource('/')
+
+ eventSource.onmessage = (message) => {
+ if (!message || !message.data) return console.error('skipping empty message')
+ try {
+ const data = JSON.parse(message.data, {})
+ console.log(data)
+ if (data.type === 'all') {
+ showLatestVideos(data.videos, document.querySelector('.channels-container'))
+ handleNewVideos()
+ }
+ if (data.type === 'channel') {
+ const $existingChannelSection = document.querySelector(`details[data-channel="${data.name}"]`)
+ if ($existingChannelSection) {
+ console.log('replacing old channel section', data.name)
+ $existingChannelSection.querySelector(`.videos-container`).remove()
+ $existingChannelSection.appendChild(channelVideosContents(data.videos))
+ } else {
+ const $channelSection = document.createElement('details')
+ $channelSection.dataset['channel'] = data.name
+ $channelSection.classList.add('channel-details')
+ $channelSection.innerHTML = `<summary>${data.name}</summary><h2>${data.name}</h2>`
+ $channelSection.appendChild(channelVideosContents(data.videos))
+ document.querySelector('.channels-container').appendChild($channelSection)
+ }
+ handleNewVideos()
+ }
+ } catch (err) {
+ console.error('sse parse error', err)
+ }
+ }
+
const $showThumbnails = document.getElementById('show-thumbnails')
const $foldedChannels = document.getElementById('folded-channels')
const showThumbnailsKey = 'showThumbnails'
const foldedChannelsKey = 'foldedChannels'
-
- handleShowThumbnails(localStorage.getItem(showThumbnailsKey) === 'false')
- handleFoldedChannels(localStorage.getItem(foldedChannelsKey) === 'false')
$showThumbnails.addEventListener('click', (event) => {
localStorage.setItem(showThumbnailsKey, localStorage.getItem(showThumbnailsKey) === 'true' ? 'false' : 'true')
@@ -257,7 +286,6 @@
})
.then(() => {
document.getElementById('add-channel-form').reset()
- updateVideosList()
})
.catch(error => {
console.error('Error adding channel:', error)
@@ -285,44 +313,39 @@
for (const [name, videos] of Object.entries(videosByChannel)) {
const $channelSection = document.createElement('details')
+ $channelSection.dataset['channel'] = name
$channelSection.classList.add('channel-details')
$channelSection.innerHTML = `<summary>${name}</summary><h2>${name}</h2>`
- const $videosContainer = document.createElement('div')
- $videosContainer.classList.add('videos-container')
- $channelSection.appendChild($videosContainer)
- for (const video of videos) {
- const $video = document.createElement('div')
- $video.classList.add('video')
- $video.innerHTML = `
- <div _href="${video.url}" target="_blank">
- <img src="${video.thumbnail}"/>
- <span>${video.publishedTime}</span> | <span>${video.viewCount}</span> | <span>${video.duration || 'N/A'}</span><br/>
- ${video.title}
- <div class="actions">
- ${!video.downloaded ? `<span class="action download" data-video-id="${video.id}">⬇️ Download</span>` : ''}
- ${video.downloaded ? `<a href="/videos/${video.id}" target="_blank" class="action watch" data-video-id="${video.id}">👀 watch</span>`: ``}
- </div>
- </div>
- `
- $videosContainer.appendChild($video)
- }
+ $channelSection.appendChild(channelVideosContents(videos))
$channelsContainer.appendChild($channelSection)
}
}
-
- async function updateVideosList() {
- return fetchVideos()
- .then((videosByChannel) => {
- showLatestVideos(videosByChannel, document.querySelector('.channels-container'))
- })
+ function channelVideosContents (videos) {
+ const $videosContainer = document.createElement('div')
+ $videosContainer.classList.add('videos-container')
+ for (const video of videos) {
+ const $video = document.createElement('div')
+ $video.classList.add('video')
+ $video.innerHTML = `
+ <div _href="${video.url}" target="_blank">
+ <img src="${video.thumbnail}"/>
+ <span>${video.publishedTime}</span> | <span>${video.viewCount}</span> | <span>${video.duration || 'N/A'}</span><br/>
+ ${video.title}
+ <div class="actions">
+ ${!video.downloaded ? `<span class="action download" data-video-id="${video.id}">⬇️ Download</span>` : ''}
+ ${video.downloaded ? `<a href="/videos/${video.id}" target="_blank" class="action watch" data-video-id="${video.id}">👀 watch</span>`: ``}
+ </div>
+ </div>
+ `
+ $videosContainer.appendChild($video)
+ }
+ return $videosContainer
}
-
- updateVideosList()
- .then(() => {
+
+ function handleNewVideos () {
handleShowThumbnails(localStorage.getItem(showThumbnailsKey) === 'false')
handleFoldedChannels(localStorage.getItem(foldedChannelsKey) === 'false')
- })
- .then(() => {
+
document.querySelectorAll('.video .actions .action.watch')
.forEach($watchAction => {
$watchAction.addEventListener('click', (event) => {
@@ -338,7 +361,6 @@
</p>
</video>
`
- // window.open(`/videos/${videoId}`, '_blank')
})
})
@@ -360,7 +382,8 @@
})
})
})
- })
+ }
+
</script>
</body>
</html>
diff --git a/server.js b/server.js
index 8a67199..c54dee8 100644
--- a/server.js
+++ b/server.js
@@ -5,7 +5,9 @@ import fs from 'fs'
fs.mkdirSync('./data', { recursive: true })
fs.mkdirSync('./data/videos', { recursive: true })
-
+
+const connections = []
+
class Repository {
constructor() {
this.channels = []
@@ -60,12 +62,12 @@ class Repository {
async function main ({port = 3000} = {}) {
const repo = new Repository()
- await updateAndPersistVideos(repo)
-
fs.readdirSync('./data/videos').forEach(file => {
const videoId = file.replace('.mp4', '')
repo.setVideoDownloaded(videoId)
})
+ updateAndPersistVideos(repo)
+
createServer({repo, port})
.listen(port, () => {
@@ -80,10 +82,24 @@ if (import.meta.url.endsWith('server.js')) {
async function updateAndPersistVideos (repo) {
const channels = repo.getChannels()
+ const existingVideos = repo.getVideos()
for (const channel of channels) {
console.log('updating videos for', channel.name)
const videos = await getVideosFor(channel.name)
- if (videos) repo.saveChannelVideos(channel.name, videos)
+ const existingChannelVideos = existingVideos[channel.name]
+ if (existingChannelVideos) {
+ for (const video of videos) {
+ const existingVideo = existingChannelVideos.find(v => v.id === video.id)
+ if (existingVideo && existingVideo.downloaded) {
+ video.downloaded = existingVideo.downloaded
+ console.log('setting video as downloaded', video.id)
+ }
+ }
+ }
+ if (videos) {
+ repo.saveChannelVideos(channel.name, videos)
+ broadcastSSE(JSON.stringify({type: 'channel', name: channel.name, videos}), connections)
+ }
}
console.log('All videos updated')
}
@@ -92,6 +108,7 @@ async function updateAndPersistVideosForChannel(repo, name) {
const videos = await getVideosFor(name)
if (videos) repo.saveChannelVideos(name, videos)
console.log('videos for channel updated', name)
+ return videos
}
async function downloadVideo(id, repo) {
@@ -141,6 +158,27 @@ async function getVideosFor(channelName) {
}
}
+function handleSSE (res, connections = []) {
+ connections.push(res)
+ res.on('close', () => {
+ connections.splice(connections.findIndex(c => res === c), 1)
+ })
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ Connection: 'keep-alive'
+ })
+}
+
+function broadcastSSE (data, connections = []) {
+ connections.forEach(connection => {
+ if (!connection) return
+ const id = new Date().toISOString()
+ connection.write('id: ' + id + '\n')
+ connection.write('data: ' + data + '\n\n')
+ })
+}
+
function createServer ({repo, port = 3000}) {
return http.createServer(async (req, res) => {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`)
@@ -159,7 +197,8 @@ function createServer ({repo, port = 3000}) {
name = name.trim()
console.log('adding channel', name)
repo.addChannel(name)
- await updateAndPersistVideosForChannel(repo, name)
+ const videos = await updateAndPersistVideosForChannel(repo, name)
+ broadcastSSE(JSON.stringify({type: 'channel', name, videos}), connections)
res.writeHead(201, { 'Content-Type': 'text/plain' })
res.end('Channel added')
})
@@ -172,7 +211,12 @@ function createServer ({repo, port = 3000}) {
})
req.on('end', () => {
const { id } = JSON.parse(body)
+ const {channelName} = repo.getVideo(id)
+ const videos = repo.getVideos()[channelName]
downloadVideo(id, repo)
+ .then(() => {
+ broadcastSSE(JSON.stringify({type: 'channel', name: channelName, videos}), connections)
+ })
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Download started')
})
@@ -221,6 +265,10 @@ function createServer ({repo, port = 3000}) {
}
return
}
+ if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') >= 0) {
+ handleSSE(res, connections)
+ return broadcastSSE(JSON.stringify({type: 'all', videos: repo.getVideos()}), [res])
+ }
const indexHtml = await fs.promises.readFile('index.html', 'utf8')
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(indexHtml)