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