]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/youtube-dl.ts
Don't expose constants directly in initializers/
[github/Chocobozzz/PeerTube.git] / server / helpers / youtube-dl.ts
CommitLineData
fbad87b0 1import { truncate } from 'lodash'
74dc3bca 2import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers/constants'
fbad87b0 3import { logger } from './logger'
6040f87d 4import { generateVideoImportTmpPath } from './utils'
606c946e
C
5import { join } from 'path'
6import { root } from './core-utils'
cf9166cf 7import { ensureDir, writeFile, remove } from 'fs-extra'
606c946e
C
8import * as request from 'request'
9import { createWriteStream } from 'fs'
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> {
4f1f6f03 27 return new Promise<YoutubeDLInfo>(async (res, rej) => {
9fa0ea41 28 const args = opts || [ '-j', '--flat-playlist' ]
fbad87b0 29
4f1f6f03 30 const youtubeDL = await safeGetYoutubeDL()
9fa0ea41 31 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
fbad87b0 32 if (err) return rej(err)
1a893f9c 33 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
fbad87b0 34
5d112d0c
C
35 const obj = buildVideoInfo(normalizeObject(info))
36 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
fbad87b0 37
5d112d0c 38 return res(obj)
fbad87b0
C
39 })
40 })
41}
42
cf9166cf 43function downloadYoutubeDLVideo (url: string, timeout: number) {
6040f87d 44 const path = generateVideoImportTmpPath(url)
cf9166cf 45 let timer
fbad87b0 46
ce33919c 47 logger.info('Importing youtubeDL video %s', url)
fbad87b0
C
48
49 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
50
5322589d
C
51 if (process.env.FFMPEG_PATH) {
52 options.push('--ffmpeg-location')
53 options.push(process.env.FFMPEG_PATH)
54 }
55
4f1f6f03
C
56 return new Promise<string>(async (res, rej) => {
57 const youtubeDL = await safeGetYoutubeDL()
cc680494 58 youtubeDL.exec(url, options, processOptions, err => {
cf9166cf
C
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 }
fbad87b0
C
67
68 return res(path)
69 })
cf9166cf
C
70
71 timer = setTimeout(async () => {
72 await remove(path)
73
74 return rej(new Error('YoutubeDL download timeout.'))
75 }, timeout)
fbad87b0
C
76 })
77}
78
606c946e
C
79// Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
80// We rewrote it to avoid sync calls
81async 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
4f1f6f03
C
137async function safeGetYoutubeDL () {
138 let youtubeDL
139
140 try {
141 youtubeDL = require('youtube-dl')
142 } catch (e) {
143 // Download binary
606c946e 144 await updateYoutubeDLBinary()
4f1f6f03
C
145 youtubeDL = require('youtube-dl')
146 }
147
148 return youtubeDL
149}
150
c74c9be9
C
151function 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
8704acf4
RK
170// ---------------------------------------------------------------------------
171
172export {
0491173a 173 updateYoutubeDLBinary,
8704acf4
RK
174 downloadYoutubeDLVideo,
175 getYoutubeDLInfo,
c74c9be9
C
176 safeGetYoutubeDL,
177 buildOriginallyPublishedAt
8704acf4
RK
178}
179
180// ---------------------------------------------------------------------------
181
fbad87b0
C
182function 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
201function 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),
4e553a41 209 thumbnailUrl: obj.thumbnail || undefined,
c74c9be9 210 originallyPublishedAt: buildOriginallyPublishedAt(obj)
fbad87b0
C
211 }
212}
213
214function titleTruncation (title: string) {
215 return truncate(title, {
216 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
217 'separator': /,? +/,
218 'omission': ' […]'
219 })
220}
221
222function descriptionTruncation (description: string) {
ed31c059 223 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
fbad87b0
C
224
225 return truncate(description, {
226 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
227 'separator': /,? +/,
228 'omission': ' […]'
229 })
230}
231
232function isNSFW (info: any) {
233 return info.age_limit && info.age_limit >= 16
234}
235
236function 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
245function getLicence (licence: string) {
246 if (!licence) return undefined
247
590fb506 248 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
fbad87b0
C
249
250 return undefined
251}
252
253function 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}