Skip to content

armgit / my-yt

Public Imported from GitHub
0

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

JavaScript

feat: download single video without subscribing to channel

Christian Feicf85083b9226
diff --git a/client/components/search-videos.js b/client/components/search-videos.js
index c2a1583..76e2505 100644
--- a/client/components/search-videos.js
+++ b/client/components/search-videos.js
@@ -17,11 +17,11 @@ class SearchVideos extends HTMLElement {
this.querySelector('input').removeEventListener('keyup', this.searchHandler.bind(this))
}
render () {
- this.innerHTML = /*html*/`<input type="search" incremental="incremental" id="search" placeholder="Search videos" autofocus>`
+ this.innerHTML = /*html*/`<input type="search" incremental="incremental" id="search" placeholder="Search videos or paste video url" autofocus>`
}
searchHandler (event) {
event.preventDefault()
- const searchTerm = event.target.value.trim().toLowerCase()
+ let searchTerm = event.target.value.trim()
const $status = document.querySelector('#filter-results-status')
const $videos = document.querySelectorAll('.video')
if (!searchTerm) {
@@ -30,6 +30,21 @@ class SearchVideos extends HTMLElement {
document.body.classList.remove('searching')
return console.log('no search term')
}
+
+ if (searchTerm.match('https?://')) {
+ const id = searchTerm.replace(/^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/watch\?v=(.+)$/, '$4')
+ fetch('/api/download-video', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ id, external: true }),
+ })
+ .then(() => console.log('Download started'))
+ .catch((error) => console.error('Error starting download:', error))
+ event.target.value = ''
+ return
+ }
+
+ searchTerm = searchTerm.toLowerCase()
document.body.classList.add('searching')
let filteredCount = 0
$videos.forEach($video => {
diff --git a/lib/repository.js b/lib/repository.js
index b69695b..215a5b9 100644
--- a/lib/repository.js
+++ b/lib/repository.js
@@ -34,7 +34,7 @@ export default class Repository {
getVideos () {
return this.videos
.sort((a, b) => +new Date(b.publishedAt) - +new Date(a.publishedAt))
- .filter((_, i) => i < 2000)
+ // .filter((_, i) => i < 2000)
}
getVideo(id) {
return this.videos.find(v => v.id === id)
diff --git a/lib/server.js b/lib/server.js
index c9fbd98..247f787 100644
--- a/lib/server.js
+++ b/lib/server.js
@@ -122,12 +122,14 @@ export function createServer ({repo, connections = []}) {
async function downloadVideoHandler(req, res, repo, connections = []) {
const body = await getBody(req)
- const { id} = JSON.parse(body)
+ const { id, external } = JSON.parse(body)
downloadVideo(id, repo, (line) =>
broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections))
- .then(() =>
- broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id}), connections))
+ .then(() => {
+ broadcastSSE(JSON.stringify({type: 'downloaded', videoId: id}), connections)
+ if (external) broadcastSSE(JSON.stringify({type: 'new-videos', videos: [repo.getVideo(id)]}), connections)
+ })
.catch((error) =>
broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.stderr}), connections))
diff --git a/lib/youtube.js b/lib/youtube.js
index 458ca1d..2e1b0af 100644
--- a/lib/youtube.js
+++ b/lib/youtube.js
@@ -17,6 +17,7 @@ function getOptionalCookiesPath() {
export async function downloadVideo(id, repo, callback = () => {}) {
return new Promise(async (resolve, reject) => {
+ if (id.startsWith('http')) id = id.replace(/^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/watch\?v=(.+)$/, '$4')
try {
const cookiesPath = getOptionalCookiesPath()
let cookiesOption = cookiesPath ? `--cookies ${cookiesPath}` : ''
@@ -24,6 +25,12 @@ export async function downloadVideo(id, repo, callback = () => {}) {
console.log(line)
callback(line)
}
+
+ if (!repo.getVideo(id)) {
+ const video = await getVideo(id)
+ repo.upsertVideos([video])
+ callback(`downloaded external video ${id}`)
+ }
repo.setVideoDownloaded(id)
console.log('Download completed')
@@ -108,12 +115,12 @@ export async function getVideosFor(channelName) {
}
export async function getVideo (id) {
- if (id.startsWith('http')) id = id.replace('https://www.youtube.com/watch?v=', '')
+ if (id.startsWith('http')) id = id.replace(/^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/watch\?v=(.+)$/, '$4')
try {
const {output} = await spawn('yt-dlp', ['-j', '--', id])
const json = JSON.parse(output)
return {
- channelName: json.uploader_id,
+ channelName: json.uploader_id.replace(/^@/, ''),
title: json.title,
url: `https://www.youtube.com/watch?v=${id}`,
thumbnail: `https://img.youtube.com/vi/${id}/mq2.jpg`,
diff --git a/test/youtube.test.js b/test/youtube.test.js
index 4e23c32..7210bf7 100644
--- a/test/youtube.test.js
+++ b/test/youtube.test.js
@@ -20,7 +20,7 @@ test('gets videos for channel', 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.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')