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