From 62549e6c9818f422698f030e0b242609115493ed Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 21 Oct 2021 16:28:39 +0200 Subject: Rewrite youtube-dl import Use python3 binary Allows to use a custom youtube-dl release URL Allows to use yt-dlp (youtube-dl fork) Remove proxy config from configuration to use HTTP_PROXY and HTTPS_PROXY env variables --- server/controllers/api/videos/import.ts | 10 +- server/helpers/requests.ts | 9 +- server/helpers/youtube-dl.ts | 394 ------------- server/helpers/youtube-dl/index.ts | 3 + server/helpers/youtube-dl/youtube-dl-cli.ts | 198 +++++++ .../helpers/youtube-dl/youtube-dl-info-builder.ts | 154 +++++ server/helpers/youtube-dl/youtube-dl-wrapper.ts | 135 +++++ server/initializers/config.ts | 13 +- server/initializers/constants.ts | 7 + server/lib/job-queue/handlers/video-import.ts | 6 +- .../lib/schedulers/youtube-dl-update-scheduler.ts | 4 +- server/tests/api/server/proxy.ts | 107 +++- server/tests/api/videos/video-imports.ts | 632 ++++++++++++--------- .../tests/fixtures/video_import_preview_yt_dlp.jpg | Bin 0 -> 15844 bytes .../fixtures/video_import_thumbnail_yt_dlp.jpg | Bin 0 -> 10163 bytes server/tools/peertube-import-videos.ts | 179 ++---- 16 files changed, 1010 insertions(+), 841 deletions(-) delete mode 100644 server/helpers/youtube-dl.ts create mode 100644 server/helpers/youtube-dl/index.ts create mode 100644 server/helpers/youtube-dl/youtube-dl-cli.ts create mode 100644 server/helpers/youtube-dl/youtube-dl-info-builder.ts create mode 100644 server/helpers/youtube-dl/youtube-dl-wrapper.ts create mode 100644 server/tests/fixtures/video_import_preview_yt_dlp.jpg create mode 100644 server/tests/fixtures/video_import_thumbnail_yt_dlp.jpg (limited to 'server') diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index 4265f3217..eddb9b32d 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -26,7 +26,7 @@ import { isArray } from '../../../helpers/custom-validators/misc' import { cleanUpReqFiles, createReqFiles } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' import { getSecureTorrentName } from '../../../helpers/utils' -import { YoutubeDL, YoutubeDLInfo } from '../../../helpers/youtube-dl' +import { YoutubeDLWrapper, YoutubeDLInfo } from '../../../helpers/youtube-dl' import { CONFIG } from '../../../initializers/config' import { MIMETYPES } from '../../../initializers/constants' import { sequelizeTypescript } from '../../../initializers/database' @@ -134,12 +134,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, ServerConfigManager.Instance.getEnabledResolutions('vod')) + const youtubeDL = new YoutubeDLWrapper(targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod')) // Get video infos let youtubeDLInfo: YoutubeDLInfo try { - youtubeDLInfo = await youtubeDL.getYoutubeDLInfo() + youtubeDLInfo = await youtubeDL.getInfoForDownload() } catch (err) { logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) @@ -373,9 +373,9 @@ function extractNameFromArray (name: string | string[]) { return isArray(name) ? name[0] : name } -async function processYoutubeSubtitles (youtubeDL: YoutubeDL, targetUrl: string, videoId: number) { +async function processYoutubeSubtitles (youtubeDL: YoutubeDLWrapper, targetUrl: string, videoId: number) { try { - const subtitles = await youtubeDL.getYoutubeDLSubs() + const subtitles = await youtubeDL.getSubtitles() logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) diff --git a/server/helpers/requests.ts b/server/helpers/requests.ts index 991270952..d93f55776 100644 --- a/server/helpers/requests.ts +++ b/server/helpers/requests.ts @@ -1,9 +1,9 @@ import { createWriteStream, remove } from 'fs-extra' -import got, { CancelableRequest, Options as GotOptions, RequestError } from 'got' +import got, { CancelableRequest, Options as GotOptions, RequestError, Response } from 'got' import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent' import { join } from 'path' import { CONFIG } from '../initializers/config' -import { ACTIVITY_PUB, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants' +import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants' import { pipelinePromise } from './core-utils' import { processImage } from './image-utils' import { logger } from './logger' @@ -180,12 +180,17 @@ function getUserAgent () { return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})` } +function isBinaryResponse (result: Response) { + return BINARY_CONTENT_TYPES.has(result.headers['content-type']) +} + // --------------------------------------------------------------------------- export { doRequest, doJSONRequest, doRequestAndSaveToFile, + isBinaryResponse, downloadImage, peertubeGot } diff --git a/server/helpers/youtube-dl.ts b/server/helpers/youtube-dl.ts deleted file mode 100644 index 0392ec4c7..000000000 --- a/server/helpers/youtube-dl.ts +++ /dev/null @@ -1,394 +0,0 @@ -import { createWriteStream } from 'fs' -import { ensureDir, move, pathExists, remove, writeFile } from 'fs-extra' -import { join } from 'path' -import { CONFIG } from '@server/initializers/config' -import { HttpStatusCode } from '../../shared/models/http/http-error-codes' -import { VideoResolution } from '../../shared/models/videos' -import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants' -import { peertubeTruncate, pipelinePromise, root } from './core-utils' -import { isVideoFileExtnameValid } from './custom-validators/videos' -import { logger } from './logger' -import { peertubeGot } from './requests' -import { generateVideoImportTmpPath } from './utils' - -export type YoutubeDLInfo = { - name?: string - description?: string - category?: number - language?: string - licence?: number - nsfw?: boolean - tags?: string[] - thumbnailUrl?: string - ext?: string - originallyPublishedAt?: Date -} - -export type YoutubeDLSubs = { - language: string - filename: string - path: string -}[] - -const processOptions = { - maxBuffer: 1024 * 1024 * 10 // 10MB -} - -class YoutubeDL { - - constructor (private readonly url: string = '', private readonly enabledResolutions: number[] = []) { - - } - - getYoutubeDLInfo (opts?: string[]): Promise { - return new Promise((res, rej) => { - let args = opts || [] - - 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 ]) - } - - logger.debug('YoutubeDL options for %s.', this.url, { options }) - - return new Promise((res, rej) => { - YoutubeDL.safeGetYoutubeDL() - .then(youtubeDL => { - youtubeDL.exec(this.url, options, processOptions, async err => { - clearTimeout(timer) - - 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 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)) - }) - } - - buildOriginallyPublishedAt (obj: any) { - let originallyPublishedAt: Date = null - - const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date) - if (uploadDateMatcher) { - originallyPublishedAt = new Date() - originallyPublishedAt.setHours(0, 0, 0, 0) - - const year = parseInt(uploadDateMatcher[1], 10) - // Month starts from 0 - const month = parseInt(uploadDateMatcher[2], 10) - 1 - const day = parseInt(uploadDateMatcher[3], 10) - - originallyPublishedAt.setFullYear(year, month, day) - } - - return originallyPublishedAt - } - - private async 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) - } - - 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 gotContext = { bodyKBLimit: 20_000 } - - const result = await peertubeGot(url, { followRedirect: false, context: gotContext }) - - 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 = /\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl$/.exec(newUrl)[1] - - const downloadFileStream = peertubeGot.stream(newUrl, { context: gotContext }) - 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 { - YoutubeDL -} diff --git a/server/helpers/youtube-dl/index.ts b/server/helpers/youtube-dl/index.ts new file mode 100644 index 000000000..6afc77dcf --- /dev/null +++ b/server/helpers/youtube-dl/index.ts @@ -0,0 +1,3 @@ +export * from './youtube-dl-cli' +export * from './youtube-dl-info-builder' +export * from './youtube-dl-wrapper' diff --git a/server/helpers/youtube-dl/youtube-dl-cli.ts b/server/helpers/youtube-dl/youtube-dl-cli.ts new file mode 100644 index 000000000..440869205 --- /dev/null +++ b/server/helpers/youtube-dl/youtube-dl-cli.ts @@ -0,0 +1,198 @@ +import execa from 'execa' +import { pathExists, writeFile } from 'fs-extra' +import { join } from 'path' +import { CONFIG } from '@server/initializers/config' +import { VideoResolution } from '@shared/models' +import { logger, loggerTagsFactory } from '../logger' +import { getProxy, isProxyEnabled } from '../proxy' +import { isBinaryResponse, peertubeGot } from '../requests' + +const lTags = loggerTagsFactory('youtube-dl') + +const youtubeDLBinaryPath = join(CONFIG.STORAGE.BIN_DIR, CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME) + +export class YoutubeDLCLI { + + static async safeGet () { + if (!await pathExists(youtubeDLBinaryPath)) { + await this.updateYoutubeDLBinary() + } + + return new YoutubeDLCLI() + } + + static async updateYoutubeDLBinary () { + const url = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.URL + + logger.info('Updating youtubeDL binary from %s.', url, lTags()) + + const gotOptions = { context: { bodyKBLimit: 20_000 }, responseType: 'buffer' as 'buffer' } + + try { + let gotResult = await peertubeGot(url, gotOptions) + + if (!isBinaryResponse(gotResult)) { + const json = JSON.parse(gotResult.body.toString()) + const latest = json.filter(release => release.prerelease === false)[0] + if (!latest) throw new Error('Cannot find latest release') + + const releaseName = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME + const releaseAsset = latest.assets.find(a => a.name === releaseName) + if (!releaseAsset) throw new Error(`Cannot find appropriate release with name ${releaseName} in release assets`) + + gotResult = await peertubeGot(releaseAsset.browser_download_url, gotOptions) + } + + if (!isBinaryResponse(gotResult)) { + throw new Error('Not a binary response') + } + + await writeFile(youtubeDLBinaryPath, gotResult.body) + + logger.info('youtube-dl updated %s.', youtubeDLBinaryPath, lTags()) + } catch (err) { + logger.error('Cannot update youtube-dl from %s.', url, { err, ...lTags() }) + } + } + + static getYoutubeDLVideoFormat (enabledResolutions: VideoResolution[]) { + /** + * 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 = 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('/') + } + + private constructor () { + + } + + download (options: { + url: string + format: string + output: string + processOptions: execa.NodeOptions + additionalYoutubeDLArgs?: string[] + }) { + return this.run({ + url: options.url, + processOptions: options.processOptions, + args: (options.additionalYoutubeDLArgs || []).concat([ '-f', options.format, '-o', options.output ]) + }) + } + + async getInfo (options: { + url: string + format: string + processOptions: execa.NodeOptions + additionalYoutubeDLArgs?: string[] + }) { + const { url, format, additionalYoutubeDLArgs = [], processOptions } = options + + const completeArgs = additionalYoutubeDLArgs.concat([ '--dump-json', '-f', format ]) + + const data = await this.run({ url, args: completeArgs, processOptions }) + const info = data.map(this.parseInfo) + + return info.length === 1 + ? info[0] + : info + } + + async getSubs (options: { + url: string + format: 'vtt' + processOptions: execa.NodeOptions + }) { + const { url, format, processOptions } = options + + const args = [ '--skip-download', '--all-subs', `--sub-format=${format}` ] + + const data = await this.run({ url, args, processOptions }) + const files: string[] = [] + + const skipString = '[info] Writing video subtitles to: ' + + for (let i = 0, len = data.length; i < len; i++) { + const line = data[i] + + if (line.indexOf(skipString) === 0) { + files.push(line.slice(skipString.length)) + } + } + + return files + } + + private async run (options: { + url: string + args: string[] + processOptions: execa.NodeOptions + }) { + const { url, args, processOptions } = options + + let completeArgs = this.wrapWithProxyOptions(args) + completeArgs = this.wrapWithIPOptions(completeArgs) + completeArgs = this.wrapWithFFmpegOptions(completeArgs) + + const output = await execa('python', [ youtubeDLBinaryPath, ...completeArgs, url ], processOptions) + + logger.debug('Runned youtube-dl command.', { command: output.command, stdout: output.stdout, ...lTags() }) + + return output.stdout + ? output.stdout.trim().split(/\r?\n/) + : undefined + } + + private wrapWithProxyOptions (args: string[]) { + if (isProxyEnabled()) { + logger.debug('Using proxy %s for YoutubeDL', getProxy(), lTags()) + + return [ '--proxy', getProxy() ].concat(args) + } + + return args + } + + private wrapWithIPOptions (args: string[]) { + if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) { + logger.debug('Force ipv4 for YoutubeDL') + + return [ '--force-ipv4' ].concat(args) + } + + return args + } + + private wrapWithFFmpegOptions (args: string[]) { + if (process.env.FFMPEG_PATH) { + logger.debug('Using ffmpeg location %s for YoutubeDL', process.env.FFMPEG_PATH, lTags()) + + return [ '--ffmpeg-location', process.env.FFMPEG_PATH ].concat(args) + } + + return args + } + + private parseInfo (data: string) { + return JSON.parse(data) + } +} diff --git a/server/helpers/youtube-dl/youtube-dl-info-builder.ts b/server/helpers/youtube-dl/youtube-dl-info-builder.ts new file mode 100644 index 000000000..9746a7067 --- /dev/null +++ b/server/helpers/youtube-dl/youtube-dl-info-builder.ts @@ -0,0 +1,154 @@ +import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../../initializers/constants' +import { peertubeTruncate } from '../core-utils' + +type YoutubeDLInfo = { + name?: string + description?: string + category?: number + language?: string + licence?: number + nsfw?: boolean + tags?: string[] + thumbnailUrl?: string + ext?: string + originallyPublishedAt?: Date +} + +class YoutubeDLInfoBuilder { + private readonly info: any + + constructor (info: any) { + this.info = { ...info } + } + + getInfo () { + const obj = this.buildVideoInfo(this.normalizeObject(this.info)) + if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video' + + return obj + } + + 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 buildOriginallyPublishedAt (obj: any) { + let originallyPublishedAt: Date = null + + const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date) + if (uploadDateMatcher) { + originallyPublishedAt = new Date() + originallyPublishedAt.setHours(0, 0, 0, 0) + + const year = parseInt(uploadDateMatcher[1], 10) + // Month starts from 0 + const month = parseInt(uploadDateMatcher[2], 10) - 1 + const day = parseInt(uploadDateMatcher[3], 10) + + originallyPublishedAt.setFullYear(year, month, day) + } + + return originallyPublishedAt + } + + 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 >= 16 + } + + private getTags (tags: string[]) { + 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 + } +} + +// --------------------------------------------------------------------------- + +export { + YoutubeDLInfo, + YoutubeDLInfoBuilder +} diff --git a/server/helpers/youtube-dl/youtube-dl-wrapper.ts b/server/helpers/youtube-dl/youtube-dl-wrapper.ts new file mode 100644 index 000000000..6960fbae4 --- /dev/null +++ b/server/helpers/youtube-dl/youtube-dl-wrapper.ts @@ -0,0 +1,135 @@ +import { move, pathExists, readdir, remove } from 'fs-extra' +import { dirname, join } from 'path' +import { CONFIG } from '@server/initializers/config' +import { isVideoFileExtnameValid } from '../custom-validators/videos' +import { logger, loggerTagsFactory } from '../logger' +import { generateVideoImportTmpPath } from '../utils' +import { YoutubeDLCLI } from './youtube-dl-cli' +import { YoutubeDLInfo, YoutubeDLInfoBuilder } from './youtube-dl-info-builder' + +const lTags = loggerTagsFactory('youtube-dl') + +export type YoutubeDLSubs = { + language: string + filename: string + path: string +}[] + +const processOptions = { + maxBuffer: 1024 * 1024 * 10 // 10MB +} + +class YoutubeDLWrapper { + + constructor (private readonly url: string = '', private readonly enabledResolutions: number[] = []) { + + } + + async getInfoForDownload (youtubeDLArgs: string[] = []): Promise { + const youtubeDL = await YoutubeDLCLI.safeGet() + + const info = await youtubeDL.getInfo({ + url: this.url, + format: YoutubeDLCLI.getYoutubeDLVideoFormat(this.enabledResolutions), + additionalYoutubeDLArgs: youtubeDLArgs, + processOptions + }) + + if (info.is_live === true) throw new Error('Cannot download a live streaming.') + + const infoBuilder = new YoutubeDLInfoBuilder(info) + + return infoBuilder.getInfo() + } + + async getSubtitles (): Promise { + const cwd = CONFIG.STORAGE.TMP_DIR + + const youtubeDL = await YoutubeDLCLI.safeGet() + + const files = await youtubeDL.getSubs({ url: this.url, format: 'vtt', processOptions: { cwd } }) + if (!files) return [] + + logger.debug('Get subtitles from youtube dl.', { url: this.url, files, ...lTags() }) + + 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 subtitles + } + + async downloadVideo (fileExt: string, timeout: number): Promise { + // Leave empty the extension, youtube-dl will add it + const pathWithoutExtension = generateVideoImportTmpPath(this.url, '') + + let timer: NodeJS.Timeout + + logger.info('Importing youtubeDL video %s to %s', this.url, pathWithoutExtension, lTags()) + + const youtubeDL = await YoutubeDLCLI.safeGet() + + const timeoutPromise = new Promise((_, rej) => { + timer = setTimeout(() => rej(new Error('YoutubeDL download timeout.')), timeout) + }) + + const downloadPromise = youtubeDL.download({ + url: this.url, + format: YoutubeDLCLI.getYoutubeDLVideoFormat(this.enabledResolutions), + output: pathWithoutExtension, + processOptions + }).then(() => clearTimeout(timer)) + .then(async () => { + // 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 this.guessVideoPathWithExtension(pathWithoutExtension, fileExt) + }) + + return Promise.race([ downloadPromise, timeoutPromise ]) + .catch(async err => { + const path = await this.guessVideoPathWithExtension(pathWithoutExtension, fileExt) + + remove(path) + .catch(err => logger.error('Cannot remove file in youtubeDL timeout.', { err, ...lTags() })) + + throw err + }) + } + + private async 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 + } + + const directoryContent = await readdir(dirname(tmpPath)) + + throw new Error(`Cannot guess path of ${tmpPath}. Directory content: ${directoryContent.join(', ')}`) + } +} + +// --------------------------------------------------------------------------- + +export { + YoutubeDLWrapper +} diff --git a/server/initializers/config.ts b/server/initializers/config.ts index 3a7c72a1c..e20efe02c 100644 --- a/server/initializers/config.ts +++ b/server/initializers/config.ts @@ -69,6 +69,7 @@ const CONFIG = { STORAGE: { TMP_DIR: buildPath(config.get('storage.tmp')), + BIN_DIR: buildPath(config.get('storage.bin')), ACTOR_IMAGES: buildPath(config.get('storage.avatars')), LOG_DIR: buildPath(config.get('storage.logs')), VIDEOS_DIR: buildPath(config.get('storage.videos')), @@ -292,11 +293,13 @@ const CONFIG = { HTTP: { get ENABLED () { return config.get('import.videos.http.enabled') }, - get FORCE_IPV4 () { return config.get('import.videos.http.force_ipv4') }, - PROXY: { - get ENABLED () { return config.get('import.videos.http.proxy.enabled') }, - get URL () { return config.get('import.videos.http.proxy.url') } - } + + YOUTUBE_DL_RELEASE: { + get URL () { return config.get('import.videos.http.youtube_dl_release.url') }, + get NAME () { return config.get('import.videos.http.youtube_dl_release.name') } + }, + + get FORCE_IPV4 () { return config.get('import.videos.http.force_ipv4') } }, TORRENT: { get ENABLED () { return config.get('import.videos.torrent.enabled') } diff --git a/server/initializers/constants.ts b/server/initializers/constants.ts index dcbad9264..1d434d5ab 100644 --- a/server/initializers/constants.ts +++ b/server/initializers/constants.ts @@ -497,6 +497,12 @@ const MIMETYPES = { MIMETYPES.AUDIO.EXT_MIMETYPE = invert(MIMETYPES.AUDIO.MIMETYPE_EXT) MIMETYPES.IMAGE.EXT_MIMETYPE = invert(MIMETYPES.IMAGE.MIMETYPE_EXT) +const BINARY_CONTENT_TYPES = new Set([ + 'binary/octet-stream', + 'application/octet-stream', + 'application/x-binary' +]) + // --------------------------------------------------------------------------- const OVERVIEWS = { @@ -903,6 +909,7 @@ export { MIMETYPES, CRAWL_REQUEST_CONCURRENCY, DEFAULT_AUDIO_RESOLUTION, + BINARY_CONTENT_TYPES, JOB_COMPLETED_LIFETIME, HTTP_SIGNATURE, VIDEO_IMPORT_STATES, diff --git a/server/lib/job-queue/handlers/video-import.ts b/server/lib/job-queue/handlers/video-import.ts index 8313c2561..4ce1a6c30 100644 --- a/server/lib/job-queue/handlers/video-import.ts +++ b/server/lib/job-queue/handlers/video-import.ts @@ -2,7 +2,7 @@ import { Job } from 'bull' import { move, remove, stat } from 'fs-extra' import { getLowercaseExtension } from '@server/helpers/core-utils' import { retryTransactionWrapper } from '@server/helpers/database-utils' -import { YoutubeDL } from '@server/helpers/youtube-dl' +import { YoutubeDLWrapper } from '@server/helpers/youtube-dl' import { isPostImportVideoAccepted } from '@server/lib/moderation' import { generateWebTorrentVideoFilename } from '@server/lib/paths' import { Hooks } from '@server/lib/plugins/hooks' @@ -77,10 +77,10 @@ async function processYoutubeDLImport (job: Job, payload: VideoImportYoutubeDLPa videoImportId: videoImport.id } - const youtubeDL = new YoutubeDL(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod')) + const youtubeDL = new YoutubeDLWrapper(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod')) return processFile( - () => youtubeDL.downloadYoutubeDLVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT), + () => youtubeDL.downloadVideo(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 898691c13..93d02f8a9 100644 --- a/server/lib/schedulers/youtube-dl-update-scheduler.ts +++ b/server/lib/schedulers/youtube-dl-update-scheduler.ts @@ -1,4 +1,4 @@ -import { YoutubeDL } from '@server/helpers/youtube-dl' +import { YoutubeDLCLI } from '@server/helpers/youtube-dl' import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants' import { AbstractScheduler } from './abstract-scheduler' @@ -13,7 +13,7 @@ export class YoutubeDlUpdateScheduler extends AbstractScheduler { } protected internalExecute () { - return YoutubeDL.updateYoutubeDLBinary() + return YoutubeDLCLI.updateYoutubeDLBinary() } static get Instance () { diff --git a/server/tests/api/server/proxy.ts b/server/tests/api/server/proxy.ts index 72bd49078..29f3e10d8 100644 --- a/server/tests/api/server/proxy.ts +++ b/server/tests/api/server/proxy.ts @@ -2,8 +2,18 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { + cleanupTests, + createMultipleServers, + doubleFollow, + FIXTURE_URLS, + PeerTubeServer, + setAccessTokensToServers, + setDefaultVideoChannel, + waitJobs +} from '@shared/extra-utils' import { MockProxy } from '@shared/extra-utils/mock-servers/mock-proxy' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -25,43 +35,90 @@ describe('Test proxy', function () { goodEnv.HTTP_PROXY = 'http://localhost:' + proxyPort await setAccessTokensToServers(servers) + await setDefaultVideoChannel(servers) await doubleFollow(servers[0], servers[1]) }) - it('Should succeed federation with the appropriate proxy config', async function () { - await servers[0].kill() - await servers[0].run({}, { env: goodEnv }) + describe('Federation', function () { - await servers[0].videos.quickUpload({ name: 'video 1' }) + it('Should succeed federation with the appropriate proxy config', async function () { + this.timeout(40000) - await waitJobs(servers) + await servers[0].kill() + await servers[0].run({}, { env: goodEnv }) - for (const server of servers) { - const { total, data } = await server.videos.list() - expect(total).to.equal(1) - expect(data).to.have.lengthOf(1) - } + await servers[0].videos.quickUpload({ name: 'video 1' }) + + await waitJobs(servers) + + for (const server of servers) { + const { total, data } = await server.videos.list() + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + } + }) + + it('Should fail federation with a wrong proxy config', async function () { + this.timeout(40000) + + await servers[0].kill() + await servers[0].run({}, { env: badEnv }) + + await servers[0].videos.quickUpload({ name: 'video 2' }) + + await waitJobs(servers) + + { + const { total, data } = await servers[0].videos.list() + expect(total).to.equal(2) + expect(data).to.have.lengthOf(2) + } + + { + const { total, data } = await servers[1].videos.list() + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + } + }) }) - it('Should fail federation with a wrong proxy config', async function () { - await servers[0].kill() - await servers[0].run({}, { env: badEnv }) + describe('Videos import', async function () { + + function quickImport (expectedStatus: HttpStatusCode = HttpStatusCode.OK_200) { + return servers[0].imports.importVideo({ + attributes: { + name: 'video import', + channelId: servers[0].store.channel.id, + privacy: VideoPrivacy.PUBLIC, + targetUrl: FIXTURE_URLS.peertube_long + }, + expectedStatus + }) + } + + it('Should succeed import with the appropriate proxy config', async function () { + this.timeout(40000) + + await servers[0].kill() + await servers[0].run({}, { env: goodEnv }) - await servers[0].videos.quickUpload({ name: 'video 2' }) + await quickImport() - await waitJobs(servers) + await waitJobs(servers) - { const { total, data } = await servers[0].videos.list() - expect(total).to.equal(2) - expect(data).to.have.lengthOf(2) - } + expect(total).to.equal(3) + expect(data).to.have.lengthOf(3) + }) - { - const { total, data } = await servers[1].videos.list() - expect(total).to.equal(1) - expect(data).to.have.lengthOf(1) - } + it('Should fail import with a wrong proxy config', async function () { + this.timeout(40000) + + await servers[0].kill() + await servers[0].run({}, { env: badEnv }) + + await quickImport(HttpStatusCode.BAD_REQUEST_400) + }) }) after(async function () { diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 948c779e8..cfb188060 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -1,368 +1,444 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import * as chai from 'chai' +import { expect } from 'chai' +import { pathExists, remove } from 'fs-extra' +import { join } from 'path' import { areHttpImportTestsDisabled, cleanupTests, createMultipleServers, + createSingleServer, doubleFollow, FIXTURE_URLS, PeerTubeServer, setAccessTokensToServers, + setDefaultVideoChannel, testCaptionFile, testImage, waitJobs } from '@shared/extra-utils' import { VideoPrivacy, VideoResolution } from '@shared/models' -const expect = chai.expect +async function checkVideosServer1 (server: PeerTubeServer, idHttp: string, idMagnet: string, idTorrent: string) { + const videoHttp = await server.videos.get({ id: idHttp }) + + expect(videoHttp.name).to.equal('small video - youtube') + // FIXME: youtube-dl seems broken + // expect(videoHttp.category.label).to.equal('News & Politics') + // expect(videoHttp.licence.label).to.equal('Attribution') + expect(videoHttp.language.label).to.equal('Unknown') + expect(videoHttp.nsfw).to.be.false + expect(videoHttp.description).to.equal('this is a super description') + expect(videoHttp.tags).to.deep.equal([ 'tag1', 'tag2' ]) + expect(videoHttp.files).to.have.lengthOf(1) + + const originallyPublishedAt = new Date(videoHttp.originallyPublishedAt) + expect(originallyPublishedAt.getDate()).to.equal(14) + expect(originallyPublishedAt.getMonth()).to.equal(0) + expect(originallyPublishedAt.getFullYear()).to.equal(2019) + + const videoMagnet = await server.videos.get({ id: idMagnet }) + const videoTorrent = await server.videos.get({ id: idTorrent }) + + for (const video of [ videoMagnet, videoTorrent ]) { + expect(video.category.label).to.equal('Misc') + expect(video.licence.label).to.equal('Unknown') + expect(video.language.label).to.equal('Unknown') + expect(video.nsfw).to.be.false + expect(video.description).to.equal('this is a super torrent description') + expect(video.tags).to.deep.equal([ 'tag_torrent1', 'tag_torrent2' ]) + expect(video.files).to.have.lengthOf(1) + } + + expect(videoTorrent.name).to.contain('你好 世界 720p.mp4') + expect(videoMagnet.name).to.contain('super peertube2 video') + + const bodyCaptions = await server.captions.list({ videoId: idHttp }) + expect(bodyCaptions.total).to.equal(2) +} + +async function checkVideoServer2 (server: PeerTubeServer, id: number | string) { + const video = await server.videos.get({ id }) + + expect(video.name).to.equal('my super name') + expect(video.category.label).to.equal('Entertainment') + expect(video.licence.label).to.equal('Public Domain Dedication') + expect(video.language.label).to.equal('English') + expect(video.nsfw).to.be.false + expect(video.description).to.equal('my super description') + expect(video.tags).to.deep.equal([ 'supertag1', 'supertag2' ]) + + expect(video.files).to.have.lengthOf(1) + + const bodyCaptions = await server.captions.list({ videoId: id }) + expect(bodyCaptions.total).to.equal(2) +} describe('Test video imports', function () { - let servers: PeerTubeServer[] = [] - let channelIdServer1: number - let channelIdServer2: number if (areHttpImportTestsDisabled()) return - async function checkVideosServer1 (server: PeerTubeServer, idHttp: string, idMagnet: string, idTorrent: string) { - const videoHttp = await server.videos.get({ id: idHttp }) - - expect(videoHttp.name).to.equal('small video - youtube') - // FIXME: youtube-dl seems broken - // expect(videoHttp.category.label).to.equal('News & Politics') - // expect(videoHttp.licence.label).to.equal('Attribution') - expect(videoHttp.language.label).to.equal('Unknown') - expect(videoHttp.nsfw).to.be.false - expect(videoHttp.description).to.equal('this is a super description') - expect(videoHttp.tags).to.deep.equal([ 'tag1', 'tag2' ]) - expect(videoHttp.files).to.have.lengthOf(1) - - const originallyPublishedAt = new Date(videoHttp.originallyPublishedAt) - expect(originallyPublishedAt.getDate()).to.equal(14) - expect(originallyPublishedAt.getMonth()).to.equal(0) - expect(originallyPublishedAt.getFullYear()).to.equal(2019) - - const videoMagnet = await server.videos.get({ id: idMagnet }) - const videoTorrent = await server.videos.get({ id: idTorrent }) - - for (const video of [ videoMagnet, videoTorrent ]) { - expect(video.category.label).to.equal('Misc') - expect(video.licence.label).to.equal('Unknown') - expect(video.language.label).to.equal('Unknown') - expect(video.nsfw).to.be.false - expect(video.description).to.equal('this is a super torrent description') - expect(video.tags).to.deep.equal([ 'tag_torrent1', 'tag_torrent2' ]) - expect(video.files).to.have.lengthOf(1) - } + function runSuite (mode: 'youtube-dl' | 'yt-dlp') { - expect(videoTorrent.name).to.contain('你好 世界 720p.mp4') - expect(videoMagnet.name).to.contain('super peertube2 video') + describe('Import ' + mode, function () { + let servers: PeerTubeServer[] = [] - const bodyCaptions = await server.captions.list({ videoId: idHttp }) - expect(bodyCaptions.total).to.equal(2) - } + before(async function () { + this.timeout(30_000) - async function checkVideoServer2 (server: PeerTubeServer, id: number | string) { - const video = await server.videos.get({ id }) + // Run servers + servers = await createMultipleServers(2, { + import: { + videos: { + http: { + youtube_dl_release: { + url: mode === 'youtube-dl' + ? 'https://yt-dl.org/downloads/latest/youtube-dl' + : 'https://api.github.com/repos/yt-dlp/yt-dlp/releases', - expect(video.name).to.equal('my super name') - expect(video.category.label).to.equal('Entertainment') - expect(video.licence.label).to.equal('Public Domain Dedication') - expect(video.language.label).to.equal('English') - expect(video.nsfw).to.be.false - expect(video.description).to.equal('my super description') - expect(video.tags).to.deep.equal([ 'supertag1', 'supertag2' ]) + name: mode + } + } + } + } + }) - expect(video.files).to.have.lengthOf(1) + await setAccessTokensToServers(servers) + await setDefaultVideoChannel(servers) - const bodyCaptions = await server.captions.list({ videoId: id }) - expect(bodyCaptions.total).to.equal(2) - } + await doubleFollow(servers[0], servers[1]) + }) - before(async function () { - this.timeout(30_000) + it('Should import videos on server 1', async function () { + this.timeout(60_000) - // Run servers - servers = await createMultipleServers(2) + const baseAttributes = { + channelId: servers[0].store.channel.id, + privacy: VideoPrivacy.PUBLIC + } - await setAccessTokensToServers(servers) + { + const attributes = { ...baseAttributes, targetUrl: FIXTURE_URLS.youtube } + const { video } = await servers[0].imports.importVideo({ attributes }) + expect(video.name).to.equal('small video - youtube') - { - const { videoChannels } = await servers[0].users.getMyInfo() - channelIdServer1 = videoChannels[0].id - } + { + expect(video.thumbnailPath).to.match(new RegExp(`^/static/thumbnails/.+.jpg$`)) + expect(video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.jpg$`)) - { - const { videoChannels } = await servers[1].users.getMyInfo() - channelIdServer2 = videoChannels[0].id - } + const suffix = mode === 'yt-dlp' + ? '_yt_dlp' + : '' - await doubleFollow(servers[0], servers[1]) - }) + await testImage(servers[0].url, 'video_import_thumbnail' + suffix, video.thumbnailPath) + await testImage(servers[0].url, 'video_import_preview' + suffix, video.previewPath) + } - it('Should import videos on server 1', async function () { - this.timeout(60_000) + const bodyCaptions = await servers[0].captions.list({ videoId: video.id }) + const videoCaptions = bodyCaptions.data + expect(videoCaptions).to.have.lengthOf(2) - const baseAttributes = { - channelId: channelIdServer1, - privacy: VideoPrivacy.PUBLIC - } + { + const enCaption = videoCaptions.find(caption => caption.language.id === 'en') + expect(enCaption).to.exist + expect(enCaption.language.label).to.equal('English') + expect(enCaption.captionPath).to.match(new RegExp(`^/lazy-static/video-captions/.+-en.vtt$`)) - { - const attributes = { ...baseAttributes, targetUrl: FIXTURE_URLS.youtube } - const { video } = await servers[0].imports.importVideo({ attributes }) - expect(video.name).to.equal('small video - youtube') + const regex = `WEBVTT[ \n]+Kind: captions[ \n]+Language: en[ \n]+00:00:01.600 --> 00:00:04.200[ \n]+English \\(US\\)[ \n]+` + + `00:00:05.900 --> 00:00:07.999[ \n]+This is a subtitle in American English[ \n]+` + + `00:00:10.000 --> 00:00:14.000[ \n]+Adding subtitles is very easy to do` + await testCaptionFile(servers[0].url, enCaption.captionPath, new RegExp(regex)) + } - expect(video.thumbnailPath).to.match(new RegExp(`^/static/thumbnails/.+.jpg$`)) - expect(video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.jpg$`)) + { + const frCaption = videoCaptions.find(caption => caption.language.id === 'fr') + expect(frCaption).to.exist + expect(frCaption.language.label).to.equal('French') + expect(frCaption.captionPath).to.match(new RegExp(`^/lazy-static/video-captions/.+-fr.vtt`)) - await testImage(servers[0].url, 'video_import_thumbnail', video.thumbnailPath) - await testImage(servers[0].url, 'video_import_preview', video.previewPath) + const regex = `WEBVTT[ \n]+Kind: captions[ \n]+Language: fr[ \n]+00:00:01.600 --> 00:00:04.200[ \n]+` + + `Français \\(FR\\)[ \n]+00:00:05.900 --> 00:00:07.999[ \n]+C'est un sous-titre français[ \n]+` + + `00:00:10.000 --> 00:00:14.000[ \n]+Ajouter un sous-titre est vraiment facile` - const bodyCaptions = await servers[0].captions.list({ videoId: video.id }) - const videoCaptions = bodyCaptions.data - expect(videoCaptions).to.have.lengthOf(2) + await testCaptionFile(servers[0].url, frCaption.captionPath, new RegExp(regex)) + } + } - const enCaption = videoCaptions.find(caption => caption.language.id === 'en') - expect(enCaption).to.exist - expect(enCaption.language.label).to.equal('English') - expect(enCaption.captionPath).to.match(new RegExp(`^/lazy-static/video-captions/.+-en.vtt$`)) - await testCaptionFile(servers[0].url, enCaption.captionPath, `WEBVTT -Kind: captions -Language: en + { + const attributes = { + ...baseAttributes, + magnetUri: FIXTURE_URLS.magnet, + description: 'this is a super torrent description', + tags: [ 'tag_torrent1', 'tag_torrent2' ] + } + const { video } = await servers[0].imports.importVideo({ attributes }) + expect(video.name).to.equal('super peertube2 video') + } -00:00:01.600 --> 00:00:04.200 -English (US) + { + const attributes = { + ...baseAttributes, + torrentfile: 'video-720p.torrent' as any, + description: 'this is a super torrent description', + tags: [ 'tag_torrent1', 'tag_torrent2' ] + } + const { video } = await servers[0].imports.importVideo({ attributes }) + expect(video.name).to.equal('你好 世界 720p.mp4') + } + }) -00:00:05.900 --> 00:00:07.999 -This is a subtitle in American English + it('Should list the videos to import in my videos on server 1', async function () { + const { total, data } = await servers[0].videos.listMyVideos({ sort: 'createdAt' }) -00:00:10.000 --> 00:00:14.000 -Adding subtitles is very easy to do`) + expect(total).to.equal(3) - const frCaption = videoCaptions.find(caption => caption.language.id === 'fr') - expect(frCaption).to.exist - expect(frCaption.language.label).to.equal('French') - expect(frCaption.captionPath).to.match(new RegExp(`^/lazy-static/video-captions/.+-fr.vtt`)) - await testCaptionFile(servers[0].url, frCaption.captionPath, `WEBVTT -Kind: captions -Language: fr + expect(data).to.have.lengthOf(3) + expect(data[0].name).to.equal('small video - youtube') + expect(data[1].name).to.equal('super peertube2 video') + expect(data[2].name).to.equal('你好 世界 720p.mp4') + }) -00:00:01.600 --> 00:00:04.200 -Français (FR) + it('Should list the videos to import in my imports on server 1', async function () { + const { total, data: videoImports } = await servers[0].imports.getMyVideoImports({ sort: '-createdAt' }) + expect(total).to.equal(3) -00:00:05.900 --> 00:00:07.999 -C'est un sous-titre français + expect(videoImports).to.have.lengthOf(3) -00:00:10.000 --> 00:00:14.000 -Ajouter un sous-titre est vraiment facile`) - } + expect(videoImports[2].targetUrl).to.equal(FIXTURE_URLS.youtube) + expect(videoImports[2].magnetUri).to.be.null + expect(videoImports[2].torrentName).to.be.null + expect(videoImports[2].video.name).to.equal('small video - youtube') - { - const attributes = { - ...baseAttributes, - magnetUri: FIXTURE_URLS.magnet, - description: 'this is a super torrent description', - tags: [ 'tag_torrent1', 'tag_torrent2' ] - } - const { video } = await servers[0].imports.importVideo({ attributes }) - expect(video.name).to.equal('super peertube2 video') - } + expect(videoImports[1].targetUrl).to.be.null + expect(videoImports[1].magnetUri).to.equal(FIXTURE_URLS.magnet) + expect(videoImports[1].torrentName).to.be.null + expect(videoImports[1].video.name).to.equal('super peertube2 video') - { - const attributes = { - ...baseAttributes, - torrentfile: 'video-720p.torrent' as any, - description: 'this is a super torrent description', - tags: [ 'tag_torrent1', 'tag_torrent2' ] - } - const { video } = await servers[0].imports.importVideo({ attributes }) - expect(video.name).to.equal('你好 世界 720p.mp4') - } - }) + expect(videoImports[0].targetUrl).to.be.null + expect(videoImports[0].magnetUri).to.be.null + expect(videoImports[0].torrentName).to.equal('video-720p.torrent') + expect(videoImports[0].video.name).to.equal('你好 世界 720p.mp4') + }) - it('Should list the videos to import in my videos on server 1', async function () { - const { total, data } = await servers[0].videos.listMyVideos({ sort: 'createdAt' }) + it('Should have the video listed on the two instances', async function () { + this.timeout(120_000) - expect(total).to.equal(3) + await waitJobs(servers) - expect(data).to.have.lengthOf(3) - expect(data[0].name).to.equal('small video - youtube') - expect(data[1].name).to.equal('super peertube2 video') - expect(data[2].name).to.equal('你好 世界 720p.mp4') - }) + for (const server of servers) { + const { total, data } = await server.videos.list() + expect(total).to.equal(3) + expect(data).to.have.lengthOf(3) - it('Should list the videos to import in my imports on server 1', async function () { - const { total, data: videoImports } = await servers[0].imports.getMyVideoImports({ sort: '-createdAt' }) - expect(total).to.equal(3) + const [ videoHttp, videoMagnet, videoTorrent ] = data + await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) + } + }) + + it('Should import a video on server 2 with some fields', async function () { + this.timeout(60_000) + + const attributes = { + targetUrl: FIXTURE_URLS.youtube, + channelId: servers[1].store.channel.id, + privacy: VideoPrivacy.PUBLIC, + category: 10, + licence: 7, + language: 'en', + name: 'my super name', + description: 'my super description', + tags: [ 'supertag1', 'supertag2' ] + } + const { video } = await servers[1].imports.importVideo({ attributes }) + expect(video.name).to.equal('my super name') + }) - expect(videoImports).to.have.lengthOf(3) + it('Should have the videos listed on the two instances', async function () { + this.timeout(120_000) - expect(videoImports[2].targetUrl).to.equal(FIXTURE_URLS.youtube) - expect(videoImports[2].magnetUri).to.be.null - expect(videoImports[2].torrentName).to.be.null - expect(videoImports[2].video.name).to.equal('small video - youtube') + await waitJobs(servers) - expect(videoImports[1].targetUrl).to.be.null - expect(videoImports[1].magnetUri).to.equal(FIXTURE_URLS.magnet) - expect(videoImports[1].torrentName).to.be.null - expect(videoImports[1].video.name).to.equal('super peertube2 video') + for (const server of servers) { + const { total, data } = await server.videos.list() + expect(total).to.equal(4) + expect(data).to.have.lengthOf(4) - expect(videoImports[0].targetUrl).to.be.null - expect(videoImports[0].magnetUri).to.be.null - expect(videoImports[0].torrentName).to.equal('video-720p.torrent') - expect(videoImports[0].video.name).to.equal('你好 世界 720p.mp4') - }) + await checkVideoServer2(server, data[0].uuid) - it('Should have the video listed on the two instances', async function () { - this.timeout(120_000) + const [ , videoHttp, videoMagnet, videoTorrent ] = data + await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) + } + }) - await waitJobs(servers) + it('Should import a video that will be transcoded', async function () { + this.timeout(240_000) - for (const server of servers) { - const { total, data } = await server.videos.list() - expect(total).to.equal(3) - expect(data).to.have.lengthOf(3) + const attributes = { + name: 'transcoded video', + magnetUri: FIXTURE_URLS.magnet, + channelId: servers[1].store.channel.id, + privacy: VideoPrivacy.PUBLIC + } + const { video } = await servers[1].imports.importVideo({ attributes }) + const videoUUID = video.uuid - const [ videoHttp, videoMagnet, videoTorrent ] = data - await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) - } - }) + await waitJobs(servers) - it('Should import a video on server 2 with some fields', async function () { - this.timeout(60_000) - - const attributes = { - targetUrl: FIXTURE_URLS.youtube, - channelId: channelIdServer2, - privacy: VideoPrivacy.PUBLIC, - category: 10, - licence: 7, - language: 'en', - name: 'my super name', - description: 'my super description', - tags: [ 'supertag1', 'supertag2' ] - } - const { video } = await servers[1].imports.importVideo({ attributes }) - expect(video.name).to.equal('my super name') - }) + for (const server of servers) { + const video = await server.videos.get({ id: videoUUID }) - it('Should have the videos listed on the two instances', async function () { - this.timeout(120_000) + expect(video.name).to.equal('transcoded video') + expect(video.files).to.have.lengthOf(4) + } + }) + + it('Should import no HDR version on a HDR video', async function () { + this.timeout(300_000) + + const config = { + transcoding: { + enabled: true, + resolutions: { + '240p': true, + '360p': false, + '480p': false, + '720p': false, + '1080p': false, // the resulting resolution shouldn't be higher than this, and not vp9.2/av01 + '1440p': false, + '2160p': false + }, + webtorrent: { enabled: true }, + hls: { enabled: false } + }, + import: { + videos: { + http: { + enabled: true + }, + torrent: { + enabled: true + } + } + } + } + await servers[0].config.updateCustomSubConfig({ newConfig: config }) - await waitJobs(servers) + const attributes = { + name: 'hdr video', + targetUrl: FIXTURE_URLS.youtubeHDR, + channelId: servers[0].store.channel.id, + privacy: VideoPrivacy.PUBLIC + } + const { video: videoImported } = await servers[0].imports.importVideo({ attributes }) + const videoUUID = videoImported.uuid + + await waitJobs(servers) + + // test resolution + const video = await servers[0].videos.get({ id: videoUUID }) + expect(video.name).to.equal('hdr video') + const maxResolution = Math.max.apply(Math, video.files.map(function (o) { return o.resolution.id })) + expect(maxResolution, 'expected max resolution not met').to.equals(VideoResolution.H_240P) + }) + + it('Should import a peertube video', async function () { + this.timeout(120_000) + + // TODO: include peertube_short when https://github.com/ytdl-org/youtube-dl/pull/29475 is merged + for (const targetUrl of [ FIXTURE_URLS.peertube_long ]) { + // for (const targetUrl of [ FIXTURE_URLS.peertube_long, FIXTURE_URLS.peertube_short ]) { + await servers[0].config.disableTranscoding() + + const attributes = { + targetUrl, + channelId: servers[0].store.channel.id, + privacy: VideoPrivacy.PUBLIC + } + const { video } = await servers[0].imports.importVideo({ attributes }) + const videoUUID = video.uuid - for (const server of servers) { - const { total, data } = await server.videos.list() - expect(total).to.equal(4) - expect(data).to.have.lengthOf(4) + await waitJobs(servers) - await checkVideoServer2(server, data[0].uuid) + for (const server of servers) { + const video = await server.videos.get({ id: videoUUID }) - const [ , videoHttp, videoMagnet, videoTorrent ] = data - await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) - } - }) + expect(video.name).to.equal('E2E tests') + } + } + }) - it('Should import a video that will be transcoded', async function () { - this.timeout(240_000) + after(async function () { + await cleanupTests(servers) + }) + }) + } - const attributes = { - name: 'transcoded video', - magnetUri: FIXTURE_URLS.magnet, - channelId: channelIdServer2, - privacy: VideoPrivacy.PUBLIC - } - const { video } = await servers[1].imports.importVideo({ attributes }) - const videoUUID = video.uuid + runSuite('youtube-dl') - await waitJobs(servers) + runSuite('yt-dlp') - for (const server of servers) { - const video = await server.videos.get({ id: videoUUID }) + describe('Auto update', function () { + let server: PeerTubeServer - expect(video.name).to.equal('transcoded video') - expect(video.files).to.have.lengthOf(4) + function quickPeerTubeImport () { + const attributes = { + targetUrl: FIXTURE_URLS.peertube_long, + channelId: server.store.channel.id, + privacy: VideoPrivacy.PUBLIC + } + + return server.imports.importVideo({ attributes }) } - }) - it('Should import no HDR version on a HDR video', async function () { - this.timeout(300_000) - - const config = { - transcoding: { - enabled: true, - resolutions: { - '240p': true, - '360p': false, - '480p': false, - '720p': false, - '1080p': false, // the resulting resolution shouldn't be higher than this, and not vp9.2/av01 - '1440p': false, - '2160p': false - }, - webtorrent: { enabled: true }, - hls: { enabled: false } - }, - import: { - videos: { - http: { - enabled: true - }, - torrent: { - enabled: true + async function testBinaryUpdate (releaseUrl: string, releaseName: string) { + await remove(join(server.servers.buildDirectory('bin'), releaseName)) + + await server.kill() + await server.run({ + import: { + videos: { + http: { + youtube_dl_release: { + url: releaseUrl, + name: releaseName + } + } } } - } - } - await servers[0].config.updateCustomSubConfig({ newConfig: config }) + }) + + await quickPeerTubeImport() - const attributes = { - name: 'hdr video', - targetUrl: FIXTURE_URLS.youtubeHDR, - channelId: channelIdServer1, - privacy: VideoPrivacy.PUBLIC + expect(await pathExists(join(server.servers.buildDirectory('bin'), releaseName))).to.be.true } - const { video: videoImported } = await servers[0].imports.importVideo({ attributes }) - const videoUUID = videoImported.uuid - await waitJobs(servers) + before(async function () { + this.timeout(30_000) - // test resolution - const video = await servers[0].videos.get({ id: videoUUID }) - expect(video.name).to.equal('hdr video') - const maxResolution = Math.max.apply(Math, video.files.map(function (o) { return o.resolution.id })) - expect(maxResolution, 'expected max resolution not met').to.equals(VideoResolution.H_240P) - }) + // Run servers + server = await createSingleServer(1) - it('Should import a peertube video', async function () { - this.timeout(120_000) + await setAccessTokensToServers([ server ]) + await setDefaultVideoChannel([ server ]) + }) - // TODO: include peertube_short when https://github.com/ytdl-org/youtube-dl/pull/29475 is merged - for (const targetUrl of [ FIXTURE_URLS.peertube_long ]) { - // for (const targetUrl of [ FIXTURE_URLS.peertube_long, FIXTURE_URLS.peertube_short ]) { - await servers[0].config.disableTranscoding() + it('Should update youtube-dl from github URL', async function () { + this.timeout(120_000) - const attributes = { - targetUrl, - channelId: channelIdServer1, - privacy: VideoPrivacy.PUBLIC - } - const { video } = await servers[0].imports.importVideo({ attributes }) - const videoUUID = video.uuid + await testBinaryUpdate('https://api.github.com/repos/ytdl-org/youtube-dl/releases', 'youtube-dl') + }) - await waitJobs(servers) + it('Should update youtube-dl from raw URL', async function () { + this.timeout(120_000) - for (const server of servers) { - const video = await server.videos.get({ id: videoUUID }) + await testBinaryUpdate('https://yt-dl.org/downloads/latest/youtube-dl', 'youtube-dl') + }) - expect(video.name).to.equal('E2E tests') - } - } - }) + it('Should update youtube-dl from youtube-dl fork', async function () { + this.timeout(120_000) - after(async function () { - await cleanupTests(servers) + await testBinaryUpdate('https://api.github.com/repos/yt-dlp/yt-dlp/releases', 'yt-dlp') + }) }) }) diff --git a/server/tests/fixtures/video_import_preview_yt_dlp.jpg b/server/tests/fixtures/video_import_preview_yt_dlp.jpg new file mode 100644 index 000000000..9e8833bf9 Binary files /dev/null and b/server/tests/fixtures/video_import_preview_yt_dlp.jpg differ diff --git a/server/tests/fixtures/video_import_thumbnail_yt_dlp.jpg b/server/tests/fixtures/video_import_thumbnail_yt_dlp.jpg new file mode 100644 index 000000000..f672a785a Binary files /dev/null and b/server/tests/fixtures/video_import_thumbnail_yt_dlp.jpg differ diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index 758b561e1..54ac910e6 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -4,13 +4,9 @@ registerTSPaths() import { program } from 'commander' import { accessSync, constants } from 'fs' import { remove } from 'fs-extra' -import { truncate } from 'lodash' import { join } from 'path' -import { promisify } from 'util' -import { YoutubeDL } from '@server/helpers/youtube-dl' import { sha256 } from '../helpers/core-utils' import { doRequestAndSaveToFile } from '../helpers/requests' -import { CONSTRAINTS_FIELDS } from '../initializers/constants' import { assignToken, buildCommonVideoOptions, @@ -19,8 +15,8 @@ import { getLogger, getServerCredentials } from './cli' -import { PeerTubeServer } from '@shared/extra-utils' - +import { wait } from '@shared/extra-utils' +import { YoutubeDLCLI, YoutubeDLInfo, YoutubeDLInfoBuilder } from '@server/helpers/youtube-dl' import prompt = require('prompt') const processOptions = { @@ -73,7 +69,7 @@ getServerCredentials(command) async function run (url: string, username: string, password: string) { if (!password) password = await promptPassword() - const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL() + const youtubeDLBinary = await YoutubeDLCLI.safeGet() let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args) @@ -96,8 +92,6 @@ async function run (url: string, username: string, password: string) { } else if (options.last) { infoArray = infoArray.slice(-options.last) } - // Normalize utf8 fields - infoArray = infoArray.map(i => normalizeObject(i)) log.info('Will download and upload %d videos.\n', infoArray.length) @@ -105,8 +99,9 @@ async function run (url: string, username: string, password: string) { try { if (index > 0 && options.waitInterval) { log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000) - await new Promise(res => setTimeout(res, options.waitInterval)) + await wait(options.waitInterval) } + await processVideo({ cwd: options.tmpdir, url, @@ -131,29 +126,26 @@ async function processVideo (parameters: { youtubeInfo: any }) { const { youtubeInfo, cwd, url, username, password } = parameters - const youtubeDL = new YoutubeDL('', []) log.debug('Fetching object.', youtubeInfo) const videoInfo = await fetchObject(youtubeInfo) log.debug('Fetched object.', 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)) + if (options.since && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() < options.since.getTime()) { + log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.since)) return } - if (options.until && originallyPublishedAt && originallyPublishedAt.getTime() > options.until.getTime()) { - log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.title, formatDate(options.until)) + if (options.until && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() > options.until.getTime()) { + log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.until)) return } const server = buildServer(url) const { data } = await server.search.advancedVideoSearch({ search: { - search: videoInfo.title, + search: videoInfo.name, sort: '-match', searchTarget: 'local' } @@ -161,28 +153,32 @@ async function processVideo (parameters: { log.info('############################################################\n') - if (data.find(v => v.name === videoInfo.title)) { - log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title) + if (data.find(v => v.name === videoInfo.name)) { + log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.name) return } const path = join(cwd, sha256(videoInfo.url) + '.mp4') - log.info('Downloading video "%s"...', videoInfo.title) + log.info('Downloading video "%s"...', videoInfo.name) - const youtubeDLOptions = [ '-f', youtubeDL.getYoutubeDLVideoFormat(), ...command.args, '-o', path ] try { - const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL() - const youtubeDLExec = promisify(youtubeDLBinary.exec).bind(youtubeDLBinary) - const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions) + const youtubeDLBinary = await YoutubeDLCLI.safeGet() + const output = await youtubeDLBinary.download({ + url: videoInfo.url, + format: YoutubeDLCLI.getYoutubeDLVideoFormat([]), + output: path, + additionalYoutubeDLArgs: command.args, + processOptions + }) + log.info(output.join('\n')) await uploadVideoOnPeerTube({ - youtubeDL, cwd, url, username, password, - videoInfo: normalizeObject(videoInfo), + videoInfo, videoPath: path }) } catch (err) { @@ -191,57 +187,34 @@ async function processVideo (parameters: { } async function uploadVideoOnPeerTube (parameters: { - youtubeDL: YoutubeDL - videoInfo: any + videoInfo: YoutubeDLInfo videoPath: string cwd: string url: string username: string password: string }) { - const { youtubeDL, videoInfo, videoPath, cwd, url, username, password } = parameters + const { videoInfo, videoPath, cwd, url, username, password } = parameters const server = buildServer(url) await assignToken(server, username, password) - const category = await getCategory(server, videoInfo.categories) - const licence = getLicence(videoInfo.license) - let tags = [] - if (Array.isArray(videoInfo.tags)) { - tags = videoInfo.tags - .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min) - .map(t => t.normalize()) - .slice(0, 5) - } - - let thumbnailfile - if (videoInfo.thumbnail) { - thumbnailfile = join(cwd, sha256(videoInfo.thumbnail) + '.jpg') + let thumbnailfile: string + if (videoInfo.thumbnailUrl) { + thumbnailfile = join(cwd, sha256(videoInfo.thumbnailUrl) + '.jpg') - await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile) + await doRequestAndSaveToFile(videoInfo.thumbnailUrl, thumbnailfile) } - const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo) - - const defaultAttributes = { - name: truncate(videoInfo.title, { - length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, - separator: /,? +/, - omission: ' […]' - }), - category, - licence, - nsfw: isNSFW(videoInfo), - description: videoInfo.description, - tags - } - - const baseAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes) + const baseAttributes = await buildVideoAttributesFromCommander(server, program, videoInfo) const attributes = { ...baseAttributes, - originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null, + originallyPublishedAt: videoInfo.originallyPublishedAt + ? videoInfo.originallyPublishedAt.toISOString() + : null, + thumbnailfile, previewfile: thumbnailfile, fixture: videoPath @@ -266,67 +239,26 @@ async function uploadVideoOnPeerTube (parameters: { await remove(videoPath) if (thumbnailfile) await remove(thumbnailfile) - log.warn('Uploaded video "%s"!\n', attributes.name) + log.info('Uploaded video "%s"!\n', attributes.name) } /* ---------------------------------------------------------- */ -async function getCategory (server: PeerTubeServer, categories: string[]) { - if (!categories) return undefined - - const categoryString = categories[0] - - if (categoryString === 'News & Politics') return 11 - - const categoriesServer = await server.videos.getCategories() - - for (const key of Object.keys(categoriesServer)) { - const categoryServer = categoriesServer[key] - if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10) - } - - return undefined -} - -function getLicence (licence: string) { - if (!licence) return undefined - - if (licence.includes('Creative Commons Attribution licence')) return 1 - - return undefined -} - -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 - } - } +async function fetchObject (info: any) { + const url = buildUrl(info) - return newObj -} + const youtubeDLCLI = await YoutubeDLCLI.safeGet() + const result = await youtubeDLCLI.getInfo({ + url, + format: YoutubeDLCLI.getYoutubeDLVideoFormat([]), + processOptions + }) -function fetchObject (info: any) { - const url = buildUrl(info) + const builder = new YoutubeDLInfoBuilder(result) - return new Promise(async (res, rej) => { - const youtubeDL = await YoutubeDL.safeGetYoutubeDL() - youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => { - if (err) return rej(err) + const videoInfo = builder.getInfo() - const videoInfoWithUrl = Object.assign(videoInfo, { url }) - return res(normalizeObject(videoInfoWithUrl)) - }) - }) + return { ...videoInfo, url } } function buildUrl (info: any) { @@ -340,10 +272,6 @@ function buildUrl (info: any) { return 'https://www.youtube.com/watch?v=' + info.id } -function isNSFW (info: any) { - return info.age_limit && info.age_limit >= 16 -} - function normalizeTargetUrl (url: string) { let normalizedUrl = url.replace(/\/+$/, '') @@ -404,14 +332,11 @@ function exitError (message: string, ...meta: any[]) { process.exit(-1) } -function getYoutubeDLInfo (youtubeDL: any, url: string, args: string[]) { - return new Promise((res, rej) => { - const options = [ '-j', '--flat-playlist', '--playlist-reverse', ...args ] - - youtubeDL.getInfo(url, options, processOptions, (err, info) => { - if (err) return rej(err) - - return res(info) - }) +function getYoutubeDLInfo (youtubeDLCLI: YoutubeDLCLI, url: string, args: string[]) { + return youtubeDLCLI.getInfo({ + url, + format: YoutubeDLCLI.getYoutubeDLVideoFormat([]), + additionalYoutubeDLArgs: [ '-j', '--flat-playlist', '--playlist-reverse', ...args ], + processOptions }) } -- cgit v1.2.3