From 1bcb03a100d172903b877d6a0e4ed11d63b14f3d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 11 May 2021 10:54:05 +0200 Subject: [PATCH] Use a class for youtube-dl --- server/controllers/api/videos/import.ts | 9 +- server/controllers/static.ts | 3 +- server/helpers/youtube-dl.ts | 657 +++++++++--------- server/lib/config.ts | 12 +- server/lib/job-queue/handlers/video-import.ts | 7 +- .../schedulers/youtube-dl-update-scheduler.ts | 6 +- server/lib/video-transcoding.ts | 13 +- server/tools/peertube-import-videos.ts | 25 +- 8 files changed, 368 insertions(+), 364 deletions(-) diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index 3b9b887e2..37fd42b90 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -3,6 +3,7 @@ import { move, readFile } from 'fs-extra' import * as magnetUtil from 'magnet-uri' import * as parseTorrent from 'parse-torrent' import { join } from 'path' +import { getEnabledResolutions } from '@server/lib/config' import { setVideoTags } from '@server/lib/video' import { MChannelAccountDefault, @@ -24,7 +25,7 @@ import { isArray } from '../../../helpers/custom-validators/misc' import { createReqFiles } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' import { getSecureTorrentName } from '../../../helpers/utils' -import { getYoutubeDLInfo, getYoutubeDLSubs, YoutubeDLInfo } from '../../../helpers/youtube-dl' +import { YoutubeDL, YoutubeDLInfo } from '../../../helpers/youtube-dl' import { CONFIG } from '../../../initializers/config' import { MIMETYPES } from '../../../initializers/constants' import { sequelizeTypescript } from '../../../initializers/database' @@ -139,10 +140,12 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) const targetUrl = body.targetUrl const user = res.locals.oauth.token.User + const youtubeDL = new YoutubeDL(targetUrl, getEnabledResolutions('vod')) + // Get video infos let youtubeDLInfo: YoutubeDLInfo try { - youtubeDLInfo = await getYoutubeDLInfo(targetUrl) + youtubeDLInfo = await youtubeDL.getYoutubeDLInfo() } catch (err) { logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) @@ -188,7 +191,7 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) // Get video subtitles try { - const subtitles = await getYoutubeDLSubs(targetUrl) + const subtitles = await youtubeDL.getYoutubeDLSubs() logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) diff --git a/server/controllers/static.ts b/server/controllers/static.ts index 8d9003a3e..5cf4e9575 100644 --- a/server/controllers/static.ts +++ b/server/controllers/static.ts @@ -2,7 +2,7 @@ import * as cors from 'cors' import * as express from 'express' import { join } from 'path' import { serveIndexHTML } from '@server/lib/client-html' -import { getRegisteredPlugins, getRegisteredThemes } from '@server/lib/config' +import { getEnabledResolutions, getRegisteredPlugins, getRegisteredThemes } from '@server/lib/config' import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo' import { root } from '../helpers/core-utils' @@ -18,7 +18,6 @@ import { WEBSERVER } from '../initializers/constants' import { getThemeOrDefault } from '../lib/plugins/theme-utils' -import { getEnabledResolutions } from '../lib/video-transcoding' import { asyncMiddleware } from '../middlewares' import { cacheRoute } from '../middlewares/cache' import { UserModel } from '../models/account/user' diff --git a/server/helpers/youtube-dl.ts b/server/helpers/youtube-dl.ts index fac3da6ba..d003ea3cf 100644 --- a/server/helpers/youtube-dl.ts +++ b/server/helpers/youtube-dl.ts @@ -6,7 +6,6 @@ import { CONFIG } from '@server/initializers/config' import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' import { VideoResolution } from '../../shared/models/videos' import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants' -import { getEnabledResolutions } from '../lib/video-transcoding' import { peertubeTruncate, pipelinePromise, root } from './core-utils' import { isVideoFileExtnameValid } from './custom-validators/videos' import { logger } from './logger' @@ -35,361 +34,359 @@ const processOptions = { maxBuffer: 1024 * 1024 * 10 // 10MB } -function getYoutubeDLInfo (url: string, opts?: string[]): Promise { - return new Promise((res, rej) => { - let args = opts || [ '-j', '--flat-playlist' ] +class YoutubeDL { - if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) { - args.push('--force-ipv4') + constructor (private readonly url: string = '', private readonly enabledResolutions: number[] = []) { + + } + + getYoutubeDLInfo (opts?: string[]): Promise { + return new Promise((res, rej) => { + let args = opts || [ '-j', '--flat-playlist' ] + + if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) { + args.push('--force-ipv4') + } + + args = this.wrapWithProxyOptions(args) + args = [ '-f', this.getYoutubeDLVideoFormat() ].concat(args) + + YoutubeDL.safeGetYoutubeDL() + .then(youtubeDL => { + youtubeDL.getInfo(this.url, args, processOptions, (err, info) => { + if (err) return rej(err) + if (info.is_live === true) return rej(new Error('Cannot download a live streaming.')) + + const obj = this.buildVideoInfo(this.normalizeObject(info)) + if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video' + + return res(obj) + }) + }) + .catch(err => rej(err)) + }) + } + + getYoutubeDLSubs (opts?: object): Promise { + return new Promise((res, rej) => { + const cwd = CONFIG.STORAGE.TMP_DIR + const options = opts || { all: true, format: 'vtt', cwd } + + YoutubeDL.safeGetYoutubeDL() + .then(youtubeDL => { + youtubeDL.getSubs(this.url, options, (err, files) => { + if (err) return rej(err) + if (!files) return [] + + logger.debug('Get subtitles from youtube dl.', { url: this.url, files }) + + const subtitles = files.reduce((acc, filename) => { + const matched = filename.match(/\.([a-z]{2})(-[a-z]+)?\.(vtt|ttml)/i) + if (!matched || !matched[1]) return acc + + return [ + ...acc, + { + language: matched[1], + path: join(cwd, filename), + filename + } + ] + }, []) + + return res(subtitles) + }) + }) + .catch(err => rej(err)) + }) + } + + getYoutubeDLVideoFormat () { + /** + * list of format selectors in order or preference + * see https://github.com/ytdl-org/youtube-dl#format-selection + * + * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope + * of being able to do a "quick-transcode" + * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9) + * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback + * + * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499 + **/ + const resolution = this.enabledResolutions.length === 0 + ? VideoResolution.H_720P + : Math.max(...this.enabledResolutions) + + return [ + `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1 + `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2 + `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]`, // case #3 + `bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio`, + 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats + 'best' // Ultimate fallback + ].join('/') + } + + downloadYoutubeDLVideo (fileExt: string, timeout: number) { + // Leave empty the extension, youtube-dl will add it + const pathWithoutExtension = generateVideoImportTmpPath(this.url, '') + + let timer + + logger.info('Importing youtubeDL video %s to %s', this.url, pathWithoutExtension) + + let options = [ '-f', this.getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ] + options = this.wrapWithProxyOptions(options) + + if (process.env.FFMPEG_PATH) { + options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ]) } - args = wrapWithProxyOptions(args) - args = [ '-f', getYoutubeDLVideoFormat() ].concat(args) + logger.debug('YoutubeDL options for %s.', this.url, { options }) - safeGetYoutubeDL() - .then(youtubeDL => { - youtubeDL.getInfo(url, args, processOptions, (err, info) => { - if (err) return rej(err) - if (info.is_live === true) return rej(new Error('Cannot download a live streaming.')) + return new Promise((res, rej) => { + YoutubeDL.safeGetYoutubeDL() + .then(youtubeDL => { + youtubeDL.exec(this.url, options, processOptions, async err => { + clearTimeout(timer) - const obj = buildVideoInfo(normalizeObject(info)) - if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video' - - return res(obj) - }) - }) - .catch(err => rej(err)) - }) -} - -function getYoutubeDLSubs (url: string, opts?: object): Promise { - return new Promise((res, rej) => { - const cwd = CONFIG.STORAGE.TMP_DIR - const options = opts || { all: true, format: 'vtt', cwd } - - safeGetYoutubeDL() - .then(youtubeDL => { - youtubeDL.getSubs(url, options, (err, files) => { - if (err) return rej(err) - if (!files) return [] - - logger.debug('Get subtitles from youtube dl.', { url, files }) - - const subtitles = files.reduce((acc, filename) => { - const matched = filename.match(/\.([a-z]{2})(-[a-z]+)?\.(vtt|ttml)/i) - if (!matched || !matched[1]) return acc - - return [ - ...acc, - { - language: matched[1], - path: join(cwd, filename), - filename + try { + // If youtube-dl did not guess an extension for our file, just use .mp4 as default + if (await pathExists(pathWithoutExtension)) { + await move(pathWithoutExtension, pathWithoutExtension + '.mp4') } - ] - }, []) - return res(subtitles) + const path = await this.guessVideoPathWithExtension(pathWithoutExtension, fileExt) + + if (err) { + remove(path) + .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err })) + + return rej(err) + } + + return res(path) + } catch (err) { + return rej(err) + } + }) + + timer = setTimeout(() => { + const err = new Error('YoutubeDL download timeout.') + + this.guessVideoPathWithExtension(pathWithoutExtension, fileExt) + .then(path => remove(path)) + .finally(() => rej(err)) + .catch(err => { + logger.error('Cannot remove file in youtubeDL timeout.', { err }) + return rej(err) + }) + }, timeout) }) - }) - .catch(err => rej(err)) - }) -} - -function getYoutubeDLVideoFormat () { - /** - * list of format selectors in order or preference - * see https://github.com/ytdl-org/youtube-dl#format-selection - * - * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope - * of being able to do a "quick-transcode" - * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9) - * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback - * - * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499 - **/ - const enabledResolutions = getEnabledResolutions('vod') - const resolution = enabledResolutions.length === 0 - ? VideoResolution.H_720P - : Math.max(...enabledResolutions) - - return [ - `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1 - `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2 - `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]`, // case #3 - `bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio`, - 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats - 'best' // Ultimate fallback - ].join('/') -} - -function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number) { - // Leave empty the extension, youtube-dl will add it - const pathWithoutExtension = generateVideoImportTmpPath(url, '') - - let timer - - logger.info('Importing youtubeDL video %s to %s', url, pathWithoutExtension) - - let options = [ '-f', getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ] - options = wrapWithProxyOptions(options) - - if (process.env.FFMPEG_PATH) { - options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ]) + .catch(err => rej(err)) + }) } - logger.debug('YoutubeDL options for %s.', url, { options }) + buildOriginallyPublishedAt (obj: any) { + let originallyPublishedAt: Date = null - return new Promise((res, rej) => { - safeGetYoutubeDL() - .then(youtubeDL => { - youtubeDL.exec(url, options, processOptions, async err => { - clearTimeout(timer) + const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date) + if (uploadDateMatcher) { + originallyPublishedAt = new Date() + originallyPublishedAt.setHours(0, 0, 0, 0) - try { - // If youtube-dl did not guess an extension for our file, just use .mp4 as default - if (await pathExists(pathWithoutExtension)) { - await move(pathWithoutExtension, pathWithoutExtension + '.mp4') - } + const year = parseInt(uploadDateMatcher[1], 10) + // Month starts from 0 + const month = parseInt(uploadDateMatcher[2], 10) - 1 + const day = parseInt(uploadDateMatcher[3], 10) - const path = await guessVideoPathWithExtension(pathWithoutExtension, fileExt) - - if (err) { - remove(path) - .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err })) - - return rej(err) - } - - return res(path) - } catch (err) { - return rej(err) - } - }) - - timer = setTimeout(() => { - const err = new Error('YoutubeDL download timeout.') - - guessVideoPathWithExtension(pathWithoutExtension, fileExt) - .then(path => remove(path)) - .finally(() => rej(err)) - .catch(err => { - logger.error('Cannot remove file in youtubeDL timeout.', { err }) - return rej(err) - }) - }, timeout) - }) - .catch(err => rej(err)) - }) -} - -// Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js -// We rewrote it to avoid sync calls -async function updateYoutubeDLBinary () { - logger.info('Updating youtubeDL binary.') - - const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin') - const bin = join(binDirectory, 'youtube-dl') - const detailsPath = join(binDirectory, 'details') - const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl' - - await ensureDir(binDirectory) - - try { - const result = await got(url, { followRedirect: false }) - - if (result.statusCode !== HttpStatusCode.FOUND_302) { - logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode) - return + originallyPublishedAt.setFullYear(year, month, day) } - const newUrl = result.headers.location - const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(newUrl)[1] - - const downloadFileStream = got.stream(newUrl) - const writeStream = createWriteStream(bin, { mode: 493 }) - - await pipelinePromise( - downloadFileStream, - writeStream - ) - - const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' }) - await writeFile(detailsPath, details, { encoding: 'utf8' }) - - logger.info('youtube-dl updated to version %s.', newVersion) - } catch (err) { - logger.error('Cannot update youtube-dl.', { err }) - } -} - -async function safeGetYoutubeDL () { - let youtubeDL - - try { - youtubeDL = require('youtube-dl') - } catch (e) { - // Download binary - await updateYoutubeDLBinary() - youtubeDL = require('youtube-dl') + return originallyPublishedAt } - return youtubeDL -} + private async guessVideoPathWithExtension (tmpPath: string, sourceExt: string) { + if (!isVideoFileExtnameValid(sourceExt)) { + throw new Error('Invalid video extension ' + sourceExt) + } -function buildOriginallyPublishedAt (obj: any) { - let originallyPublishedAt: Date = null + const extensions = [ sourceExt, '.mp4', '.mkv', '.webm' ] - const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date) - if (uploadDateMatcher) { - originallyPublishedAt = new Date() - originallyPublishedAt.setHours(0, 0, 0, 0) + for (const extension of extensions) { + const path = tmpPath + extension - const year = parseInt(uploadDateMatcher[1], 10) - // Month starts from 0 - const month = parseInt(uploadDateMatcher[2], 10) - 1 - const day = parseInt(uploadDateMatcher[3], 10) + if (await pathExists(path)) return path + } - originallyPublishedAt.setFullYear(year, month, day) + throw new Error('Cannot guess path of ' + tmpPath) } - return originallyPublishedAt + private normalizeObject (obj: any) { + const newObj: any = {} + + for (const key of Object.keys(obj)) { + // Deprecated key + if (key === 'resolution') continue + + const value = obj[key] + + if (typeof value === 'string') { + newObj[key] = value.normalize() + } else { + newObj[key] = value + } + } + + return newObj + } + + private buildVideoInfo (obj: any): YoutubeDLInfo { + return { + name: this.titleTruncation(obj.title), + description: this.descriptionTruncation(obj.description), + category: this.getCategory(obj.categories), + licence: this.getLicence(obj.license), + language: this.getLanguage(obj.language), + nsfw: this.isNSFW(obj), + tags: this.getTags(obj.tags), + thumbnailUrl: obj.thumbnail || undefined, + originallyPublishedAt: this.buildOriginallyPublishedAt(obj), + ext: obj.ext + } + } + + private titleTruncation (title: string) { + return peertubeTruncate(title, { + length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, + separator: /,? +/, + omission: ' […]' + }) + } + + private descriptionTruncation (description: string) { + if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined + + return peertubeTruncate(description, { + length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max, + separator: /,? +/, + omission: ' […]' + }) + } + + private isNSFW (info: any) { + return info.age_limit && info.age_limit >= 16 + } + + private getTags (tags: any) { + if (Array.isArray(tags) === false) return [] + + return tags + .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min) + .map(t => t.normalize()) + .slice(0, 5) + } + + private getLicence (licence: string) { + if (!licence) return undefined + + if (licence.includes('Creative Commons Attribution')) return 1 + + for (const key of Object.keys(VIDEO_LICENCES)) { + const peertubeLicence = VIDEO_LICENCES[key] + if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10) + } + + return undefined + } + + private getCategory (categories: string[]) { + if (!categories) return undefined + + const categoryString = categories[0] + if (!categoryString || typeof categoryString !== 'string') return undefined + + if (categoryString === 'News & Politics') return 11 + + for (const key of Object.keys(VIDEO_CATEGORIES)) { + const category = VIDEO_CATEGORIES[key] + if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10) + } + + return undefined + } + + private getLanguage (language: string) { + return VIDEO_LANGUAGES[language] ? language : undefined + } + + private wrapWithProxyOptions (options: string[]) { + if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) { + logger.debug('Using proxy for YoutubeDL') + + return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options) + } + + return options + } + + // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js + // We rewrote it to avoid sync calls + static async updateYoutubeDLBinary () { + logger.info('Updating youtubeDL binary.') + + const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin') + const bin = join(binDirectory, 'youtube-dl') + const detailsPath = join(binDirectory, 'details') + const url = process.env.YOUTUBE_DL_DOWNLOAD_HOST || 'https://yt-dl.org/downloads/latest/youtube-dl' + + await ensureDir(binDirectory) + + try { + const result = await got(url, { followRedirect: false }) + + if (result.statusCode !== HttpStatusCode.FOUND_302) { + logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode) + return + } + + const newUrl = result.headers.location + const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(newUrl)[1] + + const downloadFileStream = got.stream(newUrl) + const writeStream = createWriteStream(bin, { mode: 493 }) + + await pipelinePromise( + downloadFileStream, + writeStream + ) + + const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' }) + await writeFile(detailsPath, details, { encoding: 'utf8' }) + + logger.info('youtube-dl updated to version %s.', newVersion) + } catch (err) { + logger.error('Cannot update youtube-dl.', { err }) + } + } + + static async safeGetYoutubeDL () { + let youtubeDL + + try { + youtubeDL = require('youtube-dl') + } catch (e) { + // Download binary + await this.updateYoutubeDLBinary() + youtubeDL = require('youtube-dl') + } + + return youtubeDL + } } // --------------------------------------------------------------------------- export { - updateYoutubeDLBinary, - getYoutubeDLVideoFormat, - downloadYoutubeDLVideo, - getYoutubeDLSubs, - getYoutubeDLInfo, - safeGetYoutubeDL, - buildOriginallyPublishedAt -} - -// --------------------------------------------------------------------------- - -async function guessVideoPathWithExtension (tmpPath: string, sourceExt: string) { - if (!isVideoFileExtnameValid(sourceExt)) { - throw new Error('Invalid video extension ' + sourceExt) - } - - const extensions = [ sourceExt, '.mp4', '.mkv', '.webm' ] - - for (const extension of extensions) { - const path = tmpPath + extension - - if (await pathExists(path)) return path - } - - throw new Error('Cannot guess path of ' + tmpPath) -} - -function normalizeObject (obj: any) { - const newObj: any = {} - - for (const key of Object.keys(obj)) { - // Deprecated key - if (key === 'resolution') continue - - const value = obj[key] - - if (typeof value === 'string') { - newObj[key] = value.normalize() - } else { - newObj[key] = value - } - } - - return newObj -} - -function buildVideoInfo (obj: any): YoutubeDLInfo { - return { - name: titleTruncation(obj.title), - description: descriptionTruncation(obj.description), - category: getCategory(obj.categories), - licence: getLicence(obj.license), - language: getLanguage(obj.language), - nsfw: isNSFW(obj), - tags: getTags(obj.tags), - thumbnailUrl: obj.thumbnail || undefined, - originallyPublishedAt: buildOriginallyPublishedAt(obj), - ext: obj.ext - } -} - -function titleTruncation (title: string) { - return peertubeTruncate(title, { - length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, - separator: /,? +/, - omission: ' […]' - }) -} - -function descriptionTruncation (description: string) { - if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined - - return peertubeTruncate(description, { - length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max, - separator: /,? +/, - omission: ' […]' - }) -} - -function isNSFW (info: any) { - return info.age_limit && info.age_limit >= 16 -} - -function getTags (tags: any) { - if (Array.isArray(tags) === false) return [] - - return tags - .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min) - .map(t => t.normalize()) - .slice(0, 5) -} - -function getLicence (licence: string) { - if (!licence) return undefined - - if (licence.includes('Creative Commons Attribution')) return 1 - - for (const key of Object.keys(VIDEO_LICENCES)) { - const peertubeLicence = VIDEO_LICENCES[key] - if (peertubeLicence.toLowerCase() === licence.toLowerCase()) return parseInt(key, 10) - } - - return undefined -} - -function getCategory (categories: string[]) { - if (!categories) return undefined - - const categoryString = categories[0] - if (!categoryString || typeof categoryString !== 'string') return undefined - - if (categoryString === 'News & Politics') return 11 - - for (const key of Object.keys(VIDEO_CATEGORIES)) { - const category = VIDEO_CATEGORIES[key] - if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10) - } - - return undefined -} - -function getLanguage (language: string) { - return VIDEO_LANGUAGES[language] ? language : undefined -} - -function wrapWithProxyOptions (options: string[]) { - if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) { - logger.debug('Using proxy for YoutubeDL') - - return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options) - } - - return options + YoutubeDL } diff --git a/server/lib/config.ts b/server/lib/config.ts index b4c4c9299..eb4510680 100644 --- a/server/lib/config.ts +++ b/server/lib/config.ts @@ -6,7 +6,6 @@ import { RegisteredExternalAuthConfig, RegisteredIdAndPassAuthConfig, ServerConf import { Hooks } from './plugins/hooks' import { PluginManager } from './plugins/plugin-manager' import { getThemeOrDefault } from './plugins/theme-utils' -import { getEnabledResolutions } from './video-transcoding' import { VideoTranscodingProfilesManager } from './video-transcoding-profiles' let serverCommit: string @@ -208,11 +207,22 @@ function getRegisteredPlugins () { })) } +function getEnabledResolutions (type: 'vod' | 'live') { + const transcoding = type === 'vod' + ? CONFIG.TRANSCODING + : CONFIG.LIVE.TRANSCODING + + return Object.keys(transcoding.RESOLUTIONS) + .filter(key => transcoding.ENABLED && transcoding.RESOLUTIONS[key] === true) + .map(r => parseInt(r, 10)) +} + // --------------------------------------------------------------------------- export { getServerConfig, getRegisteredThemes, + getEnabledResolutions, getRegisteredPlugins } diff --git a/server/lib/job-queue/handlers/video-import.ts b/server/lib/job-queue/handlers/video-import.ts index ed2c5eac0..3067ce214 100644 --- a/server/lib/job-queue/handlers/video-import.ts +++ b/server/lib/job-queue/handlers/video-import.ts @@ -23,7 +23,6 @@ import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } fro import { logger } from '../../../helpers/logger' import { getSecureTorrentName } from '../../../helpers/utils' import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent' -import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl' import { CONFIG } from '../../../initializers/config' import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants' import { sequelizeTypescript } from '../../../initializers/database' @@ -34,6 +33,8 @@ import { MThumbnail } from '../../../types/models/video/thumbnail' import { federateVideoIfNeeded } from '../../activitypub/videos' import { Notifier } from '../../notifier' import { generateVideoMiniature } from '../../thumbnail' +import { YoutubeDL } from '@server/helpers/youtube-dl' +import { getEnabledResolutions } from '@server/lib/config' async function processVideoImport (job: Bull.Job) { const payload = job.data as VideoImportPayload @@ -75,8 +76,10 @@ async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutub videoImportId: videoImport.id } + const youtubeDL = new YoutubeDL(videoImport.targetUrl, getEnabledResolutions('vod')) + return processFile( - () => downloadYoutubeDLVideo(videoImport.targetUrl, payload.fileExt, VIDEO_IMPORT_TIMEOUT), + () => youtubeDL.downloadYoutubeDLVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT), videoImport, options ) diff --git a/server/lib/schedulers/youtube-dl-update-scheduler.ts b/server/lib/schedulers/youtube-dl-update-scheduler.ts index aefe6aba4..898691c13 100644 --- a/server/lib/schedulers/youtube-dl-update-scheduler.ts +++ b/server/lib/schedulers/youtube-dl-update-scheduler.ts @@ -1,6 +1,6 @@ -import { AbstractScheduler } from './abstract-scheduler' +import { YoutubeDL } from '@server/helpers/youtube-dl' import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants' -import { updateYoutubeDLBinary } from '../../helpers/youtube-dl' +import { AbstractScheduler } from './abstract-scheduler' export class YoutubeDlUpdateScheduler extends AbstractScheduler { @@ -13,7 +13,7 @@ export class YoutubeDlUpdateScheduler extends AbstractScheduler { } protected internalExecute () { - return updateYoutubeDLBinary() + return YoutubeDL.updateYoutubeDLBinary() } static get Instance () { diff --git a/server/lib/video-transcoding.ts b/server/lib/video-transcoding.ts index c949dca2e..51949f51a 100644 --- a/server/lib/video-transcoding.ts +++ b/server/lib/video-transcoding.ts @@ -215,16 +215,6 @@ function generateHlsPlaylistResolution (options: { }) } -function getEnabledResolutions (type: 'vod' | 'live') { - const transcoding = type === 'vod' - ? CONFIG.TRANSCODING - : CONFIG.LIVE.TRANSCODING - - return Object.keys(transcoding.RESOLUTIONS) - .filter(key => transcoding.ENABLED && transcoding.RESOLUTIONS[key] === true) - .map(r => parseInt(r, 10)) -} - // --------------------------------------------------------------------------- export { @@ -232,8 +222,7 @@ export { generateHlsPlaylistResolutionFromTS, optimizeOriginalVideofile, transcodeNewWebTorrentResolution, - mergeAudioVideofile, - getEnabledResolutions + mergeAudioVideofile } // --------------------------------------------------------------------------- diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index 915995031..b3f57a8f9 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -11,9 +11,9 @@ import { promisify } from 'util' import { advancedVideosSearch, getClient, getVideoCategories, login, uploadVideo } from '../../shared/extra-utils/index' import { sha256 } from '../helpers/core-utils' import { doRequestAndSaveToFile } from '../helpers/requests' -import { buildOriginallyPublishedAt, getYoutubeDLVideoFormat, safeGetYoutubeDL } from '../helpers/youtube-dl' import { CONSTRAINTS_FIELDS } from '../initializers/constants' import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli' +import { YoutubeDL } from '@server/helpers/youtube-dl' type UserInfo = { username: string @@ -74,9 +74,9 @@ async function run (url: string, user: UserInfo) { user.password = await promptPassword() } - const youtubeDL = await safeGetYoutubeDL() + const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL() - let info = await getYoutubeDLInfo(youtubeDL, options.targetUrl, command.args) + let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args) if (!Array.isArray(info)) info = [ info ] @@ -86,7 +86,7 @@ async function run (url: string, user: UserInfo) { if (uploadsObject) { console.log('Fixing URL to %s.', uploadsObject.url) - info = await getYoutubeDLInfo(youtubeDL, uploadsObject.url, command.args) + info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args) } let infoArray: any[] @@ -130,13 +130,14 @@ async function processVideo (parameters: { youtubeInfo: any }) { const { youtubeInfo, cwd, url, user } = parameters + const youtubeDL = new YoutubeDL('', []) log.debug('Fetching object.', youtubeInfo) const videoInfo = await fetchObject(youtubeInfo) log.debug('Fetched object.', videoInfo) - const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo) + const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo) if (options.since && originallyPublishedAt && originallyPublishedAt.getTime() < options.since.getTime()) { log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.title, formatDate(options.since)) @@ -161,13 +162,14 @@ async function processVideo (parameters: { log.info('Downloading video "%s"...', videoInfo.title) - const youtubeDLOptions = [ '-f', getYoutubeDLVideoFormat(), ...command.args, '-o', path ] + const youtubeDLOptions = [ '-f', youtubeDL.getYoutubeDLVideoFormat(), ...command.args, '-o', path ] try { - const youtubeDL = await safeGetYoutubeDL() - const youtubeDLExec = promisify(youtubeDL.exec).bind(youtubeDL) + const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL() + const youtubeDLExec = promisify(youtubeDLBinary.exec).bind(youtubeDLBinary) const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions) log.info(output.join('\n')) await uploadVideoOnPeerTube({ + youtubeDL, cwd, url, user, @@ -180,13 +182,14 @@ async function processVideo (parameters: { } async function uploadVideoOnPeerTube (parameters: { + youtubeDL: YoutubeDL videoInfo: any videoPath: string cwd: string url: string user: { username: string, password: string } }) { - const { videoInfo, videoPath, cwd, url, user } = parameters + const { youtubeDL, videoInfo, videoPath, cwd, url, user } = parameters const category = await getCategory(videoInfo.categories, url) const licence = getLicence(videoInfo.license) @@ -205,7 +208,7 @@ async function uploadVideoOnPeerTube (parameters: { await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile) } - const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo) + const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo) const defaultAttributes = { name: truncate(videoInfo.title, { @@ -304,7 +307,7 @@ function fetchObject (info: any) { const url = buildUrl(info) return new Promise(async (res, rej) => { - const youtubeDL = await safeGetYoutubeDL() + const youtubeDL = await YoutubeDL.safeGetYoutubeDL() youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => { if (err) return rej(err)