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: get single video information

Christian Feif422e85b6fe6
diff --git a/lib/youtube.js b/lib/youtube.js
index b37059d..458ca1d 100644
--- a/lib/youtube.js
+++ b/lib/youtube.js
@@ -107,6 +107,29 @@ export async function getVideosFor(channelName) {
}
}
+export async function getVideo (id) {
+ if (id.startsWith('http')) id = id.replace('https://www.youtube.com/watch?v=', '')
+ try {
+ const {output} = await spawn('yt-dlp', ['-j', '--', id])
+ const json = JSON.parse(output)
+ return {
+ channelName: json.uploader_id,
+ title: json.title,
+ 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,
+ }
+ } catch (err) {
+ console.error(err)
+ return null
+ }
+}
+
function parseRelativeTime(relativeTime) {
if (!relativeTime) return
const now = new Date();
diff --git a/test/youtube.test.js b/test/youtube.test.js
index 2fcbe73..4e23c32 100644
--- a/test/youtube.test.js
+++ b/test/youtube.test.js
@@ -1,6 +1,6 @@
import { test } from 'node:test'
import assert from 'assert';
-import { getVideosFor } from '../lib/youtube.js'
+import { getVideosFor, getVideo } from '../lib/youtube.js'
test('gets videos for channel', async () => {
const videos = await getVideosFor('veritasium')
@@ -15,4 +15,18 @@ test('gets videos for channel', async () => {
assert.ok(video.viewCount)
assert.ok(video.duration)
assert.ok(videos.length > 0)
+})
+
+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:36')
})
\ No newline at end of file