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