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