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