-import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
-import { logger } from './logger'
-import { generateVideoImportTmpPath } from './utils'
-import { getEnabledResolutions } from '../lib/video-transcoding'
-import { join } from 'path'
-import { peertubeTruncate, root } from './core-utils'
-import { ensureDir, remove, writeFile } from 'fs-extra'
-import * as request from 'request'
import { createWriteStream } from 'fs'
+import { ensureDir, move, pathExists, remove, writeFile } from 'fs-extra'
+import got from 'got'
+import { join } from 'path'
import { CONFIG } from '@server/initializers/config'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
import { VideoResolution } from '../../shared/models/videos'
+import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants'
+import { getEnabledResolutions } from '../lib/video-transcoding'
+import { peertubeTruncate, pipelinePromise, root } from './core-utils'
+import { isVideoFileExtnameValid } from './custom-validators/videos'
+import { logger } from './logger'
+import { generateVideoImportTmpPath } from './utils'
export type YoutubeDLInfo = {
name?: string
tags?: string[]
thumbnailUrl?: string
ext?: string
- mergeExt?: string
originallyPublishedAt?: Date
}
youtubeDL.getInfo(url, args, processOptions, (err, info) => {
if (err) return rej(err)
if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
- if (info.format_id?.includes('+')) {
- // this is a merge format and its extension will be appended
- if (info.ext === 'mp4') {
- info.mergeExt = 'mp4'
- } else {
- info.mergeExt = 'mkv'
- }
- }
const obj = buildVideoInfo(normalizeObject(info))
if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
logger.debug('Get subtitles from youtube dl.', { url, files })
const subtitles = files.reduce((acc, filename) => {
- const matched = filename.match(/\.([a-z]{2})\.(vtt|ttml)/i)
+ const matched = filename.match(/\.([a-z]{2})(-[a-z]+)?\.(vtt|ttml)/i)
if (!matched || !matched[1]) return acc
return [
].join('/')
}
-function downloadYoutubeDLVideo (url: string, extension: string, timeout: number, mergeExtension?: string) {
- const path = generateVideoImportTmpPath(url, extension)
- const finalPath = mergeExtension ? path.replace(new RegExp(`${extension}$`), mergeExtension) : path
+function downloadYoutubeDLVideo (url: string, fileExt: string, timeout: number) {
+ // Leave empty the extension, youtube-dl will add it
+ const pathWithoutExtension = generateVideoImportTmpPath(url, '')
+
let timer
- logger.info('Importing youtubeDL video %s to %s', url, finalPath)
+ logger.info('Importing youtubeDL video %s to %s', url, pathWithoutExtension)
- let options = [ '-f', getYoutubeDLVideoFormat(), '-o', path ]
+ let options = [ '-f', getYoutubeDLVideoFormat(), '-o', pathWithoutExtension ]
options = wrapWithProxyOptions(options)
if (process.env.FFMPEG_PATH) {
options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
}
+ logger.debug('YoutubeDL options for %s.', url, { options })
+
return new Promise<string>((res, rej) => {
safeGetYoutubeDL()
.then(youtubeDL => {
- youtubeDL.exec(url, options, processOptions, err => {
+ youtubeDL.exec(url, options, processOptions, async err => {
clearTimeout(timer)
- if (err) {
- remove(path)
- .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
+ 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 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)
}
-
- return res(finalPath)
})
timer = setTimeout(() => {
const err = new Error('YoutubeDL download timeout.')
- remove(path)
+ guessVideoPathWithExtension(pathWithoutExtension, fileExt)
+ .then(path => remove(path))
.finally(() => rej(err))
.catch(err => {
- logger.error('Cannot remove %s in youtubeDL timeout.', path, { err })
+ logger.error('Cannot remove file in youtubeDL timeout.', { err })
return rej(err)
})
}, timeout)
await ensureDir(binDirectory)
- return new Promise(res => {
- request.get(url, { followRedirect: false }, (err, result) => {
- if (err) {
- logger.error('Cannot update youtube-dl.', { err })
- return res()
- }
-
- 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 res()
- }
-
- const url = result.headers.location
- const downloadFile = request.get(url)
- const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1]
-
- downloadFile.on('response', result => {
- if (result.statusCode !== HttpStatusCode.OK_200) {
- logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
- return res()
- }
-
- const writeStream = createWriteStream(bin, { mode: 493 }).on('error', err => {
- logger.error('youtube-dl update error in write stream', { err })
- return res()
- })
+ try {
+ const result = await got(url, { followRedirect: false })
- downloadFile.pipe(writeStream)
- })
+ 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
+ }
- downloadFile.on('error', err => {
- logger.error('youtube-dl update error.', { err })
- return res()
- })
+ const newUrl = result.headers.location
+ const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(newUrl)[1]
- downloadFile.on('end', () => {
- const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
- writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
- if (err) {
- logger.error('youtube-dl update error: cannot write details.', { err })
- return res()
- }
+ const downloadFileStream = got.stream(newUrl)
+ const writeStream = createWriteStream(bin, { mode: 493 })
- logger.info('youtube-dl updated to version %s.', newVersion)
- return res()
- })
- })
- })
- })
+ await pipelinePromise(
+ downloadFileStream,
+ writeStream
+ )
+
+ const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
+ await writeFile(detailsPath, details, { encoding: 'utf8' })
+
+ logger.info('youtube-dl updated to version %s.', newVersion)
+ } catch (err) {
+ logger.error('Cannot update youtube-dl.', { err })
+ }
}
async function safeGetYoutubeDL () {
// ---------------------------------------------------------------------------
+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 = {}
tags: getTags(obj.tags),
thumbnailUrl: obj.thumbnail || undefined,
originallyPublishedAt: buildOriginallyPublishedAt(obj),
- ext: obj.ext,
- mergeExt: obj.mergeExt
+ ext: obj.ext
}
}