1 import * as express from 'express'
2 import * as magnetUtil from 'magnet-uri'
3 import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
4 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
5 import { MIMETYPES } from '../../../initializers/constants'
6 import { getYoutubeDLInfo, YoutubeDLInfo } from '../../../helpers/youtube-dl'
7 import { createReqFiles } from '../../../helpers/express-utils'
8 import { logger } from '../../../helpers/logger'
9 import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
10 import { VideoModel } from '../../../models/video/video'
11 import { getVideoActivityPubUrl } from '../../../lib/activitypub'
12 import { TagModel } from '../../../models/video/tag'
13 import { VideoImportModel } from '../../../models/video/video-import'
14 import { JobQueue } from '../../../lib/job-queue/job-queue'
15 import { join } from 'path'
16 import { isArray } from '../../../helpers/custom-validators/misc'
17 import * as Bluebird from 'bluebird'
18 import * as parseTorrent from 'parse-torrent'
19 import { getSecureTorrentName } from '../../../helpers/utils'
20 import { move, readFile } from 'fs-extra'
21 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
22 import { CONFIG } from '../../../initializers/config'
23 import { sequelizeTypescript } from '../../../initializers/database'
24 import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail'
25 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
27 MChannelAccountDefault,
32 MVideoThumbnailAccountDefault,
33 MVideoWithBlacklistLight
34 } from '@server/typings/models'
35 import { MVideoImport, MVideoImportFormattable } from '@server/typings/models/video/video-import'
37 const auditLogger = auditLoggerFactory('video-imports')
38 const videoImportsRouter = express.Router()
40 const reqVideoFileImport = createReqFiles(
41 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
42 Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
44 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
45 previewfile: CONFIG.STORAGE.TMP_DIR,
46 torrentfile: CONFIG.STORAGE.TMP_DIR
50 videoImportsRouter.post('/imports',
53 asyncMiddleware(videoImportAddValidator),
54 asyncRetryTransactionMiddleware(addVideoImport)
57 // ---------------------------------------------------------------------------
63 // ---------------------------------------------------------------------------
65 function addVideoImport (req: express.Request, res: express.Response) {
66 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
68 const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
69 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
72 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
73 const body: VideoImportCreate = req.body
74 const user = res.locals.oauth.token.User
77 let torrentName: string
81 torrentName = torrentfile.originalname
83 // Rename the torrent to a secured name
84 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
85 await move(torrentfile.path, newTorrentPath)
86 torrentfile.path = newTorrentPath
88 const buf = await readFile(torrentfile.path)
89 const parsedTorrent = parseTorrent(buf)
91 videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name as string
93 magnetUri = body.magnetUri
95 const parsed = magnetUtil.decode(magnetUri)
96 videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
99 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
101 const thumbnailModel = await processThumbnail(req, video)
102 const previewModel = await processPreview(req, video)
104 const tags = body.tags || undefined
105 const videoImportAttributes = {
108 state: VideoImportState.PENDING,
111 const videoImport = await insertIntoDB({
115 videoChannel: res.locals.videoChannel,
117 videoImportAttributes,
121 // Create job to import the video
123 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
124 videoImportId: videoImport.id,
127 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
129 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
131 return res.json(videoImport.toFormattedJSON()).end()
134 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
135 const body: VideoImportCreate = req.body
136 const targetUrl = body.targetUrl
137 const user = res.locals.oauth.token.User
139 let youtubeDLInfo: YoutubeDLInfo
141 youtubeDLInfo = await getYoutubeDLInfo(targetUrl)
143 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
145 return res.status(400).json({
146 error: 'Cannot fetch remote information of this URL.'
150 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
152 const thumbnailModel = await processThumbnail(req, video)
153 const previewModel = await processPreview(req, video)
155 const tags = body.tags || youtubeDLInfo.tags
156 const videoImportAttributes = {
158 state: VideoImportState.PENDING,
161 const videoImport = await insertIntoDB({
165 videoChannel: res.locals.videoChannel,
167 videoImportAttributes,
171 // Create job to import the video
173 type: 'youtube-dl' as 'youtube-dl',
174 videoImportId: videoImport.id,
175 thumbnailUrl: youtubeDLInfo.thumbnailUrl,
176 downloadThumbnail: !thumbnailModel,
177 downloadPreview: !previewModel
179 await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
181 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
183 return res.json(videoImport.toFormattedJSON()).end()
186 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
188 name: body.name || importData.name || 'Unknown name',
190 category: body.category || importData.category,
191 licence: body.licence || importData.licence,
192 language: body.language || undefined,
193 commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
194 downloadEnabled: body.downloadEnabled !== false,
195 waitTranscoding: body.waitTranscoding || false,
196 state: VideoState.TO_IMPORT,
197 nsfw: body.nsfw || importData.nsfw || false,
198 description: body.description || importData.description,
199 support: body.support || null,
200 privacy: body.privacy || VideoPrivacy.PRIVATE,
201 duration: 0, // duration will be set by the import job
202 channelId: channelId,
203 originallyPublishedAt: importData.originallyPublishedAt
205 const video = new VideoModel(videoData)
206 video.url = getVideoActivityPubUrl(video)
211 async function processThumbnail (req: express.Request, video: VideoModel) {
212 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
213 if (thumbnailField) {
214 const thumbnailPhysicalFile = thumbnailField[0]
216 return createVideoMiniatureFromExisting(thumbnailPhysicalFile.path, video, ThumbnailType.MINIATURE, false)
222 async function processPreview (req: express.Request, video: VideoModel) {
223 const previewField = req.files ? req.files['previewfile'] : undefined
225 const previewPhysicalFile = previewField[0]
227 return createVideoMiniatureFromExisting(previewPhysicalFile.path, video, ThumbnailType.PREVIEW, false)
233 function insertIntoDB (parameters: {
234 video: MVideoThumbnailAccountDefault
235 thumbnailModel: MThumbnail
236 previewModel: MThumbnail
237 videoChannel: MChannelAccountDefault
239 videoImportAttributes: Partial<MVideoImport>
241 }): Bluebird<MVideoImportFormattable> {
242 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
244 return sequelizeTypescript.transaction(async t => {
245 const sequelizeOptions = { transaction: t }
247 // Save video object in database
248 const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
249 videoCreated.VideoChannel = videoChannel
251 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
252 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
254 await autoBlacklistVideoIfNeeded({
263 // Set tags to the video
265 const tagInstances = await TagModel.findOrCreateTags(tags, t)
267 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
268 videoCreated.Tags = tagInstances
270 videoCreated.Tags = []
273 // Create video import object in database
274 const videoImport = await VideoImportModel.create(
275 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
277 ) as MVideoImportFormattable
278 videoImport.Video = videoCreated