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