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