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