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