Use a class for youtube-dl

This commit is contained in:
Chocobozzz 2021-05-11 10:54:05 +02:00
parent ac2a5b5427
commit 1bcb03a100
No known key found for this signature in database
GPG Key ID: 583A612D890159BE
8 changed files with 368 additions and 364 deletions

View File

@ -3,6 +3,7 @@ import { move, readFile } from 'fs-extra'
import * as magnetUtil from 'magnet-uri' import * as magnetUtil from 'magnet-uri'
import * as parseTorrent from 'parse-torrent' import * as parseTorrent from 'parse-torrent'
import { join } from 'path' import { join } from 'path'
import { getEnabledResolutions } from '@server/lib/config'
import { setVideoTags } from '@server/lib/video' import { setVideoTags } from '@server/lib/video'
import { import {
MChannelAccountDefault, MChannelAccountDefault,
@ -24,7 +25,7 @@ import { isArray } from '../../../helpers/custom-validators/misc'
import { createReqFiles } from '../../../helpers/express-utils' import { createReqFiles } from '../../../helpers/express-utils'
import { logger } from '../../../helpers/logger' import { logger } from '../../../helpers/logger'
import { getSecureTorrentName } from '../../../helpers/utils' 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 { CONFIG } from '../../../initializers/config'
import { MIMETYPES } from '../../../initializers/constants' import { MIMETYPES } from '../../../initializers/constants'
import { sequelizeTypescript } from '../../../initializers/database' import { sequelizeTypescript } from '../../../initializers/database'
@ -139,10 +140,12 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response)
const targetUrl = body.targetUrl const targetUrl = body.targetUrl
const user = res.locals.oauth.token.User const user = res.locals.oauth.token.User
const youtubeDL = new YoutubeDL(targetUrl, getEnabledResolutions('vod'))
// Get video infos // Get video infos
let youtubeDLInfo: YoutubeDLInfo let youtubeDLInfo: YoutubeDLInfo
try { try {
youtubeDLInfo = await getYoutubeDLInfo(targetUrl) youtubeDLInfo = await youtubeDL.getYoutubeDLInfo()
} catch (err) { } catch (err) {
logger.info('Cannot fetch information from import for URL %s.', targetUrl, { 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 // Get video subtitles
try { try {
const subtitles = await getYoutubeDLSubs(targetUrl) const subtitles = await youtubeDL.getYoutubeDLSubs()
logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)

View File

@ -2,7 +2,7 @@ import * as cors from 'cors'
import * as express from 'express' import * as express from 'express'
import { join } from 'path' import { join } from 'path'
import { serveIndexHTML } from '@server/lib/client-html' 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 { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo' import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo'
import { root } from '../helpers/core-utils' import { root } from '../helpers/core-utils'
@ -18,7 +18,6 @@ import {
WEBSERVER WEBSERVER
} from '../initializers/constants' } from '../initializers/constants'
import { getThemeOrDefault } from '../lib/plugins/theme-utils' import { getThemeOrDefault } from '../lib/plugins/theme-utils'
import { getEnabledResolutions } from '../lib/video-transcoding'
import { asyncMiddleware } from '../middlewares' import { asyncMiddleware } from '../middlewares'
import { cacheRoute } from '../middlewares/cache' import { cacheRoute } from '../middlewares/cache'
import { UserModel } from '../models/account/user' import { UserModel } from '../models/account/user'

View File

@ -6,7 +6,6 @@ import { CONFIG } from '@server/initializers/config'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
import { VideoResolution } from '../../shared/models/videos' import { VideoResolution } from '../../shared/models/videos'
import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants' 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 { peertubeTruncate, pipelinePromise, root } from './core-utils'
import { isVideoFileExtnameValid } from './custom-validators/videos' import { isVideoFileExtnameValid } from './custom-validators/videos'
import { logger } from './logger' import { logger } from './logger'
@ -35,7 +34,13 @@ const processOptions = {
maxBuffer: 1024 * 1024 * 10 // 10MB maxBuffer: 1024 * 1024 * 10 // 10MB
} }
function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> { class YoutubeDL {
constructor (private readonly url: string = '', private readonly enabledResolutions: number[] = []) {
}
getYoutubeDLInfo (opts?: string[]): Promise<YoutubeDLInfo> {
return new Promise<YoutubeDLInfo>((res, rej) => { return new Promise<YoutubeDLInfo>((res, rej) => {
let args = opts || [ '-j', '--flat-playlist' ] let args = opts || [ '-j', '--flat-playlist' ]
@ -43,16 +48,16 @@ function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo>
args.push('--force-ipv4') args.push('--force-ipv4')
} }
args = wrapWithProxyOptions(args) args = this.wrapWithProxyOptions(args)
args = [ '-f', getYoutubeDLVideoFormat() ].concat(args) args = [ '-f', this.getYoutubeDLVideoFormat() ].concat(args)
safeGetYoutubeDL() YoutubeDL.safeGetYoutubeDL()
.then(youtubeDL => { .then(youtubeDL => {
youtubeDL.getInfo(url, args, processOptions, (err, info) => { youtubeDL.getInfo(this.url, args, processOptions, (err, info) => {
if (err) return rej(err) if (err) return rej(err)
if (info.is_live === true) return rej(new Error('Cannot download a live streaming.')) if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
const obj = buildVideoInfo(normalizeObject(info)) const obj = this.buildVideoInfo(this.normalizeObject(info))
if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video' if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
return res(obj) return res(obj)
@ -62,18 +67,18 @@ function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo>
}) })
} }
function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> { getYoutubeDLSubs (opts?: object): Promise<YoutubeDLSubs> {
return new Promise<YoutubeDLSubs>((res, rej) => { return new Promise<YoutubeDLSubs>((res, rej) => {
const cwd = CONFIG.STORAGE.TMP_DIR const cwd = CONFIG.STORAGE.TMP_DIR
const options = opts || { all: true, format: 'vtt', cwd } const options = opts || { all: true, format: 'vtt', cwd }
safeGetYoutubeDL() YoutubeDL.safeGetYoutubeDL()
.then(youtubeDL => { .then(youtubeDL => {
youtubeDL.getSubs(url, options, (err, files) => { youtubeDL.getSubs(this.url, options, (err, files) => {
if (err) return rej(err) if (err) return rej(err)
if (!files) return [] if (!files) return []
logger.debug('Get subtitles from youtube dl.', { url, files }) logger.debug('Get subtitles from youtube dl.', { url: this.url, files })
const subtitles = files.reduce((acc, filename) => { const subtitles = files.reduce((acc, filename) => {
const matched = filename.match(/\.([a-z]{2})(-[a-z]+)?\.(vtt|ttml)/i) const matched = filename.match(/\.([a-z]{2})(-[a-z]+)?\.(vtt|ttml)/i)
@ -96,7 +101,7 @@ function getYoutubeDLSubs (url: string, opts?: object): Promise<YoutubeDLSubs> {
}) })
} }
function getYoutubeDLVideoFormat () { getYoutubeDLVideoFormat () {
/** /**
* list of format selectors in order or preference * list of format selectors in order or preference
* see https://github.com/ytdl-org/youtube-dl#format-selection * see https://github.com/ytdl-org/youtube-dl#format-selection
@ -108,10 +113,9 @@ function getYoutubeDLVideoFormat () {
* *
* in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499 * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499
**/ **/
const enabledResolutions = getEnabledResolutions('vod') const resolution = this.enabledResolutions.length === 0
const resolution = enabledResolutions.length === 0
? VideoResolution.H_720P ? VideoResolution.H_720P
: Math.max(...enabledResolutions) : Math.max(...this.enabledResolutions)
return [ return [
`bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1 `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1
@ -123,27 +127,27 @@ function getYoutubeDLVideoFormat () {
].join('/') ].join('/')
} }
function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number) { downloadYoutubeDLVideo (fileExt: string, timeout: number) {
// Leave empty the extension, youtube-dl will add it // Leave empty the extension, youtube-dl will add it
const pathWithoutExtension = generateVideoImportTmpPath(url, '') const pathWithoutExtension = generateVideoImportTmpPath(this.url, '')
let timer let timer
logger.info('Importing youtubeDL video %s to %s', url, pathWithoutExtension) logger.info('Importing youtubeDL video %s to %s', this.url, pathWithoutExtension)
let options = [ '-f', getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ] let options = [ '-f', this.getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ]
options = wrapWithProxyOptions(options) options = this.wrapWithProxyOptions(options)
if (process.env.FFMPEG_PATH) { if (process.env.FFMPEG_PATH) {
options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ]) options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
} }
logger.debug('YoutubeDL options for %s.', url, { options }) logger.debug('YoutubeDL options for %s.', this.url, { options })
return new Promise<string>((res, rej) => { return new Promise<string>((res, rej) => {
safeGetYoutubeDL() YoutubeDL.safeGetYoutubeDL()
.then(youtubeDL => { .then(youtubeDL => {
youtubeDL.exec(url, options, processOptions, async err => { youtubeDL.exec(this.url, options, processOptions, async err => {
clearTimeout(timer) clearTimeout(timer)
try { try {
@ -152,7 +156,7 @@ function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number)
await move(pathWithoutExtension, pathWithoutExtension + '.mp4') await move(pathWithoutExtension, pathWithoutExtension + '.mp4')
} }
const path = await guessVideoPathWithExtension(pathWithoutExtension, fileExt) const path = await this.guessVideoPathWithExtension(pathWithoutExtension, fileExt)
if (err) { if (err) {
remove(path) remove(path)
@ -170,7 +174,7 @@ function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number)
timer = setTimeout(() => { timer = setTimeout(() => {
const err = new Error('YoutubeDL download timeout.') const err = new Error('YoutubeDL download timeout.')
guessVideoPathWithExtension(pathWithoutExtension, fileExt) this.guessVideoPathWithExtension(pathWithoutExtension, fileExt)
.then(path => remove(path)) .then(path => remove(path))
.finally(() => rej(err)) .finally(() => rej(err))
.catch(err => { .catch(err => {
@ -183,9 +187,152 @@ function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number)
}) })
} }
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 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
// We rewrote it to avoid sync calls // We rewrote it to avoid sync calls
async function updateYoutubeDLBinary () { static async updateYoutubeDLBinary () {
logger.info('Updating youtubeDL binary.') logger.info('Updating youtubeDL binary.')
const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin') const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
@ -223,173 +370,23 @@ async function updateYoutubeDLBinary () {
} }
} }
async function safeGetYoutubeDL () { static async safeGetYoutubeDL () {
let youtubeDL let youtubeDL
try { try {
youtubeDL = require('youtube-dl') youtubeDL = require('youtube-dl')
} catch (e) { } catch (e) {
// Download binary // Download binary
await updateYoutubeDLBinary() await this.updateYoutubeDLBinary()
youtubeDL = require('youtube-dl') youtubeDL = require('youtube-dl')
} }
return youtubeDL return youtubeDL
} }
function 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
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export { export {
updateYoutubeDLBinary, YoutubeDL
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
} }

View File

@ -6,7 +6,6 @@ import { RegisteredExternalAuthConfig, RegisteredIdAndPassAuthConfig, ServerConf
import { Hooks } from './plugins/hooks' import { Hooks } from './plugins/hooks'
import { PluginManager } from './plugins/plugin-manager' import { PluginManager } from './plugins/plugin-manager'
import { getThemeOrDefault } from './plugins/theme-utils' import { getThemeOrDefault } from './plugins/theme-utils'
import { getEnabledResolutions } from './video-transcoding'
import { VideoTranscodingProfilesManager } from './video-transcoding-profiles' import { VideoTranscodingProfilesManager } from './video-transcoding-profiles'
let serverCommit: string 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 { export {
getServerConfig, getServerConfig,
getRegisteredThemes, getRegisteredThemes,
getEnabledResolutions,
getRegisteredPlugins getRegisteredPlugins
} }

View File

@ -23,7 +23,6 @@ import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } fro
import { logger } from '../../../helpers/logger' import { logger } from '../../../helpers/logger'
import { getSecureTorrentName } from '../../../helpers/utils' import { getSecureTorrentName } from '../../../helpers/utils'
import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent' import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
import { CONFIG } from '../../../initializers/config' import { CONFIG } from '../../../initializers/config'
import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants' import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
import { sequelizeTypescript } from '../../../initializers/database' import { sequelizeTypescript } from '../../../initializers/database'
@ -34,6 +33,8 @@ import { MThumbnail } from '../../../types/models/video/thumbnail'
import { federateVideoIfNeeded } from '../../activitypub/videos' import { federateVideoIfNeeded } from '../../activitypub/videos'
import { Notifier } from '../../notifier' import { Notifier } from '../../notifier'
import { generateVideoMiniature } from '../../thumbnail' import { generateVideoMiniature } from '../../thumbnail'
import { YoutubeDL } from '@server/helpers/youtube-dl'
import { getEnabledResolutions } from '@server/lib/config'
async function processVideoImport (job: Bull.Job) { async function processVideoImport (job: Bull.Job) {
const payload = job.data as VideoImportPayload const payload = job.data as VideoImportPayload
@ -75,8 +76,10 @@ async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutub
videoImportId: videoImport.id videoImportId: videoImport.id
} }
const youtubeDL = new YoutubeDL(videoImport.targetUrl, getEnabledResolutions('vod'))
return processFile( return processFile(
() => downloadYoutubeDLVideo(videoImport.targetUrl, payload.fileExt, VIDEO_IMPORT_TIMEOUT), () => youtubeDL.downloadYoutubeDLVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT),
videoImport, videoImport,
options options
) )

View File

@ -1,6 +1,6 @@
import { AbstractScheduler } from './abstract-scheduler' import { YoutubeDL } from '@server/helpers/youtube-dl'
import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants' import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants'
import { updateYoutubeDLBinary } from '../../helpers/youtube-dl' import { AbstractScheduler } from './abstract-scheduler'
export class YoutubeDlUpdateScheduler extends AbstractScheduler { export class YoutubeDlUpdateScheduler extends AbstractScheduler {
@ -13,7 +13,7 @@ export class YoutubeDlUpdateScheduler extends AbstractScheduler {
} }
protected internalExecute () { protected internalExecute () {
return updateYoutubeDLBinary() return YoutubeDL.updateYoutubeDLBinary()
} }
static get Instance () { static get Instance () {

View File

@ -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 { export {
@ -232,8 +222,7 @@ export {
generateHlsPlaylistResolutionFromTS, generateHlsPlaylistResolutionFromTS,
optimizeOriginalVideofile, optimizeOriginalVideofile,
transcodeNewWebTorrentResolution, transcodeNewWebTorrentResolution,
mergeAudioVideofile, mergeAudioVideofile
getEnabledResolutions
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------

View File

@ -11,9 +11,9 @@ import { promisify } from 'util'
import { advancedVideosSearch, getClient, getVideoCategories, login, uploadVideo } from '../../shared/extra-utils/index' import { advancedVideosSearch, getClient, getVideoCategories, login, uploadVideo } from '../../shared/extra-utils/index'
import { sha256 } from '../helpers/core-utils' import { sha256 } from '../helpers/core-utils'
import { doRequestAndSaveToFile } from '../helpers/requests' import { doRequestAndSaveToFile } from '../helpers/requests'
import { buildOriginallyPublishedAt, getYoutubeDLVideoFormat, safeGetYoutubeDL } from '../helpers/youtube-dl'
import { CONSTRAINTS_FIELDS } from '../initializers/constants' import { CONSTRAINTS_FIELDS } from '../initializers/constants'
import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli' import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli'
import { YoutubeDL } from '@server/helpers/youtube-dl'
type UserInfo = { type UserInfo = {
username: string username: string
@ -74,9 +74,9 @@ async function run (url: string, user: UserInfo) {
user.password = await promptPassword() 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 ] if (!Array.isArray(info)) info = [ info ]
@ -86,7 +86,7 @@ async function run (url: string, user: UserInfo) {
if (uploadsObject) { if (uploadsObject) {
console.log('Fixing URL to %s.', uploadsObject.url) 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[] let infoArray: any[]
@ -130,13 +130,14 @@ async function processVideo (parameters: {
youtubeInfo: any youtubeInfo: any
}) { }) {
const { youtubeInfo, cwd, url, user } = parameters const { youtubeInfo, cwd, url, user } = parameters
const youtubeDL = new YoutubeDL('', [])
log.debug('Fetching object.', youtubeInfo) log.debug('Fetching object.', youtubeInfo)
const videoInfo = await fetchObject(youtubeInfo) const videoInfo = await fetchObject(youtubeInfo)
log.debug('Fetched object.', videoInfo) log.debug('Fetched object.', videoInfo)
const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo) const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo)
if (options.since && originallyPublishedAt && originallyPublishedAt.getTime() < options.since.getTime()) { if (options.since && originallyPublishedAt && originallyPublishedAt.getTime() < options.since.getTime()) {
log.info('Video "%s" has been published before "%s", don\'t upload it.\n', log.info('Video "%s" has been published before "%s", don\'t upload it.\n',
videoInfo.title, formatDate(options.since)) videoInfo.title, formatDate(options.since))
@ -161,13 +162,14 @@ async function processVideo (parameters: {
log.info('Downloading video "%s"...', videoInfo.title) 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 { try {
const youtubeDL = await safeGetYoutubeDL() const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL()
const youtubeDLExec = promisify(youtubeDL.exec).bind(youtubeDL) const youtubeDLExec = promisify(youtubeDLBinary.exec).bind(youtubeDLBinary)
const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions) const output = await youtubeDLExec(videoInfo.url, youtubeDLOptions, processOptions)
log.info(output.join('\n')) log.info(output.join('\n'))
await uploadVideoOnPeerTube({ await uploadVideoOnPeerTube({
youtubeDL,
cwd, cwd,
url, url,
user, user,
@ -180,13 +182,14 @@ async function processVideo (parameters: {
} }
async function uploadVideoOnPeerTube (parameters: { async function uploadVideoOnPeerTube (parameters: {
youtubeDL: YoutubeDL
videoInfo: any videoInfo: any
videoPath: string videoPath: string
cwd: string cwd: string
url: string url: string
user: { username: string, password: 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 category = await getCategory(videoInfo.categories, url)
const licence = getLicence(videoInfo.license) const licence = getLicence(videoInfo.license)
@ -205,7 +208,7 @@ async function uploadVideoOnPeerTube (parameters: {
await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile) await doRequestAndSaveToFile(videoInfo.thumbnail, thumbnailfile)
} }
const originallyPublishedAt = buildOriginallyPublishedAt(videoInfo) const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo)
const defaultAttributes = { const defaultAttributes = {
name: truncate(videoInfo.title, { name: truncate(videoInfo.title, {
@ -304,7 +307,7 @@ function fetchObject (info: any) {
const url = buildUrl(info) const url = buildUrl(info)
return new Promise<any>(async (res, rej) => { return new Promise<any>(async (res, rej) => {
const youtubeDL = await safeGetYoutubeDL() const youtubeDL = await YoutubeDL.safeGetYoutubeDL()
youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => { youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => {
if (err) return rej(err) if (err) return rej(err)