]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/import.ts
More robust youtube-dl thumbnail import
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / import.ts
1 import express from 'express'
2 import { move, readFile } from 'fs-extra'
3 import { decode } from 'magnet-uri'
4 import parseTorrent, { Instance } from 'parse-torrent'
5 import { join } from 'path'
6 import { isVideoFileExtnameValid } from '@server/helpers/custom-validators/videos'
7 import { ServerConfigManager } from '@server/lib/server-config-manager'
8 import { setVideoTags } from '@server/lib/video'
9 import { FilteredModelAttributes } from '@server/types'
10 import {
11 MChannelAccountDefault,
12 MThumbnail,
13 MUser,
14 MVideoAccountDefault,
15 MVideoCaption,
16 MVideoTag,
17 MVideoThumbnail,
18 MVideoWithBlacklistLight
19 } from '@server/types/models'
20 import { MVideoImportFormattable } from '@server/types/models/video/video-import'
21 import { ServerErrorCode, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
22 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
23 import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
24 import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
25 import { isArray } from '../../../helpers/custom-validators/misc'
26 import { cleanUpReqFiles, createReqFiles } from '../../../helpers/express-utils'
27 import { logger } from '../../../helpers/logger'
28 import { getSecureTorrentName } from '../../../helpers/utils'
29 import { YoutubeDL, YoutubeDLInfo } from '../../../helpers/youtube-dl'
30 import { CONFIG } from '../../../initializers/config'
31 import { MIMETYPES } from '../../../initializers/constants'
32 import { sequelizeTypescript } from '../../../initializers/database'
33 import { getLocalVideoActivityPubUrl } from '../../../lib/activitypub/url'
34 import { JobQueue } from '../../../lib/job-queue/job-queue'
35 import { updateVideoMiniatureFromExisting, updateVideoMiniatureFromUrl } from '../../../lib/thumbnail'
36 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
37 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
38 import { VideoModel } from '../../../models/video/video'
39 import { VideoCaptionModel } from '../../../models/video/video-caption'
40 import { VideoImportModel } from '../../../models/video/video-import'
41
42 const auditLogger = auditLoggerFactory('video-imports')
43 const videoImportsRouter = express.Router()
44
45 const reqVideoFileImport = createReqFiles(
46 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
47 Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
48 {
49 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
50 previewfile: CONFIG.STORAGE.TMP_DIR,
51 torrentfile: CONFIG.STORAGE.TMP_DIR
52 }
53 )
54
55 videoImportsRouter.post('/imports',
56 authenticate,
57 reqVideoFileImport,
58 asyncMiddleware(videoImportAddValidator),
59 asyncRetryTransactionMiddleware(addVideoImport)
60 )
61
62 // ---------------------------------------------------------------------------
63
64 export {
65 videoImportsRouter
66 }
67
68 // ---------------------------------------------------------------------------
69
70 function addVideoImport (req: express.Request, res: express.Response) {
71 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
72
73 const file = req.files?.['torrentfile']?.[0]
74 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
75 }
76
77 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
78 const body: VideoImportCreate = req.body
79 const user = res.locals.oauth.token.User
80
81 let videoName: string
82 let torrentName: string
83 let magnetUri: string
84
85 if (torrentfile) {
86 const result = await processTorrentOrAbortRequest(req, res, torrentfile)
87 if (!result) return
88
89 videoName = result.name
90 torrentName = result.torrentName
91 } else {
92 const result = processMagnetURI(body)
93 magnetUri = result.magnetUri
94 videoName = result.name
95 }
96
97 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
98
99 const thumbnailModel = await processThumbnail(req, video)
100 const previewModel = await processPreview(req, video)
101
102 const videoImport = await insertIntoDB({
103 video,
104 thumbnailModel,
105 previewModel,
106 videoChannel: res.locals.videoChannel,
107 tags: body.tags || undefined,
108 user,
109 videoImportAttributes: {
110 magnetUri,
111 torrentName,
112 state: VideoImportState.PENDING,
113 userId: user.id
114 }
115 })
116
117 // Create job to import the video
118 const payload = {
119 type: torrentfile
120 ? 'torrent-file' as 'torrent-file'
121 : 'magnet-uri' as 'magnet-uri',
122 videoImportId: videoImport.id,
123 magnetUri
124 }
125 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
126
127 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
128
129 return res.json(videoImport.toFormattedJSON()).end()
130 }
131
132 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
133 const body: VideoImportCreate = req.body
134 const targetUrl = body.targetUrl
135 const user = res.locals.oauth.token.User
136
137 const youtubeDL = new YoutubeDL(targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
138
139 // Get video infos
140 let youtubeDLInfo: YoutubeDLInfo
141 try {
142 youtubeDLInfo = await youtubeDL.getYoutubeDLInfo()
143 } catch (err) {
144 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
145
146 return res.fail({
147 message: 'Cannot fetch remote information of this URL.',
148 data: {
149 targetUrl
150 }
151 })
152 }
153
154 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
155
156 // Process video thumbnail from request.files
157 let thumbnailModel = await processThumbnail(req, video)
158
159 // Process video thumbnail from url if processing from request.files failed
160 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
161 try {
162 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
163 } catch (err) {
164 logger.warn('Cannot process thumbnail %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
165 }
166 }
167
168 // Process video preview from request.files
169 let previewModel = await processPreview(req, video)
170
171 // Process video preview from url if processing from request.files failed
172 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
173 try {
174 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
175 } catch (err) {
176 logger.warn('Cannot process preview %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
177 }
178 }
179
180 const videoImport = await insertIntoDB({
181 video,
182 thumbnailModel,
183 previewModel,
184 videoChannel: res.locals.videoChannel,
185 tags: body.tags || youtubeDLInfo.tags,
186 user,
187 videoImportAttributes: {
188 targetUrl,
189 state: VideoImportState.PENDING,
190 userId: user.id
191 }
192 })
193
194 // Get video subtitles
195 await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
196
197 let fileExt = `.${youtubeDLInfo.ext}`
198 if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4'
199
200 // Create job to import the video
201 const payload = {
202 type: 'youtube-dl' as 'youtube-dl',
203 videoImportId: videoImport.id,
204 fileExt
205 }
206 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
207
208 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
209
210 return res.json(videoImport.toFormattedJSON()).end()
211 }
212
213 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
214 const videoData = {
215 name: body.name || importData.name || 'Unknown name',
216 remote: false,
217 category: body.category || importData.category,
218 licence: body.licence || importData.licence,
219 language: body.language || importData.language,
220 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
221 downloadEnabled: body.downloadEnabled !== false,
222 waitTranscoding: body.waitTranscoding || false,
223 state: VideoState.TO_IMPORT,
224 nsfw: body.nsfw || importData.nsfw || false,
225 description: body.description || importData.description,
226 support: body.support || null,
227 privacy: body.privacy || VideoPrivacy.PRIVATE,
228 duration: 0, // duration will be set by the import job
229 channelId: channelId,
230 originallyPublishedAt: body.originallyPublishedAt
231 ? new Date(body.originallyPublishedAt)
232 : importData.originallyPublishedAt
233 }
234 const video = new VideoModel(videoData)
235 video.url = getLocalVideoActivityPubUrl(video)
236
237 return video
238 }
239
240 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
241 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
242 if (thumbnailField) {
243 const thumbnailPhysicalFile = thumbnailField[0]
244
245 return updateVideoMiniatureFromExisting({
246 inputPath: thumbnailPhysicalFile.path,
247 video,
248 type: ThumbnailType.MINIATURE,
249 automaticallyGenerated: false
250 })
251 }
252
253 return undefined
254 }
255
256 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
257 const previewField = req.files ? req.files['previewfile'] : undefined
258 if (previewField) {
259 const previewPhysicalFile = previewField[0]
260
261 return updateVideoMiniatureFromExisting({
262 inputPath: previewPhysicalFile.path,
263 video,
264 type: ThumbnailType.PREVIEW,
265 automaticallyGenerated: false
266 })
267 }
268
269 return undefined
270 }
271
272 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
273 try {
274 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
275 } catch (err) {
276 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
277 return undefined
278 }
279 }
280
281 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
282 try {
283 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
284 } catch (err) {
285 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
286 return undefined
287 }
288 }
289
290 async function insertIntoDB (parameters: {
291 video: MVideoThumbnail
292 thumbnailModel: MThumbnail
293 previewModel: MThumbnail
294 videoChannel: MChannelAccountDefault
295 tags: string[]
296 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
297 user: MUser
298 }): Promise<MVideoImportFormattable> {
299 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
300
301 const videoImport = await sequelizeTypescript.transaction(async t => {
302 const sequelizeOptions = { transaction: t }
303
304 // Save video object in database
305 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
306 videoCreated.VideoChannel = videoChannel
307
308 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
309 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
310
311 await autoBlacklistVideoIfNeeded({
312 video: videoCreated,
313 user,
314 notify: false,
315 isRemote: false,
316 isNew: true,
317 transaction: t
318 })
319
320 await setVideoTags({ video: videoCreated, tags, transaction: t })
321
322 // Create video import object in database
323 const videoImport = await VideoImportModel.create(
324 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
325 sequelizeOptions
326 ) as MVideoImportFormattable
327 videoImport.Video = videoCreated
328
329 return videoImport
330 })
331
332 return videoImport
333 }
334
335 async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
336 const torrentName = torrentfile.originalname
337
338 // Rename the torrent to a secured name
339 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
340 await move(torrentfile.path, newTorrentPath, { overwrite: true })
341 torrentfile.path = newTorrentPath
342
343 const buf = await readFile(torrentfile.path)
344 const parsedTorrent = parseTorrent(buf) as Instance
345
346 if (parsedTorrent.files.length !== 1) {
347 cleanUpReqFiles(req)
348
349 res.fail({
350 type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
351 message: 'Torrents with only 1 file are supported.'
352 })
353 return undefined
354 }
355
356 return {
357 name: extractNameFromArray(parsedTorrent.name),
358 torrentName
359 }
360 }
361
362 function processMagnetURI (body: VideoImportCreate) {
363 const magnetUri = body.magnetUri
364 const parsed = decode(magnetUri)
365
366 return {
367 name: extractNameFromArray(parsed.name),
368 magnetUri
369 }
370 }
371
372 function extractNameFromArray (name: string | string[]) {
373 return isArray(name) ? name[0] : name
374 }
375
376 async function processYoutubeSubtitles (youtubeDL: YoutubeDL, targetUrl: string, videoId: number) {
377 try {
378 const subtitles = await youtubeDL.getYoutubeDLSubs()
379
380 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
381
382 for (const subtitle of subtitles) {
383 const videoCaption = new VideoCaptionModel({
384 videoId,
385 language: subtitle.language,
386 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
387 }) as MVideoCaption
388
389 // Move physical file
390 await moveAndProcessCaptionFile(subtitle, videoCaption)
391
392 await sequelizeTypescript.transaction(async t => {
393 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
394 })
395 }
396 } catch (err) {
397 logger.warn('Cannot get video subtitles.', { err })
398 }
399 }