A clean and minimal youtube frontend, without all the ads and whistles
JavaScript
cleanup & extract
Christian Fei6af6b8851d0d
diff --git a/index.html b/index.htmlindex 182e9fc..5f7008a 100644--- a/index.html+++ b/index.html@@ -4,175 +4,7 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>my-yt</title>- <style>- body {- font-family: Arial, sans-serif;- margin: 20px;- }- form {- margin-bottom: 20px;- }- main {- user-select: none;- -webkit-user-select: none;- }- .m-0 {- margin: 0;- }- .loader {- display: inline-block;- border: 2px solid #f3f3f3;- border-top: 2px solid #3498db;- border-radius: 50%;- width: 0.5rem;- height: 0.5rem;- animation: spin 2s linear infinite;- opacity: 0;- }- .loader.show {- opacity: 1;- }- @keyframes spin {- 0% { transform: rotate(0deg); }- 100% { transform: rotate(360deg); }- }- </style>- <style>- .channel-details.has-new-videos {- background-color: #aeaeae- }- .videos-container {- display: flex;- justify-content: space-around;- flex-wrap: wrap;- align-items: center;- gap: 10px;- padding: 10px;- margin: 0;- }- .video {- display: flex;- flex-wrap: wrap;- align-items: center;- width: 280px;- max-height: 300px;- text-align: left;- text-decoration: none;- color: black;- font-weight: bold;- padding: 5px;- background-color: #f0f0f0;- margin: 5px;- }- .video img {- width: 100%;- height: auto;- }- .hide-thumbnails .video img {- display: none !important;- visibility: hidden !important;- opacity: 0 !important;-- }- .video span {- font-size: 12px;- color: #555;- }- .video a {- font-size: 12px;- text-decoration: none;- color: black;- }-- .video .actions {- font-size: 0.9rem;- }- .video .actions > * {- cursor: pointer;- }-- .download-log {- position: fixed;- bottom: 10px;- right: 10px;- width: 300px;- overflow: hidden;- /* height: 200px; */- font-size: 10px;- background-color: white;- border: 1px solid lightgrey;- box-shadow: 2px 2px 10px rgba(0,0,0,0.1);- overflow-y: auto;- padding: 10px;- background-color: #f0f0f0;- color: #000;- border-radius: 8px;- }- .download-log .lines {- max-height: 100px;- overflow-y: scroll;- }- </style>- <style>- #open-settings {- position: fixed;- top: 0;- right: 0;- display: block;- background: white;- border: 1px solid lightgrey;- border-radius: 4px;- font-size: 1rem;- padding: 0.5rem;- }- #settings {- position: relative;- }- #settings #close {- position:absolute;- top: 0.5rem;- right: 0.5rem;- }- ::backdrop {- background-image: linear-gradient(- 45deg,- #fff,- #292828- );- opacity: 0.85;- }- body.dialog-opened {- overflow: hidden;- }- </style>- <style>- body > header {- padding: 1em 0.5em;- margin-bottom: 3rem;- }-- details {- padding: 10px;- border: 5px solid #f7f7f7;- border-radius: 3px;- }-- details {- transition: 0.2s background linear;- }-- details:hover {- /* background: #eaeaea; */- }-- details > summary {- transition: color 1s;- }-- details[open] > summary {- color: #171717;- }- </style>+ <link rel="stylesheet" href="/main.css"></head><body><header>@@ -229,398 +61,6 @@</details></main>-- <script>- // app: sse updates and renders- const eventSource = new window.EventSource('/')- const $channelsContainer = document.querySelector('.channels-container')-- eventSource.onmessage = (message) => {- if (!message || !message.data) return console.error('skipping empty message')- try {- const data = JSON.parse(message.data, {})- console.log('[sse] message', data)-- if (data.type === 'download-log-line' && data.line) {- const $downloadLog = document.querySelector('.download-log');- $downloadLog.open = true;- const $downloadLogLines = document.querySelector('.download-log .lines');- const text = $downloadLogLines.innerText- let lines = text.split('\n')- lines = lines.join('\n') + '\n' + data.line- $downloadLogLines.innerText = lines- $downloadLogLines.scrollTop = $downloadLogLines.scrollHeight;- }-- if (data.type === 'all' && data.videos) {- $channelsContainer.innerHTML = ''-- for (const [name, videos] of Object.entries(data.videos)) {- appendChannelSectionTo(name, videos, $channelsContainer)- updateDownloadedVideos(videos)- }- handleNewVideos(data.videos)- window.videos = data.videos- applyFoldedChannels(store.get(store.foldedChannelsKey))- }-- if (data.type === 'channel' && data.name && Array.isArray(data.videos)) {- const $existingChannelSection = document.querySelector(`details[data-channel="${data.name}"]`)- if ($existingChannelSection) {- $existingChannelSection.querySelector(`.videos-container`).replaceWith(channelVideosContents(data.videos))- } else {- appendChannelSectionTo(data.name, data.videos, $channelsContainer)- }- updateDownloadedVideos(data.videos)- window.videos[data.name] = data.videos- handleNewVideos(data.videos)- }-- } catch (err) {- console.error('sse parse error', err)- }- }-- function appendChannelSectionTo (name, videos, $channelsContainer) {- const $channelSection = document.createElement('details')- $channelSection.open = store.get(store.foldedChannelsKey)- $channelSection.dataset['channel'] = name- $channelSection.classList.add('channel-details')- $channelSection.innerHTML = `<summary>${name}</summary>`- $channelSection.appendChild(channelVideosContents(videos))- $channelsContainer.appendChild($channelSection)- }-- function updateDownloadedVideos (videos) {- const $downloadedVideosContainer = document.querySelector('details.downloaded-videos-container')- const $videosContainer = $downloadedVideosContainer.querySelector('.videos-container')- videos.filter(v => v.downloaded).forEach(v => {- const $existing = $downloadedVideosContainer.querySelector(`[data-video-id="${v.id}"]`)- if ($existing) {- const $video = createVideoElement(v)- $existing.replaceWith($video)- return- }- const $video = createVideoElement(v)- $videosContainer.appendChild($video)- })- }-- // store- class Store {- showThumbnailsKey = 'showThumbnails'- foldedChannelsKey = 'foldedChannels'- ignoreVideoKey = 'ignoreVideo'- lastVideosKey = 'lastVideos'-- constructor() {- if (!localStorage.getItem(this.ignoreVideoKey)) localStorage.setItem(this.ignoreVideoKey, '[]')- if (!localStorage.getItem(this.showThumbnailsKey)) localStorage.setItem(this.showThumbnailsKey, 'true')- if (!localStorage.getItem(this.foldedChannelsKey)) localStorage.setItem(this.foldedChannelsKey, 'true')- if (!localStorage.getItem(this.lastVideosKey)) localStorage.setItem(this.lastVideosKey, '{}')- }-- toggle (key) {- if (![this.showThumbnailsKey, this.foldedChannelsKey].includes(key)) return console.error('invalid key', key)- localStorage.setItem(key, localStorage.getItem(key) === 'true' ? 'false' : 'true')- }- get(key) {- if (![this.showThumbnailsKey, this.foldedChannelsKey, this.ignoreVideoKey, this.lastVideosKey].includes(key)) return console.error('invalid key', key)- return JSON.parse(localStorage.getItem(key))- }- set(key, value) {- if (typeof value === 'string') {- localStorage.setItem(key, value)- } else {- localStorage.setItem(key, JSON.stringify(value))- }- }- push(key, item) {- if (![this.ignoreVideoKey].includes(key)) return console.error('invalid key', key)- const list = this.get(key)- list.push(item)- this.set(key, list)- return item- }- }-- const store = new Store()-- // settings modal- const $settings = document.querySelector("dialog#settings")- const $openSettings = document.querySelector("#open-settings")- const $closeSettings = $settings.querySelector("button")- $openSettings.addEventListener("click", () => $settings.showModal())- $closeSettings.addEventListener("click", () => $settings.close())-- // video player modal- const $videoPlayer = document.querySelector('dialog#video-player')- const $closeVideoPlayer = $videoPlayer.querySelector("button")- $closeVideoPlayer.addEventListener("click", () => $videoPlayer.close())- $videoPlayer.addEventListener('close', () => $videoPlayer.querySelector('video')?.pause())-- // summary modal- const $summaryModal = document.querySelector('dialog#summary')- const $closeSummary = $summaryModal.querySelector("button")- $closeSummary.addEventListener("click", () => $summaryModal.close())- $summaryModal.addEventListener('close', () => {})-- // settings ui- const $showThumbnails = document.getElementById('show-thumbnails')- const $foldedChannels = document.getElementById('folded-channels')- $showThumbnails.addEventListener('click', (event) => {- store.toggle(store.showThumbnailsKey)- applyShowThumbnails(store.get(store.showThumbnailsKey))- })- $foldedChannels.addEventListener('click', (event) => {- store.toggle(store.foldedChannelsKey)- applyFoldedChannels(store.get(store.foldedChannelsKey))- })-- // apply settings- applyShowThumbnails(store.get(store.showThumbnailsKey))- applyFoldedChannels(store.get(store.foldedChannelsKey))-- // observe dialog open/close and prevent body background scroll- observeDialogOpenPreventScroll($settings)- observeDialogOpenPreventScroll($videoPlayer)- observeDialogOpenPreventScroll($summaryModal)--- function observeDialogOpenPreventScroll (dialog) {- new MutationObserver((mutationList, observer) => {- for (const mutation of mutationList) {- if (mutation.type === "attributes" && mutation.attributeName === 'open') {- document.body.classList[mutation.target.open ? 'add' : 'remove']('dialog-opened')- }- }- }).observe(dialog, { attributes: true, childList: true, subtree: true })- }-- function applyShowThumbnails(showThumbnails) {- if (showThumbnails) {- document.body.classList.remove('hide-thumbnails')- } else {- document.body.classList.add('hide-thumbnails')- }- document.querySelector('#show-thumbnails').checked = showThumbnails- }-- function applyFoldedChannels (foldedChannels) {- console.log('applyFoldedChannels', foldedChannels)- if (foldedChannels) {- [...document.querySelectorAll('.channels-container details')]- .forEach(d => d.open = false)- } else {- [...document.querySelectorAll('.channels-container details')]- .forEach(d => d.open = true)- }- document.querySelector('#folded-channels').checked = foldedChannels- }-- // app: add channel- document.getElementById('add-channel-form').addEventListener('submit', addChannelHandler)-- function addChannelHandler(event) {- event.preventDefault()-- const form = event.target- const button = form.querySelector('button')- const input = form.querySelector('input')- const loader = form.querySelector('.loader')- freezeForm()-- const channelName = document.getElementById('channel-name').value-- if (!channelName) return alert('empty channel name'), unfreezeForm();-- fetch('/channels', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ name: channelName })- })- .then(() => document.getElementById('add-channel-form').reset())- .catch(error => console.error('Error adding channel:', error))- .finally(unfreezeForm)-- function freezeForm() {- input.disabled = true- button.disabled = true- loader.classList.add('show')- }- function unfreezeForm() {- input.disabled = false- button.disabled = false- loader.classList.remove('show')- }- }-- function channelVideosContents (videos) {- if (!videos) return- const ignoreList = store.get(store.ignoreVideoKey)- const $videosContainer = document.createElement('div')- $videosContainer.classList.add('videos-container')- for (const video of videos) {- if (ignoreList.includes(video.id)) {- console.log('ignoring video', video.id)- continue- }- $videosContainer.appendChild(createVideoElement(video))- }- return $videosContainer- }-- function createVideoElement (video) {- const $video = document.createElement('div')- $video.classList.add('video')- $video.dataset['videoId'] = video.id- $video.innerHTML = `- ${video.downloaded- ? `<video controls width="280">- <source src="/videos/${video.id}" type="video/mp4" />- <p>- Your browser does not support the video tag.- Download the video instead <a href="/videos/${video.id}" target="_blank">here</a>- </p>- </video>`- : `<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- ? `<a tabindex="0" href="/videos/${video.id}" target="_blank" class="action watch" data-video-id="${video.id}">π watch</a>`- : `<span tabindex="0" class="action download" data-video-id="${video.id}">β¬οΈ Download</span>`}- ${!video.summary- ? `<span tabindex="0" class="action summarize" data-video-id="${video.id}">π Summarize</span>`- : `<span tabindex="0" class="action show-summary" data-video-id="${video.id}">π Summary</span>`}- <span tabindex="0" class="action ignore" data-video-id="${video.id}">π Ignore</span>- </div>- `- return $video- }-- function handleNewVideos (videos) {- document.querySelectorAll('.video .actions .action.watch')- .forEach($watchAction => {- $watchAction.removeEventListener('click', watchVideoHandler)- $watchAction.addEventListener('click', watchVideoHandler)- $watchAction.removeEventListener('keydown', (event) => event.key === 'Enter' && watchVideoHandler(event))- $watchAction.addEventListener('keydown', (event) => event.key === 'Enter' && watchVideoHandler(event))- })-- document.querySelectorAll('.video .actions .action.download')- .forEach($downloadAction => {- $downloadAction.removeEventListener('click', downloadVideoHandler)- $downloadAction.addEventListener('click', downloadVideoHandler)- $downloadAction.removeEventListener('keydown', (event) => event.key === 'Enter' && downloadVideoHandler(event))- $downloadAction.addEventListener('keydown', (event) => event.key === 'Enter' && downloadVideoHandler(event))- })-- document.querySelectorAll('.video .actions .action.ignore')- .forEach($ignoreAction => {- $ignoreAction.removeEventListener('click', ignoreVideoHandler)- $ignoreAction.addEventListener('click', ignoreVideoHandler)- $ignoreAction.removeEventListener('keydown', (event) => event.key === 'Enter' && ignoreVideoHandler(event))- $ignoreAction.addEventListener('keydown', (event) => event.key === 'Enter' && ignoreVideoHandler(event))- })-- document.querySelectorAll('.video .actions .action.summarize')- .forEach($ignoreAction => {- $ignoreAction.removeEventListener('click', summarizeVideoHandler)- $ignoreAction.addEventListener('click', summarizeVideoHandler)- $ignoreAction.removeEventListener('keydown', (event) => event.key === 'Enter' && summarizeVideoHandler(event))- $ignoreAction.addEventListener('keydown', (event) => event.key === 'Enter' && summarizeVideoHandler(event))- })-- document.querySelectorAll('.video .actions .action.show-summary')- .forEach($ignoreAction => {- $ignoreAction.removeEventListener('click', showSummaryHandler)- $ignoreAction.addEventListener('click', showSummaryHandler)- $ignoreAction.removeEventListener('keydown', (event) => event.key === 'Enter' && showSummaryHandler(event))- $ignoreAction.addEventListener('keydown', (event) => event.key === 'Enter' && showSummaryHandler(event))- })-- if (typeof videos === 'object' && !Array.isArray(videos)) {- const lastVideos = store.get(store.lastVideosKey)- for (const [name, vids] of Object.entries(videos)) {- if (lastVideos[name] != vids[0]?.id)- document.querySelector(`details[data-channel="${name}"]`)?.classList.add('has-new-videos')- lastVideos[name] = vids[0]?.id- }- store.set(store.lastVideosKey, lastVideos)- }- }-- function watchVideoHandler (event) {- event.preventDefault()- const videoId = event.target.dataset.videoId- $videoPlayer.showModal()- $videoPlayer.querySelector('div').innerHTML = `- <video autoplay controls width="500">- <source src="/videos/${videoId}" type="video/mp4" />- <p>- Your browser does not support the video tag.- Download the video instead <a href="/videos/${videoId}" target="_blank">here</a>- </p>- </video>- `- }-- function ignoreVideoHandler (event) {- event.preventDefault()- const videoId = event.target.dataset.videoId- store.push(store.ignoreVideoKey, videoId)- event.target.parentNode?.parentNode?.remove()- }-- function downloadVideoHandler (event) {- event.preventDefault()- const downloadStartedText = 'β‘οΈ Download started'- if (event.target.innerText === downloadStartedText) return console.log('already downloading')- event.target.innerText = downloadStartedText- fetch('/download-video', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ id: event.target.dataset.videoId }),- })- .then(() => {- console.log('Download started')- })- .catch((error) => {- console.error('Error starting download:', error)- })- }-- function summarizeVideoHandler (event) {- event.preventDefault()- const summaryStartedText = 'β‘οΈ summary started'- if (event.target.innerText === summaryStartedText) return console.log('already summarizing')- event.target.innerText = summaryStartedText- fetch('/summarize-video', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ id: event.target.dataset.videoId }),- })- .then(() => {- console.log('summary started')- })- .catch((error) => {- console.error('Error starting summary:', error)- })- }-- function showSummaryHandler (event) {- event.preventDefault()- const videoId = event.target.dataset.videoId- for (const [name, videos] of Object.entries(window.videos)) {- const video = videos.find(video => video.id === videoId)- if (video) {- document.querySelector('dialog#summary').showModal()- document.querySelector('dialog#summary div').innerText = video.summary- return- }- }- }- </script>+ <script src="/main.js"></script></body></html>diff --git a/lib/server.js b/lib/server.jsindex bb28ff2..724b260 100644--- a/lib/server.js+++ b/lib/server.js@@ -4,6 +4,7 @@ import fs from 'fs'import { summarizeVideo } from './subtitles-summary.js'import { handleSSE, broadcastSSE } from './sse.js'import { downloadVideo, getVideosFor } from './youtube.js'+export function createServer ({repo, port = 3000, connections = []}) {updateAndPersistVideos(repo, ({name, videos}) => {broadcastSSE(JSON.stringify({type: 'channel', name, videos}), connections)@@ -17,119 +18,136 @@ export function createServer ({repo, port = 3000, connections = []}) {return http.createServer(async (req, res) => {const parsedUrl = new URL(req.url, `http://${req.headers.host}`)- if (parsedUrl.pathname === '/channels' && req.method === 'POST') {- let body = ''- req.on('data', chunk => {- body += chunk.toString()- })- req.on('end', async () => {- let { name } = JSON.parse(body)- name = name.trim()- const videos = await updateAndPersistVideosForChannel(name, repo)- if (Array.isArray(videos)) {- repo.addChannel(name)- broadcastSSE(JSON.stringify({type: 'channel', name, videos}), connections)- res.writeHead(201, { 'Content-Type': 'text/plain' })- res.end('Channel added')- } else {- res.writeHead(404, { 'Content-Type': 'text/plain' })- res.end('Channel not found')- }- })- return- }- if (parsedUrl.pathname === '/download-video' && req.method === 'POST') {- let body = ''- req.on('data', chunk => {- body += chunk.toString()- })- req.on('end', () => {- const { id } = JSON.parse(body)- const {channelName} = repo.getVideo(id)- const videos = repo.getChannelVideos(channelName)- downloadVideo(id, repo, (line) =>- broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))- .catch((error) => console.error(error))- .finally(() =>- broadcastSSE(JSON.stringify({type: 'channel', name: channelName, videos}), connections))- res.writeHead(200, { 'Content-Type': 'text/plain' })- res.end('Download started')- })- return- }- if (parsedUrl.pathname === '/summarize-video' && req.method === 'POST') {- let body = ''- req.on('data', chunk => {- body += chunk.toString()- })- req.on('end', () => {- const { id } = JSON.parse(body)- const {channelName} = repo.getVideo(id)- const videos = repo.getChannelVideos(channelName)- summarizeVideo(id, repo, (line) =>- broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))- .catch((error) => console.error(error))- .finally(() =>- broadcastSSE(JSON.stringify({type: 'channel', name: channelName, videos}), connections))- res.writeHead(200, { 'Content-Type': 'text/plain' })- res.end('Download started')- })- return- }- if (parsedUrl.pathname.match('\/videos\/.*') && req.method === 'GET') {- const videoPath = parsedUrl.pathname.replace('/videos/', './data/videos/') + '.mp4'- if (!fs.existsSync(videoPath)) {- res.writeHead(404, { 'Content-Type': 'text/plain' })- res.end('Video not found')- return- }- try {- const stats = fs.statSync(videoPath)- //https://stackoverflow.com/questions/4360060/video-streaming-with-html-5-via-node-js/29126190#29126190- var range = req.headers.range || "";- var total = stats.size;- if (range) {- var parts = range.replace(/bytes=/, "").split("-");- var partialstart = parts[0];- var partialend = parts[1];-- var start = parseInt(partialstart, 10);- var end = partialend > 0 ? parseInt(partialend, 10) : total-1;-- var chunksize = (end-start)+1;- res.writeHead(206, {- "Content-Range": "bytes " + start + "-" + end + "/" + total,- "Accept-Ranges": "bytes",- "Content-Length": chunksize,- "Content-Type": 'video/mp4'- });- } else {- res.writeHead(200, {- "Accept-Ranges": "bytes",- "Content-Length": stats.size,- "Content-Type": 'video/mp4'- });- }- fs.createReadStream(videoPath).pipe(res)- } catch (error) {- console.error('error reading file ' + videoPath)- console.error(error)- res.writeHead(404, { 'Content-Type': 'text/plain' })- res.end('Video not found')- }- return- }if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') >= 0) {handleSSE(res, connections)broadcastSSE(JSON.stringify({type: 'all', videos: repo.getVideos()}), [res])return}- const indexHtml = await fs.promises.readFile('index.html', 'utf8')- res.writeHead(200, { 'Content-Type': 'text/html' })- res.end(indexHtml)++ if (parsedUrl.pathname === '/channels' && req.method === 'POST')+ return addChannelHandler(req, res)+ if (parsedUrl.pathname === '/download-video' && req.method === 'POST')+ return downloadVideoHandler(req, res, connections)+ if (parsedUrl.pathname === '/summarize-video' && req.method === 'POST')+ return summariVideoHandler(req, res, connections)+ if (parsedUrl.pathname.match('\/videos\/.*') && req.method === 'GET')+ return watchVideoHandler(req, res)+ if (parsedUrl.pathname === '/main.css')+ return fileHandler('main.css', 'text/css')+ if (parsedUrl.pathname === '/main.js')+ return fileHandler('main.js', 'application/javascript')+ return fileHandler('index.html', 'text/html')})++ function fileHandler (filePath, contentType) {+ res.writeHead(200, { 'Content-Type': contentType })+ res.end(fs.readFileSync(filePath, 'utf8'))+ return+ }+ function addChannelHandler(req, res) {+ let body = ''+ req.on('data', chunk => {+ body += chunk.toString()+ })+ req.on('end', async () => {+ let { name } = JSON.parse(body)+ name = name.trim()+ const videos = await updateAndPersistVideosForChannel(name, repo)+ if (Array.isArray(videos)) {+ repo.addChannel(name)+ broadcastSSE(JSON.stringify({type: 'channel', name, videos}), connections)+ res.writeHead(201, { 'Content-Type': 'text/plain' })+ res.end('Channel added')+ } else {+ res.writeHead(404, { 'Content-Type': 'text/plain' })+ res.end('Channel not found')+ }+ })+ }++ function downloadVideoHandler(req, res, connections = []) {+ let body = ''+ req.on('data', chunk => {+ body += chunk.toString()+ })+ req.on('end', () => {+ const { id } = JSON.parse(body)+ const {channelName} = repo.getVideo(id)+ const videos = repo.getChannelVideos(channelName)+ downloadVideo(id, repo, (line) =>+ broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))+ .catch((error) => console.error(error))+ .finally(() =>+ broadcastSSE(JSON.stringify({type: 'channel', name: channelName, videos}), connections))+ res.writeHead(200, { 'Content-Type': 'text/plain' })+ res.end('Download started')+ })+ }++ function summariVideoHandler(req, res, connections = []) {+ let body = ''+ req.on('data', chunk => {+ body += chunk.toString()+ })+ req.on('end', () => {+ const { id } = JSON.parse(body)+ const {channelName} = repo.getVideo(id)+ const videos = repo.getChannelVideos(channelName)++ summarizeVideo(id, repo, (line) =>+ broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))+ .catch((error) => console.error(error))+ .finally(() =>+ broadcastSSE(JSON.stringify({type: 'channel', name: channelName, videos}), connections))+ res.writeHead(200, { 'Content-Type': 'text/plain' })+ res.end('Download started')+ })+ }++ function watchVideoHandler(req, res) {+ const videoPath = req.url.replace('/videos/', './data/videos/') + '.mp4'+ if (!fs.existsSync(videoPath)) {+ res.writeHead(404, { 'Content-Type': 'text/plain' })+ res.end('Video not found')+ return+ }+ try {+ const stats = fs.statSync(videoPath)+ //https://stackoverflow.com/questions/4360060/video-streaming-with-html-5-via-node-js/29126190#29126190+ var range = req.headers.range || "";+ var total = stats.size;+ if (range) {+ var parts = range.replace(/bytes=/, "").split("-");+ var partialstart = parts[0];+ var partialend = parts[1];++ var start = parseInt(partialstart, 10);+ var end = partialend > 0 ? parseInt(partialend, 10) : total-1;++ var chunksize = (end-start)+1;+ res.writeHead(206, {+ "Content-Range": "bytes " + start + "-" + end + "/" + total,+ "Accept-Ranges": "bytes",+ "Content-Length": chunksize,+ "Content-Type": 'video/mp4'+ });+ } else {+ res.writeHead(200, {+ "Accept-Ranges": "bytes",+ "Content-Length": stats.size,+ "Content-Type": 'video/mp4'+ });+ }+ fs.createReadStream(videoPath).pipe(res)+ } catch (error) {+ console.error('error reading file ' + videoPath)+ console.error(error)+ res.writeHead(404, { 'Content-Type': 'text/plain' })+ res.end('Video not found')+ }+ }}async function updateAndPersistVideos (repo, callback = () => {}) {diff --git a/lib/subtitles-summary.js b/lib/subtitles-summary.jsindex 63710a2..47cf40d 100644--- a/lib/subtitles-summary.js+++ b/lib/subtitles-summary.js@@ -1,24 +1,9 @@-import { execa } from "execa"import fs from "fs"--export function cleanTranscript (transcript) {- return transcript- .split('\n')- .map(line => {- if (/^\d+/.test(line)) return- line = line.replace(/\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}/g, '')- return line.replace(/<[^>]+>/g, '').trim()- }).filter(Boolean).join('\n').trim()-}+import { getVideoSubtitles } from "./youtube.js"export async function summarizeVideo(id, repo, callback = () => {}) {try {- for await (const line of execa`yt-dlp --skip-download --write-subs --write-auto-subs --sub-lang en --sub-format ttml --convert-subs srt --default-search ytsearch ${id} -o ./data/videos/${id}-sub`.iterable()) {- callback(line)- console.log(line)- }- const transcriptPath = `./data/videos/${id}-sub.en.srt`- const transcript = fs.readFileSync(transcriptPath, 'utf-8')+ const transcript = await getVideoSubtitles(id, callback)let cleanedTranscript = cleanTranscript(transcript)console.log('cleanedTranscript.length', cleanedTranscript.length)repo.setVideoTranscript(id, cleanedTranscript)@@ -35,6 +20,15 @@ export async function summarizeVideo(id, repo, callback = () => {}) {console.error('Error downloading video:', error)}}+export function cleanTranscript (transcript) {+ return transcript+ .split('\n')+ .map(line => {+ if (/^\d+/.test(line)) return+ line = line.replace(/\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}/g, '')+ return line.replace(/<[^>]+>/g, '').trim()+ }).filter(Boolean).join('\n').trim()+}async function fetchAIResponseLMSTUDIO (prompt) {diff --git a/lib/youtube.js b/lib/youtube.jsindex a5e37bd..01e364b 100644--- a/lib/youtube.js+++ b/lib/youtube.js@@ -14,6 +14,15 @@ export async function downloadVideo(id, repo, callback = () => {}) {}}+export async function getVideoSubtitles (id, callback = () => {}) {+ for await (const line of execa`yt-dlp --skip-download --write-subs --write-auto-subs --sub-lang en --sub-format ttml --convert-subs srt --default-search ytsearch ${id} -o ./data/videos/${id}-sub`.iterable()) {+ callback(line)+ console.log(line)+ }+ const transcriptPath = `./data/videos/${id}-sub.en.srt`+ const transcript = fs.readFileSync(transcriptPath, 'utf-8')+ return transcript+}export async function getVideosFor(channelName) {try {diff --git a/main.css b/main.cssnew file mode 100644index 0000000..4437176--- /dev/null+++ b/main.css@@ -0,0 +1,186 @@+body {+ font-family: Arial, sans-serif;+ margin: 20px;+}+form {+ margin-bottom: 20px;+}+main {+ user-select: none;+ -webkit-user-select: none;+}+.m-0 {+ margin: 0;+}+.loader {+ display: inline-block;+ border: 2px solid #f3f3f3;+ border-top: 2px solid #3498db;+ border-radius: 50%;+ width: 0.5rem;+ height: 0.5rem;+ animation: spin 2s linear infinite;+ opacity: 0;+}+.loader.show {+ opacity: 1;+}+@keyframes spin {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(360deg); }+}+++++++.channel-details.has-new-videos {+ background-color: #aeaeae+}+.videos-container {+ display: flex;+ justify-content: space-around;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px;+ padding: 10px;+ margin: 0;+}+.video {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ width: 280px;+ max-height: 300px;+ text-align: left;+ text-decoration: none;+ color: black;+ font-weight: bold;+ padding: 5px;+ background-color: #f0f0f0;+ margin: 5px;+}+.video img {+ width: 100%;+ height: auto;+}+.hide-thumbnails .video img {+ display: none !important;+ visibility: hidden !important;+ opacity: 0 !important;++}+.video span {+ font-size: 12px;+ color: #555;+}+.video a {+ font-size: 12px;+ text-decoration: none;+ color: black;+}++.video .actions {+ font-size: 0.9rem;+}+.video .actions > * {+ cursor: pointer;+}++.download-log {+ position: fixed;+ bottom: 10px;+ right: 10px;+ width: 300px;+ overflow: hidden;+ /* height: 200px; */+ font-size: 10px;+ background-color: white;+ border: 1px solid lightgrey;+ box-shadow: 2px 2px 10px rgba(0,0,0,0.1);+ overflow-y: auto;+ padding: 10px;+ background-color: #f0f0f0;+ color: #000;+ border-radius: 8px;+}+.download-log .lines {+ max-height: 100px;+ overflow-y: scroll;+}++++++++#open-settings {+ position: fixed;+ top: 0;+ right: 0;+ display: block;+ background: white;+ border: 1px solid lightgrey;+ border-radius: 4px;+ font-size: 1rem;+ padding: 0.5rem;+}+#settings {+ position: relative;+}+#settings #close {+ position:absolute;+ top: 0.5rem;+ right: 0.5rem;+}+::backdrop {+ background-image: linear-gradient(+ 45deg,+ #fff,+ #292828+ );+ opacity: 0.85;+}+body.dialog-opened {+ overflow: hidden;+}+++++++++++++body > header {+ padding: 1em 0.5em;+ margin-bottom: 3rem;+}++details {+ padding: 10px;+ border: 5px solid #f7f7f7;+ border-radius: 3px;+}++details {+ transition: 0.2s background linear;+}++details:hover {+ /* background: #eaeaea; */+}++details > summary {+ transition: color 1s;+}++details[open] > summary {+ color: #171717;+}diff --git a/main.js b/main.jsnew file mode 100644index 0000000..9d8cd8d--- /dev/null+++ b/main.js@@ -0,0 +1,390 @@+// app: sse updates and renders+const eventSource = new window.EventSource('/')+const $channelsContainer = document.querySelector('.channels-container')++eventSource.onmessage = (message) => {+ if (!message || !message.data) return console.error('skipping empty message')+ try {+ const data = JSON.parse(message.data, {})+ console.log('[sse] message', data)++ if (data.type === 'download-log-line' && data.line) {+ const $downloadLog = document.querySelector('.download-log');+ $downloadLog.open = true;+ const $downloadLogLines = document.querySelector('.download-log .lines');+ const text = $downloadLogLines.innerText+ let lines = text.split('\n')+ lines = lines.join('\n') + '\n' + data.line+ $downloadLogLines.innerText = lines+ $downloadLogLines.scrollTop = $downloadLogLines.scrollHeight;+ }++ if (data.type === 'all' && data.videos) {+ $channelsContainer.innerHTML = ''++ for (const [name, videos] of Object.entries(data.videos)) {+ appendChannelSectionTo(name, videos, $channelsContainer)+ updateDownloadedVideos(videos)+ }+ handleNewVideos(data.videos)+ window.videos = data.videos+ applyFoldedChannels(store.get(store.foldedChannelsKey))+ }++ if (data.type === 'channel' && data.name && Array.isArray(data.videos)) {+ const $existingChannelSection = document.querySelector(`details[data-channel="${data.name}"]`)+ if ($existingChannelSection) {+ $existingChannelSection.querySelector(`.videos-container`).replaceWith(channelVideosContents(data.videos))+ } else {+ appendChannelSectionTo(data.name, data.videos, $channelsContainer)+ }+ updateDownloadedVideos(data.videos)+ window.videos[data.name] = data.videos+ handleNewVideos(data.videos)+ }++ } catch (err) {+ console.error('sse parse error', err)+ }+}++function appendChannelSectionTo (name, videos, $channelsContainer) {+ const $channelSection = document.createElement('details')+ $channelSection.open = store.get(store.foldedChannelsKey)+ $channelSection.dataset['channel'] = name+ $channelSection.classList.add('channel-details')+ $channelSection.innerHTML = `<summary>${name}</summary>`+ $channelSection.appendChild(channelVideosContents(videos))+ $channelsContainer.appendChild($channelSection)+}++function updateDownloadedVideos (videos) {+ const $downloadedVideosContainer = document.querySelector('details.downloaded-videos-container')+ const $videosContainer = $downloadedVideosContainer.querySelector('.videos-container')+ videos.filter(v => v.downloaded).forEach(v => {+ const $existing = $downloadedVideosContainer.querySelector(`[data-video-id="${v.id}"]`)+ if ($existing) {+ const $video = createVideoElement(v)+ $existing.replaceWith($video)+ return+ }+ const $video = createVideoElement(v)+ $videosContainer.appendChild($video)+ })+}++// store+class Store {+ showThumbnailsKey = 'showThumbnails'+ foldedChannelsKey = 'foldedChannels'+ ignoreVideoKey = 'ignoreVideo'+ lastVideosKey = 'lastVideos'++ constructor() {+ if (!localStorage.getItem(this.ignoreVideoKey)) localStorage.setItem(this.ignoreVideoKey, '[]')+ if (!localStorage.getItem(this.showThumbnailsKey)) localStorage.setItem(this.showThumbnailsKey, 'true')+ if (!localStorage.getItem(this.foldedChannelsKey)) localStorage.setItem(this.foldedChannelsKey, 'true')+ if (!localStorage.getItem(this.lastVideosKey)) localStorage.setItem(this.lastVideosKey, '{}')+ }++ toggle (key) {+ if (![this.showThumbnailsKey, this.foldedChannelsKey].includes(key)) return console.error('invalid key', key)+ localStorage.setItem(key, localStorage.getItem(key) === 'true' ? 'false' : 'true')+ }+ get(key) {+ if (![this.showThumbnailsKey, this.foldedChannelsKey, this.ignoreVideoKey, this.lastVideosKey].includes(key)) return console.error('invalid key', key)+ return JSON.parse(localStorage.getItem(key))+ }+ set(key, value) {+ if (typeof value === 'string') {+ localStorage.setItem(key, value)+ } else {+ localStorage.setItem(key, JSON.stringify(value))+ }+ }+ push(key, item) {+ if (![this.ignoreVideoKey].includes(key)) return console.error('invalid key', key)+ const list = this.get(key)+ list.push(item)+ this.set(key, list)+ return item+ }+}++const store = new Store()++// settings modal+const $settings = document.querySelector("dialog#settings")+const $openSettings = document.querySelector("#open-settings")+const $closeSettings = $settings.querySelector("button")+$openSettings.addEventListener("click", () => $settings.showModal())+$closeSettings.addEventListener("click", () => $settings.close())++// video player modal+const $videoPlayer = document.querySelector('dialog#video-player')+const $closeVideoPlayer = $videoPlayer.querySelector("button")+$closeVideoPlayer.addEventListener("click", () => $videoPlayer.close())+$videoPlayer.addEventListener('close', () => $videoPlayer.querySelector('video')?.pause())++// summary modal+const $summaryModal = document.querySelector('dialog#summary')+const $closeSummary = $summaryModal.querySelector("button")+$closeSummary.addEventListener("click", () => $summaryModal.close())+$summaryModal.addEventListener('close', () => {})++// settings ui+const $showThumbnails = document.getElementById('show-thumbnails')+const $foldedChannels = document.getElementById('folded-channels')+$showThumbnails.addEventListener('click', (event) => {+ store.toggle(store.showThumbnailsKey)+ applyShowThumbnails(store.get(store.showThumbnailsKey))+})+$foldedChannels.addEventListener('click', (event) => {+ store.toggle(store.foldedChannelsKey)+ applyFoldedChannels(store.get(store.foldedChannelsKey))+})++// apply settings+applyShowThumbnails(store.get(store.showThumbnailsKey))+applyFoldedChannels(store.get(store.foldedChannelsKey))++// observe dialog open/close and prevent body background scroll+observeDialogOpenPreventScroll($settings)+observeDialogOpenPreventScroll($videoPlayer)+observeDialogOpenPreventScroll($summaryModal)+++function observeDialogOpenPreventScroll (dialog) {+ new MutationObserver((mutationList, observer) => {+ for (const mutation of mutationList) {+ if (mutation.type === "attributes" && mutation.attributeName === 'open') {+ document.body.classList[mutation.target.open ? 'add' : 'remove']('dialog-opened')+ }+ }+ }).observe(dialog, { attributes: true, childList: true, subtree: true })+}++function applyShowThumbnails(showThumbnails) {+ if (showThumbnails) {+ document.body.classList.remove('hide-thumbnails')+ } else {+ document.body.classList.add('hide-thumbnails')+ }+ document.querySelector('#show-thumbnails').checked = showThumbnails+}++function applyFoldedChannels (foldedChannels) {+ console.log('applyFoldedChannels', foldedChannels)+ if (foldedChannels) {+ [...document.querySelectorAll('.channels-container details')]+ .forEach(d => d.open = false)+ } else {+ [...document.querySelectorAll('.channels-container details')]+ .forEach(d => d.open = true)+ }+ document.querySelector('#folded-channels').checked = foldedChannels+}++// app: add channel+document.getElementById('add-channel-form').addEventListener('submit', addChannelHandler)++function addChannelHandler(event) {+ event.preventDefault()++ const form = event.target+ const button = form.querySelector('button')+ const input = form.querySelector('input')+ const loader = form.querySelector('.loader')+ freezeForm()++ const channelName = document.getElementById('channel-name').value++ if (!channelName) return alert('empty channel name'), unfreezeForm();++ fetch('/channels', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: channelName })+ })+ .then(() => document.getElementById('add-channel-form').reset())+ .catch(error => console.error('Error adding channel:', error))+ .finally(unfreezeForm)++ function freezeForm() {+ input.disabled = true+ button.disabled = true+ loader.classList.add('show')+ }+ function unfreezeForm() {+ input.disabled = false+ button.disabled = false+ loader.classList.remove('show')+ }+}++function channelVideosContents (videos) {+ if (!videos) return+ const ignoreList = store.get(store.ignoreVideoKey)+ const $videosContainer = document.createElement('div')+ $videosContainer.classList.add('videos-container')+ for (const video of videos) {+ if (ignoreList.includes(video.id)) {+ console.log('ignoring video', video.id)+ continue+ }+ $videosContainer.appendChild(createVideoElement(video))+ }+ return $videosContainer+}++function createVideoElement (video) {+ const $video = document.createElement('div')+ $video.classList.add('video')+ $video.dataset['videoId'] = video.id+ $video.innerHTML = `+ ${video.downloaded+ ? `<video controls width="280">+ <source src="/videos/${video.id}" type="video/mp4" />+ <p>+ Your browser does not support the video tag.+ Download the video instead <a href="/videos/${video.id}" target="_blank">here</a>+ </p>+ </video>`+ : `<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+ ? `<a tabindex="0" href="/videos/${video.id}" target="_blank" class="action watch" data-video-id="${video.id}">π watch</a>`+ : `<span tabindex="0" class="action download" data-video-id="${video.id}">β¬οΈ Download</span>`}+ ${!video.summary+ ? `<span tabindex="0" class="action summarize" data-video-id="${video.id}">π Summarize</span>`+ : `<span tabindex="0" class="action show-summary" data-video-id="${video.id}">π Summary</span>`}+ <span tabindex="0" class="action ignore" data-video-id="${video.id}">π Ignore</span>+ </div>+ `+ return $video+}++function handleNewVideos (videos) {+ document.querySelectorAll('.video .actions .action.watch')+ .forEach($watchAction => {+ $watchAction.removeEventListener('click', watchVideoHandler)+ $watchAction.addEventListener('click', watchVideoHandler)+ $watchAction.removeEventListener('keydown', (event) => event.key === 'Enter' && watchVideoHandler(event))+ $watchAction.addEventListener('keydown', (event) => event.key === 'Enter' && watchVideoHandler(event))+ })++ document.querySelectorAll('.video .actions .action.download')+ .forEach($downloadAction => {+ $downloadAction.removeEventListener('click', downloadVideoHandler)+ $downloadAction.addEventListener('click', downloadVideoHandler)+ $downloadAction.removeEventListener('keydown', (event) => event.key === 'Enter' && downloadVideoHandler(event))+ $downloadAction.addEventListener('keydown', (event) => event.key === 'Enter' && downloadVideoHandler(event))+ })++ document.querySelectorAll('.video .actions .action.ignore')+ .forEach($ignoreAction => {+ $ignoreAction.removeEventListener('click', ignoreVideoHandler)+ $ignoreAction.addEventListener('click', ignoreVideoHandler)+ $ignoreAction.removeEventListener('keydown', (event) => event.key === 'Enter' && ignoreVideoHandler(event))+ $ignoreAction.addEventListener('keydown', (event) => event.key === 'Enter' && ignoreVideoHandler(event))+ })++ document.querySelectorAll('.video .actions .action.summarize')+ .forEach($ignoreAction => {+ $ignoreAction.removeEventListener('click', summarizeVideoHandler)+ $ignoreAction.addEventListener('click', summarizeVideoHandler)+ $ignoreAction.removeEventListener('keydown', (event) => event.key === 'Enter' && summarizeVideoHandler(event))+ $ignoreAction.addEventListener('keydown', (event) => event.key === 'Enter' && summarizeVideoHandler(event))+ })++ document.querySelectorAll('.video .actions .action.show-summary')+ .forEach($ignoreAction => {+ $ignoreAction.removeEventListener('click', showSummaryHandler)+ $ignoreAction.addEventListener('click', showSummaryHandler)+ $ignoreAction.removeEventListener('keydown', (event) => event.key === 'Enter' && showSummaryHandler(event))+ $ignoreAction.addEventListener('keydown', (event) => event.key === 'Enter' && showSummaryHandler(event))+ })++ if (typeof videos === 'object' && !Array.isArray(videos)) {+ const lastVideos = store.get(store.lastVideosKey)+ for (const [name, vids] of Object.entries(videos)) {+ if (lastVideos[name] != vids[0]?.id)+ document.querySelector(`details[data-channel="${name}"]`)?.classList.add('has-new-videos')+ lastVideos[name] = vids[0]?.id+ }+ store.set(store.lastVideosKey, lastVideos)+ }+}++function watchVideoHandler (event) {+ event.preventDefault()+ const videoId = event.target.dataset.videoId+ $videoPlayer.showModal()+ $videoPlayer.querySelector('div').innerHTML = `+ <video autoplay controls width="500">+ <source src="/videos/${videoId}" type="video/mp4" />+ <p>+ Your browser does not support the video tag.+ Download the video instead <a href="/videos/${videoId}" target="_blank">here</a>+ </p>+ </video>+ `+}++function ignoreVideoHandler (event) {+ event.preventDefault()+ const videoId = event.target.dataset.videoId+ store.push(store.ignoreVideoKey, videoId)+ event.target.parentNode?.parentNode?.remove()+}++function downloadVideoHandler (event) {+ event.preventDefault()+ const downloadStartedText = 'β‘οΈ Download started'+ if (event.target.innerText === downloadStartedText) return console.log('already downloading')+ event.target.innerText = downloadStartedText+ fetch('/download-video', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ id: event.target.dataset.videoId }),+ })+ .then(() => {+ console.log('Download started')+ })+ .catch((error) => {+ console.error('Error starting download:', error)+ })+}++function summarizeVideoHandler (event) {+ event.preventDefault()+ const summaryStartedText = 'β‘οΈ summary started'+ if (event.target.innerText === summaryStartedText) return console.log('already summarizing')+ event.target.innerText = summaryStartedText+ fetch('/summarize-video', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ id: event.target.dataset.videoId }),+ })+ .then(() => {+ console.log('summary started')+ })+ .catch((error) => {+ console.error('Error starting summary:', error)+ })+}++function showSummaryHandler (event) {+ event.preventDefault()+ const videoId = event.target.dataset.videoId+ for (const [name, videos] of Object.entries(window.videos)) {+ const video = videos.find(video => video.id === videoId)+ if (video) {+ document.querySelector('dialog#summary').showModal()+ document.querySelector('dialog#summary div').innerText = video.summary+ return+ }+ }+}