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'
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 { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
22 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
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 { YoutubeDL, YoutubeDLInfo } 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 { createVideoMiniatureFromExisting, createVideoMiniatureFromUrl } 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 torrentName = torrentfile.originalname
88 // Rename the torrent to a secured name
89 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
90 await move(torrentfile.path, newTorrentPath, { overwrite: true })
91 torrentfile.path = newTorrentPath
93 const buf = await readFile(torrentfile.path)
94 const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance
96 if (parsedTorrent.files.length !== 1) {
99 return res.status(HttpStatusCode.BAD_REQUEST_400)
101 code: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
102 error: 'Torrents with only 1 file are supported.'
106 videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name
108 magnetUri = body.magnetUri
110 const parsed = magnetUtil.decode(magnetUri)
111 videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
114 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
116 const thumbnailModel = await processThumbnail(req, video)
117 const previewModel = await processPreview(req, video)
119 const tags = body.tags || undefined
120 const videoImportAttributes = {
123 state: VideoImportState.PENDING,
126 const videoImport = await insertIntoDB({
130 videoChannel: res.locals.videoChannel,
132 videoImportAttributes,
136 // Create job to import the video
138 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
139 videoImportId: videoImport.id,
142 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
144 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
146 return res.json(videoImport.toFormattedJSON()).end()
149 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
150 const body: VideoImportCreate = req.body
151 const targetUrl = body.targetUrl
152 const user = res.locals.oauth.token.User
154 const youtubeDL = new YoutubeDL(targetUrl, getEnabledResolutions('vod'))
157 let youtubeDLInfo: YoutubeDLInfo
159 youtubeDLInfo = await youtubeDL.getYoutubeDLInfo()
161 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
163 return res.status(HttpStatusCode.BAD_REQUEST_400)
165 error: 'Cannot fetch remote information of this URL.'
169 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
171 // Process video thumbnail from request.files
172 let thumbnailModel = await processThumbnail(req, video)
174 // Process video thumbnail from url if processing from request.files failed
175 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
176 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
179 // Process video preview from request.files
180 let previewModel = await processPreview(req, video)
182 // Process video preview from url if processing from request.files failed
183 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
184 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
187 const tags = body.tags || youtubeDLInfo.tags
188 const videoImportAttributes = {
190 state: VideoImportState.PENDING,
193 const videoImport = await insertIntoDB({
197 videoChannel: res.locals.videoChannel,
199 videoImportAttributes,
203 // Get video subtitles
205 const subtitles = await youtubeDL.getYoutubeDLSubs()
207 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
209 for (const subtitle of subtitles) {
210 const videoCaption = new VideoCaptionModel({
212 language: subtitle.language,
213 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
216 // Move physical file
217 await moveAndProcessCaptionFile(subtitle, videoCaption)
219 await sequelizeTypescript.transaction(async t => {
220 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
224 logger.warn('Cannot get video subtitles.', { err })
227 // Create job to import the video
229 type: 'youtube-dl' as 'youtube-dl',
230 videoImportId: videoImport.id,
231 fileExt: `.${youtubeDLInfo.ext || 'mp4'}`
233 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
235 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
237 return res.json(videoImport.toFormattedJSON()).end()
240 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
242 name: body.name || importData.name || 'Unknown name',
244 category: body.category || importData.category,
245 licence: body.licence || importData.licence,
246 language: body.language || importData.language,
247 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
248 downloadEnabled: body.downloadEnabled !== false,
249 waitTranscoding: body.waitTranscoding || false,
250 state: VideoState.TO_IMPORT,
251 nsfw: body.nsfw || importData.nsfw || false,
252 description: body.description || importData.description,
253 support: body.support || null,
254 privacy: body.privacy || VideoPrivacy.PRIVATE,
255 duration: 0, // duration will be set by the import job
256 channelId: channelId,
257 originallyPublishedAt: body.originallyPublishedAt
258 ? new Date(body.originallyPublishedAt)
259 : importData.originallyPublishedAt
261 const video = new VideoModel(videoData)
262 video.url = getLocalVideoActivityPubUrl(video)
267 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
268 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
269 if (thumbnailField) {
270 const thumbnailPhysicalFile = thumbnailField[0]
272 return createVideoMiniatureFromExisting({
273 inputPath: thumbnailPhysicalFile.path,
275 type: ThumbnailType.MINIATURE,
276 automaticallyGenerated: false
283 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
284 const previewField = req.files ? req.files['previewfile'] : undefined
286 const previewPhysicalFile = previewField[0]
288 return createVideoMiniatureFromExisting({
289 inputPath: previewPhysicalFile.path,
291 type: ThumbnailType.PREVIEW,
292 automaticallyGenerated: false
299 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
301 return createVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.MINIATURE })
303 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
308 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
310 return createVideoMiniatureFromUrl({ downloadUrl: url, video, type: ThumbnailType.PREVIEW })
312 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
317 async function insertIntoDB (parameters: {
318 video: MVideoThumbnail
319 thumbnailModel: MThumbnail
320 previewModel: MThumbnail
321 videoChannel: MChannelAccountDefault
323 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
325 }): Promise<MVideoImportFormattable> {
326 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
328 const videoImport = await sequelizeTypescript.transaction(async t => {
329 const sequelizeOptions = { transaction: t }
331 // Save video object in database
332 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
333 videoCreated.VideoChannel = videoChannel
335 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
336 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
338 await autoBlacklistVideoIfNeeded({
347 await setVideoTags({ video: videoCreated, tags, transaction: t })
349 // Create video import object in database
350 const videoImport = await VideoImportModel.create(
351 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
353 ) as MVideoImportFormattable
354 videoImport.Video = videoCreated