]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Use async/await in controllers
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
4d4e5cd4 2import * as multer from 'multer'
93e1258c 3import { extname, join } from 'path'
9f10b292 4
e02643f3 5import { database as db } from '../../../initializers/database'
65fcc311
C
6import {
7 CONFIG,
8 REQUEST_VIDEO_QADU_TYPES,
9 REQUEST_VIDEO_EVENT_TYPES,
10 VIDEO_CATEGORIES,
11 VIDEO_LICENCES,
12 VIDEO_LANGUAGES
13} from '../../../initializers'
14import {
15 addEventToRemoteVideo,
16 quickAndDirtyUpdateVideoToFriends,
17 addVideoToFriends,
93e1258c
C
18 updateVideoToFriends,
19 JobScheduler
65fcc311
C
20} from '../../../lib'
21import {
22 authenticate,
23 paginationValidator,
24 videosSortValidator,
25 setVideosSort,
26 setPagination,
27 setVideosSearch,
28 videosUpdateValidator,
29 videosSearchValidator,
30 videosAddValidator,
31 videosGetValidator,
eb080476
C
32 videosRemoveValidator,
33 asyncMiddleware
65fcc311
C
34} from '../../../middlewares'
35import {
36 logger,
65fcc311 37 retryTransactionWrapper,
65fcc311 38 generateRandomString,
0aef76c4 39 getFormattedObjects,
14d3270f 40 renamePromise,
eb080476
C
41 getVideoFileHeight,
42 resetSequelizeInstance
65fcc311 43} from '../../../helpers'
40298b02 44import { TagInstance, VideoInstance } from '../../../models'
14d3270f 45import { VideoCreate, VideoUpdate } from '../../../../shared'
65fcc311
C
46
47import { abuseVideoRouter } from './abuse'
48import { blacklistRouter } from './blacklist'
49import { rateVideoRouter } from './rate'
72c7248b 50import { videoChannelRouter } from './channel'
65fcc311
C
51
52const videosRouter = express.Router()
9f10b292
C
53
54// multer configuration
f0f5567b 55const storage = multer.diskStorage({
075f16ca 56 destination: (req, file, cb) => {
65fcc311 57 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
9f10b292
C
58 },
59
075f16ca 60 filename: (req, file, cb) => {
f0f5567b 61 let extension = ''
9f10b292
C
62 if (file.mimetype === 'video/webm') extension = 'webm'
63 else if (file.mimetype === 'video/mp4') extension = 'mp4'
64 else if (file.mimetype === 'video/ogg') extension = 'ogv'
6fcd19ba
C
65 generateRandomString(16)
66 .then(randomString => {
556ddc31 67 cb(null, randomString + '.' + extension)
6fcd19ba
C
68 })
69 .catch(err => {
ad0997ad 70 logger.error('Cannot generate random string for file name.', err)
6fcd19ba
C
71 throw err
72 })
9f10b292
C
73 }
74})
75
8c9c1942 76const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
8c308c2b 77
65fcc311
C
78videosRouter.use('/', abuseVideoRouter)
79videosRouter.use('/', blacklistRouter)
80videosRouter.use('/', rateVideoRouter)
72c7248b 81videosRouter.use('/', videoChannelRouter)
d33242b0 82
65fcc311
C
83videosRouter.get('/categories', listVideoCategories)
84videosRouter.get('/licences', listVideoLicences)
85videosRouter.get('/languages', listVideoLanguages)
6e07c3de 86
65fcc311
C
87videosRouter.get('/',
88 paginationValidator,
89 videosSortValidator,
90 setVideosSort,
91 setPagination,
eb080476 92 asyncMiddleware(listVideos)
fbf1134e 93)
65fcc311
C
94videosRouter.put('/:id',
95 authenticate,
65fcc311 96 videosUpdateValidator,
eb080476 97 asyncMiddleware(updateVideoRetryWrapper)
7b1f49de 98)
e95561cd 99videosRouter.post('/upload',
65fcc311 100 authenticate,
fbf1134e 101 reqFiles,
65fcc311 102 videosAddValidator,
eb080476 103 asyncMiddleware(addVideoRetryWrapper)
fbf1134e 104)
65fcc311
C
105videosRouter.get('/:id',
106 videosGetValidator,
68ce3ae0 107 getVideo
fbf1134e 108)
198b205c 109
65fcc311
C
110videosRouter.delete('/:id',
111 authenticate,
112 videosRemoveValidator,
eb080476 113 asyncMiddleware(removeVideoRetryWrapper)
fbf1134e 114)
198b205c 115
65fcc311
C
116videosRouter.get('/search/:value',
117 videosSearchValidator,
118 paginationValidator,
119 videosSortValidator,
120 setVideosSort,
121 setPagination,
122 setVideosSearch,
eb080476 123 asyncMiddleware(searchVideos)
fbf1134e 124)
8c308c2b 125
9f10b292 126// ---------------------------------------------------------------------------
c45f7f84 127
65fcc311
C
128export {
129 videosRouter
130}
c45f7f84 131
9f10b292 132// ---------------------------------------------------------------------------
c45f7f84 133
556ddc31 134function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 135 res.json(VIDEO_CATEGORIES)
6e07c3de
C
136}
137
556ddc31 138function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 139 res.json(VIDEO_LICENCES)
6f0c39e2
C
140}
141
556ddc31 142function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 143 res.json(VIDEO_LANGUAGES)
3092476e
C
144}
145
ed04d94f
C
146// Wrapper to video add that retry the function if there is a database error
147// We need this because we run the transaction in SERIALIZABLE isolation that can fail
eb080476 148async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018 149 const options = {
556ddc31 150 arguments: [ req, res, req.files['videofile'][0] ],
d6a5b018
C
151 errorMessage: 'Cannot insert the video with many retries.'
152 }
ed04d94f 153
eb080476
C
154 await retryTransactionWrapper(addVideo, options)
155
156 // TODO : include Location of the new video -> 201
157 res.type('json').status(204).end()
ed04d94f
C
158}
159
eb080476 160async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
556ddc31 161 const videoInfo: VideoCreate = req.body
6d33593a 162 let videoUUID = ''
9f10b292 163
eb080476
C
164 await db.sequelize.transaction(async t => {
165 const sequelizeOptions = { transaction: t }
166
167 const videoData = {
168 name: videoInfo.name,
169 remote: false,
170 extname: extname(videoPhysicalFile.filename),
171 category: videoInfo.category,
172 licence: videoInfo.licence,
173 language: videoInfo.language,
174 nsfw: videoInfo.nsfw,
175 description: videoInfo.description,
176 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
177 channelId: res.locals.videoChannel.id
178 }
179 const video = db.Video.build(videoData)
6fcd19ba 180
eb080476
C
181 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
182 const videoFileHeight = await getVideoFileHeight(videoFilePath)
93e1258c 183
eb080476
C
184 const videoFileData = {
185 extname: extname(videoPhysicalFile.filename),
186 resolution: videoFileHeight,
187 size: videoPhysicalFile.size
188 }
189 const videoFile = db.VideoFile.build(videoFileData)
190 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
191 const source = join(videoDir, videoPhysicalFile.filename)
192 const destination = join(videoDir, video.getVideoFilename(videoFile))
193
194 await renamePromise(source, destination)
195 // This is important in case if there is another attempt in the retry process
196 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
197
198 const tasks = []
199
200 tasks.push(
201 video.createTorrentAndSetInfoHash(videoFile),
202 video.createThumbnail(videoFile),
203 video.createPreview(videoFile)
204 )
205
206 if (CONFIG.TRANSCODING.ENABLED === true) {
207 // Put uuid because we don't have id auto incremented for now
208 const dataInput = {
209 videoUUID: video.uuid
210 }
211
212 tasks.push(
213 JobScheduler.Instance.createJob(t, 'videoFileOptimizer', dataInput)
214 )
215 }
216 await Promise.all(tasks)
93e1258c 217
eb080476
C
218 const videoCreated = await video.save(sequelizeOptions)
219 // Do not forget to add video channel information to the created video
220 videoCreated.VideoChannel = res.locals.videoChannel
221 videoUUID = videoCreated.uuid
7920c273 222
eb080476 223 videoFile.videoId = video.id
feb4bdfd 224
eb080476
C
225 await videoFile.save(sequelizeOptions)
226 video.VideoFiles = [videoFile]
93e1258c 227
eb080476
C
228 if (videoInfo.tags) {
229 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
230
231 await video.setTags(tagInstances, sequelizeOptions)
232 video.Tags = tagInstances
233 }
234
235 // Let transcoding job send the video to friends because the video file extension might change
236 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
237
238 const remoteVideo = await video.toAddRemoteJSON()
239 // Now we'll add the video's meta data to our friends
240 return addVideoToFriends(remoteVideo, t)
7b1f49de 241 })
eb080476
C
242
243 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
7b1f49de
C
244}
245
eb080476 246async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
247 const options = {
248 arguments: [ req, res ],
249 errorMessage: 'Cannot update the video with many retries.'
250 }
ed04d94f 251
eb080476
C
252 await retryTransactionWrapper(updateVideo, options)
253
254 return res.type('json').status(204).end()
ed04d94f
C
255}
256
eb080476 257async function updateVideo (req: express.Request, res: express.Response) {
818f7987 258 const videoInstance = res.locals.video
7f4e7c36 259 const videoFieldsSave = videoInstance.toJSON()
556ddc31 260 const videoInfoToUpdate: VideoUpdate = req.body
7b1f49de 261
eb080476
C
262 try {
263 await db.sequelize.transaction(async t => {
264 const sequelizeOptions = {
265 transaction: t
266 }
7b1f49de 267
eb080476
C
268 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
269 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
270 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
271 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
272 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
273 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
7b1f49de 274
eb080476 275 await videoInstance.save(sequelizeOptions)
7b1f49de 276
eb080476
C
277 if (videoInfoToUpdate.tags) {
278 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 279
eb080476
C
280 await videoInstance.setTags(tagInstances, sequelizeOptions)
281 videoInstance.Tags = tagInstances
282 }
7920c273 283
eb080476 284 const json = videoInstance.toUpdateRemoteJSON()
7f4e7c36 285
eb080476
C
286 // Now we'll update the video's meta data to our friends
287 return updateVideoToFriends(json, t)
288 })
6fcd19ba 289
eb080476
C
290 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
291 } catch (err) {
6fcd19ba
C
292 // Force fields we want to update
293 // If the transaction is retried, sequelize will think the object has not changed
294 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 295 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
296
297 throw err
eb080476 298 }
9f10b292 299}
8c308c2b 300
556ddc31 301function getVideo (req: express.Request, res: express.Response) {
818f7987 302 const videoInstance = res.locals.video
9e167724
C
303
304 if (videoInstance.isOwned()) {
305 // The increment is done directly in the database, not using the instance value
eb080476
C
306 // FIXME: make a real view system
307 // For example, only add a view when a user watch a video during 30s etc
6fcd19ba
C
308 videoInstance.increment('views')
309 .then(() => {
6fcd19ba
C
310 const qaduParams = {
311 videoId: videoInstance.id,
312 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
313 }
314 return quickAndDirtyUpdateVideoToFriends(qaduParams)
315 })
eb080476 316 .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err))
e4c87ec2
C
317 } else {
318 // Just send the event to our friends
d38b8281
C
319 const eventParams = {
320 videoId: videoInstance.id,
65fcc311 321 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
d38b8281 322 }
65fcc311 323 addEventToRemoteVideo(eventParams)
eb080476 324 .catch(err => logger.error('Cannot add event to remote video %s.', videoInstance.uuid, err))
9e167724
C
325 }
326
327 // Do not wait the view system
eb080476 328 return res.json(videoInstance.toFormattedDetailsJSON())
9f10b292 329}
8c308c2b 330
eb080476
C
331async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
332 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
333
334 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 335}
c45f7f84 336
eb080476 337async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
91f6f169
C
338 const options = {
339 arguments: [ req, res ],
340 errorMessage: 'Cannot remove the video with many retries.'
341 }
8c308c2b 342
eb080476
C
343 await retryTransactionWrapper(removeVideo, options)
344
345 return res.type('json').status(204).end()
91f6f169
C
346}
347
eb080476 348async function removeVideo (req: express.Request, res: express.Response) {
91f6f169
C
349 const videoInstance: VideoInstance = res.locals.video
350
eb080476
C
351 await db.sequelize.transaction(async t => {
352 await videoInstance.destroy({ transaction: t })
91f6f169 353 })
eb080476
C
354
355 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
9f10b292 356}
8c308c2b 357
eb080476
C
358async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
359 const resultList = await db.Video.searchAndPopulateAuthorAndPodAndTags(
360 req.params.value,
361 req.query.field,
362 req.query.start,
363 req.query.count,
364 req.query.sort
365 )
366
367 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 368}