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