add quarantine videos feature (#1637)
[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, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
5 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
6 import { CONFIG, MIMETYPES, PREVIEWS_SIZE, sequelizeTypescript, THUMBNAILS_SIZE } from '../../../initializers'
7 import { getYoutubeDLInfo, YoutubeDLInfo } from '../../../helpers/youtube-dl'
8 import { createReqFiles } from '../../../helpers/express-utils'
9 import { logger } from '../../../helpers/logger'
10 import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
11 import { VideoModel } from '../../../models/video/video'
12 import { getVideoActivityPubUrl } from '../../../lib/activitypub'
13 import { TagModel } from '../../../models/video/tag'
14 import { VideoImportModel } from '../../../models/video/video-import'
15 import { JobQueue } from '../../../lib/job-queue/job-queue'
16 import { processImage } from '../../../helpers/image-utils'
17 import { join } from 'path'
18 import { isArray } from '../../../helpers/custom-validators/misc'
19 import { FilteredModelAttributes } from 'sequelize-typescript/lib/models/Model'
20 import { VideoChannelModel } from '../../../models/video/video-channel'
21 import { UserModel } from '../../../models/account/user'
22 import * as Bluebird from 'bluebird'
23 import * as parseTorrent from 'parse-torrent'
24 import { getSecureTorrentName } from '../../../helpers/utils'
25 import { readFile, move } from 'fs-extra'
26 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
27
28 const auditLogger = auditLoggerFactory('video-imports')
29 const videoImportsRouter = express.Router()
30
31 const reqVideoFileImport = createReqFiles(
32   [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
33   Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
34   {
35     thumbnailfile: CONFIG.STORAGE.TMP_DIR,
36     previewfile: CONFIG.STORAGE.TMP_DIR,
37     torrentfile: CONFIG.STORAGE.TMP_DIR
38   }
39 )
40
41 videoImportsRouter.post('/imports',
42   authenticate,
43   reqVideoFileImport,
44   asyncMiddleware(videoImportAddValidator),
45   asyncRetryTransactionMiddleware(addVideoImport)
46 )
47
48 // ---------------------------------------------------------------------------
49
50 export {
51   videoImportsRouter
52 }
53
54 // ---------------------------------------------------------------------------
55
56 function addVideoImport (req: express.Request, res: express.Response) {
57   if (req.body.targetUrl) return addYoutubeDLImport(req, res)
58
59   const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
60   if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
61 }
62
63 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
64   const body: VideoImportCreate = req.body
65   const user = res.locals.oauth.token.User
66
67   let videoName: string
68   let torrentName: string
69   let magnetUri: string
70
71   if (torrentfile) {
72     torrentName = torrentfile.originalname
73
74     // Rename the torrent to a secured name
75     const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
76     await move(torrentfile.path, newTorrentPath)
77     torrentfile.path = newTorrentPath
78
79     const buf = await readFile(torrentfile.path)
80     const parsedTorrent = parseTorrent(buf)
81
82     videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[ 0 ] : parsedTorrent.name as string
83   } else {
84     magnetUri = body.magnetUri
85
86     const parsed = magnetUtil.decode(magnetUri)
87     videoName = isArray(parsed.name) ? parsed.name[ 0 ] : parsed.name as string
88   }
89
90   const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName }, user)
91
92   await processThumbnail(req, video)
93   await processPreview(req, video)
94
95   const tags = body.tags || undefined
96   const videoImportAttributes = {
97     magnetUri,
98     torrentName,
99     state: VideoImportState.PENDING,
100     userId: user.id
101   }
102   const videoImport = await insertIntoDB(video, res.locals.videoChannel, tags, videoImportAttributes)
103
104   // Create job to import the video
105   const payload = {
106     type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
107     videoImportId: videoImport.id,
108     magnetUri
109   }
110   await JobQueue.Instance.createJob({ type: 'video-import', payload })
111
112   auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
113
114   return res.json(videoImport.toFormattedJSON()).end()
115 }
116
117 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
118   const body: VideoImportCreate = req.body
119   const targetUrl = body.targetUrl
120   const user = res.locals.oauth.token.User
121
122   let youtubeDLInfo: YoutubeDLInfo
123   try {
124     youtubeDLInfo = await getYoutubeDLInfo(targetUrl)
125   } catch (err) {
126     logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
127
128     return res.status(400).json({
129       error: 'Cannot fetch remote information of this URL.'
130     }).end()
131   }
132
133   const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo, user)
134
135   const downloadThumbnail = !await processThumbnail(req, video)
136   const downloadPreview = !await processPreview(req, video)
137
138   const tags = body.tags || youtubeDLInfo.tags
139   const videoImportAttributes = {
140     targetUrl,
141     state: VideoImportState.PENDING,
142     userId: user.id
143   }
144   const videoImport = await insertIntoDB(video, res.locals.videoChannel, tags, videoImportAttributes)
145
146   // Create job to import the video
147   const payload = {
148     type: 'youtube-dl' as 'youtube-dl',
149     videoImportId: videoImport.id,
150     thumbnailUrl: youtubeDLInfo.thumbnailUrl,
151     downloadThumbnail,
152     downloadPreview
153   }
154   await JobQueue.Instance.createJob({ type: 'video-import', payload })
155
156   auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
157
158   return res.json(videoImport.toFormattedJSON()).end()
159 }
160
161 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo, user: UserModel) {
162   const videoData = {
163     name: body.name || importData.name || 'Unknown name',
164     remote: false,
165     category: body.category || importData.category,
166     licence: body.licence || importData.licence,
167     language: body.language || undefined,
168     commentsEnabled: body.commentsEnabled || true,
169     downloadEnabled: body.downloadEnabled || true,
170     waitTranscoding: body.waitTranscoding || false,
171     state: VideoState.TO_IMPORT,
172     nsfw: body.nsfw || importData.nsfw || false,
173     description: body.description || importData.description,
174     support: body.support || null,
175     privacy: body.privacy || VideoPrivacy.PRIVATE,
176     duration: 0, // duration will be set by the import job
177     channelId: channelId,
178     originallyPublishedAt: importData.originallyPublishedAt
179   }
180   const video = new VideoModel(videoData)
181   video.url = getVideoActivityPubUrl(video)
182
183   return video
184 }
185
186 async function processThumbnail (req: express.Request, video: VideoModel) {
187   const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
188   if (thumbnailField) {
189     const thumbnailPhysicalFile = thumbnailField[ 0 ]
190     await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
191
192     return true
193   }
194
195   return false
196 }
197
198 async function processPreview (req: express.Request, video: VideoModel) {
199   const previewField = req.files ? req.files['previewfile'] : undefined
200   if (previewField) {
201     const previewPhysicalFile = previewField[0]
202     await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
203
204     return true
205   }
206
207   return false
208 }
209
210 function insertIntoDB (
211   video: VideoModel,
212   videoChannel: VideoChannelModel,
213   tags: string[],
214   videoImportAttributes: FilteredModelAttributes<VideoImportModel>
215 ): Bluebird<VideoImportModel> {
216   return sequelizeTypescript.transaction(async t => {
217     const sequelizeOptions = { transaction: t }
218
219     // Save video object in database
220     const videoCreated = await video.save(sequelizeOptions)
221     videoCreated.VideoChannel = videoChannel
222
223     await autoBlacklistVideoIfNeeded(video, videoChannel.Account.User, t)
224
225     // Set tags to the video
226     if (tags) {
227       const tagInstances = await TagModel.findOrCreateTags(tags, t)
228
229       await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
230       videoCreated.Tags = tagInstances
231     } else {
232       videoCreated.Tags = []
233     }
234
235     // Create video import object in database
236     const videoImport = await VideoImportModel.create(
237       Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
238       sequelizeOptions
239     )
240     videoImport.Video = videoCreated
241
242     return videoImport
243   })
244 }