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