+function addVideoImport (req: express.Request, res: express.Response) {
+ if (req.body.targetUrl) return addYoutubeDLImport(req, res)
+
+ const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
+ if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
+}
+
+async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
+ const body: VideoImportCreate = req.body
+ const user = res.locals.oauth.token.User
+
+ let videoName: string
+ let torrentName: string
+ let magnetUri: string
+
+ if (torrentfile) {
+ torrentName = torrentfile.originalname
+
+ // Rename the torrent to a secured name
+ const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
+ await rename(torrentfile.path, newTorrentPath)
+ torrentfile.path = newTorrentPath
+
+ const buf = await readFile(torrentfile.path)
+ const parsedTorrent = parseTorrent(buf)
+
+ videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[ 0 ] : parsedTorrent.name as string
+ } else {
+ magnetUri = body.magnetUri
+
+ const parsed = magnetUtil.decode(magnetUri)
+ videoName = isArray(parsed.name) ? parsed.name[ 0 ] : parsed.name as string
+ }
+
+ const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
+
+ await processThumbnail(req, video)
+ await processPreview(req, video)
+
+ const tags = body.tags || undefined
+ const videoImportAttributes = {
+ magnetUri,
+ torrentName,
+ state: VideoImportState.PENDING,
+ userId: user.id
+ }
+ const videoImport: VideoImportModel = await insertIntoDB(video, res.locals.videoChannel, tags, videoImportAttributes)
+
+ // Create job to import the video
+ const payload = {
+ type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
+ videoImportId: videoImport.id,
+ magnetUri
+ }
+ await JobQueue.Instance.createJob({ type: 'video-import', payload })
+
+ auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
+
+ return res.json(videoImport.toFormattedJSON()).end()
+}
+
+async function addYoutubeDLImport (req: express.Request, res: express.Response) {