]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/youtube-dl.ts
Fix transcoding
[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 originallyPublishedAt?: Date
20 }
21
22 const processOptions = {
23 maxBuffer: 1024 * 1024 * 10 // 10MB
24 }
25
26 function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
27 return new Promise<YoutubeDLInfo>(async (res, rej) => {
28 let args = opts || [ '-j', '--flat-playlist' ]
29 args = wrapWithProxyOptions(args)
30
31 const youtubeDL = await safeGetYoutubeDL()
32 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
33 if (err) return rej(err)
34 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
35
36 const obj = buildVideoInfo(normalizeObject(info))
37 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
38
39 return res(obj)
40 })
41 })
42 }
43
44 function downloadYoutubeDLVideo (url: string, timeout: number) {
45 const path = generateVideoImportTmpPath(url)
46 let timer
47
48 logger.info('Importing youtubeDL video %s', url)
49
50 let options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
51 options = wrapWithProxyOptions(options)
52
53 if (process.env.FFMPEG_PATH) {
54 options = options.concat([ '--ffmpeg-location', process.env.FFMPEG_PATH ])
55 }
56
57 return new Promise<string>(async (res, rej) => {
58 const youtubeDL = await safeGetYoutubeDL()
59 youtubeDL.exec(url, options, processOptions, err => {
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 }
68
69 return res(path)
70 })
71
72 timer = setTimeout(async () => {
73 await remove(path)
74
75 return rej(new Error('YoutubeDL download timeout.'))
76 }, timeout)
77 })
78 }
79
80 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
81 // We rewrote it to avoid sync calls
82 async 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
138 async function safeGetYoutubeDL () {
139 let youtubeDL
140
141 try {
142 youtubeDL = require('youtube-dl')
143 } catch (e) {
144 // Download binary
145 await updateYoutubeDLBinary()
146 youtubeDL = require('youtube-dl')
147 }
148
149 return youtubeDL
150 }
151
152 function 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
171 // ---------------------------------------------------------------------------
172
173 export {
174 updateYoutubeDLBinary,
175 downloadYoutubeDLVideo,
176 getYoutubeDLInfo,
177 safeGetYoutubeDL,
178 buildOriginallyPublishedAt
179 }
180
181 // ---------------------------------------------------------------------------
182
183 function 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
202 function 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),
210 thumbnailUrl: obj.thumbnail || undefined,
211 originallyPublishedAt: buildOriginallyPublishedAt(obj)
212 }
213 }
214
215 function titleTruncation (title: string) {
216 return peertubeTruncate(title, {
217 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
218 separator: /,? +/,
219 omission: ' […]'
220 })
221 }
222
223 function descriptionTruncation (description: string) {
224 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
225
226 return peertubeTruncate(description, {
227 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
228 separator: /,? +/,
229 omission: ' […]'
230 })
231 }
232
233 function isNSFW (info: any) {
234 return info.age_limit && info.age_limit >= 16
235 }
236
237 function 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
246 function getLicence (licence: string) {
247 if (!licence) return undefined
248
249 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
250
251 return undefined
252 }
253
254 function 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 }
269
270 function 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 }