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