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'
12 MChannelAccountDefault,
19 MVideoWithBlacklistLight
20 } from '@server/types/models'
21 import { MVideoImportFormattable } from '@server/types/models/video/video-import'
22 import { ServerErrorCode, ThumbnailType, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '@shared/models'
23 import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
24 import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
25 import { isArray } from '../../../helpers/custom-validators/misc'
26 import { cleanUpReqFiles, createReqFiles } from '../../../helpers/express-utils'
27 import { logger } from '../../../helpers/logger'
28 import { getSecureTorrentName } from '../../../helpers/utils'
29 import { YoutubeDLInfo, YoutubeDLWrapper } from '../../../helpers/youtube-dl'
30 import { CONFIG } from '../../../initializers/config'
31 import { MIMETYPES } from '../../../initializers/constants'
32 import { sequelizeTypescript } from '../../../initializers/database'
33 import { getLocalVideoActivityPubUrl } from '../../../lib/activitypub/url'
34 import { JobQueue } from '../../../lib/job-queue/job-queue'
35 import { updateVideoMiniatureFromExisting, updateVideoMiniatureFromUrl } from '../../../lib/thumbnail'
36 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
37 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
38 import { VideoModel } from '../../../models/video/video'
39 import { VideoCaptionModel } from '../../../models/video/video-caption'
40 import { VideoImportModel } from '../../../models/video/video-import'
42 const auditLogger = auditLoggerFactory('video-imports')
43 const videoImportsRouter = express.Router()
45 const reqVideoFileImport = createReqFiles(
46 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
47 Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
49 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
50 previewfile: CONFIG.STORAGE.TMP_DIR,
51 torrentfile: CONFIG.STORAGE.TMP_DIR
55 videoImportsRouter.post('/imports',
58 asyncMiddleware(videoImportAddValidator),
59 asyncRetryTransactionMiddleware(addVideoImport)
62 // ---------------------------------------------------------------------------
68 // ---------------------------------------------------------------------------
70 function addVideoImport (req: express.Request, res: express.Response) {
71 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
73 const file = req.files?.['torrentfile']?.[0]
74 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
77 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
78 const body: VideoImportCreate = req.body
79 const user = res.locals.oauth.token.User
82 let torrentName: string
86 const result = await processTorrentOrAbortRequest(req, res, torrentfile)
89 videoName = result.name
90 torrentName = result.torrentName
92 const result = processMagnetURI(body)
93 magnetUri = result.magnetUri
94 videoName = result.name
97 const video = await buildVideo(res.locals.videoChannel.id, body, { name: videoName })
99 const thumbnailModel = await processThumbnail(req, video)
100 const previewModel = await processPreview(req, video)
102 const videoImport = await insertIntoDB({
106 videoChannel: res.locals.videoChannel,
107 tags: body.tags || undefined,
109 videoImportAttributes: {
112 state: VideoImportState.PENDING,
117 // Create job to import the video
120 ? 'torrent-file' as 'torrent-file'
121 : 'magnet-uri' as 'magnet-uri',
122 videoImportId: videoImport.id,
125 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
127 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
129 return res.json(videoImport.toFormattedJSON()).end()
132 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
133 const body: VideoImportCreate = req.body
134 const targetUrl = body.targetUrl
135 const user = res.locals.oauth.token.User
137 const youtubeDL = new YoutubeDLWrapper(targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
140 let youtubeDLInfo: YoutubeDLInfo
142 youtubeDLInfo = await youtubeDL.getInfoForDownload()
144 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
147 message: 'Cannot fetch remote information of this URL.',
154 const video = await buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
156 // Process video thumbnail from request.files
157 let thumbnailModel = await processThumbnail(req, video)
159 // Process video thumbnail from url if processing from request.files failed
160 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
162 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
164 logger.warn('Cannot process thumbnail %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
168 // Process video preview from request.files
169 let previewModel = await processPreview(req, video)
171 // Process video preview from url if processing from request.files failed
172 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
174 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
176 logger.warn('Cannot process preview %s from youtubedl.', youtubeDLInfo.thumbnailUrl, { err })
180 const videoImport = await insertIntoDB({
184 videoChannel: res.locals.videoChannel,
185 tags: body.tags || youtubeDLInfo.tags,
187 videoImportAttributes: {
189 state: VideoImportState.PENDING,
194 // Get video subtitles
195 await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
197 let fileExt = `.${youtubeDLInfo.ext}`
198 if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4'
200 // Create job to import the video
202 type: 'youtube-dl' as 'youtube-dl',
203 videoImportId: videoImport.id,
206 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
208 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
210 return res.json(videoImport.toFormattedJSON()).end()
213 async function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): Promise<MVideoThumbnail> {
215 name: body.name || importData.name || 'Unknown name',
217 category: body.category || importData.category,
218 licence: body.licence ?? importData.licence ?? CONFIG.DEFAULTS.PUBLISH.LICENCE,
219 language: body.language || importData.language,
220 commentsEnabled: body.commentsEnabled ?? CONFIG.DEFAULTS.PUBLISH.COMMENTS_ENABLED,
221 downloadEnabled: body.downloadEnabled ?? CONFIG.DEFAULTS.PUBLISH.DOWNLOAD_ENABLED,
222 waitTranscoding: body.waitTranscoding || false,
223 state: VideoState.TO_IMPORT,
224 nsfw: body.nsfw || importData.nsfw || false,
225 description: body.description || importData.description,
226 support: body.support || null,
227 privacy: body.privacy || VideoPrivacy.PRIVATE,
228 duration: 0, // duration will be set by the import job
229 channelId: channelId,
230 originallyPublishedAt: body.originallyPublishedAt
231 ? new Date(body.originallyPublishedAt)
232 : importData.originallyPublishedAt
235 videoData = await Hooks.wrapObject(
238 ? 'filter:api.video.import-url.video-attribute.result'
239 : 'filter:api.video.import-torrent.video-attribute.result'
242 const video = new VideoModel(videoData)
243 video.url = getLocalVideoActivityPubUrl(video)
248 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
249 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
250 if (thumbnailField) {
251 const thumbnailPhysicalFile = thumbnailField[0]
253 return updateVideoMiniatureFromExisting({
254 inputPath: thumbnailPhysicalFile.path,
256 type: ThumbnailType.MINIATURE,
257 automaticallyGenerated: false
264 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
265 const previewField = req.files ? req.files['previewfile'] : undefined
267 const previewPhysicalFile = previewField[0]
269 return updateVideoMiniatureFromExisting({
270 inputPath: previewPhysicalFile.path,
272 type: ThumbnailType.PREVIEW,
273 automaticallyGenerated: false
280 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
282 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
284 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
289 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
291 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
293 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
298 async function insertIntoDB (parameters: {
299 video: MVideoThumbnail
300 thumbnailModel: MThumbnail
301 previewModel: MThumbnail
302 videoChannel: MChannelAccountDefault
304 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
306 }): Promise<MVideoImportFormattable> {
307 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
309 const videoImport = await sequelizeTypescript.transaction(async t => {
310 const sequelizeOptions = { transaction: t }
312 // Save video object in database
313 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
314 videoCreated.VideoChannel = videoChannel
316 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
317 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
319 await autoBlacklistVideoIfNeeded({
328 await setVideoTags({ video: videoCreated, tags, transaction: t })
330 // Create video import object in database
331 const videoImport = await VideoImportModel.create(
332 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
334 ) as MVideoImportFormattable
335 videoImport.Video = videoCreated
343 async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
344 const torrentName = torrentfile.originalname
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
351 const buf = await readFile(torrentfile.path)
352 const parsedTorrent = parseTorrent(buf) as Instance
354 if (parsedTorrent.files.length !== 1) {
358 type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
359 message: 'Torrents with only 1 file are supported.'
365 name: extractNameFromArray(parsedTorrent.name),
370 function processMagnetURI (body: VideoImportCreate) {
371 const magnetUri = body.magnetUri
372 const parsed = decode(magnetUri)
375 name: extractNameFromArray(parsed.name),
380 function extractNameFromArray (name: string | string[]) {
381 return isArray(name) ? name[0] : name
384 async function processYoutubeSubtitles (youtubeDL: YoutubeDLWrapper, targetUrl: string, videoId: number) {
386 const subtitles = await youtubeDL.getSubtitles()
388 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
390 for (const subtitle of subtitles) {
391 const videoCaption = new VideoCaptionModel({
393 language: subtitle.language,
394 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
397 // Move physical file
398 await moveAndProcessCaptionFile(subtitle, videoCaption)
400 await sequelizeTypescript.transaction(async t => {
401 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
405 logger.warn('Cannot get video subtitles.', { err })