]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/youtube-dl.ts
db2bddf78cc3af8acd1beae2d016b858b8c06163
[github/Chocobozzz/PeerTube.git] / server / helpers / youtube-dl.ts
1 import { truncate } from 'lodash'
2 import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers'
3 import { logger } from './logger'
4 import { generateVideoTmpPath } from './utils'
5 import { join } from 'path'
6 import { root } from './core-utils'
7 import { ensureDir, writeFile } from 'fs-extra'
8 import * as request from 'request'
9 import { createWriteStream } from 'fs'
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 }
20
21 function getYoutubeDLInfo (url: string): Promise<YoutubeDLInfo> {
22 return new Promise<YoutubeDLInfo>(async (res, rej) => {
23 const options = [ '-j', '--flat-playlist' ]
24
25 const youtubeDL = await safeGetYoutubeDL()
26 youtubeDL.getInfo(url, options, (err, info) => {
27 if (err) return rej(err)
28 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
29
30 const obj = buildVideoInfo(normalizeObject(info))
31 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
32
33 return res(obj)
34 })
35 })
36 }
37
38 function downloadYoutubeDLVideo (url: string) {
39 const path = generateVideoTmpPath(url)
40
41 logger.info('Importing youtubeDL video %s', url)
42
43 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
44
45 return new Promise<string>(async (res, rej) => {
46 const youtubeDL = await safeGetYoutubeDL()
47 youtubeDL.exec(url, options, err => {
48 if (err) return rej(err)
49
50 return res(path)
51 })
52 })
53 }
54
55 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
56 // We rewrote it to avoid sync calls
57 async function updateYoutubeDLBinary () {
58 logger.info('Updating youtubeDL binary.')
59
60 const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin')
61 const bin = join(binDirectory, 'youtube-dl')
62 const detailsPath = join(binDirectory, 'details')
63 const url = 'https://yt-dl.org/downloads/latest/youtube-dl'
64
65 await ensureDir(binDirectory)
66
67 return new Promise(res => {
68 request.get(url, { followRedirect: false }, (err, result) => {
69 if (err) {
70 logger.error('Cannot update youtube-dl.', { err })
71 return res()
72 }
73
74 if (result.statusCode !== 302) {
75 logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', result.statusCode)
76 return res()
77 }
78
79 const url = result.headers.location
80 const downloadFile = request.get(url)
81 const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[ 1 ]
82
83 downloadFile.on('response', result => {
84 if (result.statusCode !== 200) {
85 logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', result.statusCode)
86 return res()
87 }
88
89 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
90 })
91
92 downloadFile.on('error', err => {
93 logger.error('youtube-dl update error.', { err })
94 return res()
95 })
96
97 downloadFile.on('end', () => {
98 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
99 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
100 if (err) {
101 logger.error('youtube-dl update error: cannot write details.', { err })
102 return res()
103 }
104
105 logger.info('youtube-dl updated to version %s.', newVersion)
106 return res()
107 })
108 })
109 })
110 })
111 }
112
113 // ---------------------------------------------------------------------------
114
115 export {
116 updateYoutubeDLBinary,
117 downloadYoutubeDLVideo,
118 getYoutubeDLInfo
119 }
120
121 // ---------------------------------------------------------------------------
122
123 async function safeGetYoutubeDL () {
124 let youtubeDL
125
126 try {
127 youtubeDL = require('youtube-dl')
128 } catch (e) {
129 // Download binary
130 await updateYoutubeDLBinary()
131 youtubeDL = require('youtube-dl')
132 }
133
134 return youtubeDL
135 }
136
137 function normalizeObject (obj: any) {
138 const newObj: any = {}
139
140 for (const key of Object.keys(obj)) {
141 // Deprecated key
142 if (key === 'resolution') continue
143
144 const value = obj[key]
145
146 if (typeof value === 'string') {
147 newObj[key] = value.normalize()
148 } else {
149 newObj[key] = value
150 }
151 }
152
153 return newObj
154 }
155
156 function buildVideoInfo (obj: any) {
157 return {
158 name: titleTruncation(obj.title),
159 description: descriptionTruncation(obj.description),
160 category: getCategory(obj.categories),
161 licence: getLicence(obj.license),
162 nsfw: isNSFW(obj),
163 tags: getTags(obj.tags),
164 thumbnailUrl: obj.thumbnail || undefined
165 }
166 }
167
168 function titleTruncation (title: string) {
169 return truncate(title, {
170 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
171 'separator': /,? +/,
172 'omission': ' […]'
173 })
174 }
175
176 function descriptionTruncation (description: string) {
177 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
178
179 return truncate(description, {
180 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
181 'separator': /,? +/,
182 'omission': ' […]'
183 })
184 }
185
186 function isNSFW (info: any) {
187 return info.age_limit && info.age_limit >= 16
188 }
189
190 function getTags (tags: any) {
191 if (Array.isArray(tags) === false) return []
192
193 return tags
194 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
195 .map(t => t.normalize())
196 .slice(0, 5)
197 }
198
199 function getLicence (licence: string) {
200 if (!licence) return undefined
201
202 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
203
204 return undefined
205 }
206
207 function getCategory (categories: string[]) {
208 if (!categories) return undefined
209
210 const categoryString = categories[0]
211 if (!categoryString || typeof categoryString !== 'string') return undefined
212
213 if (categoryString === 'News & Politics') return 11
214
215 for (const key of Object.keys(VIDEO_CATEGORIES)) {
216 const category = VIDEO_CATEGORIES[key]
217 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
218 }
219
220 return undefined
221 }