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