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