]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/import.ts
Refactor user build and express file middlewares
[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 }
a1587156 166 await JobQueue.Instance.createJobWithPromise({ 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
62549e6c 178 const youtubeDL = new YoutubeDLWrapper(targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
1bcb03a1 179
50ad0a1c 180 // Get video infos
fbad87b0
C
181 let youtubeDLInfo: YoutubeDLInfo
182 try {
62549e6c 183 youtubeDLInfo = await youtubeDL.getInfoForDownload()
fbad87b0
C
184 } catch (err) {
185 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
186
76148b27
RK
187 return res.fail({
188 message: 'Cannot fetch remote information of this URL.',
189 data: {
190 targetUrl
191 }
192 })
fbad87b0
C
193 }
194
474542d7
C
195 if (!await hasUnicastURLsOnly(youtubeDLInfo)) {
196 return res.fail({
197 status: HttpStatusCode.FORBIDDEN_403,
198 message: 'Cannot use non unicast IP as targetUrl.'
199 })
200 }
201
d17d7430 202 const video = await buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
ce33919c 203
b1770a0a 204 // Process video thumbnail from request.files
6302d599 205 let thumbnailModel = await processThumbnail(req, video)
b1770a0a
K
206
207 // Process video thumbnail from url if processing from request.files failed
86ad0cde 208 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
731a32e3
C
209 try {
210 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
211 } catch (err) {
212 logger.warn('Cannot process thumbnail %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
213 }
b1770a0a
K
214 }
215
b1770a0a 216 // Process video preview from request.files
6302d599 217 let previewModel = await processPreview(req, video)
b1770a0a
K
218
219 // Process video preview from url if processing from request.files failed
86ad0cde 220 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
731a32e3
C
221 try {
222 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
223 } catch (err) {
224 logger.warn('Cannot process preview %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
225 }
b1770a0a 226 }
ce33919c 227
e8bafea3 228 const videoImport = await insertIntoDB({
03371ad9 229 video,
e8bafea3
C
230 thumbnailModel,
231 previewModel,
232 videoChannel: res.locals.videoChannel,
c158a5fa
C
233 tags: body.tags || youtubeDLInfo.tags,
234 user,
235 videoImportAttributes: {
236 targetUrl,
237 state: VideoImportState.PENDING,
238 userId: user.id
239 }
e8bafea3 240 })
ce33919c 241
50ad0a1c 242 // Get video subtitles
c158a5fa 243 await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
50ad0a1c 244
e3c9ea72
C
245 let fileExt = `.${youtubeDLInfo.ext}`
246 if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4'
247
ce33919c
C
248 // Create job to import the video
249 const payload = {
250 type: 'youtube-dl' as 'youtube-dl',
251 videoImportId: videoImport.id,
e3c9ea72 252 fileExt
ce33919c 253 }
a1587156 254 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
ce33919c 255
993cef4b 256 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
257
258 return res.json(videoImport.toFormattedJSON()).end()
259}
260
d17d7430
C
261async function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): Promise<MVideoThumbnail> {
262 let videoData = {
ce33919c 263 name: body.name || importData.name || 'Unknown name',
fbad87b0 264 remote: false,
ce33919c 265 category: body.category || importData.category,
3cf68b86 266 licence: body.licence ?? importData.licence ?? CONFIG.DEFAULTS.PUBLISH.LICENCE,
86ad0cde 267 language: body.language || importData.language,
3cf68b86
C
268 commentsEnabled: body.commentsEnabled ?? CONFIG.DEFAULTS.PUBLISH.COMMENTS_ENABLED,
269 downloadEnabled: body.downloadEnabled ?? CONFIG.DEFAULTS.PUBLISH.DOWNLOAD_ENABLED,
fbad87b0
C
270 waitTranscoding: body.waitTranscoding || false,
271 state: VideoState.TO_IMPORT,
ce33919c
C
272 nsfw: body.nsfw || importData.nsfw || false,
273 description: body.description || importData.description,
fbad87b0
C
274 support: body.support || null,
275 privacy: body.privacy || VideoPrivacy.PRIVATE,
276 duration: 0, // duration will be set by the import job
4e553a41 277 channelId: channelId,
16c016e8
C
278 originallyPublishedAt: body.originallyPublishedAt
279 ? new Date(body.originallyPublishedAt)
280 : importData.originallyPublishedAt
fbad87b0 281 }
d17d7430
C
282
283 videoData = await Hooks.wrapObject(
284 videoData,
285 body.targetUrl
286 ? 'filter:api.video.import-url.video-attribute.result'
287 : 'filter:api.video.import-torrent.video-attribute.result'
288 )
289
fbad87b0 290 const video = new VideoModel(videoData)
de94ac86 291 video.url = getLocalVideoActivityPubUrl(video)
fbad87b0 292
ce33919c
C
293 return video
294}
295
6302d599 296async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
5d08a6a7 297 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
fbad87b0 298 if (thumbnailField) {
a1587156 299 const thumbnailPhysicalFile = thumbnailField[0]
ce33919c 300
91f8f8db 301 return updateVideoMiniatureFromExisting({
1ef65f4c
C
302 inputPath: thumbnailPhysicalFile.path,
303 video,
304 type: ThumbnailType.MINIATURE,
305 automaticallyGenerated: false
306 })
fbad87b0
C
307 }
308
e8bafea3 309 return undefined
ce33919c
C
310}
311
6302d599 312async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
5d08a6a7 313 const previewField = req.files ? req.files['previewfile'] : undefined
fbad87b0
C
314 if (previewField) {
315 const previewPhysicalFile = previewField[0]
ce33919c 316
91f8f8db 317 return updateVideoMiniatureFromExisting({
1ef65f4c
C
318 inputPath: previewPhysicalFile.path,
319 video,
320 type: ThumbnailType.PREVIEW,
321 automaticallyGenerated: false
322 })
fbad87b0
C
323 }
324
e8bafea3 325 return undefined
ce33919c
C
326}
327
6302d599 328async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
b1770a0a 329 try {
91f8f8db 330 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
b1770a0a
K
331 } catch (err) {
332 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
333 return undefined
334 }
335}
336
6302d599 337async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
b1770a0a 338 try {
91f8f8db 339 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
b1770a0a
K
340 } catch (err) {
341 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
342 return undefined
343 }
344}
345
a35a2279 346async function insertIntoDB (parameters: {
6302d599 347 video: MVideoThumbnail
a1587156
C
348 thumbnailModel: MThumbnail
349 previewModel: MThumbnail
350 videoChannel: MChannelAccountDefault
351 tags: string[]
16c016e8 352 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
453e83ea 353 user: MUser
b49f22d8 354}): Promise<MVideoImportFormattable> {
03371ad9 355 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
e8bafea3 356
a35a2279 357 const videoImport = await sequelizeTypescript.transaction(async t => {
fbad87b0
C
358 const sequelizeOptions = { transaction: t }
359
360 // Save video object in database
1ca9f7c3 361 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
ce33919c 362 videoCreated.VideoChannel = videoChannel
fbad87b0 363
3acc5084
C
364 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
365 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 366
5b77537c 367 await autoBlacklistVideoIfNeeded({
453e83ea 368 video: videoCreated,
5b77537c
C
369 user,
370 notify: false,
371 isRemote: false,
372 isNew: true,
373 transaction: t
374 })
7ccddd7b 375
1ef65f4c 376 await setVideoTags({ video: videoCreated, tags, transaction: t })
fbad87b0
C
377
378 // Create video import object in database
ce33919c
C
379 const videoImport = await VideoImportModel.create(
380 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
381 sequelizeOptions
1ca9f7c3 382 ) as MVideoImportFormattable
fbad87b0
C
383 videoImport.Video = videoCreated
384
385 return videoImport
386 })
a35a2279
C
387
388 return videoImport
fbad87b0 389}
c158a5fa
C
390
391async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
392 const torrentName = torrentfile.originalname
393
394 // Rename the torrent to a secured name
395 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
396 await move(torrentfile.path, newTorrentPath, { overwrite: true })
397 torrentfile.path = newTorrentPath
398
399 const buf = await readFile(torrentfile.path)
41fb13c3 400 const parsedTorrent = parseTorrent(buf) as Instance
c158a5fa
C
401
402 if (parsedTorrent.files.length !== 1) {
403 cleanUpReqFiles(req)
404
76148b27 405 res.fail({
3866ea02 406 type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
76148b27
RK
407 message: 'Torrents with only 1 file are supported.'
408 })
c158a5fa
C
409 return undefined
410 }
411
412 return {
413 name: extractNameFromArray(parsedTorrent.name),
414 torrentName
415 }
416}
417
418function processMagnetURI (body: VideoImportCreate) {
419 const magnetUri = body.magnetUri
41fb13c3 420 const parsed = decode(magnetUri)
c158a5fa
C
421
422 return {
423 name: extractNameFromArray(parsed.name),
424 magnetUri
425 }
426}
427
428function extractNameFromArray (name: string | string[]) {
429 return isArray(name) ? name[0] : name
430}
431
62549e6c 432async function processYoutubeSubtitles (youtubeDL: YoutubeDLWrapper, targetUrl: string, videoId: number) {
c158a5fa 433 try {
62549e6c 434 const subtitles = await youtubeDL.getSubtitles()
c158a5fa
C
435
436 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
437
438 for (const subtitle of subtitles) {
474542d7
C
439 if (!await isVTTFileValid(subtitle.path)) {
440 await remove(subtitle.path)
441 continue
442 }
443
c158a5fa
C
444 const videoCaption = new VideoCaptionModel({
445 videoId,
446 language: subtitle.language,
447 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
448 }) as MVideoCaption
449
450 // Move physical file
451 await moveAndProcessCaptionFile(subtitle, videoCaption)
452
453 await sequelizeTypescript.transaction(async t => {
454 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
455 })
456 }
457 } catch (err) {
458 logger.warn('Cannot get video subtitles.', { err })
459 }
460}
474542d7
C
461
462async function hasUnicastURLsOnly (youtubeDLInfo: YoutubeDLInfo) {
463 const hosts = youtubeDLInfo.urls.map(u => new URL(u).hostname)
464 const uniqHosts = new Set(hosts)
465
466 for (const h of uniqHosts) {
467 if (await isResolvingToUnicastOnly(h) !== true) {
468 return false
469 }
470 }
471
472 return true
473}