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