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 { setVideoTags } from '@server/lib/video'
8 MChannelAccountDefault,
15 MVideoWithBlacklistLight
16 } from '@server/types/models'
17 import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import'
18 import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
19 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
20 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
21 import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
22 import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
23 import { isArray } from '../../../helpers/custom-validators/misc'
24 import { createReqFiles } from '../../../helpers/express-utils'
25 import { logger } from '../../../helpers/logger'
26 import { getSecureTorrentName } from '../../../helpers/utils'
27 import { getYoutubeDLInfo, getYoutubeDLSubs, YoutubeDLInfo } from '../../../helpers/youtube-dl'
28 import { CONFIG } from '../../../initializers/config'
29 import { MIMETYPES } from '../../../initializers/constants'
30 import { sequelizeTypescript } from '../../../initializers/database'
31 import { getLocalVideoActivityPubUrl } from '../../../lib/activitypub/url'
32 import { JobQueue } from '../../../lib/job-queue/job-queue'
33 import { createVideoMiniatureFromExisting, createVideoMiniatureFromUrl } from '../../../lib/thumbnail'
34 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
35 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
36 import { VideoModel } from '../../../models/video/video'
37 import { VideoCaptionModel } from '../../../models/video/video-caption'
38 import { VideoImportModel } from '../../../models/video/video-import'
40 const auditLogger = auditLoggerFactory('video-imports')
41 const videoImportsRouter = express.Router()
43 const reqVideoFileImport = createReqFiles(
44 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
45 Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
47 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
48 previewfile: CONFIG.STORAGE.TMP_DIR,
49 torrentfile: CONFIG.STORAGE.TMP_DIR
53 videoImportsRouter.post('/imports',
56 asyncMiddleware(videoImportAddValidator),
57 asyncRetryTransactionMiddleware(addVideoImport)
60 // ---------------------------------------------------------------------------
66 // ---------------------------------------------------------------------------
68 function addVideoImport (req: express.Request, res: express.Response) {
69 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
71 const file = req.files?.['torrentfile']?.[0]
72 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
75 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
76 const body: VideoImportCreate = req.body
77 const user = res.locals.oauth.token.User
80 let torrentName: string
84 torrentName = torrentfile.originalname
86 // Rename the torrent to a secured name
87 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
88 await move(torrentfile.path, newTorrentPath)
89 torrentfile.path = newTorrentPath
91 const buf = await readFile(torrentfile.path)
92 const parsedTorrent = parseTorrent(buf)
94 videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name as string
96 magnetUri = body.magnetUri
98 const parsed = magnetUtil.decode(magnetUri)
99 videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
102 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
104 const thumbnailModel = await processThumbnail(req, video)
105 const previewModel = await processPreview(req, video)
107 const tags = body.tags || undefined
108 const videoImportAttributes = {
111 state: VideoImportState.PENDING,
114 const videoImport = await insertIntoDB({
118 videoChannel: res.locals.videoChannel,
120 videoImportAttributes,
124 // Create job to import the video
126 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
127 videoImportId: videoImport.id,
130 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
132 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
134 return res.json(videoImport.toFormattedJSON()).end()
137 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
138 const body: VideoImportCreate = req.body
139 const targetUrl = body.targetUrl
140 const user = res.locals.oauth.token.User
143 let youtubeDLInfo: YoutubeDLInfo
145 youtubeDLInfo = await getYoutubeDLInfo(targetUrl)
147 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
149 return res.status(HttpStatusCode.BAD_REQUEST_400)
151 error: 'Cannot fetch remote information of this URL.'
155 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
157 // Process video thumbnail from request.files
158 let thumbnailModel = await processThumbnail(req, video)
160 // Process video thumbnail from url if processing from request.files failed
161 if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) {
162 thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video)
165 // Process video preview from request.files
166 let previewModel = await processPreview(req, video)
168 // Process video preview from url if processing from request.files failed
169 if (!previewModel && youtubeDLInfo.thumbnailUrl) {
170 previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video)
173 const tags = body.tags || youtubeDLInfo.tags
174 const videoImportAttributes = {
176 state: VideoImportState.PENDING,
179 const videoImport = await insertIntoDB({
183 videoChannel: res.locals.videoChannel,
185 videoImportAttributes,
189 // Get video subtitles
191 const subtitles = await getYoutubeDLSubs(targetUrl)
193 logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
195 for (const subtitle of subtitles) {
196 const videoCaption = new VideoCaptionModel({
198 language: subtitle.language,
199 filename: VideoCaptionModel.generateCaptionName(subtitle.language)
202 // Move physical file
203 await moveAndProcessCaptionFile(subtitle, videoCaption)
205 await sequelizeTypescript.transaction(async t => {
206 await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
210 logger.warn('Cannot get video subtitles.', { err })
213 // Create job to import the video
215 type: 'youtube-dl' as 'youtube-dl',
216 videoImportId: videoImport.id,
217 fileExt: `.${youtubeDLInfo.ext || 'mp4'}`
219 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
221 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
223 return res.json(videoImport.toFormattedJSON()).end()
226 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo): MVideoThumbnail {
228 name: body.name || importData.name || 'Unknown name',
230 category: body.category || importData.category,
231 licence: body.licence || importData.licence,
232 language: body.language || importData.language,
233 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
234 downloadEnabled: body.downloadEnabled !== false,
235 waitTranscoding: body.waitTranscoding || false,
236 state: VideoState.TO_IMPORT,
237 nsfw: body.nsfw || importData.nsfw || false,
238 description: body.description || importData.description,
239 support: body.support || null,
240 privacy: body.privacy || VideoPrivacy.PRIVATE,
241 duration: 0, // duration will be set by the import job
242 channelId: channelId,
243 originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt
245 const video = new VideoModel(videoData)
246 video.url = getLocalVideoActivityPubUrl(video)
251 async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
252 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
253 if (thumbnailField) {
254 const thumbnailPhysicalFile = thumbnailField[0]
256 return createVideoMiniatureFromExisting({
257 inputPath: thumbnailPhysicalFile.path,
259 type: ThumbnailType.MINIATURE,
260 automaticallyGenerated: false
267 async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
268 const previewField = req.files ? req.files['previewfile'] : undefined
270 const previewPhysicalFile = previewField[0]
272 return createVideoMiniatureFromExisting({
273 inputPath: previewPhysicalFile.path,
275 type: ThumbnailType.PREVIEW,
276 automaticallyGenerated: false
283 async function processThumbnailFromUrl (url: string, video: MVideoThumbnail) {
285 return createVideoMiniatureFromUrl(url, video, ThumbnailType.MINIATURE)
287 logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err })
292 async function processPreviewFromUrl (url: string, video: MVideoThumbnail) {
294 return createVideoMiniatureFromUrl(url, video, ThumbnailType.PREVIEW)
296 logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err })
301 function insertIntoDB (parameters: {
302 video: MVideoThumbnail
303 thumbnailModel: MThumbnail
304 previewModel: MThumbnail
305 videoChannel: MChannelAccountDefault
307 videoImportAttributes: Partial<MVideoImport>
309 }): Promise<MVideoImportFormattable> {
310 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
312 return sequelizeTypescript.transaction(async t => {
313 const sequelizeOptions = { transaction: t }
315 // Save video object in database
316 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
317 videoCreated.VideoChannel = videoChannel
319 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
320 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
322 await autoBlacklistVideoIfNeeded({
331 await setVideoTags({ video: videoCreated, tags, transaction: t })
333 // Create video import object in database
334 const videoImport = await VideoImportModel.create(
335 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
337 ) as MVideoImportFormattable
338 videoImport.Video = videoCreated