]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/youtube-dl.ts
Add audio-only option to transcoders and player
[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'
fbad87b0
C
9
10export type YoutubeDLInfo = {
ce33919c
C
11 name?: string
12 description?: string
13 category?: number
14 licence?: number
15 nsfw?: boolean
16 tags?: string[]
17 thumbnailUrl?: string
c74c9be9 18 originallyPublishedAt?: Date
fbad87b0
C
19}
20
cc680494
C
21const processOptions = {
22 maxBuffer: 1024 * 1024 * 10 // 10MB
23}
24
8704acf4 25function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
4f1f6f03 26 return new Promise<YoutubeDLInfo>(async (res, rej) => {
9fa0ea41 27 const args = opts || [ '-j', '--flat-playlist' ]
fbad87b0 28
4f1f6f03 29 const youtubeDL = await safeGetYoutubeDL()
9fa0ea41 30 youtubeDL.getInfo(url, args, processOptions, (err, info) => {
fbad87b0 31 if (err) return rej(err)
1a893f9c 32 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
fbad87b0 33
5d112d0c
C
34 const obj = buildVideoInfo(normalizeObject(info))
35 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
fbad87b0 36
5d112d0c 37 return res(obj)
fbad87b0
C
38 })
39 })
40}
41
cf9166cf 42function downloadYoutubeDLVideo (url: string, timeout: number) {
6040f87d 43 const path = generateVideoImportTmpPath(url)
cf9166cf 44 let timer
fbad87b0 45
ce33919c 46 logger.info('Importing youtubeDL video %s', url)
fbad87b0
C
47
48 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
49
5322589d
C
50 if (process.env.FFMPEG_PATH) {
51 options.push('--ffmpeg-location')
52 options.push(process.env.FFMPEG_PATH)
53 }
54
4f1f6f03
C
55 return new Promise<string>(async (res, rej) => {
56 const youtubeDL = await safeGetYoutubeDL()
cc680494 57 youtubeDL.exec(url, options, processOptions, err => {
cf9166cf
C
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 }
fbad87b0
C
66
67 return res(path)
68 })
cf9166cf
C
69
70 timer = setTimeout(async () => {
71 await remove(path)
72
73 return rej(new Error('YoutubeDL download timeout.'))
74 }, timeout)
fbad87b0
C
75 })
76}
77
606c946e
C
78// Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
79// We rewrote it to avoid sync calls
80async 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
4f1f6f03
C
136async function safeGetYoutubeDL () {
137 let youtubeDL
138
139 try {
140 youtubeDL = require('youtube-dl')
141 } catch (e) {
142 // Download binary
606c946e 143 await updateYoutubeDLBinary()
4f1f6f03
C
144 youtubeDL = require('youtube-dl')
145 }
146
147 return youtubeDL
148}
149
c74c9be9
C
150function 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
8704acf4
RK
169// ---------------------------------------------------------------------------
170
171export {
0491173a 172 updateYoutubeDLBinary,
8704acf4
RK
173 downloadYoutubeDLVideo,
174 getYoutubeDLInfo,
c74c9be9
C
175 safeGetYoutubeDL,
176 buildOriginallyPublishedAt
8704acf4
RK
177}
178
179// ---------------------------------------------------------------------------
180
fbad87b0
C
181function 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
200function 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),
4e553a41 208 thumbnailUrl: obj.thumbnail || undefined,
c74c9be9 209 originallyPublishedAt: buildOriginallyPublishedAt(obj)
fbad87b0
C
210 }
211}
212
213function titleTruncation (title: string) {
687c6180
C
214 return peertubeTruncate(title, {
215 length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
216 separator: /,? +/,
217 omission: ' […]'
fbad87b0
C
218 })
219}
220
221function descriptionTruncation (description: string) {
ed31c059 222 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
fbad87b0 223
687c6180
C
224 return peertubeTruncate(description, {
225 length: CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
226 separator: /,? +/,
227 omission: ' […]'
fbad87b0
C
228 })
229}
230
231function isNSFW (info: any) {
232 return info.age_limit && info.age_limit >= 16
233}
234
235function 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
244function getLicence (licence: string) {
245 if (!licence) return undefined
246
590fb506 247 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
fbad87b0
C
248
249 return undefined
250}
251
252function 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}