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