]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/youtube-dl.ts
Add RSS feed to subscribe button
[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'
ce33919c 4import { generateVideoTmpPath } from './utils'
606c946e
C
5import { join } from 'path'
6import { root } from './core-utils'
7import { ensureDir, writeFile } from 'fs-extra'
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
fbad87b0
C
19}
20
8704acf4 21function getYoutubeDLInfo (url: string, opts?: string[]): Promise<YoutubeDLInfo> {
4f1f6f03 22 return new Promise<YoutubeDLInfo>(async (res, rej) => {
8704acf4 23 const options = opts || [ '-j', '--flat-playlist' ]
fbad87b0 24
4f1f6f03 25 const youtubeDL = await safeGetYoutubeDL()
fbad87b0
C
26 youtubeDL.getInfo(url, options, (err, info) => {
27 if (err) return rej(err)
1a893f9c 28 if (info.is_live === true) return rej(new Error('Cannot download a live streaming.'))
fbad87b0 29
5d112d0c
C
30 const obj = buildVideoInfo(normalizeObject(info))
31 if (obj.name && obj.name.length < CONSTRAINTS_FIELDS.VIDEOS.NAME.min) obj.name += ' video'
fbad87b0 32
5d112d0c 33 return res(obj)
fbad87b0
C
34 })
35 })
36}
37
38function downloadYoutubeDLVideo (url: string) {
ce33919c 39 const path = generateVideoTmpPath(url)
fbad87b0 40
ce33919c 41 logger.info('Importing youtubeDL video %s', url)
fbad87b0
C
42
43 const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
44
4f1f6f03
C
45 return new Promise<string>(async (res, rej) => {
46 const youtubeDL = await safeGetYoutubeDL()
606c946e 47 youtubeDL.exec(url, options, err => {
fbad87b0
C
48 if (err) return rej(err)
49
50 return res(path)
51 })
52 })
53}
54
606c946e
C
55// Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
56// We rewrote it to avoid sync calls
57async 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
4f1f6f03
C
113async function safeGetYoutubeDL () {
114 let youtubeDL
115
116 try {
117 youtubeDL = require('youtube-dl')
118 } catch (e) {
119 // Download binary
606c946e 120 await updateYoutubeDLBinary()
4f1f6f03
C
121 youtubeDL = require('youtube-dl')
122 }
123
124 return youtubeDL
125}
126
8704acf4
RK
127// ---------------------------------------------------------------------------
128
129export {
0491173a 130 updateYoutubeDLBinary,
8704acf4
RK
131 downloadYoutubeDLVideo,
132 getYoutubeDLInfo,
133 safeGetYoutubeDL
134}
135
136// ---------------------------------------------------------------------------
137
fbad87b0
C
138function normalizeObject (obj: any) {
139 const newObj: any = {}
140
141 for (const key of Object.keys(obj)) {
142 // Deprecated key
143 if (key === 'resolution') continue
144
145 const value = obj[key]
146
147 if (typeof value === 'string') {
148 newObj[key] = value.normalize()
149 } else {
150 newObj[key] = value
151 }
152 }
153
154 return newObj
155}
156
157function buildVideoInfo (obj: any) {
158 return {
159 name: titleTruncation(obj.title),
160 description: descriptionTruncation(obj.description),
161 category: getCategory(obj.categories),
162 licence: getLicence(obj.license),
163 nsfw: isNSFW(obj),
164 tags: getTags(obj.tags),
165 thumbnailUrl: obj.thumbnail || undefined
166 }
167}
168
169function titleTruncation (title: string) {
170 return truncate(title, {
171 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
172 'separator': /,? +/,
173 'omission': ' […]'
174 })
175}
176
177function descriptionTruncation (description: string) {
ed31c059 178 if (!description || description.length < CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.min) return undefined
fbad87b0
C
179
180 return truncate(description, {
181 'length': CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max,
182 'separator': /,? +/,
183 'omission': ' […]'
184 })
185}
186
187function isNSFW (info: any) {
188 return info.age_limit && info.age_limit >= 16
189}
190
191function getTags (tags: any) {
192 if (Array.isArray(tags) === false) return []
193
194 return tags
195 .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
196 .map(t => t.normalize())
197 .slice(0, 5)
198}
199
200function getLicence (licence: string) {
201 if (!licence) return undefined
202
590fb506 203 if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
fbad87b0
C
204
205 return undefined
206}
207
208function getCategory (categories: string[]) {
209 if (!categories) return undefined
210
211 const categoryString = categories[0]
212 if (!categoryString || typeof categoryString !== 'string') return undefined
213
214 if (categoryString === 'News & Politics') return 11
215
216 for (const key of Object.keys(VIDEO_CATEGORIES)) {
217 const category = VIDEO_CATEGORIES[key]
218 if (categoryString.toLowerCase() === category.toLowerCase()) return parseInt(key, 10)
219 }
220
221 return undefined
222}