Skip to content

armgit / my-yt

Public Imported from GitHub
0

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

JavaScript

chore: cleanup with standard

Christian Feif4e908c1b9f2
diff --git a/client/components/add-channel-form.js b/client/components/add-channel-form.js
index c8e4583..6c5d3cc 100644
--- a/client/components/add-channel-form.js
+++ b/client/components/add-channel-form.js
@@ -2,20 +2,25 @@ class AddChannelForm extends HTMLElement {
constructor () {
super()
}
+
connectedCallback () {
this.render()
}
+
disconnectedCallback () {
this.unregisterEvents()
}
+
registerEvents () {
this.querySelector('form').addEventListener('submit', this.addChannelHandler.bind(this))
}
+
unregisterEvents () {
this.querySelector('form').removeEventListener('submit', this.addChannelHandler.bind(this))
}
+
render () {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<form id="add-channel-form">
<div class="flex space-between">
<label for="channel-name">Add a new channel</label>
@@ -31,38 +36,38 @@ class AddChannelForm extends HTMLElement {
addChannelHandler (event) {
event.preventDefault()
-
+
const form = event.target
const input = form.querySelector('input')
const loader = form.querySelector('.loader')
const status = form.querySelector('.status')
-
+
const channelName = document.getElementById('channel-name').value
if (!channelName) return alert('empty channel name')
freezeForm()
-
+
fetch('/api/channels', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: channelName })
})
- .then(res => res.text())
- .then((text) => {
- form.reset()
- status.innerText = text // `Successfully added ${channelName}`
- })
- .catch(error => {
- console.error('Error adding channel:', error)
- status.innerText = `There was an error adding the channel ${channelName}, please check your application logs`
- })
- .finally(unfreezeForm)
-
- function freezeForm() {
+ .then(res => res.text())
+ .then((text) => {
+ form.reset()
+ status.innerText = text // `Successfully added ${channelName}`
+ })
+ .catch(error => {
+ console.error('Error adding channel:', error)
+ status.innerText = `There was an error adding the channel ${channelName}, please check your application logs`
+ })
+ .finally(unfreezeForm)
+
+ function freezeForm () {
input.disabled = true
loader.classList.add('show')
}
- function unfreezeForm() {
+ function unfreezeForm () {
input.disabled = false
loader.classList.remove('show')
}
diff --git a/client/components/channels-list.js b/client/components/channels-list.js
index b9e9ab7..9f1addd 100644
--- a/client/components/channels-list.js
+++ b/client/components/channels-list.js
@@ -1,49 +1,55 @@
-import { addClickListener, removeClickListener } from "/lib/utils.js"
+import { addClickListener, removeClickListener } from '../../../../../../lib/utils.js'
class ChannelsList extends HTMLElement {
constructor () {
super()
this.channels = []
}
+
connectedCallback () {
this.render()
}
+
disconnectedCallback () {
this.unregisterEvents()
}
- static get observedAttributes() {
- return ['data-list'];
+
+ static get observedAttributes () {
+ return ['data-list']
}
- attributeChangedCallback(name, _, newValue) {
+ attributeChangedCallback (name, _, newValue) {
if (name === 'data-list') {
- this.channels = JSON.parse(this.dataset['list'])
+ this.channels = JSON.parse(this.dataset.list)
this.render()
}
}
-
+
render () {
if (this.channels.length === 0) this.classList.add('hide')
else this.classList.remove('hide')
this.unregisterEvents()
-
- this.innerHTML = /*html*/`
+
+ this.innerHTML = /* html */`
<details class="channels-container">
<summary>Channels</summary>
- <div>${this.channels.map(channel => /*html*/`<span tabindex=0 data-channel="${channel}" class="channel">${channel}</span>`).join('')}</div>
+ <div>${this.channels.map(channel => /* html */`<span tabindex=0 data-channel="${channel}" class="channel">${channel}</span>`).join('')}</div>
</details>
`
this.registerEvents()
}
- registerEvents() {
+
+ registerEvents () {
const channels = this.querySelectorAll('.channel')
channels.forEach(channel => addClickListener(channel, this.channelClick.bind(this)))
}
- unregisterEvents() {
+
+ unregisterEvents () {
const channels = this.querySelectorAll('.channel')
channels.forEach(channel => removeClickListener(channel, this.channelClick.bind(this)))
}
- channelClick(event) {
+
+ channelClick (event) {
const $searchInput = document.querySelector('#search')
if (!$searchInput) return
const channel = `@${event.target.innerText}`
diff --git a/client/components/empty-state.js b/client/components/empty-state.js
index a3df4fe..a87cad2 100644
--- a/client/components/empty-state.js
+++ b/client/components/empty-state.js
@@ -11,22 +11,23 @@ class EmptyState extends HTMLElement {
this.render()
}
- static get observedAttributes() {
- return ['data-has-channels'];
+ static get observedAttributes () {
+ return ['data-has-channels']
}
- attributeChangedCallback(name, _, newValue) {
+ attributeChangedCallback (name, _, newValue) {
this.render()
}
+
render () {
- if (this.dataset['hasChannels']) {
- this.innerHTML = /*html*/`
+ if (this.dataset.hasChannels) {
+ this.innerHTML = /* html */`
<h1>All caught up!</h1>
<p>Enjoy the world outside</p>
<div class="extra-big">☀️</div>
`
} else {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<h1>Nothing to show...</h1>
<p>Add YouTube channels you want to track in <a href="/settings">/settings</a></p>
<div class="extra-big">🙈</div>
diff --git a/client/components/excluded-terms-form.js b/client/components/excluded-terms-form.js
index 019eb2e..e91bce8 100644
--- a/client/components/excluded-terms-form.js
+++ b/client/components/excluded-terms-form.js
@@ -2,23 +2,28 @@ class ExcludedTermsForm extends HTMLElement {
constructor () {
super()
}
+
connectedCallback () {
this.render()
this.registerEvents()
this.fetchExcludedTermsHandler()
}
+
disconnectedCallback () {
this.unregisterEvents()
}
+
registerEvents () {
this.querySelector('#add-excluded-term').addEventListener('keyup', this.addExcludedTermHandler.bind(this))
}
+
unregisterEvents () {
this.querySelector('#add-excluded-term').removeEventListener('keyup', this.addExcludedTermHandler.bind(this))
}
+
render () {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<div>
<div class="flex space-between">
<div>
@@ -44,15 +49,16 @@ class ExcludedTermsForm extends HTMLElement {
fetch('/api/excluded-terms', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({term})
+ body: JSON.stringify({ term })
})
- .then(() => {
- event.target.value = ''
- })
- .catch(console.error)
- .finally(this.fetchExcludedTermsHandler.bind(this))
+ .then(() => {
+ event.target.value = ''
+ })
+ .catch(console.error)
+ .finally(this.fetchExcludedTermsHandler.bind(this))
}
}
+
fetchExcludedTermsHandler () {
fetch('/api/excluded-terms')
.then(response => response.json())
@@ -66,15 +72,15 @@ class ExcludedTermsForm extends HTMLElement {
$excludedTerms.appendChild($li)
$li.addEventListener('click', () => {
if (!confirm('Remove "' + term + '" from excluded terms?')) return
- fetch(`/api/excluded-terms`, {
+ fetch('/api/excluded-terms', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ term })
})
- .then(() => $li.remove())
- .catch(error => {
- console.error(error)
- })
+ .then(() => $li.remove())
+ .catch(error => {
+ console.error(error)
+ })
})
})
})
diff --git a/client/components/manage-channels-form.js b/client/components/manage-channels-form.js
index fcf87bb..ef294eb 100644
--- a/client/components/manage-channels-form.js
+++ b/client/components/manage-channels-form.js
@@ -1,37 +1,43 @@
-import { addClickListener, removeClickListener } from "/lib/utils.js"
+import { addClickListener, removeClickListener } from '../../../../../../lib/utils.js'
class ManageChannelsForm extends HTMLElement {
constructor () {
super()
}
+
connectedCallback () {
this.render()
this.fetchData()
}
+
disconnectedCallback () {
this.unregisterEvents()
}
- fetchData() {
+
+ fetchData () {
fetch('/api/channels')
- .then(res => res.json())
- .then(channels => {
- const $container = this.querySelector('#manage-channels')
- $container.innerHTML = /*html*/`
- ${channels.map(channel =>
- /*html*/`<div style="margin-bottom: 10px" tabindex=0 data-channel="${channel.name}" class="channel">❌ ${channel.name}</div>`).join('')}
+ .then(res => res.json())
+ .then(channels => {
+ const $container = this.querySelector('#manage-channels')
+ $container.innerHTML = /* html */`
+ ${channels.map(channel =>
+ /* html */`<div style="margin-bottom: 10px" tabindex=0 data-channel="${channel.name}" class="channel">❌ ${channel.name}</div>`).join('')}
`
- })
- .then(this.registerEvents.bind(this))
+ })
+ .then(this.registerEvents.bind(this))
}
+
registerEvents () {
this.querySelectorAll('[data-channel]')
- .forEach($channel => addClickListener($channel, this.removeChannel.bind(this)))
+ .forEach($channel => addClickListener($channel, this.removeChannel.bind(this)))
}
+
unregisterEvents () {
this.querySelectorAll('[data-channel]')
- .forEach($channel => removeClickListener($channel, this.removeChannel.bind(this)))
+ .forEach($channel => removeClickListener($channel, this.removeChannel.bind(this)))
}
+
render () {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<details>
<summary>Manage channels</summary>
<br>
@@ -42,24 +48,24 @@ class ManageChannelsForm extends HTMLElement {
removeChannel (event) {
event.preventDefault()
-
+
const $channel = event.target
- const channelName = $channel.dataset['channel']
+ const channelName = $channel.dataset.channel
if (!channelName) return alert('empty channel name')
if (!confirm(`Do you want to delete the channel ${channelName}?`)) return
-
+
fetch('/api/channels', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: channelName })
})
- .then(() => {
- $channel.remove()
- })
- .catch(error => {
- console.error('Error deleting channel:', error)
- status.innerText = `There was an error deleting the channel ${channelName}, please check your application logs`
- })
+ .then(() => {
+ $channel.remove()
+ })
+ .catch(error => {
+ console.error('Error deleting channel:', error)
+ status.innerText = `There was an error deleting the channel ${channelName}, please check your application logs`
+ })
}
}
customElements.define('manage-channels-form', ManageChannelsForm)
diff --git a/client/components/manage-disk-space-form.js b/client/components/manage-disk-space-form.js
index 8cbcaa5..6cc671b 100644
--- a/client/components/manage-disk-space-form.js
+++ b/client/components/manage-disk-space-form.js
@@ -2,24 +2,29 @@ class ManageDiskSpaceForm extends HTMLElement {
constructor () {
super()
}
+
connectedCallback () {
this.render()
this.registerEvents()
this.updateDiskSpaceUsed()
}
+
disconnectedCallback () {
this.unregisterEvents()
}
+
registerEvents () {
this.querySelector('#reclaim-disk-space').addEventListener('click', this.reclaimDiskSpace.bind(this))
this.querySelector('#delete-only-ignored').addEventListener('change', this.updateDiskSpaceUsed.bind(this))
}
+
unregisterEvents () {
this.querySelector('#reclaim-disk-space').removeEventListener('click', this.reclaimDiskSpace.bind(this))
this.querySelector('#delete-only-ignored').removeEventListener('change', this.updateDiskSpaceUsed.bind(this))
}
+
render () {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<form>
<div class="flex space-between">
<div>
@@ -38,15 +43,15 @@ class ManageDiskSpaceForm extends HTMLElement {
`
}
- updateDiskSpaceUsed() {
+ updateDiskSpaceUsed () {
const onlyIgnored = this.querySelector('#delete-only-ignored').checked
const $diskUsage = this.querySelector('#disk-usage')
fetch(onlyIgnored ? '/api/disk-usage?onlyIgnored=true' : '/api/disk-usage')
- .then(response => response.text())
- .then((diskSpaceUsed) => {
- $diskUsage.innerHTML = /*html*/`Currently <span id="disk-space-used">${diskSpaceUsed}</span> of disk space used`
- })
- .catch(err => console.error(err))
+ .then(response => response.text())
+ .then((diskSpaceUsed) => {
+ $diskUsage.innerHTML = /* html */`Currently <span id="disk-space-used">${diskSpaceUsed}</span> of disk space used`
+ })
+ .catch(err => console.error(err))
}
reclaimDiskSpace (event) {
@@ -58,12 +63,12 @@ class ManageDiskSpaceForm extends HTMLElement {
method: 'POST',
body: JSON.stringify({ onlyIgnored })
})
- .then(() => {
- $diskUsage.innerText = 'Successfully reclaimed disk space'
- })
- .catch((error) => {
- $diskUsage.innerHTML = `Failed to reclaim disk space: <br><pre>${error.message}</pre>`
- })
+ .then(() => {
+ $diskUsage.innerText = 'Successfully reclaimed disk space'
+ })
+ .catch((error) => {
+ $diskUsage.innerHTML = `Failed to reclaim disk space: <br><pre>${error.message}</pre>`
+ })
}
}
customElements.define('manage-disk-space-form', ManageDiskSpaceForm)
diff --git a/client/components/search-videos.js b/client/components/search-videos.js
index c800114..318a46d 100644
--- a/client/components/search-videos.js
+++ b/client/components/search-videos.js
@@ -1,34 +1,39 @@
-import { createVideoElement, addToast } from "/lib/utils.js"
-import Store from '/lib/store.js'
+import { createVideoElement, addToast } from '../../../../../../lib/utils.js'
+import Store from '../../../../../../lib/store.js'
const store = new Store()
const searchEventSupported = 'search' in document.createElement('input')
-console.log({searchEventSupported})
+console.log({ searchEventSupported })
class SearchVideos extends HTMLElement {
constructor () {
super()
this.previousSearchTerm = ''
}
+
connectedCallback () {
this.render()
this.registerEvents()
}
+
disconnectedCallback () {
this.unregisterEvents()
}
+
registerEvents () {
this.querySelector('#search').addEventListener('input', this.searchHandler.bind(this))
this.querySelector('#with-excluded').addEventListener('change', this.searchHandler.bind(this))
this.querySelector('#only-downloaded').addEventListener('change', this.searchHandler.bind(this))
}
+
unregisterEvents () {
this.querySelector('#search').removeEventListener('input', this.searchHandler.bind(this))
this.querySelector('#with-excluded').removeEventListener('change', this.searchHandler.bind(this))
this.querySelector('#only-downloaded').removeEventListener('change', this.searchHandler.bind(this))
}
+
render () {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<input type="search" incremental="incremental" id="search" placeholder="🔍 Search videos or paste video url" autofocus>
<div class="flex">
<div class="flex-1">
@@ -42,6 +47,7 @@ class SearchVideos extends HTMLElement {
</div>
`
}
+
searchHandler (event) {
event.preventDefault()
const $search = this.querySelector('#search')
@@ -57,17 +63,17 @@ class SearchVideos extends HTMLElement {
fetch('/api/download-video', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: searchTerm, external: true }),
+ body: JSON.stringify({ id: searchTerm, external: true })
})
- .catch((error) => console.error('Error starting download:', error))
+ .catch((error) => console.error('Error starting download:', error))
$search.value = ''
return
}
searchTerm = searchTerm.toLowerCase()
document.body.classList.add('searching')
- let withExcluded = this.querySelector('#with-excluded').checked
- let onlyDownloaded = this.querySelector('#only-downloaded').checked
+ const withExcluded = this.querySelector('#with-excluded').checked
+ const onlyDownloaded = this.querySelector('#only-downloaded').checked
if (withExcluded) {
this.querySelector('#only-downloaded').disabled = true
@@ -81,29 +87,29 @@ class SearchVideos extends HTMLElement {
}
fetch(`/api/videos?filter=${encodeURIComponent(searchTerm)}${withExcluded ? '&excluded=true' : ''}${onlyDownloaded ? '&downloaded=true' : ''}`)
- .then(res => res.json())
- .then((videos) => {
- const $videosContainer = document.querySelector('.main-videos-container')
- if (!$videosContainer) return
- $videosContainer.innerHTML = ''
- const showOriginalThumbnail = store.get(store.showOriginalThumbnailKey)
- videos.forEach(video =>
- $videosContainer.appendChild(createVideoElement(video, showOriginalThumbnail))
- )
- if (!searchTerm) {
- $status.innerText = ''
- } else {
- if (videos.length > 0) $status.innerText = `Found ${videos.length} videos`
- else $status.innerText = `No videos found`
- }
- })
- .catch(err => {
- console.error(err)
- $status.innerText = `An error occurred: ${err.message}`
- })
- .finally(() => {
- document.body.classList.remove('searching')
- })
+ .then(res => res.json())
+ .then((videos) => {
+ const $videosContainer = document.querySelector('.main-videos-container')
+ if (!$videosContainer) return
+ $videosContainer.innerHTML = ''
+ const showOriginalThumbnail = store.get(store.showOriginalThumbnailKey)
+ videos.forEach(video =>
+ $videosContainer.appendChild(createVideoElement(video, showOriginalThumbnail))
+ )
+ if (!searchTerm) {
+ $status.innerText = ''
+ } else {
+ if (videos.length > 0) $status.innerText = `Found ${videos.length} videos`
+ else $status.innerText = 'No videos found'
+ }
+ })
+ .catch(err => {
+ console.error(err)
+ $status.innerText = `An error occurred: ${err.message}`
+ })
+ .finally(() => {
+ document.body.classList.remove('searching')
+ })
}
}
customElements.define('search-videos', SearchVideos)
diff --git a/client/components/transcode-videos-form.js b/client/components/transcode-videos-form.js
index 958f650..a696c62 100644
--- a/client/components/transcode-videos-form.js
+++ b/client/components/transcode-videos-form.js
@@ -2,28 +2,33 @@ class TranscodeVideosForm extends HTMLElement {
constructor () {
super()
}
+
connectedCallback () {
this.render()
this.registerEvents()
fetch('/api/transcode-videos')
- .then(response => response.json())
- .then((transcodeVideos) => {
- this.querySelector('#transcode-videos').checked = transcodeVideos
- })
- .catch(error => console.error('Error:', error))
+ .then(response => response.json())
+ .then((transcodeVideos) => {
+ this.querySelector('#transcode-videos').checked = transcodeVideos
+ })
+ .catch(error => console.error('Error:', error))
}
+
disconnectedCallback () {
this.unregisterEvents()
}
+
registerEvents () {
this.querySelector('#transcode-videos').addEventListener('change', this.setTranscodeVideosHandler.bind(this))
}
+
unregisterEvents () {
this.querySelector('#transcode-videos').removeEventListener('change', this.setTranscodeVideosHandler.bind(this))
}
+
render () {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<form>
<div class="flex space-between">
<div>
diff --git a/client/components/video-element.js b/client/components/video-element.js
index 60ad4e2..0908065 100644
--- a/client/components/video-element.js
+++ b/client/components/video-element.js
@@ -1,6 +1,5 @@
-import { addClickListener, removeClickListener } from "/lib/utils.js"
-import Store from "/lib/store.js"
-import { addToast } from "/lib/utils.js"
+import { addClickListener, removeClickListener, addToast } from '../../../../../../lib/utils.js'
+import Store from '../../../../../../lib/store.js'
const store = new Store()
class VideoElement extends HTMLElement {
@@ -11,19 +10,21 @@ class VideoElement extends HTMLElement {
}
connectedCallback () {
- this.video = JSON.parse(this.dataset['data'])
+ this.video = JSON.parse(this.dataset.data)
this.render()
}
+
disconnectedCallback () {
this.unregisterEvents()
}
- static get observedAttributes() {
- return ['data-data', 'data-summarizing', 'data-downloading'];
+
+ static get observedAttributes () {
+ return ['data-data', 'data-summarizing', 'data-downloading']
}
- attributeChangedCallback(name, _, newValue) {
+ attributeChangedCallback (name, _, newValue) {
if (name === 'data-data') {
- this.video = JSON.parse(this.dataset['data'])
+ this.video = JSON.parse(this.dataset.data)
this.render()
}
if (name === 'data-downloading' && this.querySelector('.action.download')) {
@@ -33,21 +34,22 @@ class VideoElement extends HTMLElement {
this.querySelector('.action.summarize').innerText = this.summaryStartedText
}
}
+
render () {
if (!this.video) return
this.unregisterEvents()
this.classList.add('video')
- this.dataset['videoId'] = this.video.id
- this.dataset['date'] = this.video.publishedAt
- this.dataset['summarized'] = this.video.summary ? 'true' : 'false'
- this.dataset['downloaded'] = this.video.downloaded ? 'true' : 'false'
- this.dataset['ignored'] = this.video.ignored ? 'true' : 'false'
+ this.dataset.videoId = this.video.id
+ this.dataset.date = this.video.publishedAt
+ this.dataset.summarized = this.video.summary ? 'true' : 'false'
+ this.dataset.downloaded = this.video.downloaded ? 'true' : 'false'
+ this.dataset.ignored = this.video.ignored ? 'true' : 'false'
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
${this.video.downloaded
- ? /*html*/`
+ ? /* html */`
<div class="video-wrapper">
<div class="play video-placeholder" style="background-image: url(${this.video.thumbnail})">
<div class="play-icon"></div>
@@ -55,7 +57,7 @@ class VideoElement extends HTMLElement {
</div>
</div>
`
- : /*html*/`
+ : /* html */`
<div class="video-wrapper">
<img title="${this.video.title}" loading="lazy" src="${this.video.thumbnail}"/>
<span class="info-duration">${this.video.duration || 'N/A'}</span>
@@ -72,27 +74,27 @@ class VideoElement extends HTMLElement {
</div>
<div class="actions flex">
${this.video.downloaded
- ? /*html*/`<span tabindex="0" class="action delete" data-video-id="${this.video.id}">🗑️ Delete</span>`
- : /*html*/`<span tabindex="0" class="action download" data-video-id="${this.video.id}">⬇️ Download</span>`}
- ${store.get(store.useTLDWTubeKey) ?
- /*html*/`<a target="_blank" href="https://tldw.tube/?v=${this.video.id}">📖 tldw.tube</a>`
+ ? /* html */`<span tabindex="0" class="action delete" data-video-id="${this.video.id}">🗑️ Delete</span>`
+ : /* html */`<span tabindex="0" class="action download" data-video-id="${this.video.id}">⬇️ Download</span>`}
+ ${store.get(store.useTLDWTubeKey)
+ /* html */? `<a target="_blank" href="https://tldw.tube/?v=${this.video.id}">📖 tldw.tube</a>`
: !this.video.summary
- ? /*html*/`<span tabindex="0" class="action summarize" data-video-id="${this.video.id}">📖 Summarize</span>`
- : /*html*/`<span tabindex="0" class="action show-summary" data-video-id="${this.video.id}">📖 Summary</span>`}
+ ? /* html */`<span tabindex="0" class="action summarize" data-video-id="${this.video.id}">📖 Summarize</span>`
+ : /* html */`<span tabindex="0" class="action show-summary" data-video-id="${this.video.id}">📖 Summary</span>`}
<a href="https://www.youtube.com/watch?v=${this.video.id}" class="action open-externally" target="_blank">📺 external</a>
</div>
`
-
if (window.state && window.state.downloading && window.state.downloading[this.video.id]) {
- this.dataset['downloading'] = 'true'
+ this.dataset.downloading = 'true'
}
if (window.state && window.state.summarizing && window.state.summarizing[this.video.id]) {
- this.dataset['summarizing'] = 'true'
+ this.dataset.summarizing = 'true'
}
this.registerEvents()
}
+
registerEvents () {
addClickListener(this.querySelector('.action.download'), this.downloadVideoHandler.bind(this))
addClickListener(this.querySelector('.action.delete'), this.deleteVideoHandler.bind(this))
@@ -103,6 +105,7 @@ class VideoElement extends HTMLElement {
addClickListener(this.querySelector('.channel-name'), this.filterByChannelHandler.bind(this))
addClickListener(this.querySelector('.play.video-placeholder'), this.watchVideoHandler.bind(this))
}
+
unregisterEvents () {
removeClickListener(this.querySelector('.action.download'), this.downloadVideoHandler.bind(this))
removeClickListener(this.querySelector('.action.delete'), this.deleteVideoHandler.bind(this))
@@ -114,12 +117,13 @@ class VideoElement extends HTMLElement {
removeClickListener(this.querySelector('.play.video-placeholder'), this.watchVideoHandler.bind(this))
this.querySelector('video') && this.unregisterVideoEvents(this.querySelector('video'))
}
+
watchVideoHandler (event) {
event.preventDefault()
- this.querySelector('.play.video-placeholder').outerHTML = /*html*/`
+ this.querySelector('.play.video-placeholder').outerHTML = /* html */`
<video controls playsinline style="user-select: none; width: 400px; width: -webkit-fill-available;">
<source src="/api/videos/${this.video.id}.${this.video.format || 'mp4'}" type="video/${this.video.format || 'mp4'}" />
- ${store.get(store.showCaptionsKey) ? /*html*/`
+ ${store.get(store.showCaptionsKey) ? /* html */`
<track default kind="captions" srclang="en" src="/api/captions/${this.video.id}" />
` : ''}
<p>
@@ -131,13 +135,14 @@ class VideoElement extends HTMLElement {
this.querySelector('video').play()
this.registerVideoEvents(this.querySelector('video'))
}
+
downloadVideoHandler (event) {
event.preventDefault()
- if (this.dataset['downloading'] === 'true') return
- this.dataset['downloading'] = 'true'
+ if (this.dataset.downloading === 'true') return
+ this.dataset.downloading = 'true'
- let $downloadButton = event.target.classList.contains('.action') ? event.target : this.querySelector('.action.download')
+ const $downloadButton = event.target.classList.contains('.action') ? event.target : this.querySelector('.action.download')
$downloadButton.innerText = this.downloadStartedText
addToast('Downloading video...')
@@ -145,32 +150,34 @@ class VideoElement extends HTMLElement {
fetch('/api/download-video', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: this.video.id }),
+ body: JSON.stringify({ id: this.video.id })
})
- .catch((error) => console.error('Error starting download:', error))
+ .catch((error) => console.error('Error starting download:', error))
}
+
deleteVideoHandler (event) {
event.preventDefault()
if (!confirm('About to delete video files, are you sure?')) return
fetch('/api/delete-video', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: this.video.id }),
- })
- .then(() => {
- this.video.downloaded = false
- this.classList.remove('downloading')
- this.classList.remove('big')
- this.querySelector('video') && this.unregisterVideoEvents(this.querySelector('video'))
- this.render()
+ body: JSON.stringify({ id: this.video.id })
})
- .catch((error) => console.error('Error deleting video:', error))
+ .then(() => {
+ this.video.downloaded = false
+ this.classList.remove('downloading')
+ this.classList.remove('big')
+ this.querySelector('video') && this.unregisterVideoEvents(this.querySelector('video'))
+ this.render()
+ })
+ .catch((error) => console.error('Error deleting video:', error))
}
+
summarizeVideoHandler (event) {
event.preventDefault()
- if (this.dataset['summarizing'] === 'true') return
- this.dataset['summarizing'] = 'true'
+ if (this.dataset.summarizing === 'true') return
+ this.dataset.summarizing = 'true'
event.target.innerText = this.summaryStartedText
@@ -179,16 +186,17 @@ class VideoElement extends HTMLElement {
fetch('/api/summarize-video', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: this.video.id }),
+ body: JSON.stringify({ id: this.video.id })
})
- .catch((error) => console.error('Error starting summary:', error))
+ .catch((error) => console.error('Error starting summary:', error))
}
+
showSummaryHandler (event) {
event.preventDefault()
const video = this.video
if (video) {
document.querySelector('dialog#summary').showModal()
- document.querySelector('dialog#summary div').innerHTML = /*html*/`
+ document.querySelector('dialog#summary div').innerHTML = /* html */`
<pre>${video.summary}</pre>
<details>
<summary>transcript</summary>
@@ -197,40 +205,46 @@ class VideoElement extends HTMLElement {
`
}
}
+
toggleIgnoreVideoHandler (event) {
event.preventDefault()
fetch('/api/ignore-video', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: this.video.id }),
- })
- .then(() => this.remove())
- .catch((error) => {
- console.error('Error ignoring video:', error)
- this.classList.remove('hide')
- this.render()
+ body: JSON.stringify({ id: this.video.id })
})
+ .then(() => this.remove())
+ .catch((error) => {
+ console.error('Error ignoring video:', error)
+ this.classList.remove('hide')
+ this.render()
+ })
}
+
openExternallyHandler (event) {
this.querySelector('video') && this.querySelector('video').pause()
}
+
filterByChannelHandler (event) {
const $searchInput = document.querySelector('#search')
const channel = `@${this.video.channelName}`
$searchInput.value = ($searchInput && $searchInput.value !== channel) ? channel : ''
$searchInput.dispatchEvent(new Event('input'))
}
+
registerVideoEvents (video) {
video.addEventListener('play', () => {
this.classList.add('big')
- setTimeout(this.scrollIntoViewWithOffset.bind(this, document.querySelector('body > header').clientHeight, "smooth"), 110)
+ setTimeout(this.scrollIntoViewWithOffset.bind(this, document.querySelector('body > header').clientHeight, 'smooth'), 110)
this.pauseOtherVideos(video)
})
}
+
unregisterVideoEvents (video) {
video.removeEventListener('play', this.pauseOtherVideos.bind(this, video))
}
+
pauseOtherVideos (video) {
document.querySelectorAll('video').forEach(v => {
if (v !== video) {
@@ -248,12 +262,12 @@ class VideoElement extends HTMLElement {
customElements.define('video-element', VideoElement)
-function tryFormatDate(date) {
+function tryFormatDate (date) {
try {
return new Intl.DateTimeFormat(navigator.language, {
- year: "numeric",
- month: "numeric",
- day: "numeric",
+ year: 'numeric',
+ month: 'numeric',
+ day: 'numeric'
}).format(new Date(date))
} catch (err) {
return (date || '').substring(0, 10)
diff --git a/client/components/video-quality-form.js b/client/components/video-quality-form.js
index 17193b6..761f5f8 100644
--- a/client/components/video-quality-form.js
+++ b/client/components/video-quality-form.js
@@ -2,26 +2,31 @@ class VideoQualityForm extends HTMLElement {
constructor () {
super()
}
+
connectedCallback () {
this.render()
this.registerEvents()
fetch('/api/video-quality')
- .then(response => response.json())
- .then((videoQuality) => this.querySelector('#video-quality').value = +videoQuality)
- .catch(error => console.error('Error:', error))
+ .then(response => response.json())
+ .then((videoQuality) => this.querySelector('#video-quality').value = +videoQuality)
+ .catch(error => console.error('Error:', error))
}
+
disconnectedCallback () {
this.unregisterEvents()
}
+
registerEvents () {
this.querySelector('#video-quality').addEventListener('change', this.setVideoQualityHandler.bind(this))
}
+
unregisterEvents () {
this.querySelector('#video-quality').removeEventListener('change', this.setVideoQualityHandler.bind(this))
}
+
render () {
- this.innerHTML = /*html*/`
+ this.innerHTML = /* html */`
<form>
<div class="flex space-between">
<div>
diff --git a/client/lib/router.js b/client/lib/router.js
index ee2a928..441c913 100644
--- a/client/lib/router.js
+++ b/client/lib/router.js
@@ -1,87 +1,96 @@
-import { createVideoElement, applyShowBigPlayer, applyShowThumbnails } from "/lib/utils.js"
-import Store from '/lib/store.js'
+import { createVideoElement, applyShowBigPlayer, applyShowThumbnails } from '../../../../../../lib/utils.js'
+import Store from '../../../../../../lib/store.js'
const store = new Store()
const routes = {
- '/': { template: document.getElementById('main-template'), async initialize() {
- document.getElementById('home-link').classList.add('hide')
-
- let $videosContainer = document.querySelector('.main-videos-container')
- let videos = await fetch('/api/videos').then(res => res.json())
-
- document.querySelector('search-videos #search').removeAttribute('disabled', 'disabled')
- document.querySelector('search-videos').classList.remove('hide')
-
- $videosContainer.innerHTML = ''
- const showOriginalThumbnail = store.get(store.showOriginalThumbnailKey)
-
- videos = videos
- .sort((a, b) => +new Date(b.publishedAt) - +new Date(a.publishedAt))
-
- videos.forEach(video => $videosContainer.appendChild(createVideoElement(video, showOriginalThumbnail)))
-
- const channels = await fetch('/api/channels').then(res => res.json())
- document.querySelector('channels-list').dataset['list'] = JSON.stringify(channels.map(c => c.name).filter(Boolean))
-
- document.querySelector('empty-state').dataset['hasChannels'] = channels.length > 0
- handleEmptyState()
-
- new MutationObserver((mutationList, observer) => {
- for (const mutation of mutationList) {
- handleEmptyState()
- }
- }).observe($videosContainer, { attributes: false, childList: true, subtree: true })
-
- applyShowThumbnails(store.get(store.showThumbnailsKey))
- applyShowBigPlayer(store.get(store.showBigPlayerKey))
- } },
- '/settings': { template: document.getElementById('settings-template'), async initialize () {
- document.getElementById('home-link').classList.remove('hide')
-
- document.querySelector('search-videos #search').setAttribute('disabled', 'disabled')
- document.querySelector('search-videos').classList.add('hide')
-
- const $showThumbnails = document.getElementById('show-thumbnails')
- store.get(store.showThumbnailsKey) ? $showThumbnails.setAttribute('checked', 'true') : $showThumbnails.removeAttribute('checked')
-
- $showThumbnails.addEventListener('click', (event) => {
- store.toggle(store.showThumbnailsKey)
- applyShowThumbnails(store.get(store.showThumbnailsKey))
- })
+ '/': {
+ template: document.getElementById('main-template'),
+ async initialize () {
+ document.getElementById('home-link').classList.add('hide')
+
+ const $videosContainer = document.querySelector('.main-videos-container')
+ let videos = await fetch('/api/videos').then(res => res.json())
+
+ document.querySelector('search-videos #search').removeAttribute('disabled', 'disabled')
+ document.querySelector('search-videos').classList.remove('hide')
+
+ $videosContainer.innerHTML = ''
+ const showOriginalThumbnail = store.get(store.showOriginalThumbnailKey)
+
+ videos = videos
+ .sort((a, b) => +new Date(b.publishedAt) - +new Date(a.publishedAt))
+
+ videos.forEach(video => $videosContainer.appendChild(createVideoElement(video, showOriginalThumbnail)))
+
+ const channels = await fetch('/api/channels').then(res => res.json())
+ document.querySelector('channels-list').dataset.list = JSON.stringify(channels.map(c => c.name).filter(Boolean))
- const $showBigPlayer = document.getElementById('show-big-player')
- store.get(store.showBigPlayerKey) ? $showBigPlayer.setAttribute('checked', 'true') : $showBigPlayer.removeAttribute('checked')
-
- $showBigPlayer.addEventListener('click', (event) => {
- store.toggle(store.showBigPlayerKey)
+ document.querySelector('empty-state').dataset.hasChannels = channels.length > 0
+ handleEmptyState()
+
+ new MutationObserver((mutationList, observer) => {
+ for (const mutation of mutationList) {
+ handleEmptyState()
+ }
+ }).observe($videosContainer, { attributes: false, childList: true, subtree: true })
+
+ applyShowThumbnails(store.get(store.showThumbnailsKey))
applyShowBigPlayer(store.get(store.showBigPlayerKey))
- })
-
- const $showOriginalThumbnail = document.getElementById('show-original-thumbnail')
- store.get(store.showOriginalThumbnailKey) ? $showOriginalThumbnail.setAttribute('checked', 'true') : $showOriginalThumbnail.removeAttribute('checked')
-
- $showOriginalThumbnail.addEventListener('click', (event) => {
- store.toggle(store.showOriginalThumbnailKey)
- })
-
- const $useTLDWTube = document.getElementById('use-tldw-tube')
- store.get(store.useTLDWTubeKey) ? $useTLDWTube.setAttribute('checked', 'true') : $useTLDWTube.removeAttribute('checked')
-
- $useTLDWTube.addEventListener('click', (event) => {
- store.toggle(store.useTLDWTubeKey)
- })
-
- const $showCaptions = document.getElementById('show-captions')
- store.get(store.showCaptionsKey) ? $showCaptions.setAttribute('checked', 'true') : $showCaptions.removeAttribute('checked')
-
- $showCaptions.addEventListener('click', (event) => {
- store.toggle(store.showCaptionsKey)
- })
- } },
- '/404': { template: document.getElementById('not-found-template'), async initialize () {
- document.querySelector('search-videos #search').setAttribute('disabled', 'disabled')
- document.querySelector('search-videos').classList.add('hide')
- } }
+ }
+ },
+ '/settings': {
+ template: document.getElementById('settings-template'),
+ async initialize () {
+ document.getElementById('home-link').classList.remove('hide')
+
+ document.querySelector('search-videos #search').setAttribute('disabled', 'disabled')
+ document.querySelector('search-videos').classList.add('hide')
+
+ const $showThumbnails = document.getElementById('show-thumbnails')
+ store.get(store.showThumbnailsKey) ? $showThumbnails.setAttribute('checked', 'true') : $showThumbnails.removeAttribute('checked')
+
+ $showThumbnails.addEventListener('click', (event) => {
+ store.toggle(store.showThumbnailsKey)
+ applyShowThumbnails(store.get(store.showThumbnailsKey))
+ })
+
+ const $showBigPlayer = document.getElementById('show-big-player')
+ store.get(store.showBigPlayerKey) ? $showBigPlayer.setAttribute('checked', 'true') : $showBigPlayer.removeAttribute('checked')
+
+ $showBigPlayer.addEventListener('click', (event) => {
+ store.toggle(store.showBigPlayerKey)
+ applyShowBigPlayer(store.get(store.showBigPlayerKey))
+ })
+
+ const $showOriginalThumbnail = document.getElementById('show-original-thumbnail')
+ store.get(store.showOriginalThumbnailKey) ? $showOriginalThumbnail.setAttribute('checked', 'true') : $showOriginalThumbnail.removeAttribute('checked')
+
+ $showOriginalThumbnail.addEventListener('click', (event) => {
+ store.toggle(store.showOriginalThumbnailKey)
+ })
+
+ const $useTLDWTube = document.getElementById('use-tldw-tube')
+ store.get(store.useTLDWTubeKey) ? $useTLDWTube.setAttribute('checked', 'true') : $useTLDWTube.removeAttribute('checked')
+
+ $useTLDWTube.addEventListener('click', (event) => {
+ store.toggle(store.useTLDWTubeKey)
+ })
+
+ const $showCaptions = document.getElementById('show-captions')
+ store.get(store.showCaptionsKey) ? $showCaptions.setAttribute('checked', 'true') : $showCaptions.removeAttribute('checked')
+
+ $showCaptions.addEventListener('click', (event) => {
+ store.toggle(store.showCaptionsKey)
+ })
+ }
+ },
+ '/404': {
+ template: document.getElementById('not-found-template'),
+ async initialize () {
+ document.querySelector('search-videos #search').setAttribute('disabled', 'disabled')
+ document.querySelector('search-videos').classList.add('hide')
+ }
+ }
}
handleRoute()
@@ -91,13 +100,12 @@ document.querySelectorAll('[href="/"],[href="/settings"]').forEach(($el) => {
event.preventDefault()
const path = new URL($el.href, location.origin).pathname
history.pushState({}, '', path)
- var popStateEvent = new PopStateEvent('popstate', {})
+ const popStateEvent = new PopStateEvent('popstate', {})
dispatchEvent(popStateEvent)
})
})
-
-function handleRoute() {
+function handleRoute () {
const route = location.pathname
if (routes[route]) {
document.querySelector('main').replaceChildren(routes[route].template.content.cloneNode(true))
@@ -114,4 +122,4 @@ function handleEmptyState () {
} else {
document.querySelector('empty-state').style.display = 'none'
}
-}
\ No newline at end of file
+}
diff --git a/client/lib/store.js b/client/lib/store.js
index 0c9ae35..e6243a3 100644
--- a/client/lib/store.js
+++ b/client/lib/store.js
@@ -7,7 +7,7 @@ export default class Store {
lastVideosKey = 'lastVideos'
ignoreTermsKey = 'ignoreTerms'
- constructor() {
+ constructor () {
if (!localStorage.getItem(this.showThumbnailsKey)) localStorage.setItem(this.showThumbnailsKey, 'true')
if (!localStorage.getItem(this.showBigPlayerKey)) localStorage.setItem(this.showBigPlayerKey, 'true')
if (!localStorage.getItem(this.showOriginalThumbnailKey)) localStorage.setItem(this.showOriginalThumbnailKey, 'false')
@@ -21,35 +21,39 @@ export default class Store {
if (![this.showThumbnailsKey, this.showBigPlayerKey, this.showOriginalThumbnailKey, this.showCaptionsKey, this.useTLDWTubeKey].includes(key)) return console.error('invalid key', key)
localStorage.setItem(key, localStorage.getItem(key) === 'true' ? 'false' : 'true')
}
- get(key) {
+
+ get (key) {
if (![this.showThumbnailsKey, this.showBigPlayerKey, this.showOriginalThumbnailKey, this.showCaptionsKey, this.useTLDWTubeKey, this.lastVideosKey, this.ignoreTermsKey].includes(key)) return console.error('invalid key', key)
return JSON.parse(localStorage.getItem(key))
}
- set(key, value) {
+
+ set (key, value) {
if (typeof value === 'string') {
localStorage.setItem(key, value)
} else {
localStorage.setItem(key, JSON.stringify(value))
}
}
- push(key, item) {
+
+ push (key, item) {
if (![this.ignoreTermsKey].includes(key)) return console.error('invalid key', key)
const list = this.get(key)
list.push(item)
this.set(key, list)
return item
}
- remove(key, item) {
+
+ remove (key, item) {
if (![this.ignoreTermsKey].includes(key)) return console.error('invalid key', key)
let list = this.get(key)
list = list.filter(i => i !== item)
this.set(key, list)
return item
}
- includes(key, item) {
+
+ includes (key, item) {
if (![this.ignoreTermsKey].includes(key)) return console.error('invalid key', key)
const list = this.get(key)
return list.includes(item)
-
}
-}
\ No newline at end of file
+}
diff --git a/client/lib/utils.js b/client/lib/utils.js
index a9555da..087ab8a 100644
--- a/client/lib/utils.js
+++ b/client/lib/utils.js
@@ -1,9 +1,11 @@
export function createVideoElement (video, showOriginalThumbnail = false) {
const $video = document.createElement('video-element')
- $video.dataset['data'] = JSON.stringify(Object.assign(video, showOriginalThumbnail ? {
- thumbnail: video.thumbnail.replace('mq2.jpg', 'mqdefault.jpg')
- } : {}))
- $video.dataset['videoId'] = video.id
+ $video.dataset.data = JSON.stringify(Object.assign(video, showOriginalThumbnail
+ ? {
+ thumbnail: video.thumbnail.replace('mq2.jpg', 'mqdefault.jpg')
+ }
+ : {}))
+ $video.dataset.videoId = video.id
return $video
}
@@ -20,7 +22,7 @@ export function addToast (text) {
}
}
-export function applyShowThumbnails(showThumbnails) {
+export function applyShowThumbnails (showThumbnails) {
if (showThumbnails) {
document.body.classList.remove('hide-thumbnails')
} else {
@@ -30,7 +32,7 @@ export function applyShowThumbnails(showThumbnails) {
if ($showThumbnailsCheckbox) $showThumbnailsCheckbox.checked = showThumbnails
}
-export function applyShowBigPlayer(showBigPlayer) {
+export function applyShowBigPlayer (showBigPlayer) {
if (showBigPlayer) {
document.body.classList.add('show-big-player')
} else {
diff --git a/client/main.js b/client/main.js
index 345fd78..2ddb29c 100644
--- a/client/main.js
+++ b/client/main.js
@@ -1,8 +1,8 @@
-import Store from '/lib/store.js'
-import { createVideoElement } from '/lib/utils.js'
+import Store from '../../../../../lib/store.js'
+import { createVideoElement } from '../../../../../lib/utils.js'
const store = new Store()
window.state = {
- downloading: {},
+ downloading: {},
summarizing: {}
}
@@ -28,11 +28,11 @@ eventSource.onmessage = (message) => {
setTimeout(() => {
Object.keys(data.state.downloading || {}).map((videoId) => {
const $video = document.querySelector(`video-element[data-video-id="${videoId}"]`)
- if ($video) $video.dataset['downloading'] = "true"
+ if ($video) $video.dataset.downloading = 'true'
})
Object.keys(data.state.summarizing || {}).map((videoId) => {
const $video = document.querySelector(`video-element[data-video-id="${videoId}"]`)
- if ($video) $video.dataset['summarizing'] = "true"
+ if ($video) $video.dataset.summarizing = 'true'
})
const count = Object.keys(data.state.summarizing).length + Object.keys(data.state.downloading).length
$count.innerText = count > 0 ? `(${count})` : ''
@@ -70,29 +70,29 @@ eventSource.onmessage = (message) => {
}
if (data.type === 'summary' && data.videoId && data.summary && data.transcript) {
;[...document.querySelectorAll(`[data-video-id="${data.videoId}"]`)].forEach($video => {
- if (!$video.dataset['data']) return
- const videoData = JSON.parse($video.dataset['data'])
+ if (!$video.dataset.data) return
+ const videoData = JSON.parse($video.dataset.data)
Object.assign(videoData, { summary: data.summary, transcript: data.transcript })
- $video.dataset['data'] = JSON.stringify(videoData)
+ $video.dataset.data = JSON.stringify(videoData)
})
return
}
if (data.type === 'downloaded' && data.videoId && data.downloaded !== undefined) {
;[...document.querySelectorAll(`[data-video-id="${data.videoId}"]`)].forEach($video => {
- if (!$video.dataset['data']) return
- const videoData = JSON.parse($video.dataset['data'])
+ if (!$video.dataset.data) return
+ const videoData = JSON.parse($video.dataset.data)
videoData.downloaded = data.downloaded
if (data.video) Object.assign(videoData, data.video)
- $video.dataset['data'] = JSON.stringify(videoData)
+ $video.dataset.data = JSON.stringify(videoData)
})
return
}
if (data.type === 'ignored' && data.videoId && data.ignored !== undefined) {
;[...document.querySelectorAll(`[data-video-id="${data.videoId}"]`)].forEach($video => {
- if (!$video.dataset['data']) return
- const videoData = JSON.parse($video.dataset['data'])
+ if (!$video.dataset.data) return
+ const videoData = JSON.parse($video.dataset.data)
videoData.ignored = data.ignored
- $video.dataset['data'] = JSON.stringify(videoData)
+ $video.dataset.data = JSON.stringify(videoData)
})
return
}
@@ -102,21 +102,19 @@ eventSource.onmessage = (message) => {
}
}
-
const $summary = document.querySelector('dialog#summary')
-const $closeSummary = $summary.querySelector("button")
-$closeSummary.addEventListener("click", () => $summary.close())
+const $closeSummary = $summary.querySelector('button')
+$closeSummary.addEventListener('click', () => $summary.close())
$summary.addEventListener('close', () => {})
-
observeDialogOpenPreventScroll($summary)
function observeDialogOpenPreventScroll (dialog) {
new MutationObserver((mutationList, observer) => {
for (const mutation of mutationList) {
- if (mutation.type === "attributes" && mutation.attributeName === 'open') {
+ 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 })
-}
\ No newline at end of file
+}
diff --git a/index.js b/index.js
index ee8d2fb..f9a42da 100644
--- a/index.js
+++ b/index.js
@@ -2,16 +2,15 @@ import os from 'os'
import Repository from './lib/repository.js'
import { createServer } from './lib/server.js'
-
-async function main ({port = 3000} = {}) {
+async function main ({ port = 3000 } = {}) {
createServer(new Repository())
- .listen(port, () => {
- console.log(`Server running at http://${os.hostname()}:${port} (or http://localhost:${port})`)
- })
+ .listen(port, () => {
+ console.log(`Server running at http://${os.hostname()}:${port} (or http://localhost:${port})`)
+ })
}
if (import.meta.url.endsWith('index.js')) {
main({
port: +process.env.PORT || 3000
})
-}
\ No newline at end of file
+}
diff --git a/lib/ffmpeg.js b/lib/ffmpeg.js
index 48c601e..6a0f96d 100644
--- a/lib/ffmpeg.js
+++ b/lib/ffmpeg.js
@@ -1,6 +1,6 @@
import spawn from 'nano-spawn'
-export function transcode(location, format) {
+export function transcode (location, format) {
console.log('trascoding video', location)
return spawn('ffmpeg', [
'-i',
@@ -21,6 +21,6 @@ export function transcode(location, format) {
'+faststart',
'-c:a',
'copy',
- location.replace(format, 'tmp.'+format)
+ location.replace(format, 'tmp.' + format)
])
-}
\ No newline at end of file
+}
diff --git a/lib/llm/index.js b/lib/llm/index.js
index fbb4132..de3ac4f 100644
--- a/lib/llm/index.js
+++ b/lib/llm/index.js
@@ -1,15 +1,15 @@
-import { Anthropic } from "./providers/anthropic.js"
-import { Generic } from "./providers/generic.js"
+import { Anthropic } from './providers/anthropic.js'
+import { Generic } from './providers/generic.js'
-export async function summarize(
+export async function summarize (
system,
prompt,
- llmSettings,
+ llmSettings
) {
try {
- const llm = llmSettings.host.includes('api.anthropic.com')
- ? new Anthropic(system, llmSettings)
- : new Generic(system, llmSettings)
+ const llm = llmSettings.host.includes('api.anthropic.com')
+ ? new Anthropic(system, llmSettings)
+ : new Generic(system, llmSettings)
return llm.summarize(prompt)
} catch (e) {
diff --git a/lib/llm/providers/anthropic.js b/lib/llm/providers/anthropic.js
index 76f94a8..a0194b9 100644
--- a/lib/llm/providers/anthropic.js
+++ b/lib/llm/providers/anthropic.js
@@ -1,10 +1,10 @@
-import { Generic } from "./generic.js"
+import { Generic } from './generic.js'
const ANTHROPIC_VERSION = '2023-06-01'
const MAX_TOKENS = 1024
export class Anthropic extends Generic {
- constructor(system, args = {
+ constructor (system, args = {
model,
host,
endpoint,
@@ -30,7 +30,7 @@ export class Anthropic extends Generic {
system: this.system,
maxTokens: this.maxTokens,
messages: [
- { role: "user", content: prompt }
+ { role: 'user', content: prompt }
]
})
}
diff --git a/lib/llm/providers/generic.js b/lib/llm/providers/generic.js
index 0910da7..af6feec 100644
--- a/lib/llm/providers/generic.js
+++ b/lib/llm/providers/generic.js
@@ -2,7 +2,7 @@ const MAX_PROMPT_LEN = 10000
const MAX_TOKENS = 1024
export class Generic {
- constructor(system, {
+ constructor (system, {
model,
host,
endpoint,
@@ -21,8 +21,8 @@ export class Generic {
getHeaders () {
return Object.assign({
- 'Content-Type': 'application/json',
- }, this.apiKey ? { 'Authorization': `Bearer ${this.apiKey}` } : {})
+ 'Content-Type': 'application/json'
+ }, this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {})
}
getBody (prompt) {
@@ -31,8 +31,8 @@ export class Generic {
temperature: Number(this.temperature),
maxTokens: this.maxTokens,
messages: [
- { role: "system", content: this.system },
- { role: "user", content: prompt }
+ { role: 'system', content: this.system },
+ { role: 'user', content: prompt }
]
})
}
@@ -42,8 +42,8 @@ export class Generic {
const message = messages[messages.length - 1]?.message?.content || ''
return message.replace('<|eot_id|>', '')
}
-
- async summarize(prompt) {
+
+ async summarize (prompt) {
if (prompt.length > MAX_PROMPT_LEN) prompt = prompt.substring(0, MAX_PROMPT_LEN)
try {
diff --git a/lib/repository.js b/lib/repository.js
index 604bdb9..49d5550 100644
--- a/lib/repository.js
+++ b/lib/repository.js
@@ -1,7 +1,7 @@
import fs from 'fs'
export default class Repository {
- constructor(basePath = './data') {
+ constructor (basePath = './data') {
this.channels = []
this.videos = []
this.basePath = basePath
@@ -10,7 +10,7 @@ export default class Repository {
channels: `${this.basePath}/channels.json`,
settings: `${this.basePath}/settings.json`
}
-
+
fs.mkdirSync(`${this.basePath}/videos`, { recursive: true })
if (!fs.existsSync(this.paths.videos)) {
fs.writeFileSync(this.paths.videos, '[]')
@@ -20,12 +20,12 @@ export default class Repository {
}
if (!fs.existsSync(this.paths.settings)) {
fs.writeFileSync(this.paths.settings, JSON.stringify({
- videoQuality: 720,
+ videoQuality: 720,
transcodeVideos: true,
- excludedTerms: []
+ excludedTerms: []
}, null, 2))
}
-
+
try {
this.videos = JSON.parse(fs.readFileSync(this.paths.videos))
this.channels = JSON.parse(fs.readFileSync(this.paths.channels))
@@ -34,7 +34,7 @@ export default class Repository {
console.error(err)
}
if (this.settings.transcodeVideos === undefined) { this.setTranscodeVideosSetting(true) }
- if (this.settings.excludedTerms === undefined) {
+ if (this.settings.excludedTerms === undefined) {
this.settings.excludedTerms = []
this.saveSettings
}
@@ -44,7 +44,7 @@ export default class Repository {
if (!['mp4', 'webm'].includes(format)) return
const videoId = file.replace(/\.(webm|mp4)$/, '')
const location = `${this.basePath}/videos/${file}`
- this.updateVideo(videoId, {downloaded: true, location, format})
+ this.updateVideo(videoId, { downloaded: true, location, format })
})
this.saveVideos()
}
@@ -53,33 +53,40 @@ export default class Repository {
channelExists (name) {
return !!this.channels.find(c => c.name === name)
}
+
addChannel (name) {
- this.channels.push({name})
+ this.channels.push({ name })
this.saveChannels()
}
+
deleteChannel (name) {
this.channels.splice(this.channels.findIndex(c => c.name === name), 1)
this.saveChannels()
}
- saveChannels() {
+
+ saveChannels () {
fs.writeFileSync(this.paths.channels, JSON.stringify(this.channels, null, 2))
}
- saveSettings() {
+
+ saveSettings () {
fs.writeFileSync(this.paths.settings, JSON.stringify(this.settings, null, 2))
}
- getAllVideos() {
+
+ getAllVideos () {
return this.videos
}
+
filterByExcludedTerms (v, excludedTerms = this.getExcludedTerms()) {
return v.downloaded || !excludedTerms.some(term => v.title?.toLowerCase().includes(term) || v.description?.toLowerCase().includes(term))
- }
+ }
+
getVideos (query = {}) {
const isFiltering = Object.keys(query).length > 0 && query.filter
let videos = this.videos
- .filter(v => query.excluded === 'true' ? true : this.filterByExcludedTerms(v))
- .filter(v => query.downloaded === 'true' ? v.downloaded : true)
- .filter(v => isFiltering ? true : !v.ignored)
- .sort((a, b) => +new Date(b.publishedAt) - +new Date(a.publishedAt))
+ .filter(v => query.excluded === 'true' ? true : this.filterByExcludedTerms(v))
+ .filter(v => query.downloaded === 'true' ? v.downloaded : true)
+ .filter(v => isFiltering ? true : !v.ignored)
+ .sort((a, b) => +new Date(b.publishedAt) - +new Date(a.publishedAt))
if (isFiltering) {
const searchTerm = query.filter.toLowerCase()
@@ -89,35 +96,39 @@ export default class Repository {
})
} else {
videos = videos.filter(v => {
- return v.channelName.toLowerCase().includes(searchTerm)
- || v.title?.toLowerCase().includes(searchTerm)
- || v.description?.toLowerCase().includes(searchTerm)
+ return v.channelName.toLowerCase().includes(searchTerm) ||
+ v.title?.toLowerCase().includes(searchTerm) ||
+ v.description?.toLowerCase().includes(searchTerm)
})
}
}
videos = videos.filter((_, i) => i < 100)
-
+
return videos
}
- getVideo(id) {
+
+ getVideo (id) {
return this.videos.find(v => v.id === id)
}
+
getChannelVideos (name) {
return this.videos.filter(v => v.channelName === name)
}
- upsertVideos(videos) {
+
+ upsertVideos (videos) {
(Array.isArray(videos) ? videos : [videos])
- .forEach(v => {
- const index = this.videos.findIndex(video => video.id === v.id)
- if (index !== -1) {
- this.videos[index] = Object.assign(this.videos[index], v)
- } else {
- this.videos.push(v)
- }
- })
+ .forEach(v => {
+ const index = this.videos.findIndex(video => video.id === v.id)
+ if (index !== -1) {
+ this.videos[index] = Object.assign(this.videos[index], v)
+ } else {
+ this.videos.push(v)
+ }
+ })
this.saveVideos()
}
- updateVideo(id, update) {
+
+ updateVideo (id, update) {
const index = this.videos.findIndex(v => v.id === id)
if (index !== -1) {
Object.assign(this.videos[index], update)
@@ -125,15 +136,16 @@ export default class Repository {
return this.videos[index]
}
}
- deleteVideo(id) {
+
+ deleteVideo (id) {
this.videos = this.videos.map(v => {
if (v.id === id) {
- return Object.assign(v, {downloaded: false})
+ return Object.assign(v, { downloaded: false })
}
return v
})
this.saveVideos()
-
+
const files = fs.readdirSync(`${this.basePath}/videos`)
files.forEach(file => {
if (file.startsWith(id)) {
@@ -144,10 +156,12 @@ export default class Repository {
}
})
}
- saveVideos() {
+
+ saveVideos () {
fs.writeFileSync(this.paths.videos, JSON.stringify(this.videos, null, 2))
}
- toggleIgnoreVideo(id) {
+
+ toggleIgnoreVideo (id) {
const index = this.videos.findIndex(v => v.id === id)
let ignored = false
if (index !== -1) {
@@ -158,23 +172,29 @@ export default class Repository {
this.saveVideos()
return ignored
}
- setVideoTranscript(id, transcript = '') {
- return this.updateVideo(id, {transcript})
+
+ setVideoTranscript (id, transcript = '') {
+ return this.updateVideo(id, { transcript })
}
- setVideoSummary(id, summary = '') {
- return this.updateVideo(id, {summary})
+
+ setVideoSummary (id, summary = '') {
+ return this.updateVideo(id, { summary })
}
- setVideoDownloaded(id, downloaded = true) {
- return this.updateVideo(id, {downloaded})
+
+ setVideoDownloaded (id, downloaded = true) {
+ return this.updateVideo(id, { downloaded })
}
- patchVideo(video) {
+
+ patchVideo (video) {
if (this.getVideo(video.id)) return video
- return Object.assign(video, {addedAt: Date.now()})
+ return Object.assign(video, { addedAt: Date.now() })
}
- getVideoQualitySetting() {
+
+ getVideoQualitySetting () {
return this.settings.videoQuality
}
- setVideoQualitySetting(videoQuality) {
+
+ setVideoQualitySetting (videoQuality) {
if ([360, 480, 720, 1080, 1440, 2160].includes(videoQuality)) {
this.settings.videoQuality = videoQuality
this.saveSettings()
@@ -183,19 +203,22 @@ export default class Repository {
}
return this.settings.videoQuality
}
- getTranscodeVideosSetting() {
+
+ getTranscodeVideosSetting () {
return this.settings.transcodeVideos
}
- setTranscodeVideosSetting(value) {
+
+ setTranscodeVideosSetting (value) {
this.settings.transcodeVideos = !!value
this.saveSettings()
return this.settings.transcodeVideos
}
- getExcludedTerms() {
+ getExcludedTerms () {
return this.settings.excludedTerms || []
}
- addExcludedTerm(term = '') {
+
+ addExcludedTerm (term = '') {
if (!term) return
term = term.trim()
const excludedTerms = this.getExcludedTerms()
@@ -205,7 +228,8 @@ export default class Repository {
this.saveSettings()
}
}
- removeExcludedTerm(term) {
+
+ removeExcludedTerm (term) {
const excludedTerms = this.getExcludedTerms()
const index = excludedTerms.indexOf(term)
if (index >= 0) {
@@ -214,4 +238,4 @@ export default class Repository {
this.saveSettings()
}
}
-}
\ No newline at end of file
+}
diff --git a/lib/router/api.js b/lib/router/api.js
index d328db3..5f15b72 100644
--- a/lib/router/api.js
+++ b/lib/router/api.js
@@ -7,7 +7,7 @@ import { downloadVideo, extractIdFromUrl, isUnsupportedUrl, isYouTubeUrl } from
import { updateAndPersistVideosForChannel } from '../update-videos.js'
const llmDefaults = {
- model:'meta-llama-3.1-8b-instruct',
+ model: 'meta-llama-3.1-8b-instruct',
host: 'http://127.0.0.1:1234',
endpoint: '/v1/chat/completions',
apiKey: '',
@@ -19,62 +19,43 @@ const llmSettings = {
host: process.env.AI_HOST ?? llmDefaults.host,
endpoint: process.env.AI_ENDPOINT ?? llmDefaults.endpoint,
apiKey: process.env.AI_APIKEY ?? llmDefaults.apiKey,
- temperature: process.env.AI_TEMPERATURE ?? llmDefaults.temperature,
+ temperature: process.env.AI_TEMPERATURE ?? llmDefaults.temperature
}
-export default function apiHandler(req, res, repo, connections = [], state = {}) {
+export default function apiHandler (req, res, repo, connections = [], state = {}) {
const url = new URL(req.url, `http://${req.headers.host}`)
- if (url.pathname === '/api/channels' && req.method === 'GET')
- return getChannelHandler(req, res, repo, connections)
- if (url.pathname === '/api/channels' && req.method === 'POST')
- return addChannelHandler(req, res, repo, connections)
- if (url.pathname === '/api/channels' && req.method === 'DELETE')
- return deleteChannelHandler(req, res, repo, connections)
- if (url.pathname === '/api/download-video' && req.method === 'POST')
- return downloadVideoHandler(req, res, repo, connections, state)
- if (url.pathname === '/api/summarize-video' && req.method === 'POST')
- return summarizeVideoHandler(req, res, repo, connections, state, llmSettings)
- if (url.pathname === '/api/ignore-video' && req.method === 'POST')
- return ignoreVideoHandler(req, res, repo, connections)
- if (url.pathname === '/api/delete-video' && req.method === 'POST')
- return deleteVideoHandler(req, res, repo, connections)
- if (url.pathname === '/api/videos' && req.method === 'GET')
- return searchVideosHandler(req, res, repo, connections)
- if (url.pathname === '/api/video-quality' && req.method === 'GET')
- return getVideoQualityHandler(req, res, repo, connections)
- if (url.pathname === '/api/video-quality' && req.method === 'POST')
- return setVideoQualityHandler(req, res, repo, connections)
- if (url.pathname === '/api/disk-usage' && req.method === 'GET')
- return diskUsageHandler(req, res, repo, connections)
- if (url.pathname === '/api/reclaim-disk-space' && req.method === 'POST')
- return reclaimDiskSpaceHandler(req, res, repo, connections)
- if (url.pathname === '/api/transcode-videos' && req.method === 'GET')
- return getTranscodeVideosHandler(req, res, repo, connections)
- if (url.pathname === '/api/transcode-videos' && req.method === 'POST')
- return setTranscodeVideosHandler(req, res, repo, connections)
- if (url.pathname === '/api/excluded-terms' && req.method === 'GET')
- return getExcludedTermsHandler(req, res, repo, connections)
- if (url.pathname === '/api/excluded-terms' && req.method === 'POST')
- return addExcludedTermHandler(req, res, repo, connections)
- if (url.pathname === '/api/excluded-terms' && req.method === 'DELETE')
- return removeExcludedTermHandler(req, res, repo, connections)
- if (url.pathname.match(/\/api\/videos\/.*/) && req.method === 'GET')
- return watchVideoHandler(req, res, repo)
- if (url.pathname.match(/\/api\/captions\/.*/) && req.method === 'GET')
- return captionsHandler(req, res, repo)
+ if (url.pathname === '/api/channels' && req.method === 'GET') { return getChannelHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/channels' && req.method === 'POST') { return addChannelHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/channels' && req.method === 'DELETE') { return deleteChannelHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/download-video' && req.method === 'POST') { return downloadVideoHandler(req, res, repo, connections, state) }
+ if (url.pathname === '/api/summarize-video' && req.method === 'POST') { return summarizeVideoHandler(req, res, repo, connections, state, llmSettings) }
+ if (url.pathname === '/api/ignore-video' && req.method === 'POST') { return ignoreVideoHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/delete-video' && req.method === 'POST') { return deleteVideoHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/videos' && req.method === 'GET') { return searchVideosHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/video-quality' && req.method === 'GET') { return getVideoQualityHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/video-quality' && req.method === 'POST') { return setVideoQualityHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/disk-usage' && req.method === 'GET') { return diskUsageHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/reclaim-disk-space' && req.method === 'POST') { return reclaimDiskSpaceHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/transcode-videos' && req.method === 'GET') { return getTranscodeVideosHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/transcode-videos' && req.method === 'POST') { return setTranscodeVideosHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/excluded-terms' && req.method === 'GET') { return getExcludedTermsHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/excluded-terms' && req.method === 'POST') { return addExcludedTermHandler(req, res, repo, connections) }
+ if (url.pathname === '/api/excluded-terms' && req.method === 'DELETE') { return removeExcludedTermHandler(req, res, repo, connections) }
+ if (url.pathname.match(/\/api\/videos\/.*/) && req.method === 'GET') { return watchVideoHandler(req, res, repo) }
+ if (url.pathname.match(/\/api\/captions\/.*/) && req.method === 'GET') { return captionsHandler(req, res, repo) }
res.writeHead(404)
return res.end()
}
-async function getChannelHandler(req, res, repo, connections = []) {
+async function getChannelHandler (req, res, repo, connections = []) {
const channels = repo.getChannels()
res.writeHead(200, { 'Content-Type': 'application/json' })
return res.end(JSON.stringify(channels))
}
-async function addChannelHandler(req, res, repo, connections = []) {
+async function addChannelHandler (req, res, repo, connections = []) {
const body = await getBody(req)
let { name } = JSON.parse(body)
name = name.trim()
@@ -88,7 +69,7 @@ async function addChannelHandler(req, res, repo, connections = []) {
const videos = await updateAndPersistVideosForChannel(name, repo)
if (Array.isArray(videos)) {
repo.addChannel(name)
- broadcastSSE(JSON.stringify({type: 'new-videos', name, videos}), connections)
+ broadcastSSE(JSON.stringify({ type: 'new-videos', name, videos }), connections)
res.writeHead(201)
return res.end('Channel added')
}
@@ -97,7 +78,7 @@ async function addChannelHandler(req, res, repo, connections = []) {
return res.end('Channel not found')
}
-async function deleteChannelHandler(req, res, repo, connections = []) {
+async function deleteChannelHandler (req, res, repo, connections = []) {
const body = await getBody(req)
let { name } = JSON.parse(body)
name = name.trim()
@@ -112,7 +93,7 @@ async function deleteChannelHandler(req, res, repo, connections = []) {
return res.end('Channel deleted')
}
-async function downloadVideoHandler(req, res, repo, connections = [], state = {}) {
+async function downloadVideoHandler (req, res, repo, connections = [], state = {}) {
const body = await getBody(req)
let { id, external } = JSON.parse(body)
@@ -124,88 +105,87 @@ async function downloadVideoHandler(req, res, repo, connections = [], state = {}
if (isYouTubeUrl(id)) { id = extractIdFromUrl(id) }
state.downloading = state.downloading || {}
- state.downloading[id] = {lines: []}
+ state.downloading[id] = { lines: [] }
let broadcastNewVideoOnce = false
downloadVideo(id, repo, (line) => {
if (external && !broadcastNewVideoOnce) {
- broadcastSSE(JSON.stringify({type: 'new-videos', videos: [repo.getVideo(id)]}), connections)
+ broadcastSSE(JSON.stringify({ type: 'new-videos', videos: [repo.getVideo(id)] }), connections)
broadcastNewVideoOnce = true
}
- broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections)
- })
- .then(() => {
- const video = repo.getVideo(id)
- broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id, downloaded: true, video}), connections)
- })
- .catch((error) => {
- broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.stderr}), connections)
- })
- .finally(() => {
- delete state.downloading[id]
+ broadcastSSE(JSON.stringify({ type: 'download-log-line', line }), connections)
})
+ .then(() => {
+ const video = repo.getVideo(id)
+ broadcastSSE(JSON.stringify({ type: 'downloaded', videoId: id, downloaded: true, video }), connections)
+ })
+ .catch((error) => {
+ broadcastSSE(JSON.stringify({ type: 'download-log-line', line: error.stderr }), connections)
+ })
+ .finally(() => {
+ delete state.downloading[id]
+ })
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Download started')
}
-async function summarizeVideoHandler(req, res, repo, connections = [], state = {}, llmSettings = {}) {
+async function summarizeVideoHandler (req, res, repo, connections = [], state = {}, llmSettings = {}) {
const body = await getBody(req)
const { id } = JSON.parse(body)
state.summarizing = state.summarizing || {}
- state.summarizing[id] = {lines: []}
+ state.summarizing[id] = { lines: [] }
summarizeVideo(id, repo, llmSettings, (line) => {
- broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections)
- })
- .then(({summary, transcript}) =>
- broadcastSSE(JSON.stringify({type: 'summary', summary, transcript, videoId: id}), connections))
- .catch((error) => {
- broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.message}), connections)
- broadcastSSE(JSON.stringify({type: 'summary-error', videoId: id}), connections)
- })
- .finally(() => {
- delete state.summarizing[id]
+ broadcastSSE(JSON.stringify({ type: 'download-log-line', line }), connections)
})
+ .then(({ summary, transcript }) =>
+ broadcastSSE(JSON.stringify({ type: 'summary', summary, transcript, videoId: id }), connections))
+ .catch((error) => {
+ broadcastSSE(JSON.stringify({ type: 'download-log-line', line: error.message }), connections)
+ broadcastSSE(JSON.stringify({ type: 'summary-error', videoId: id }), connections)
+ })
+ .finally(() => {
+ delete state.summarizing[id]
+ })
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Download started')
}
-async function ignoreVideoHandler(req, res, repo, connections = []) {
+async function ignoreVideoHandler (req, res, repo, connections = []) {
const body = await getBody(req)
- let { id } = JSON.parse(body)
+ const { id } = JSON.parse(body)
const ignored = repo.toggleIgnoreVideo(id)
- broadcastSSE(JSON.stringify({type: 'ignored', videoId: id, ignored}), connections)
+ broadcastSSE(JSON.stringify({ type: 'ignored', videoId: id, ignored }), connections)
res.writeHead(200, { 'Content-Type': 'application/json' })
return res.end(JSON.stringify(ignored))
}
-async function deleteVideoHandler(req, res, repo, connections = []) {
+async function deleteVideoHandler (req, res, repo, connections = []) {
const body = await getBody(req)
- let { id } = JSON.parse(body)
+ const { id } = JSON.parse(body)
repo.deleteVideo(id)
- broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id, downloaded: false}), connections)
+ broadcastSSE(JSON.stringify({ type: 'downloaded', videoId: id, downloaded: false }), connections)
res.writeHead(200)
res.end()
}
-export function searchVideosHandler(req, res, repo) {
+export function searchVideosHandler (req, res, repo) {
const query = getQuery(req)
const videos = repo.getVideos(query)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(videos))
}
-
-function getVideoQualityHandler(req, res, repo) {
+function getVideoQualityHandler (req, res, repo) {
const videoQuality = repo.getVideoQualitySetting()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(videoQuality))
}
-async function setVideoQualityHandler(req, res, repo) {
+async function setVideoQualityHandler (req, res, repo) {
const body = await getBody(req)
const videoQuality = JSON.parse(body)
@@ -218,75 +198,75 @@ async function setVideoQualityHandler(req, res, repo) {
res.end(JSON.stringify(newQuality))
}
-function diskUsageHandler(req, res, repo) {
+function diskUsageHandler (req, res, repo) {
const onlyIgnored = getQuery(req).onlyIgnored === 'true'
const videos = repo.getAllVideos()
const filterFn = onlyIgnored ? video => (video.downloaded || video.transcript) && video.ignored : video => (video.downloaded || video.transcript)
const diskSpaceUsed = videos.filter(filterFn)
- .reduce((total, video) => {
- try {
- const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
- return total + filenames.reduce((acc, filename) => acc + fs.statSync(`./data/videos/${filename}`).size / Math.pow(10, 9), 0)
- } catch (err) {
- console.error(err)
- return total
- }
- }, 0)
+ .reduce((total, video) => {
+ try {
+ const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
+ return total + filenames.reduce((acc, filename) => acc + fs.statSync(`./data/videos/${filename}`).size / Math.pow(10, 9), 0)
+ } catch (err) {
+ console.error(err)
+ return total
+ }
+ }, 0)
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(diskSpaceUsed.toFixed(3) + 'GB')
}
-async function reclaimDiskSpaceHandler(req, res, repo) {
+async function reclaimDiskSpaceHandler (req, res, repo) {
const body = await getBody(req)
- const {onlyIgnored} = JSON.parse(body)
+ const { onlyIgnored } = JSON.parse(body)
const videos = repo.getAllVideos()
const filterFn = onlyIgnored ? video => (video.downloaded || video.transcript) && video.ignored : video => (video.downloaded || video.transcript)
videos.filter(filterFn)
- .forEach((video) => {
- try {
- const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
- filenames.forEach(filename => {
- fs.unlinkSync(`./data/videos/${filename}`)
- })
- repo.updateVideo(video.id, {downloaded: false})
- } catch (err) {
- console.error(err.message)
- }
- })
+ .forEach((video) => {
+ try {
+ const filenames = fs.readdirSync('./data/videos').filter(f => f.startsWith(video.id))
+ filenames.forEach(filename => {
+ fs.unlinkSync(`./data/videos/${filename}`)
+ })
+ repo.updateVideo(video.id, { downloaded: false })
+ } catch (err) {
+ console.error(err.message)
+ }
+ })
repo.saveVideos()
res.writeHead(200)
res.end()
}
-async function getExcludedTermsHandler(req, res, repo) {
+async function getExcludedTermsHandler (req, res, repo) {
const excludedTerms = repo.getExcludedTerms()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(excludedTerms))
}
-async function addExcludedTermHandler(req, res, repo) {
+async function addExcludedTermHandler (req, res, repo) {
const body = await getBody(req)
const term = JSON.parse(body).term
repo.addExcludedTerm(term)
res.writeHead(200)
res.end()
}
-async function removeExcludedTermHandler(req, res, repo) {
+async function removeExcludedTermHandler (req, res, repo) {
const body = await getBody(req)
const term = JSON.parse(body).term
repo.removeExcludedTerm(term)
res.writeHead(200)
res.end()
}
-async function getTranscodeVideosHandler(req, res, repo) {
- let transcodeVideos = repo.getTranscodeVideosSetting()
+async function getTranscodeVideosHandler (req, res, repo) {
+ const transcodeVideos = repo.getTranscodeVideosSetting()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(transcodeVideos))
}
-async function setTranscodeVideosHandler(req, res, repo) {
+async function setTranscodeVideosHandler (req, res, repo) {
const body = await getBody(req)
const transcodeVideos = JSON.parse(body)
@@ -295,11 +275,11 @@ async function setTranscodeVideosHandler(req, res, repo) {
res.end()
}
-function watchVideoHandler(req, res, repo) {
+function watchVideoHandler (req, res, repo) {
const id = req.url.replace('/api/videos/', '').replace(/\.(webm|mp4)$/, '')
const video = repo.getVideo(id)
const location = video.location || `./data/videos/${id}.mp4`
- const contentType = video.format ? `video/${video.format}` : "video/mp4"
+ const contentType = video.format ? `video/${video.format}` : 'video/mp4'
if (!fs.existsSync(location)) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Video not found')
@@ -309,60 +289,60 @@ function watchVideoHandler(req, res, repo) {
// https://github.com/bootstrapping-microservices/video-streaming-example/blob/master/index.js
// https://blog.logrocket.com/streaming-video-in-safari/
- const options = {};
+ const options = {}
- let start;
- let end;
+ let start
+ let end
- const range = req.headers.range;
+ const range = req.headers.range
if (range) {
- const bytesPrefix = "bytes=";
+ const bytesPrefix = 'bytes='
if (range.startsWith(bytesPrefix)) {
- const bytesRange = range.substring(bytesPrefix.length);
- const parts = bytesRange.split("-");
+ const bytesRange = range.substring(bytesPrefix.length)
+ const parts = bytesRange.split('-')
if (parts.length === 2) {
- const rangeStart = parts[0] && parts[0].trim();
+ const rangeStart = parts[0] && parts[0].trim()
if (rangeStart && rangeStart.length > 0) {
- options.start = start = parseInt(rangeStart);
+ options.start = start = parseInt(rangeStart)
}
- const rangeEnd = parts[1] && parts[1].trim();
+ const rangeEnd = parts[1] && parts[1].trim()
if (rangeEnd && rangeEnd.length > 0) {
- options.end = end = parseInt(rangeEnd);
+ options.end = end = parseInt(rangeEnd)
}
}
}
}
- res.setHeader("content-type", contentType)
+ res.setHeader('content-type', contentType)
const stat = fs.statSync(location)
- let contentLength = stat.size
+ const contentLength = stat.size
- if (req.method === "HEAD") {
+ if (req.method === 'HEAD') {
res.statusCode = 200
- res.setHeader("accept-ranges", "bytes")
- res.setHeader("content-length", contentLength)
+ res.setHeader('accept-ranges', 'bytes')
+ res.setHeader('content-length', contentLength)
return res.end()
}
- let retrievedLength = contentLength;
+ let retrievedLength = contentLength
if (start !== undefined && end !== undefined) {
- retrievedLength = end - start + 1;
+ retrievedLength = end - start + 1
} else if (start !== undefined) {
- retrievedLength = contentLength - start;
+ retrievedLength = contentLength - start
}
res.statusCode = (start !== undefined || end !== undefined) ? 206 : 200
- res.setHeader("content-length", retrievedLength)
+ res.setHeader('content-length', retrievedLength)
if (range !== undefined) {
- res.setHeader("accept-ranges", "bytes")
- res.setHeader("content-range", `bytes ${start || 0}-${end || (contentLength-1)}/${contentLength}`)
+ res.setHeader('accept-ranges', 'bytes')
+ res.setHeader('content-range', `bytes ${start || 0}-${end || (contentLength - 1)}/${contentLength}`)
}
const fileStream = fs.createReadStream(location, options)
- fileStream.on("error", error => {
+ fileStream.on('error', error => {
console.error(`Error reading file ${location}.`, error)
res.writeHead(500)
res.end()
@@ -371,7 +351,7 @@ function watchVideoHandler(req, res, repo) {
fileStream.pipe(res)
}
-function captionsHandler(req, res) {
+function captionsHandler (req, res) {
const captionsPath = './data' + req.url.replace('api/captions', 'videos') + '.en.vtt'
if (!fs.existsSync(captionsPath)) {
res.writeHead(404)
@@ -382,11 +362,6 @@ function captionsHandler(req, res) {
}
}
-
-
-
-
-
async function getBody (req) {
return new Promise((resolve, reject) => {
let body = ''
@@ -400,6 +375,6 @@ async function getBody (req) {
function getQuery (req) {
return (req.url && req.url.indexOf('?') >= 0)
- ? querystring.parse(req.url.substring(req.url.indexOf('?') + 1))
- : {}
+ ? querystring.parse(req.url.substring(req.url.indexOf('?') + 1))
+ : {}
}
diff --git a/lib/router/app.js b/lib/router/app.js
index fa6434f..7842d0e 100644
--- a/lib/router/app.js
+++ b/lib/router/app.js
@@ -1,41 +1,25 @@
import fs from 'fs'
import { URL } from 'url'
-export default function apiHandler(req, res) {
+export default function apiHandler (req, res) {
const url = new URL(req.url, `http://${req.headers.host}`)
- if (url.pathname === '/main.css')
- return fileHandler('client/main.css', 'text/css')(req, res)
- if (url.pathname === '/normalize.css')
- return fileHandler('client/normalize.css', 'text/css')(req, res)
- if (url.pathname === '/main.js')
- return fileHandler('client/main.js', 'application/javascript')(req, res)
- if (url.pathname === '/lib/store.js')
- return fileHandler('client/lib/store.js', 'application/javascript')(req, res)
- if (url.pathname === '/lib/router.js')
- return fileHandler('client/lib/router.js', 'application/javascript')(req, res)
- if (url.pathname === '/lib/utils.js')
- return fileHandler('client/lib/utils.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/video-element.js')
- return fileHandler('client/components/video-element.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/add-channel-form.js')
- return fileHandler('client/components/add-channel-form.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/manage-channels-form.js')
- return fileHandler('client/components/manage-channels-form.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/video-quality-form.js')
- return fileHandler('client/components/video-quality-form.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/manage-disk-space-form.js')
- return fileHandler('client/components/manage-disk-space-form.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/transcode-videos-form.js')
- return fileHandler('client/components/transcode-videos-form.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/excluded-terms-form.js')
- return fileHandler('client/components/excluded-terms-form.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/search-videos.js')
- return fileHandler('client/components/search-videos.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/channels-list.js')
- return fileHandler('client/components/channels-list.js', 'application/javascript')(req, res)
- if (url.pathname === '/components/empty-state.js')
- return fileHandler('client/components/empty-state.js', 'application/javascript')(req, res)
+ if (url.pathname === '/main.css') { return fileHandler('client/main.css', 'text/css')(req, res) }
+ if (url.pathname === '/normalize.css') { return fileHandler('client/normalize.css', 'text/css')(req, res) }
+ if (url.pathname === '/main.js') { return fileHandler('client/main.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/lib/store.js') { return fileHandler('client/lib/store.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/lib/router.js') { return fileHandler('client/lib/router.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/lib/utils.js') { return fileHandler('client/lib/utils.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/video-element.js') { return fileHandler('client/components/video-element.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/add-channel-form.js') { return fileHandler('client/components/add-channel-form.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/manage-channels-form.js') { return fileHandler('client/components/manage-channels-form.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/video-quality-form.js') { return fileHandler('client/components/video-quality-form.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/manage-disk-space-form.js') { return fileHandler('client/components/manage-disk-space-form.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/transcode-videos-form.js') { return fileHandler('client/components/transcode-videos-form.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/excluded-terms-form.js') { return fileHandler('client/components/excluded-terms-form.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/search-videos.js') { return fileHandler('client/components/search-videos.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/channels-list.js') { return fileHandler('client/components/channels-list.js', 'application/javascript')(req, res) }
+ if (url.pathname === '/components/empty-state.js') { return fileHandler('client/components/empty-state.js', 'application/javascript')(req, res) }
return fileHandler('client/index.html', 'text/html')(req, res)
}
@@ -45,4 +29,4 @@ function fileHandler (filePath, contentType) {
res.writeHead(200, { 'Content-Type': contentType })
res.end(fs.readFileSync(filePath, 'utf8'))
}
-}
\ No newline at end of file
+}
diff --git a/lib/server.js b/lib/server.js
index a5bdcc3..d7d0274 100644
--- a/lib/server.js
+++ b/lib/server.js
@@ -8,22 +8,22 @@ import Repository from './repository.js'
export function createServer (repo = new Repository()) {
const stateChangeHandler = {
- get(target, key) {
+ 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)
+ 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: {},
+ summarizing: {}
}, stateChangeHandler)
const connections = []
@@ -31,16 +31,16 @@ export function createServer (repo = new Repository()) {
let lastAdded = Date.now()
runUpdateVideos(repo, connections)
setInterval(runUpdateVideos, 1000 * 60 * 30, repo, connections)
- function runUpdateVideos(repo, connections) {
+ function runUpdateVideos (repo, connections) {
console.log('update videos')
- updateAndPersistVideos(repo, ({name, videos}) => {
+ updateAndPersistVideos(repo, ({ name, videos }) => {
const newVideos = videos
- .filter(v => v.addedAt > lastAdded)
- .filter(v => repo.filterByExcludedTerms(v))
+ .filter(v => v.addedAt > lastAdded)
+ .filter(v => repo.filterByExcludedTerms(v))
lastAdded = Date.now()
if (newVideos.length > 0) {
console.log('new videos for channel', name, newVideos.length)
- broadcastSSE(JSON.stringify({type: 'new-videos', name, videos: newVideos}), connections)
+ broadcastSSE(JSON.stringify({ type: 'new-videos', name, videos: newVideos }), connections)
}
})
}
@@ -51,7 +51,7 @@ export function createServer (repo = new Repository()) {
if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') >= 0) {
handleSSE(res, connections)
- return broadcastSSE(JSON.stringify({type: 'state', state}), connections)
+ return broadcastSSE(JSON.stringify({ type: 'state', state }), connections)
}
if (url.pathname.startsWith('/api/')) return apiHandler(req, res, repo, connections, state)
@@ -59,6 +59,6 @@ export function createServer (repo = new Repository()) {
return appHandler(req, res)
} catch (error) {
console.error(error)
- }
- })
+ }
+ })
}
diff --git a/lib/sse.js b/lib/sse.js
index f94b667..2f9f658 100644
--- a/lib/sse.js
+++ b/lib/sse.js
@@ -1,4 +1,3 @@
-
export function handleSSE (res, connections = []) {
connections.push(res)
res.on('close', () => {
@@ -18,4 +17,4 @@ export function broadcastSSE (data, connections = []) {
connection.write('id: ' + id + '\n')
connection.write('data: ' + data + '\n\n')
})
-}
\ No newline at end of file
+}
diff --git a/lib/subtitles-summary.js b/lib/subtitles-summary.js
index d5553f3..c774963 100644
--- a/lib/subtitles-summary.js
+++ b/lib/subtitles-summary.js
@@ -1,8 +1,8 @@
-import fs from "fs"
-import { getVideoSubtitles } from "./youtube.js"
-import * as llm from "./llm/index.js"
+import fs from 'fs'
+import { getVideoSubtitles } from './youtube.js'
+import * as llm from './llm/index.js'
-export async function summarizeVideo(id, repo, llmSettings = {}, callback = () => {}) {
+export async function summarizeVideo (id, repo, llmSettings = {}, callback = () => {}) {
return new Promise(async (resolve, reject) => {
try {
const transcript = await getVideoSubtitles(id, callback)
@@ -11,7 +11,7 @@ export async function summarizeVideo(id, repo, llmSettings = {}, callback = () =
cleanedTranscript = cleanedTranscript.replace('\n', ' ')
fs.writeFileSync(`./data/videos/${id}.en.txt`, cleanedTranscript)
callback('prompting llm')
-
+
const userPrompt = `
Extract the key points from the following video transcript:
@@ -24,7 +24,7 @@ Do not describe or mention the video itself. Simply summarize the points it make
const summary = await llm.summarize(systemPrompt, userPrompt, llmSettings)
callback('received summary')
repo.setVideoSummary(id, summary)
- resolve({summary, transcript: cleanedTranscript})
+ resolve({ summary, transcript: cleanedTranscript })
} catch (error) {
console.error('Error summarizing video', id, error.message)
reject(error)
@@ -43,5 +43,3 @@ export function cleanTranscript (transcript) {
}
return lines.filter(Boolean).join('\n').trim()
}
-
-
diff --git a/lib/update-videos.js b/lib/update-videos.js
index 2b81aba..02f5965 100644
--- a/lib/update-videos.js
+++ b/lib/update-videos.js
@@ -7,12 +7,12 @@ export async function updateAndPersistVideos (repo, callback = () => {}) {
}
}
-export async function updateAndPersistVideosForChannel(name, repo, callback = () => {}) {
+export async function updateAndPersistVideosForChannel (name, repo, callback = () => {}) {
let videos = await getVideosFor(name)
if (videos) {
videos = videos.map(v => repo.patchVideo(v))
repo.upsertVideos(videos)
- callback({name, videos})
+ callback({ name, videos })
}
return videos
}
diff --git a/lib/youtube.js b/lib/youtube.js
index c1cfe55..7ee31c9 100644
--- a/lib/youtube.js
+++ b/lib/youtube.js
@@ -2,16 +2,16 @@ import spawn from 'nano-spawn'
import fs from 'fs'
import * as ytdlp from './yt-dlp.js'
import * as ffmpeg from './ffmpeg.js'
-import { execSync } from 'child_process';
+import { execSync } from 'child_process'
-export const ytUrlRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/(?:watch\?v=)?)([\w-]+)/;
+export const ytUrlRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/(?:watch\?v=)?)([\w-]+)/
const fetchYoutubeHeaders = {
'Accept-Language': 'en',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'
}
-export async function downloadVideo(id, repo, callback = () => {}) {
+export async function downloadVideo (id, repo, callback = () => {}) {
return new Promise(async (resolve, reject) => {
if (isUnsupportedUrl(id)) return reject(new Error('unsupported url'))
if (isYouTubeUrl(id)) id = extractIdFromUrl(id)
@@ -25,25 +25,25 @@ export async function downloadVideo(id, repo, callback = () => {}) {
console.log(line)
callback(line)
if (line.startsWith('[Merger] Merging formats into')) {
- location = line.substring(line.lastIndexOf(' ') + 1).replace(/"/g,'')
+ location = line.substring(line.lastIndexOf(' ') + 1).replace(/"/g, '')
format = location.substring(location.lastIndexOf('.') + 1)
}
}
- const video = repo.updateVideo(id, {location, format})
-
+ const video = repo.updateVideo(id, { location, format })
+
if (repo.getTranscodeVideosSetting() && video.location && video.format) {
for await (const line of ffmpeg.transcode(video.location, video.format)) {
console.log(line)
callback(line)
}
- execSync(`mv ${location.replace(format, 'tmp.'+format)} ${location}`)
-
+ execSync(`mv ${location.replace(format, 'tmp.' + format)} ${location}`)
+
console.log(`successfully transcoded video ${video.location}`)
callback(`successfully transcoded video ${video.location}`)
}
-
- repo.updateVideo(id, {downloaded: true})
-
+
+ repo.updateVideo(id, { downloaded: true })
+
normalizeSubtitleFiles(id)
resolve(id)
} catch (error) {
@@ -89,7 +89,7 @@ function normalizeSubtitleFiles (id) {
}
})
}
-export async function getVideosFor(channelName) {
+export async function getVideosFor (channelName) {
try {
const response = await fetch(`https://www.youtube.com/${channelWithAt(channelName)}/videos`, {
headers: fetchYoutubeHeaders
@@ -114,18 +114,18 @@ export async function getVideosFor(channelName) {
return null
}
- function channelWithAt(channelName = '') {
+ function channelWithAt (channelName = '') {
return channelName.startsWith('@') ? channelName : '@' + channelName
- }
+ }
- function toInternalVideo(v) {
+ function toInternalVideo (v) {
if (!v || !v.richItemRenderer) return
const data = v.richItemRenderer.content.videoRenderer
if (!data.viewCountText?.simpleText) return
// comments contain yt-dlp info downloaded with -J
return {
channelName,
- title: data.title?.runs[0].text, //.title
+ title: data.title?.runs[0].text, // .title
url: `https://www.youtube.com/watch?v=${data.videoId}`, // .url
thumbnail: `https://img.youtube.com/vi/${data.videoId}/mq2.jpg`,
description: data.descriptionSnippet?.runs[0].text, // .description
@@ -133,7 +133,7 @@ export async function getVideosFor(channelName) {
publishedTime: data.publishedTimeText?.simpleText,
publishedAt: parseRelativeTime(data.publishedTimeText?.simpleText),
viewCount: data.viewCountText?.simpleText, // .view_count
- duration: data.lengthText?.simpleText, // .duration_string
+ duration: data.lengthText?.simpleText // .duration_string
}
}
}
@@ -142,20 +142,20 @@ export async function getVideo (id) {
if (isUnsupportedUrl(id)) return null
if (isYouTubeUrl(id)) id = extractIdFromUrl(id)
try {
- let {output} = await spawn('yt-dlp', ['-j', '--', id])
+ let { output } = await spawn('yt-dlp', ['-j', '--', id])
output = output.split('\n').filter(l => l.startsWith('{'))
const json = JSON.parse(output)
return {
channelName: json.uploader_id.replace(/^@/, ''),
title: json.title,
- url: `https://www.youtube.com/watch?v=${id}`,
+ url: `https://www.youtube.com/watch?v=${id}`,
thumbnail: `https://img.youtube.com/vi/${id}/mq2.jpg`,
description: json.description,
id,
publishedTime: json.upload_date.substring(0, 4) + '-' + json.upload_date.substring(4, 6) + '-' + json.upload_date.substring(6, 8),
publishedAt: new Date(json.timestamp * 1000),
viewCount: json.view_count,
- duration: json.duration_string,
+ duration: json.duration_string
}
} catch (err) {
console.error(err)
@@ -163,56 +163,56 @@ export async function getVideo (id) {
}
}
-function parseRelativeTime(relativeTime) {
+function parseRelativeTime (relativeTime) {
if (!relativeTime) return
- const now = new Date();
- let match;
-
+ const now = new Date()
+ let match
+
const regexes = [
- { regex: /(\d+)\s+seconds? ago/, unit: 'seconds' },
- { regex: /(\d+)\s+minutes? ago/, unit: 'minutes' },
- { regex: /(\d+)\s+hours? ago/, unit: 'hours' },
- { regex: /(\d+)\s+days? ago/, unit: 'days' },
- { regex: /(\d+)\s+weeks? ago/, unit: 'weeks' },
- { regex: /(\d+)\s+months? ago/, unit: 'months' },
- { regex: /(\d+)\s+years? ago/, unit: 'years' }
- ];
+ { regex: /(\d+)\s+seconds? ago/, unit: 'seconds' },
+ { regex: /(\d+)\s+minutes? ago/, unit: 'minutes' },
+ { regex: /(\d+)\s+hours? ago/, unit: 'hours' },
+ { regex: /(\d+)\s+days? ago/, unit: 'days' },
+ { regex: /(\d+)\s+weeks? ago/, unit: 'weeks' },
+ { regex: /(\d+)\s+months? ago/, unit: 'months' },
+ { regex: /(\d+)\s+years? ago/, unit: 'years' }
+ ]
for (let i = 0; i < regexes.length; i++) {
- match = relativeTime.match(regexes[i].regex);
- if (match) {
- const amount = parseInt(match[1], 10);
- switch (regexes[i].unit) {
- case 'seconds': now.setSeconds(now.getSeconds() - amount); break;
- case 'minutes': now.setMinutes(now.getMinutes() - amount); break;
- case 'hours': now.setHours(now.getHours() - amount); break;
- case 'days': now.setDate(now.getDate() - amount); break;
- case 'weeks': now.setDate(now.getDate() - amount * 7); break;
- case 'months': now.setMonth(now.getMonth() - amount); break;
- case 'years': now.setFullYear(now.getFullYear() - amount); break;
- }
- return now;
+ match = relativeTime.match(regexes[i].regex)
+ if (match) {
+ const amount = parseInt(match[1], 10)
+ switch (regexes[i].unit) {
+ case 'seconds': now.setSeconds(now.getSeconds() - amount); break
+ case 'minutes': now.setMinutes(now.getMinutes() - amount); break
+ case 'hours': now.setHours(now.getHours() - amount); break
+ case 'days': now.setDate(now.getDate() - amount); break
+ case 'weeks': now.setDate(now.getDate() - amount * 7); break
+ case 'months': now.setMonth(now.getMonth() - amount); break
+ case 'years': now.setFullYear(now.getFullYear() - amount); break
}
+ return now
+ }
}
- console.error('Invalid relative time format', relativeTime);
+ console.error('Invalid relative time format', relativeTime)
return null
}
export function extractIdFromUrl (url) {
if (isYouTubeUrl(url)) {
- const match = url.match(ytUrlRegExp);
- return match ? match[1] : null; // Extract the first capture group
+ const match = url.match(ytUrlRegExp)
+ return match ? match[1] : null // Extract the first capture group
}
}
-export function isYouTubeUrl(url) {
+export function isYouTubeUrl (url) {
return ytUrlRegExp.test(url)
}
-export function isUnsupportedUrl(url) {
+export function isUnsupportedUrl (url) {
return !isYouTubeUrl(url) && !isVideoId(url)
}
-export function isVideoId(url) {
+export function isVideoId (url) {
return !/^https?/.test(url)
-}
\ No newline at end of file
+}
diff --git a/lib/yt-dlp.js b/lib/yt-dlp.js
index f05fa2c..4868b30 100644
--- a/lib/yt-dlp.js
+++ b/lib/yt-dlp.js
@@ -24,12 +24,12 @@ const videoYTDLPArgs = quality => [
'--merge-output-format',
'mp4',
'-f',
- `bestvideo[height<=${quality}]+bestaudio/best[height<=${quality}]`,
+ `bestvideo[height<=${quality}]+bestaudio/best[height<=${quality}]`
]
-export function video(id, quality) {
+export function video (id, quality) {
const cookiesPath = getOptionalCookiesPath()
- let cookiesOption = cookiesPath ? ['--cookies', cookiesPath] : []
+ const cookiesOption = cookiesPath ? ['--cookies', cookiesPath] : []
return spawn('yt-dlp', [
'-o',
`./data/videos/${id}.%(ext)s`,
@@ -40,9 +40,9 @@ export function video(id, quality) {
id
])
}
-export function subtitles(id) {
+export function subtitles (id) {
const cookiesPath = getOptionalCookiesPath()
- let cookiesOption = cookiesPath ? ['--cookies', cookiesPath] : []
+ const cookiesOption = cookiesPath ? ['--cookies', cookiesPath] : []
return spawn('yt-dlp', [
'-o',
`./data/videos/${id}`,
@@ -54,8 +54,7 @@ export function subtitles(id) {
])
}
-function getOptionalCookiesPath() {
+function getOptionalCookiesPath () {
if (fs.existsSync('/app/cookies.txt')) return '/app/cookies.txt'
if (fs.existsSync('./cookies.txt')) return './cookies.txt'
- return
-}
\ No newline at end of file
+}
diff --git a/test/llm/index.test.js b/test/llm/index.test.js
index 2054efc..b428a7f 100644
--- a/test/llm/index.test.js
+++ b/test/llm/index.test.js
@@ -1,12 +1,12 @@
-import {test, beforeEach, afterEach} from "node:test"
-import assert from "node:assert"
+import { test, beforeEach, afterEach } from 'node:test'
+import assert from 'node:assert'
import { MockAgent, setGlobalDispatcher } from 'undici'
-import { summarize } from "../../lib/llm/index.js"
-const system = "You are a helpful assistant."
-const prompt = "Just tell me something"
+import { summarize } from '../../lib/llm/index.js'
+const system = 'You are a helpful assistant.'
+const prompt = 'Just tell me something'
-let agent;
+let agent
beforeEach(() => {
agent = new MockAgent()
setGlobalDispatcher(agent)
@@ -28,21 +28,21 @@ test('should use Anthropic provider', async () => {
method: 'POST'
})
.reply(200, {
- "content": [
+ content: [
{
- "text": "something",
- "type": "text"
+ text: 'something',
+ type: 'text'
}
],
- "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
- "model": "claude-3-7-sonnet-20250219",
- "role": "assistant",
- "stop_reason": "end_turn",
- "stop_sequence": null,
- "type": "message",
- "usage": {
- "input_tokens": 2095,
- "output_tokens": 503
+ id: 'msg_013Zva2CMHLNnXjNJJKqJ2EF',
+ model: 'claude-3-7-sonnet-20250219',
+ role: 'assistant',
+ stop_reason: 'end_turn',
+ stop_sequence: null,
+ type: 'message',
+ usage: {
+ input_tokens: 2095,
+ output_tokens: 503
}
})
@@ -68,45 +68,45 @@ test('should use OpenAI provider', async () => {
path: '/v1/chat/completions',
headers: {
'Content-Type': 'application/json',
- 'Authorization': 'Bearer your-api-key'
+ Authorization: 'Bearer your-api-key'
},
body: '{"model":"gpt-4o","temperature":0.7,"maxTokens":1000,"messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"Just tell me something"}]}',
method: 'POST'
})
.reply(200, {
- "id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT",
- "object": "chat.completion",
- "created": 1741569952,
- "model": "gpt-4o-2024-08-06",
- "choices": [
+ id: 'chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT',
+ object: 'chat.completion',
+ created: 1741569952,
+ model: 'gpt-4o-2024-08-06',
+ choices: [
{
- "index": 0,
- "message": {
- "role": "assistant",
- "content": "something",
- "refusal": null,
- "annotations": []
+ index: 0,
+ message: {
+ role: 'assistant',
+ content: 'something',
+ refusal: null,
+ annotations: []
},
- "logprobs": null,
- "finish_reason": "stop"
+ logprobs: null,
+ finish_reason: 'stop'
}
],
- "usage": {
- "prompt_tokens": 19,
- "completion_tokens": 10,
- "total_tokens": 29,
- "prompt_tokens_details": {
- "cached_tokens": 0,
- "audio_tokens": 0
+ usage: {
+ prompt_tokens: 19,
+ completion_tokens: 10,
+ total_tokens: 29,
+ prompt_tokens_details: {
+ cached_tokens: 0,
+ audio_tokens: 0
},
- "completion_tokens_details": {
- "reasoning_tokens": 0,
- "audio_tokens": 0,
- "accepted_prediction_tokens": 0,
- "rejected_prediction_tokens": 0
+ completion_tokens_details: {
+ reasoning_tokens: 0,
+ audio_tokens: 0,
+ accepted_prediction_tokens: 0,
+ rejected_prediction_tokens: 0
}
},
- "service_tier": "default"
+ service_tier: 'default'
})
const llmSettings = {
@@ -117,9 +117,9 @@ test('should use OpenAI provider', async () => {
temperature: 0.7,
maxTokens: 1000
}
-
+
const result = await summarize(system, prompt, llmSettings)
assert.equal(result, 'something')
agent.assertNoPendingInterceptors()
assert.equal(agent.getCallHistory().logs.length, 1)
-})
\ No newline at end of file
+})
diff --git a/test/repository.test.js b/test/repository.test.js
index 51c5e81..5218678 100644
--- a/test/repository.test.js
+++ b/test/repository.test.js
@@ -1,6 +1,6 @@
import { test, describe } from 'node:test'
import fs from 'fs'
-import assert from 'assert';
+import assert from 'assert'
import Repository from '../lib/repository.js'
let repo
@@ -10,8 +10,8 @@ test.beforeEach(() => {
}
repo = new Repository('./test/data')
})
-const video1 = {id: '12345', channelName: 'tester', title: 'The Code', description: 'some description in common'}
-const video2 = {id: '67890', channelName: 'programmer', title: 'The Error', description: 'some description'}
+const video1 = { id: '12345', channelName: 'tester', title: 'The Code', description: 'some description in common' }
+const video2 = { id: '67890', channelName: 'programmer', title: 'The Error', description: 'some description' }
describe('repository', () => {
test('empty repo provisions data folder', () => {
@@ -22,7 +22,7 @@ describe('repository', () => {
assert.ok(fs.existsSync(repo.paths.videos))
assert.ok(fs.existsSync(repo.paths.channels))
})
-
+
test('adds channel', () => {
repo.addChannel('veritasium')
assert.equal(repo.getChannels().length, 1)
@@ -35,79 +35,79 @@ describe('repository', () => {
assert.equal(repo.getChannels().length, 0)
assert.equal(repo.channelExists('veritasium'), false)
})
-
+
test('gets channels', () => {
repo.addChannel('veritasium')
const channels = repo.getChannels()
assert.equal(channels.length, 1)
assert.equal(channels[0].name, 'veritasium')
})
-
+
test('upserts videos', () => {
repo.upsertVideos([video1, video2])
assert.equal(repo.getVideos().length, 2)
})
-
+
test('upserts single video', () => {
repo.upsertVideos(video1)
assert.equal(repo.getVideos().length, 1)
})
-
+
test('gets channel videos', () => {
repo.upsertVideos([video1, video2])
const videos = repo.getChannelVideos('tester')
assert.equal(videos.length, 1)
assert.equal(videos[0].title, 'The Code')
})
-
+
test('gets single video by id', () => {
repo.upsertVideos([video1, video2])
const video = repo.getVideo('12345')
assert.equal(video.title, 'The Code')
})
-
+
test('deletes a video by id and sets downloaded true', () => {
repo.upsertVideos([video1, video2])
repo.deleteVideo('12345')
assert.equal(repo.getVideos().length, 2)
- assert.deepEqual(repo.getVideo('12345'), {id: '12345', channelName: 'tester', title: 'The Code', description: 'some description in common', downloaded: false})
+ assert.deepEqual(repo.getVideo('12345'), { id: '12345', channelName: 'tester', title: 'The Code', description: 'some description in common', downloaded: false })
})
-
+
test('toggles ignore video', () => {
repo.upsertVideos([video1, video2])
repo.toggleIgnoreVideo('12345')
assert.equal(repo.getVideo('12345').ignored, true)
})
-
+
test('marks video as downloaded', () => {
repo.upsertVideos([video1, video2])
repo.setVideoDownloaded('12345')
assert.equal(repo.getVideo('12345').downloaded, true)
})
-
+
test('sets video transcript', () => {
repo.upsertVideos([video1, video2])
repo.setVideoTranscript('12345', 'This is the transcript for The Code')
assert.equal(repo.getVideo('12345').transcript, 'This is the transcript for The Code')
})
-
+
test('sets video summary', () => {
repo.upsertVideos([video1, video2])
repo.setVideoSummary('12345', 'This is the summary for The Code')
assert.equal(repo.getVideo('12345').summary, 'This is the summary for The Code')
})
-
+
test('patches new video with addedAt', () => {
const patchedVideo = repo.patchVideo(video1)
assert.ok(patchedVideo.addedAt)
})
-
+
test('updates single video by id', () => {
repo.upsertVideos(video1)
const updatedVideo = repo.updateVideo(video1.id, { title: 'Updated Title' })
assert.equal(updatedVideo.title, 'Updated Title')
})
-
+
test('gets video quality', () => {
assert.equal(repo.getVideoQualitySetting(), 720)
})
@@ -152,13 +152,13 @@ describe('excluded terms', () => {
test('returns videos based on excluded terms', async () => {
repo.addExcludedTerm('trump')
- const videos = [{title: 'The Trump Show', channel: 'CNN'}, {title: 'The Biden Report', channel: 'NBC'}]
+ const videos = [{ title: 'The Trump Show', channel: 'CNN' }, { title: 'The Biden Report', channel: 'NBC' }]
repo.upsertVideos(videos)
const results = await repo.getVideos()
assert.equal(results.length, 1)
assert.deepEqual(results[0], {
- "channel": "NBC",
- "title": "The Biden Report",
+ channel: 'NBC',
+ title: 'The Biden Report'
})
})
})
@@ -166,19 +166,19 @@ describe('excluded terms', () => {
describe('search', () => {
test('searches videos by title', async () => {
repo.upsertVideos([video1, video2])
- const results = await repo.getVideos({filter: 'The Error'})
+ const results = await repo.getVideos({ filter: 'The Error' })
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'})
+ 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'})
+ const results = await repo.getVideos({ filter: 'some description' })
assert.equal(results.length, 2)
})
-})
\ No newline at end of file
+})
diff --git a/test/search.test.js b/test/search.test.js
index 46f69f5..e9920c2 100644
--- a/test/search.test.js
+++ b/test/search.test.js
@@ -1,4 +1,4 @@
-import {test, describe} from 'node:test'
+import { test, describe } from 'node:test'
import fs from 'fs'
import assert from 'assert'
import { searchVideosHandler } from '../lib/router/api.js'
@@ -18,32 +18,32 @@ test.beforeEach(() => {
repo = new Repository('./test/data')
repo.upsertVideos([
{
- id: "1",
- channelName: "SomeChannel",
- title: "A video title",
- description: "Wow nice description",
+ id: '1',
+ channelName: 'SomeChannel',
+ title: 'A video title',
+ description: 'Wow nice description',
downloaded: true,
ignored: false,
- summary: "some summary"
+ summary: 'some summary'
},
{
- id: "2",
- channelName: "AnotherChannel",
- title: "Another video title",
- description: "What, another nice description",
+ id: '2',
+ channelName: 'AnotherChannel',
+ title: 'Another video title',
+ description: 'What, another nice description',
downloaded: false,
ignored: true,
- summary: "some summary"
+ summary: 'some summary'
},
{
- id: "3",
- channelName: "AnotherChannel",
- title: "WOW Another video title",
+ id: '3',
+ channelName: 'AnotherChannel',
+ title: 'WOW Another video title',
description: "What, another nice description, that's cool",
downloaded: true,
ignored: true,
- summary: "some summary"
- },
+ summary: 'some summary'
+ }
])
})
test('gets all videos without filters, show only not ignored videos', () => {
@@ -52,12 +52,12 @@ test('gets all videos without filters, show only not ignored videos', () => {
}), repo)
})
test('filters videos by channel name', () => {
- searchVideosHandler({url: '?filter=@SomeChannel'}, assertRes(data => {
+ 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 => {
+ searchVideosHandler({ url: '?filter=A+video+title' }, assertRes(data => {
assert.deepEqual(JSON.parse(data).length, 1)
}), repo)
-})
\ No newline at end of file
+})
diff --git a/test/server.test.js b/test/server.test.js
index 2f865b1..e152485 100644
--- a/test/server.test.js
+++ b/test/server.test.js
@@ -1,10 +1,10 @@
-import {test, describe, mock} from 'node:test'
+import { test, describe, mock } from 'node:test'
import fs from 'fs'
import assert from 'assert'
import { createServer } from '../lib/server.js'
import Repository from '../lib/repository.js'
-mock.timers.enable({ apis: ['setInterval'] });
+mock.timers.enable({ apis: ['setInterval'] })
let repo
test.beforeEach(() => {
if (fs.existsSync('./test/data')) {
@@ -25,19 +25,19 @@ describe('server - user flow', () => {
server = createServer(repo)
server.listen(3001, cb)
console.log('listening server')
- }, {timeout: 10000})
+ }, { timeout: 10000 })
test.after((cb) => {
server.close(cb)
console.log('closed server')
- }, {timeout: 10000})
+ }, { timeout: 10000 })
- test('get channels', {timeout: 5000}, async () => {
+ test('get channels', { timeout: 5000 }, async () => {
const res = await fetch('http://0.0.0.0:3001/api/channels')
const data = await res.json()
assert.equal(res.status, 200)
assert.deepEqual(data, [])
})
- test('add channel', {timeout: 10000}, async () => {
+ test('add channel', { timeout: 10000 }, async () => {
const resAddChannel = await fetch('http://0.0.0.0:3001/api/channels', {
method: 'POST',
body: JSON.stringify({
@@ -50,22 +50,22 @@ describe('server - user flow', () => {
const res = await fetch('http://0.0.0.0:3001/api/channels')
const data = await res.json()
assert.equal(res.status, 200)
- assert.deepEqual(data, [{name: 'veritasium'}])
+ assert.deepEqual(data, [{ name: 'veritasium' }])
})
- test('get channels again', {timeout: 5000}, async () => {
+ test('get channels again', { timeout: 5000 }, async () => {
const res = await fetch('http://0.0.0.0:3001/api/channels')
const data = await res.json()
assert.equal(res.status, 200)
- assert.deepEqual(data, [{name: 'veritasium'}])
+ assert.deepEqual(data, [{ name: 'veritasium' }])
})
- test('get videos', {timeout: 5000}, async () => {
+ 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 () => {
+ test('delete channel', { timeout: 5000 }, async () => {
const resDeleteChannel = await fetch('http://0.0.0.0:3001/api/channels', {
method: 'DELETE',
headers: {
@@ -79,10 +79,10 @@ describe('server - user flow', () => {
assert.equal(resGetChannels.status, 200)
assert.deepEqual(dataGetChannels, [])
})
- test('get videos again', {timeout: 5000}, async () => {
+ test('get videos again', { 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)
})
-})
\ No newline at end of file
+})
diff --git a/test/subtitles.summary.test.js b/test/subtitles.summary.test.js
index edc1a15..d010912 100644
--- a/test/subtitles.summary.test.js
+++ b/test/subtitles.summary.test.js
@@ -1,5 +1,5 @@
-import {test} from 'node:test'
-import assert from 'assert';
+import { test } from 'node:test'
+import assert from 'assert'
import { cleanTranscript } from '../lib/subtitles-summary.js'
test('cleans transcript', () => {
@@ -38,6 +38,6 @@ Open ai writes to the
US administration their position Well it is
necessary that it be free from copyright from
`.trim()
-
+
assert.strictEqual(cleanTranscript(transcript), expectedCleanTranscript)
-})
\ No newline at end of file
+})
diff --git a/test/youtube.test.js b/test/youtube.test.js
index 277893e..faf99b9 100644
--- a/test/youtube.test.js
+++ b/test/youtube.test.js
@@ -1,36 +1,36 @@
import { test } from 'node:test'
-import assert from 'assert';
+import assert from 'assert'
import { getVideosFor, getVideo, extractIdFromUrl, isYouTubeUrl, isUnsupportedUrl, isVideoId } from '../lib/youtube.js'
if (!process.env.CI) {
-test('gets videos for channel', async () => {
- const videos = await getVideosFor('veritasium')
- const video = videos[0]
- assert.ok(video.channelName)
- assert.ok(video.title)
- assert.ok(video.url)
- assert.ok(video.thumbnail)
- assert.ok(video.description)
- assert.ok(video.id)
- assert.ok(video.publishedTime)
- assert.ok(video.viewCount)
- assert.ok(video.duration)
- assert.ok(videos.length > 0)
-})
+ test('gets videos for channel', async () => {
+ const videos = await getVideosFor('veritasium')
+ const video = videos[0]
+ assert.ok(video.channelName)
+ assert.ok(video.title)
+ assert.ok(video.url)
+ assert.ok(video.thumbnail)
+ assert.ok(video.description)
+ assert.ok(video.id)
+ assert.ok(video.publishedTime)
+ assert.ok(video.viewCount)
+ assert.ok(video.duration)
+ assert.ok(videos.length > 0)
+ })
-test('gets single video', async () => {
+ test('gets single video', async () => {
// https://www.youtube.com/watch?v=qJZ1Ez28C-A
- const video = await getVideo('qJZ1Ez28C-A')
- assert.equal(video.channelName, 'veritasium')
- assert.equal(video.title, 'Something Strange Happens When You Trust Quantum Mechanics')
- assert.equal(video.url, 'https://www.youtube.com/watch?v=qJZ1Ez28C-A')
- assert.equal(video.thumbnail, 'https://img.youtube.com/vi/qJZ1Ez28C-A/mq2.jpg')
- assert.ok(video.description, '')
- assert.equal(video.id, 'qJZ1Ez28C-A')
- assert.equal(video.publishedTime, '2025-03-05')
- assert.ok(video.viewCount)
- assert.equal(video.duration, '33:00')
-})
+ const video = await getVideo('qJZ1Ez28C-A')
+ assert.equal(video.channelName, 'veritasium')
+ assert.equal(video.title, 'Something Strange Happens When You Trust Quantum Mechanics')
+ assert.equal(video.url, 'https://www.youtube.com/watch?v=qJZ1Ez28C-A')
+ assert.equal(video.thumbnail, 'https://img.youtube.com/vi/qJZ1Ez28C-A/mq2.jpg')
+ assert.ok(video.description, '')
+ assert.equal(video.id, 'qJZ1Ez28C-A')
+ assert.equal(video.publishedTime, '2025-03-05')
+ assert.ok(video.viewCount)
+ assert.equal(video.duration, '33:00')
+ })
}
test('extracts id from url', () => {
@@ -59,4 +59,4 @@ test('checks if url is a video id', () => {
assert.ok(isVideoId('SOME_ID'))
assert.ok(!isVideoId('https://www.youtube.com/watch?v=SOME_ID'))
assert.ok(!isVideoId('https://somesite.com/video'))
-})
\ No newline at end of file
+})