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 { getEnabledResolutions } from '@server/lib/config'
7 import { setVideoTags } from '@server/lib/video'
9 MChannelAccountDefault,
16 MVideoWithBlacklistLight
17 } from '@server/types/models'
18 import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import'
19 import { ServerErrorCode, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
20 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
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 { createVideoMiniatureFromExisting, createVideoMiniatureFromUrl } 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 torrentName = torrentfile.originalname
87 // Rename the torrent to a secured name
88 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
89 await move(torrentfile.path, newTorrentPath, { overwrite: true })
90 torrentfile.path = newTorrentPath
92 const buf = await readFile(torrentfile.path)
93 const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance
95 if (parsedTorrent.files.length !== 1) {
98 return res.status(HttpStatusCode.BAD_REQUEST_400)
100 code: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
101 error: 'Torrents with only 1 file are supported.'
105 videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name
107 magnetUri = body.magnetUri
109 const parsed = magnetUtil.decode(magnetUri)
110 videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
113 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
115 const thumbnailModel = await processThumbnail(req, video)
116 const previewModel = await processPreview(req, video)
118 const tags = body.tags || undefined
119 const videoImportAttributes = {
122 state: VideoImportState.PENDING,
125 const videoImport = await insertIntoDB({
129 videoChannel: res.locals.videoChannel,
131 videoImportAttributes,
135 // Create job to import the video
137 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
138 videoImportId: videoImport.id,
141 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
143 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
145 return res.json(videoImport.toFormattedJSON()).end()
148 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
149 const body: VideoImportCreate = req.body
150 const targetUrl = body.targetUrl
151 const user = res.locals.oauth.token.User
153 const youtubeDL = new YoutubeDL(targetUrl, getEnabledResolutions('vod'))
156 let youtubeDLInfo: YoutubeDLInfo
158 youtubeDLInfo = await youtubeDL.getYoutubeDLInfo()
160 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
162 return res.status(HttpStatusCode.BAD_REQUEST_400)
164 error: 'Cannot fetch remote information of this URL.'
168 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
170 // Process video thumbnail from request.files
171 let thumbnailModel = await processThumbnail(req, video)
173 // Process video thumbnail from url if processing from request.files failed
174 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
175 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
178 // Process video preview from request.files
179 let previewModel = await processPreview(req, video)
181 // Process video preview from url if processing from request.files failed
182 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
183 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
186 const tags = body.tags || youtubeDLInfo.tags
187 const videoImportAttributes = {
189 state: VideoImportState.PENDING,
192 const videoImport = await insertIntoDB({
196 videoChannel: res.locals.videoChannel,
198 videoImportAttributes,
202 // Get video subtitles
204 const subtitles = await youtubeDL.getYoutubeDLSubs()
206 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
208 for (const subtitle of subtitles) {
209 const videoCaption = new VideoCaptionModel({
211 language: subtitle.language,
212 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
215 // Move physical file
216 await moveAndProcessCaptionFile(subtitle, videoCaption)
218 await sequelizeTypescript.transaction(async t => {
219 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
223 logger.warn('Cannot get video subtitles.', { err })
226 // Create job to import the video
228 type: 'youtube-dl' as 'youtube-dl',
229 videoImportId: videoImport.id,
230 fileExt: `.${youtubeDLInfo.ext || 'mp4'}`
232 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
234 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
236 return res.json(videoImport.toFormattedJSON()).end()
239 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
241 name: body.name || importData.name || 'Unknown name',
243 category: body.category || importData.category,
244 licence: body.licence || importData.licence,
245 language: body.language || importData.language,
246 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
247 downloadEnabled: body.downloadEnabled !== false,
248 waitTranscoding: body.waitTranscoding || false,
249 state: VideoState.TO_IMPORT,
250 nsfw: body.nsfw || importData.nsfw || false,
251 description: body.description || importData.description,
252 support: body.support || null,
253 privacy: body.privacy || VideoPrivacy.PRIVATE,
254 duration: 0, // duration will be set by the import job
255 channelId: channelId,
256 originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt
258 const video = new VideoModel(videoData)
259 video.url = getLocalVideoActivityPubUrl(video)
264 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
265 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
266 if (thumbnailField) {
267 const thumbnailPhysicalFile = thumbnailField[0]
269 return createVideoMiniatureFromExisting({
270 inputPath: thumbnailPhysicalFile.path,
272 type: ThumbnailType.MINIATURE,
273 automaticallyGenerated: false
280 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
281 const previewField = req.files ? req.files['previewfile'] : undefined
283 const previewPhysicalFile = previewField[0]
285 return createVideoMiniatureFromExisting({
286 inputPath: previewPhysicalFile.path,
288 type: ThumbnailType.PREVIEW,
289 automaticallyGenerated: false
296 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
298 return createVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
300 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
305 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
307 return createVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
309 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
314 async function insertIntoDB (parameters: {
315 video: MVideoThumbnail
316 thumbnailModel: MThumbnail
317 previewModel: MThumbnail
318 videoChannel: MChannelAccountDefault
320 videoImportAttributes: Partial<MVideoImport>
322 }): Promise<MVideoImportFormattable> {
323 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
325 const videoImport = await sequelizeTypescript.transaction(async t => {
326 const sequelizeOptions = { transaction: t }
328 // Save video object in database
329 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
330 videoCreated.VideoChannel = videoChannel
332 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
333 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
335 await autoBlacklistVideoIfNeeded({
344 await setVideoTags({ video: videoCreated, tags, transaction: t })
346 // Create video import object in database
347 const videoImport = await VideoImportModel.create(
348 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
350 ) as MVideoImportFormattable
351 videoImport.Video = videoCreated