1 import * as express from 'express'
2 import * as magnetUtil from 'magnet-uri'
4 import { auditLoggerFactory, VideoImportAuditView } from '../../../helpers/audit-logger'
5 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
13 } from '../../../initializers'
14 import { getYoutubeDLInfo, YoutubeDLInfo } from '../../../helpers/youtube-dl'
15 import { createReqFiles } from '../../../helpers/express-utils'
16 import { logger } from '../../../helpers/logger'
17 import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
18 import { VideoModel } from '../../../models/video/video'
19 import { getVideoActivityPubUrl } from '../../../lib/activitypub'
20 import { TagModel } from '../../../models/video/tag'
21 import { VideoImportModel } from '../../../models/video/video-import'
22 import { JobQueue } from '../../../lib/job-queue/job-queue'
23 import { processImage } from '../../../helpers/image-utils'
24 import { join } from 'path'
25 import { isArray } from '../../../helpers/custom-validators/misc'
26 import { FilteredModelAttributes } from 'sequelize-typescript/lib/models/Model'
27 import { VideoChannelModel } from '../../../models/video/video-channel'
28 import * as Bluebird from 'bluebird'
29 import * as parseTorrent from 'parse-torrent'
30 import { readFileBufferPromise, renamePromise } from '../../../helpers/core-utils'
31 import { getSecureTorrentName } from '../../../helpers/utils'
33 const auditLogger = auditLoggerFactory('video-imports')
34 const videoImportsRouter = express.Router()
36 const reqVideoFileImport = createReqFiles(
37 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
38 Object.assign({}, TORRENT_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
40 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
41 previewfile: CONFIG.STORAGE.PREVIEWS_DIR,
42 torrentfile: CONFIG.STORAGE.TORRENTS_DIR
46 videoImportsRouter.post('/imports',
49 asyncMiddleware(videoImportAddValidator),
50 asyncRetryTransactionMiddleware(addVideoImport)
53 // ---------------------------------------------------------------------------
59 // ---------------------------------------------------------------------------
61 function addVideoImport (req: express.Request, res: express.Response) {
62 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
64 const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
65 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
68 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
69 const body: VideoImportCreate = req.body
70 const user = res.locals.oauth.token.User
73 let torrentName: string
77 torrentName = torrentfile.originalname
79 // Rename the torrent to a secured name
80 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
81 await renamePromise(torrentfile.path, newTorrentPath)
82 torrentfile.path = newTorrentPath
84 const buf = await readFileBufferPromise(torrentfile.path)
85 const parsedTorrent = parseTorrent(buf)
87 videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[ 0 ] : parsedTorrent.name as string
89 magnetUri = body.magnetUri
91 const parsed = magnetUtil.decode(magnetUri)
92 videoName = isArray(parsed.name) ? parsed.name[ 0 ] : parsed.name as string
95 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
97 await processThumbnail(req, video)
98 await processPreview(req, video)
101 const videoImportAttributes = {
104 state: VideoImportState.PENDING,
107 const videoImport: VideoImportModel = await insertIntoDB(video, res.locals.videoChannel, tags, videoImportAttributes)
109 // Create job to import the video
111 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
112 videoImportId: videoImport.id,
115 await JobQueue.Instance.createJob({ type: 'video-import', payload })
117 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoImportAuditView(videoImport.toFormattedJSON()))
119 return res.json(videoImport.toFormattedJSON()).end()
122 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
123 const body: VideoImportCreate = req.body
124 const targetUrl = body.targetUrl
125 const user = res.locals.oauth.token.User
127 let youtubeDLInfo: YoutubeDLInfo
129 youtubeDLInfo = await getYoutubeDLInfo(targetUrl)
131 logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
133 return res.status(400).json({
134 error: 'Cannot fetch remote information of this URL.'
138 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
140 const downloadThumbnail = !await processThumbnail(req, video)
141 const downloadPreview = !await processPreview(req, video)
143 const tags = body.tags || youtubeDLInfo.tags
144 const videoImportAttributes = {
146 state: VideoImportState.PENDING,
149 const videoImport: VideoImportModel = await insertIntoDB(video, res.locals.videoChannel, tags, videoImportAttributes)
151 // Create job to import the video
153 type: 'youtube-dl' as 'youtube-dl',
154 videoImportId: videoImport.id,
155 thumbnailUrl: youtubeDLInfo.thumbnailUrl,
159 await JobQueue.Instance.createJob({ type: 'video-import', payload })
161 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoImportAuditView(videoImport.toFormattedJSON()))
163 return res.json(videoImport.toFormattedJSON()).end()
166 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
168 name: body.name || importData.name || 'Unknown name',
170 category: body.category || importData.category,
171 licence: body.licence || importData.licence,
172 language: body.language || undefined,
173 commentsEnabled: body.commentsEnabled || true,
174 waitTranscoding: body.waitTranscoding || false,
175 state: VideoState.TO_IMPORT,
176 nsfw: body.nsfw || importData.nsfw || false,
177 description: body.description || importData.description,
178 support: body.support || null,
179 privacy: body.privacy || VideoPrivacy.PRIVATE,
180 duration: 0, // duration will be set by the import job
183 const video = new VideoModel(videoData)
184 video.url = getVideoActivityPubUrl(video)
189 async function processThumbnail (req: express.Request, video: VideoModel) {
190 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
191 if (thumbnailField) {
192 const thumbnailPhysicalFile = thumbnailField[ 0 ]
193 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
201 async function processPreview (req: express.Request, video: VideoModel) {
202 const previewField = req.files ? req.files['previewfile'] : undefined
204 const previewPhysicalFile = previewField[0]
205 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
213 function insertIntoDB (
215 videoChannel: VideoChannelModel,
217 videoImportAttributes: FilteredModelAttributes<VideoImportModel>
218 ): Bluebird<VideoImportModel> {
219 return sequelizeTypescript.transaction(async t => {
220 const sequelizeOptions = { transaction: t }
222 // Save video object in database
223 const videoCreated = await video.save(sequelizeOptions)
224 videoCreated.VideoChannel = videoChannel
226 // Set tags to the video
227 if (tags !== undefined) {
228 const tagInstances = await TagModel.findOrCreateTags(tags, t)
230 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
231 videoCreated.Tags = tagInstances
234 // Create video import object in database
235 const videoImport = await VideoImportModel.create(
236 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
239 videoImport.Video = videoCreated