]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/youtube-dl.ts
Downsample to the closest divisor standard framerate
[github/Chocobozzz/PeerTube.git] / server / helpers / youtube-dl.ts
CommitLineData
74dc3bca 1import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers/constants'
fbad87b0 2import { logger } from './logger'
6040f87d 3import { generateVideoImportTmpPath } from './utils'
606c946e 4import { join } from 'path'
687c6180
C
5import { peertubeTruncate, root } from './core-utils'
6import { ensureDir, remove, writeFile } from 'fs-extra'
606c946e
C
7import * as request from 'request'
8import { createWriteStream } from 'fs'
be7ca0c6 9import { CONFIG } from '@server/initializers/config'
fbad87b0
C
10
11export type YoutubeDLInfo = {
ce33919c
C
12 name?: string
13 description?: string
14 category?: number
15 licence?: number
16 nsfw?: boolean
17 tags?: string[]
18 thumbnailUrl?: string
c74c9be9 19 originallyPublishedAt?: Date
fbad87b0
C
20}
21
cc680494
C
22const processOptions = {
23 maxBuffer: 1024 * 1024 * 10 // 10MB
24}
25
8704acf4 26function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
4f1f6f03 27 return new Promise<YoutubeDLInfo>(async (res, rej) => {
93905586
C
28 let args = opts || [ '-j', '--flat-playlist' ]
29 args = wrapWithProxyOptions(args)
fbad87b0 30
4f1f6f03 31 const youtubeDL = await safeGetYoutubeDL()
9fa0ea41 32 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
fbad87b0 33 if (err) return rej(err)
1a893f9c 34 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
fbad87b0 35
5d112d0c
C
36 const obj = buildVideoInfo(normalizeObject(info))
37 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
fbad87b0 38
5d112d0c 39 return res(obj)
fbad87b0
C
40 })
41 })
42}
43
cf9166cf 44function downloadYoutubeDLVideo (url: string, timeout: number) {
6040f87d 45 const path = generateVideoImportTmpPath(url)
cf9166cf 46 let timer
fbad87b0 47
ce33919c 48 logger.info('Importing youtubeDL video %s', url)
fbad87b0 49
be7ca0c6 50 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
93905586 51 options = wrapWithProxyOptions(options)
fbad87b0 52
5322589d 53 if (process.env.FFMPEG_PATH) {
be7ca0c6 54 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
5322589d
C
55 }
56
4f1f6f03
C
57 return new Promise<string>(async (res, rej) => {
58 const youtubeDL = await safeGetYoutubeDL()
cc680494 59 youtubeDL.exec(url, options, processOptions, err => {
cf9166cf
C
60 clearTimeout(timer)
61
62 if (err) {
63 remove(path)
64 .catch(err => logger.error('Cannot delete path on YoutubeDL error.', { err }))
65
66 return rej(err)
67 }
fbad87b0
C
68
69 return res(path)
70 })
cf9166cf
C
71
72 timer = setTimeout(async () => {
73 await remove(path)
74
75 return rej(new Error('YoutubeDL download timeout.'))
76 }, timeout)
fbad87b0
C
77 })
78}
79
606c946e
C
80// Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
81// We rewrote it to avoid sync calls
82async function updateYoutubeDLBinary () {
83 logger.info('Updating youtubeDL binary.')
84
85 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
86 const bin = join(binDirectory, 'youtube-dl')
87 const detailsPath = join(binDirectory, 'details')
88 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
89
90 await ensureDir(binDirectory)
91
92 return new Promise(res => {
93 request.get(url, { followRedirect: false }, (err, result) => {
94 if (err) {
95 logger.error('Cannot update youtube-dl.', { err })
96 return res()
97 }
98
99 if (result.statusCode !== 302) {
100 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
101 return res()
102 }
103
104 const url = result.headers.location
105 const downloadFile = request.get(url)
106 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
107
108 downloadFile.on('response', result => {
109 if (result.statusCode !== 200) {
110 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
111 return res()
112 }
113
114 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
115 })
116
117 downloadFile.on('error', err => {
118 logger.error('youtube-dl update error.', { err })
119 return res()
120 })
121
122 downloadFile.on('end', () => {
123 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
124 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
125 if (err) {
126 logger.error('youtube-dl update error: cannot write details.', { err })
127 return res()
128 }
129
130 logger.info('youtube-dl updated to version %s.', newVersion)
131 return res()
132 })
133 })
134 })
135 })
136}
137
4f1f6f03
C
138async function safeGetYoutubeDL () {
139 let youtubeDL
140
141 try {
142 youtubeDL = require('youtube-dl')
143 } catch (e) {
144 // Download binary
606c946e 145 await updateYoutubeDLBinary()
4f1f6f03
C
146 youtubeDL = require('youtube-dl')
147 }
148
149 return youtubeDL
150}
151
c74c9be9
C
152function buildOriginallyPublishedAt (obj: any) {
153 let originallyPublishedAt: Date = null
154
155 const uploadDateMatcher = /^(\d{4})(\d{2})(\d{2})$/.exec(obj.upload_date)
156 if (uploadDateMatcher) {
157 originallyPublishedAt = new Date()
158 originallyPublishedAt.setHours(0, 0, 0, 0)
159
160 const year = parseInt(uploadDateMatcher[1], 10)
161 // Month starts from 0
162 const month = parseInt(uploadDateMatcher[2], 10) - 1
163 const day = parseInt(uploadDateMatcher[3], 10)
164
165 originallyPublishedAt.setFullYear(year, month, day)
166 }
167
168 return originallyPublishedAt
169}
170
8704acf4
RK
171// ---------------------------------------------------------------------------
172
173export {
0491173a 174 updateYoutubeDLBinary,
8704acf4
RK
175 downloadYoutubeDLVideo,
176 getYoutubeDLInfo,
c74c9be9
C
177 safeGetYoutubeDL,
178 buildOriginallyPublishedAt
8704acf4
RK
179}
180
181// ---------------------------------------------------------------------------
182
fbad87b0
C
183function normalizeObject (obj: any) {
184 const newObj: any = {}
185
186 for (const key of Object.keys(obj)) {
187 // Deprecated key
188 if (key === 'resolution') continue
189
190 const value = obj[key]
191
192 if (typeof value === 'string') {
193 newObj[key] = value.normalize()
194 } else {
195 newObj[key] = value
196 }
197 }
198
199 return newObj
200}
201
202function buildVideoInfo (obj: any) {
203 return {
204 name: titleTruncation(obj.title),
205 description: descriptionTruncation(obj.description),
206 category: getCategory(obj.categories),
207 licence: getLicence(obj.license),
208 nsfw: isNSFW(obj),
209 tags: getTags(obj.tags),
4e553a41 210 thumbnailUrl: obj.thumbnail || undefined,
c74c9be9 211 originallyPublishedAt: buildOriginallyPublishedAt(obj)
fbad87b0
C
212 }
213}
214
215function titleTruncation (title: string) {
687c6180
C
216 return peertubeTruncate(title, {
217 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
218 separator: /,? +/,
219 omission: ' […]'
fbad87b0
C
220 })
221}
222
223function descriptionTruncation (description: string) {
ed31c059 224 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
fbad87b0 225
687c6180
C
226 return peertubeTruncate(description, {
227 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
228 separator: /,? +/,
229 omission: ' […]'
fbad87b0
C
230 })
231}
232
233function isNSFW (info: any) {
234 return info.age_limit && info.age_limit >= 16
235}
236
237function getTags (tags: any) {
238 if (Array.isArray(tags) === false) return []
239
240 return tags
241 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
242 .map(t => t.normalize())
243 .slice(0, 5)
244}
245
246function getLicence (licence: string) {
247 if (!licence) return undefined
248
590fb506 249 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
fbad87b0
C
250
251 return undefined
252}
253
254function getCategory (categories: string[]) {
255 if (!categories) return undefined
256
257 const categoryString = categories[0]
258 if (!categoryString || typeof categoryString !== 'string') return undefined
259
260 if (categoryString === 'News & Politics') return 11
261
262 for (const key of Object.keys(VIDEO_CATEGORIES)) {
263 const category = VIDEO_CATEGORIES[key]
264 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
265 }
266
267 return undefined
268}
93905586
C
269
270function wrapWithProxyOptions (options: string[]) {
271 if (CONFIG.IMPORT.VIDEOS.HTTP.PROXY.ENABLED) {
272 logger.debug('Using proxy for YoutubeDL')
273
274 return [ '--proxy', CONFIG.IMPORT.VIDEOS.HTTP.PROXY.URL ].concat(options)
275 }
276
277 return options
278}