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