Skip to content

armgit / my-yt

Public Imported from GitHub
0

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

JavaScript

wip download single video

Christian Fei0b4d3378e9cd
diff --git a/client/components/search-videos.js b/client/components/search-videos.js
index cbeda7a..4b9081e 100644
--- a/client/components/search-videos.js
+++ b/client/components/search-videos.js
@@ -22,6 +22,20 @@ class SearchVideos extends HTMLElement {
searchHandler (event) {
event.preventDefault()
const searchTerm = event.target.value.toLowerCase()
+ if (searchTerm.startsWith('https://')) {
+ if (event.key !== 'Enter') return
+ console.log('Downloading video...')
+ event.target.value = ''
+ // send request to server to download video
+ fetch('/download-video', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url: searchTerm })
+ })
+ .then(() => alert('Video downloaded successfully'))
+ .catch(error => alert('Error downloading video: ' + error.message))
+ return
+ }
document.querySelectorAll('.video').forEach(video => {
const videoData = JSON.parse(video.dataset['data'])
if (
diff --git a/lib/youtube.js b/lib/youtube.js
index baa31fb..f92532f 100644
--- a/lib/youtube.js
+++ b/lib/youtube.js
@@ -1,7 +1,10 @@
import spawn from 'nano-spawn'
import fs from 'fs'
-const cookiesPath = './cookies.txt'
+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'
+}
function getOptionalCookiesPath() {
if (fs.existsSync('/app/cookies.txt')) return '/app/cookies.txt'
@@ -14,13 +17,20 @@ export async function downloadVideo(id, repo, callback = () => {}) {
return new Promise(async (resolve, reject) => {
try {
const cookiesPath = getOptionalCookiesPath()
- let cookiesOption = ''
- if (cookiesPath) cookiesOption = `--cookies ${cookiesPath}`
- console.log({cookiesOption})
+ let cookiesOption = cookiesPath ? `--cookies ${cookiesPath}` : ''
for await (const line of spawn('yt-dlp', `"${id}" ${cookiesOption} --default-search ytsearch --concurrent-fragments 5 -f best[ext=mp4] -o ./data/videos/${id}.mp4 --write-subs --write-auto-subs --sub-lang en --sub-format ttml --convert-subs srt`.split(' '))) {
console.log(line)
callback(line)
}
+ if (!repo.getVideo(id)) {
+ const video = await getVideoInformation(id)
+ console.log('downloaded video information', video)
+ repo.upsertVideos([video])
+ repo.setVideoDownloaded(id)
+ console.log('Download completed, new video added', id)
+ resolve(video)
+ return
+ }
repo.setVideoDownloaded(id)
console.log('Download completed')
@@ -58,12 +68,16 @@ export async function getVideoSubtitles (id, callback = () => {}) {
export async function getVideosFor(channelName) {
try {
+ console.log('fetching videos for', channelName)
const response = await fetch(`https://www.youtube.com/${channelWithAt(channelName)}/videos`, {
- headers: { 'Accept-Language': 'en' }
+ headers: fetchYoutubeHeaders
})
const text = await response.text()
const match = text.match(/var ytInitialData = (.+?);<\/script>/)
- if (!match || !match[1]) return null
+ if (!match || !match[1]) {
+ console.log('no match for', channelName)
+ return null
+ }
const json = JSON.parse(match[1].trim())
const videoTab = json.contents.twoColumnBrowseResultsRenderer.tabs.find(t => t.tabRenderer?.title === 'Videos')
@@ -139,24 +153,20 @@ export async function getVideoInformation(id) {
if (id.startsWith('https://')) id = id.replace(/https:\/\/www\.youtube\.com\/watch\?v=/, '')
try {
const response = await fetch(`https://www.youtube.com/watch?v=${id}`, {
- headers: { 'Accept-Language': 'en' }
+ headers: fetchYoutubeHeaders
})
const text = await response.text()
- const match = text.match(/var ytInitialData = (.+?);<\/script>/)
- if (!match || !match[1]) return null
- const json = JSON.parse(match[1].trim())
- console.log(JSON.stringify(json))
return {
- channelName: json.playerOverlays.playerOverlayRenderer.autoplay.playerOverlayAutoplayRenderer.byline.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl.replace('/@',''),
- title: json.playerOverlays.playerOverlayRenderer.autoplay.playerOverlayAutoplayRenderer.videoTitle.simpleText,
+ channelName: '',
+ title: '',
url: `https://www.youtube.com/watch?v=${id}`,
thumbnail: `https://img.youtube.com/vi/${id}/mqdefault.jpg`,
- description: ' ',
+ description: '',
id,
- publishedTime: json.contents.twoColumnWatchNextResults.results.results.contents[0].videoPrimaryInfoRenderer.relativeDateText.simpleText,
- publishedAt: parseRelativeTime(json.contents.twoColumnWatchNextResults.results.results.contents[0].videoPrimaryInfoRenderer.relativeDateText.simpleText),
- viewCount: ' ', // data.viewCountText?.simpleText,
- duration: ' ', // data.lengthText?.simpleText,
+ publishedTime: '',
+ publishedAt: parseRelativeTime('') || new Date(),
+ viewCount: '',
+ duration: '',
}
} catch (error) {
console.error('Error fetching video information:', error.message)