94dafcdbdc28707699f0a6a714f6b3a89962ca78
[oweals/peertube.git] / server / controllers / api / videos / import.ts
1 import * as express from 'express'
2 import * as magnetUtil from 'magnet-uri'
3 import 'multer'
4 import { auditLoggerFactory, VideoImportAuditView } from '../../../helpers/audit-logger'
5 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
6 import {
7   CONFIG,
8   IMAGE_MIMETYPE_EXT,
9   PREVIEWS_SIZE,
10   sequelizeTypescript,
11   THUMBNAILS_SIZE,
12   TORRENT_MIMETYPE_EXT
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'
32
33 const auditLogger = auditLoggerFactory('video-imports')
34 const videoImportsRouter = express.Router()
35
36 const reqVideoFileImport = createReqFiles(
37   [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
38   Object.assign({}, TORRENT_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
39   {
40     thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
41     previewfile: CONFIG.STORAGE.PREVIEWS_DIR,
42     torrentfile: CONFIG.STORAGE.TORRENTS_DIR
43   }
44 )
45
46 videoImportsRouter.post('/imports',
47   authenticate,
48   reqVideoFileImport,
49   asyncMiddleware(videoImportAddValidator),
50   asyncRetryTransactionMiddleware(addVideoImport)
51 )
52
53 // ---------------------------------------------------------------------------
54
55 export {
56   videoImportsRouter
57 }
58
59 // ---------------------------------------------------------------------------
60
61 function addVideoImport (req: express.Request, res: express.Response) {
62   if (req.body.targetUrl) return addYoutubeDLImport(req, res)
63
64   const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
65   if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
66 }
67
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
71
72   let videoName: string
73   let torrentName: string
74   let magnetUri: string
75
76   if (torrentfile) {
77     torrentName = torrentfile.originalname
78
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
83
84     const buf = await readFileBufferPromise(torrentfile.path)
85     const parsedTorrent = parseTorrent(buf)
86
87     videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[ 0 ] : parsedTorrent.name as string
88   } else {
89     magnetUri = body.magnetUri
90
91     const parsed = magnetUtil.decode(magnetUri)
92     videoName = isArray(parsed.name) ? parsed.name[ 0 ] : parsed.name as string
93   }
94
95   const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
96
97   await processThumbnail(req, video)
98   await processPreview(req, video)
99
100   const tags = null
101   const videoImportAttributes = {
102     magnetUri,
103     torrentName,
104     state: VideoImportState.PENDING,
105     userId: user.id
106   }
107   const videoImport: VideoImportModel = await insertIntoDB(video, res.locals.videoChannel, tags, videoImportAttributes)
108
109   // Create job to import the video
110   const payload = {
111     type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
112     videoImportId: videoImport.id,
113     magnetUri
114   }
115   await JobQueue.Instance.createJob({ type: 'video-import', payload })
116
117   auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoImportAuditView(videoImport.toFormattedJSON()))
118
119   return res.json(videoImport.toFormattedJSON()).end()
120 }
121
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
126
127   let youtubeDLInfo: YoutubeDLInfo
128   try {
129     youtubeDLInfo = await getYoutubeDLInfo(targetUrl)
130   } catch (err) {
131     logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
132
133     return res.status(400).json({
134       error: 'Cannot fetch remote information of this URL.'
135     }).end()
136   }
137
138   const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
139
140   const downloadThumbnail = !await processThumbnail(req, video)
141   const downloadPreview = !await processPreview(req, video)
142
143   const tags = body.tags || youtubeDLInfo.tags
144   const videoImportAttributes = {
145     targetUrl,
146     state: VideoImportState.PENDING,
147     userId: user.id
148   }
149   const videoImport: VideoImportModel = await insertIntoDB(video, res.locals.videoChannel, tags, videoImportAttributes)
150
151   // Create job to import the video
152   const payload = {
153     type: 'youtube-dl' as 'youtube-dl',
154     videoImportId: videoImport.id,
155     thumbnailUrl: youtubeDLInfo.thumbnailUrl,
156     downloadThumbnail,
157     downloadPreview
158   }
159   await JobQueue.Instance.createJob({ type: 'video-import', payload })
160
161   auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoImportAuditView(videoImport.toFormattedJSON()))
162
163   return res.json(videoImport.toFormattedJSON()).end()
164 }
165
166 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
167   const videoData = {
168     name: body.name || importData.name || 'Unknown name',
169     remote: false,
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
181     channelId: channelId
182   }
183   const video = new VideoModel(videoData)
184   video.url = getVideoActivityPubUrl(video)
185
186   return video
187 }
188
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)
194
195     return true
196   }
197
198   return false
199 }
200
201 async function processPreview (req: express.Request, video: VideoModel) {
202   const previewField = req.files ? req.files['previewfile'] : undefined
203   if (previewField) {
204     const previewPhysicalFile = previewField[0]
205     await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
206
207     return true
208   }
209
210   return false
211 }
212
213 function insertIntoDB (
214   video: VideoModel,
215   videoChannel: VideoChannelModel,
216   tags: string[],
217   videoImportAttributes: FilteredModelAttributes<VideoImportModel>
218 ): Bluebird<VideoImportModel> {
219   return sequelizeTypescript.transaction(async t => {
220     const sequelizeOptions = { transaction: t }
221
222     // Save video object in database
223     const videoCreated = await video.save(sequelizeOptions)
224     videoCreated.VideoChannel = videoChannel
225
226     // Set tags to the video
227     if (tags !== undefined) {
228       const tagInstances = await TagModel.findOrCreateTags(tags, t)
229
230       await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
231       videoCreated.Tags = tagInstances
232     }
233
234     // Create video import object in database
235     const videoImport = await VideoImportModel.create(
236       Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
237       sequelizeOptions
238     )
239     videoImport.Video = videoCreated
240
241     return videoImport
242   })
243 }