1 import * as express from 'express'
2 import { move, readFile } from 'fs-extra'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import { ServerConfigManager } from '@server/lib/server-config-manager'
7 import { setVideoTags } from '@server/lib/video'
8 import { FilteredModelAttributes } from '@server/types'
10 MChannelAccountDefault,
17 MVideoWithBlacklistLight
18 } from '@server/types/models'
19 import { MVideoImportFormattable } from '@server/types/models/video/video-import'
20 import { ServerErrorCode, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
21 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
22 import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
23 import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
24 import { isArray } from '../../../helpers/custom-validators/misc'
25 import { cleanUpReqFiles, createReqFiles } from '../../../helpers/express-utils'
26 import { logger } from '../../../helpers/logger'
27 import { getSecureTorrentName } from '../../../helpers/utils'
28 import { YoutubeDL, YoutubeDLInfo } from '../../../helpers/youtube-dl'
29 import { CONFIG } from '../../../initializers/config'
30 import { MIMETYPES } from '../../../initializers/constants'
31 import { sequelizeTypescript } from '../../../initializers/database'
32 import { getLocalVideoActivityPubUrl } from '../../../lib/activitypub/url'
33 import { JobQueue } from '../../../lib/job-queue/job-queue'
34 import { updateVideoMiniatureFromExisting, updateVideoMiniatureFromUrl } from '../../../lib/thumbnail'
35 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
36 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
37 import { VideoModel } from '../../../models/video/video'
38 import { VideoCaptionModel } from '../../../models/video/video-caption'
39 import { VideoImportModel } from '../../../models/video/video-import'
41 const auditLogger = auditLoggerFactory('video-imports')
42 const videoImportsRouter = express.Router()
44 const reqVideoFileImport = createReqFiles(
45 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
46 Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
48 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
49 previewfile: CONFIG.STORAGE.TMP_DIR,
50 torrentfile: CONFIG.STORAGE.TMP_DIR
54 videoImportsRouter.post('/imports',
57 asyncMiddleware(videoImportAddValidator),
58 asyncRetryTransactionMiddleware(addVideoImport)
61 // ---------------------------------------------------------------------------
67 // ---------------------------------------------------------------------------
69 function addVideoImport (req: express.Request, res: express.Response) {
70 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
72 const file = req.files?.['torrentfile']?.[0]
73 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
76 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
77 const body: VideoImportCreate = req.body
78 const user = res.locals.oauth.token.User
81 let torrentName: string
85 const result = await processTorrentOrAbortRequest(req, res, torrentfile)
88 videoName = result.name
89 torrentName = result.torrentName
91 const result = processMagnetURI(body)
92 magnetUri = result.magnetUri
93 videoName = result.name
96 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
98 const thumbnailModel = await processThumbnail(req, video)
99 const previewModel = await processPreview(req, video)
101 const videoImport = await insertIntoDB({
105 videoChannel: res.locals.videoChannel,
106 tags: body.tags || undefined,
108 videoImportAttributes: {
111 state: VideoImportState.PENDING,
116 // Create job to import the video
119 ? 'torrent-file' as 'torrent-file'
120 : 'magnet-uri' as 'magnet-uri',
121 videoImportId: videoImport.id,
124 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
126 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
128 return res.json(videoImport.toFormattedJSON()).end()
131 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
132 const body: VideoImportCreate = req.body
133 const targetUrl = body.targetUrl
134 const user = res.locals.oauth.token.User
136 const youtubeDL = new YoutubeDL(targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
139 let youtubeDLInfo: YoutubeDLInfo
141 youtubeDLInfo = await youtubeDL.getYoutubeDLInfo()
143 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
146 message: 'Cannot fetch remote information of this URL.',
153 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
155 // Process video thumbnail from request.files
156 let thumbnailModel = await processThumbnail(req, video)
158 // Process video thumbnail from url if processing from request.files failed
159 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
160 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
163 // Process video preview from request.files
164 let previewModel = await processPreview(req, video)
166 // Process video preview from url if processing from request.files failed
167 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
168 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
171 const videoImport = await insertIntoDB({
175 videoChannel: res.locals.videoChannel,
176 tags: body.tags || youtubeDLInfo.tags,
178 videoImportAttributes: {
180 state: VideoImportState.PENDING,
185 // Get video subtitles
186 await processYoutubeSubtitles(youtubeDL, targetUrl, video.id)
188 // Create job to import the video
190 type: 'youtube-dl' as 'youtube-dl',
191 videoImportId: videoImport.id,
192 fileExt: `.${youtubeDLInfo.ext || 'mp4'}`
194 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
196 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
198 return res.json(videoImport.toFormattedJSON()).end()
201 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
203 name: body.name || importData.name || 'Unknown name',
205 category: body.category || importData.category,
206 licence: body.licence || importData.licence,
207 language: body.language || importData.language,
208 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
209 downloadEnabled: body.downloadEnabled !== false,
210 waitTranscoding: body.waitTranscoding || false,
211 state: VideoState.TO_IMPORT,
212 nsfw: body.nsfw || importData.nsfw || false,
213 description: body.description || importData.description,
214 support: body.support || null,
215 privacy: body.privacy || VideoPrivacy.PRIVATE,
216 duration: 0, // duration will be set by the import job
217 channelId: channelId,
218 originallyPublishedAt: body.originallyPublishedAt
219 ? new Date(body.originallyPublishedAt)
220 : importData.originallyPublishedAt
222 const video = new VideoModel(videoData)
223 video.url = getLocalVideoActivityPubUrl(video)
228 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
229 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
230 if (thumbnailField) {
231 const thumbnailPhysicalFile = thumbnailField[0]
233 return updateVideoMiniatureFromExisting({
234 inputPath: thumbnailPhysicalFile.path,
236 type: ThumbnailType.MINIATURE,
237 automaticallyGenerated: false
244 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
245 const previewField = req.files ? req.files['previewfile'] : undefined
247 const previewPhysicalFile = previewField[0]
249 return updateVideoMiniatureFromExisting({
250 inputPath: previewPhysicalFile.path,
252 type: ThumbnailType.PREVIEW,
253 automaticallyGenerated: false
260 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
262 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
264 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
269 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
271 return updateVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
273 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
278 async function insertIntoDB (parameters: {
279 video: MVideoThumbnail
280 thumbnailModel: MThumbnail
281 previewModel: MThumbnail
282 videoChannel: MChannelAccountDefault
284 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
286 }): Promise<MVideoImportFormattable> {
287 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
289 const videoImport = await sequelizeTypescript.transaction(async t => {
290 const sequelizeOptions = { transaction: t }
292 // Save video object in database
293 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
294 videoCreated.VideoChannel = videoChannel
296 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
297 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
299 await autoBlacklistVideoIfNeeded({
308 await setVideoTags({ video: videoCreated, tags, transaction: t })
310 // Create video import object in database
311 const videoImport = await VideoImportModel.create(
312 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
314 ) as MVideoImportFormattable
315 videoImport.Video = videoCreated
323 async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
324 const torrentName = torrentfile.originalname
326 // Rename the torrent to a secured name
327 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
328 await move(torrentfile.path, newTorrentPath, { overwrite: true })
329 torrentfile.path = newTorrentPath
331 const buf = await readFile(torrentfile.path)
332 const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance
334 if (parsedTorrent.files.length !== 1) {
338 type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
339 message: 'Torrents with only 1 file are supported.'
345 name: extractNameFromArray(parsedTorrent.name),
350 function processMagnetURI (body: VideoImportCreate) {
351 const magnetUri = body.magnetUri
352 const parsed = magnetUtil.decode(magnetUri)
355 name: extractNameFromArray(parsed.name),
360 function extractNameFromArray (name: string | string[]) {
361 return isArray(name) ? name[0] : name
364 async function processYoutubeSubtitles (youtubeDL: YoutubeDL, targetUrl: string, videoId: number) {
366 const subtitles = await youtubeDL.getYoutubeDLSubs()
368 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
370 for (const subtitle of subtitles) {
371 const videoCaption = new VideoCaptionModel({
373 language: subtitle.language,
374 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
377 // Move physical file
378 await moveAndProcessCaptionFile(subtitle, videoCaption)
380 await sequelizeTypescript.transaction(async t => {
381 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
385 logger.warn('Cannot get video subtitles.', { err })