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 { 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 { 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)
90 torrentfile.path = newTorrentPath
92 const buf = await readFile(torrentfile.path)
93 const parsedTorrent = parseTorrent(buf)
95 videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name as string
97 magnetUri = body.magnetUri
99 const parsed = magnetUtil.decode(magnetUri)
100 videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
103 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
105 const thumbnailModel = await processThumbnail(req, video)
106 const previewModel = await processPreview(req, video)
108 const tags = body.tags || undefined
109 const videoImportAttributes = {
112 state: VideoImportState.PENDING,
115 const videoImport = await insertIntoDB({
119 videoChannel: res.locals.videoChannel,
121 videoImportAttributes,
125 // Create job to import the video
127 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
128 videoImportId: videoImport.id,
131 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
133 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
135 return res.json(videoImport.toFormattedJSON()).end()
138 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
139 const body: VideoImportCreate = req.body
140 const targetUrl = body.targetUrl
141 const user = res.locals.oauth.token.User
143 const youtubeDL = new YoutubeDL(targetUrl, getEnabledResolutions('vod'))
146 let youtubeDLInfo: YoutubeDLInfo
148 youtubeDLInfo = await youtubeDL.getYoutubeDLInfo()
150 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
152 return res.status(HttpStatusCode.BAD_REQUEST_400)
154 error: 'Cannot fetch remote information of this URL.'
158 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
160 // Process video thumbnail from request.files
161 let thumbnailModel = await processThumbnail(req, video)
163 // Process video thumbnail from url if processing from request.files failed
164 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
165 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
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) {
173 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
176 const tags = body.tags || youtubeDLInfo.tags
177 const videoImportAttributes = {
179 state: VideoImportState.PENDING,
182 const videoImport = await insertIntoDB({
186 videoChannel: res.locals.videoChannel,
188 videoImportAttributes,
192 // Get video subtitles
194 const subtitles = await youtubeDL.getYoutubeDLSubs()
196 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
198 for (const subtitle of subtitles) {
199 const videoCaption = new VideoCaptionModel({
201 language: subtitle.language,
202 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
205 // Move physical file
206 await moveAndProcessCaptionFile(subtitle, videoCaption)
208 await sequelizeTypescript.transaction(async t => {
209 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
213 logger.warn('Cannot get video subtitles.', { err })
216 // Create job to import the video
218 type: 'youtube-dl' as 'youtube-dl',
219 videoImportId: videoImport.id,
220 fileExt: `.${youtubeDLInfo.ext || 'mp4'}`
222 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
224 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
226 return res.json(videoImport.toFormattedJSON()).end()
229 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
231 name: body.name || importData.name || 'Unknown name',
233 category: body.category || importData.category,
234 licence: body.licence || importData.licence,
235 language: body.language || importData.language,
236 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
237 downloadEnabled: body.downloadEnabled !== false,
238 waitTranscoding: body.waitTranscoding || false,
239 state: VideoState.TO_IMPORT,
240 nsfw: body.nsfw || importData.nsfw || false,
241 description: body.description || importData.description,
242 support: body.support || null,
243 privacy: body.privacy || VideoPrivacy.PRIVATE,
244 duration: 0, // duration will be set by the import job
245 channelId: channelId,
246 originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt
248 const video = new VideoModel(videoData)
249 video.url = getLocalVideoActivityPubUrl(video)
254 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
255 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
256 if (thumbnailField) {
257 const thumbnailPhysicalFile = thumbnailField[0]
259 return createVideoMiniatureFromExisting({
260 inputPath: thumbnailPhysicalFile.path,
262 type: ThumbnailType.MINIATURE,
263 automaticallyGenerated: false
270 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
271 const previewField = req.files ? req.files['previewfile'] : undefined
273 const previewPhysicalFile = previewField[0]
275 return createVideoMiniatureFromExisting({
276 inputPath: previewPhysicalFile.path,
278 type: ThumbnailType.PREVIEW,
279 automaticallyGenerated: false
286 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
288 return createVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
290 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
295 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
297 return createVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
299 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
304 async function insertIntoDB (parameters: {
305 video: MVideoThumbnail
306 thumbnailModel: MThumbnail
307 previewModel: MThumbnail
308 videoChannel: MChannelAccountDefault
310 videoImportAttributes: Partial<MVideoImport>
312 }): Promise<MVideoImportFormattable> {
313 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
315 const videoImport = await sequelizeTypescript.transaction(async t => {
316 const sequelizeOptions = { transaction: t }
318 // Save video object in database
319 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
320 videoCreated.VideoChannel = videoChannel
322 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
323 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
325 await autoBlacklistVideoIfNeeded({
334 await setVideoTags({ video: videoCreated, tags, transaction: t })
336 // Create video import object in database
337 const videoImport = await VideoImportModel.create(
338 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
340 ) as MVideoImportFormattable
341 videoImport.Video = videoCreated