]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Move video file metadata in their own table
[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,
6fcd19ba
C
39 getFormatedObjects,
40 renamePromise
65fcc311 41} from '../../../helpers'
6fcd19ba 42import { TagInstance } from '../../../models'
4771e000 43import { VideoCreate, VideoUpdate } from '../../../../shared'
65fcc311
C
44
45import { abuseVideoRouter } from './abuse'
46import { blacklistRouter } from './blacklist'
47import { rateVideoRouter } from './rate'
48
49const videosRouter = express.Router()
9f10b292
C
50
51// multer configuration
f0f5567b 52const storage = multer.diskStorage({
075f16ca 53 destination: (req, file, cb) => {
65fcc311 54 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
9f10b292
C
55 },
56
075f16ca 57 filename: (req, file, cb) => {
f0f5567b 58 let extension = ''
9f10b292
C
59 if (file.mimetype === 'video/webm') extension = 'webm'
60 else if (file.mimetype === 'video/mp4') extension = 'mp4'
61 else if (file.mimetype === 'video/ogg') extension = 'ogv'
6fcd19ba
C
62 generateRandomString(16)
63 .then(randomString => {
64 const filename = randomString
65 cb(null, filename + '.' + extension)
66 })
67 .catch(err => {
ad0997ad 68 logger.error('Cannot generate random string for file name.', err)
6fcd19ba
C
69 throw err
70 })
9f10b292
C
71 }
72})
73
8c9c1942 74const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
8c308c2b 75
65fcc311
C
76videosRouter.use('/', abuseVideoRouter)
77videosRouter.use('/', blacklistRouter)
78videosRouter.use('/', rateVideoRouter)
d33242b0 79
65fcc311
C
80videosRouter.get('/categories', listVideoCategories)
81videosRouter.get('/licences', listVideoLicences)
82videosRouter.get('/languages', listVideoLanguages)
6e07c3de 83
65fcc311
C
84videosRouter.get('/',
85 paginationValidator,
86 videosSortValidator,
87 setVideosSort,
88 setPagination,
fbf1134e
C
89 listVideos
90)
65fcc311
C
91videosRouter.put('/:id',
92 authenticate,
65fcc311 93 videosUpdateValidator,
ed04d94f 94 updateVideoRetryWrapper
7b1f49de 95)
65fcc311
C
96videosRouter.post('/',
97 authenticate,
fbf1134e 98 reqFiles,
65fcc311 99 videosAddValidator,
ed04d94f 100 addVideoRetryWrapper
fbf1134e 101)
65fcc311
C
102videosRouter.get('/:id',
103 videosGetValidator,
68ce3ae0 104 getVideo
fbf1134e 105)
198b205c 106
65fcc311
C
107videosRouter.delete('/:id',
108 authenticate,
109 videosRemoveValidator,
fbf1134e
C
110 removeVideo
111)
198b205c 112
65fcc311
C
113videosRouter.get('/search/:value',
114 videosSearchValidator,
115 paginationValidator,
116 videosSortValidator,
117 setVideosSort,
118 setPagination,
119 setVideosSearch,
fbf1134e
C
120 searchVideos
121)
8c308c2b 122
9f10b292 123// ---------------------------------------------------------------------------
c45f7f84 124
65fcc311
C
125export {
126 videosRouter
127}
c45f7f84 128
9f10b292 129// ---------------------------------------------------------------------------
c45f7f84 130
69818c93 131function listVideoCategories (req: express.Request, res: express.Response, next: express.NextFunction) {
65fcc311 132 res.json(VIDEO_CATEGORIES)
6e07c3de
C
133}
134
69818c93 135function listVideoLicences (req: express.Request, res: express.Response, next: express.NextFunction) {
65fcc311 136 res.json(VIDEO_LICENCES)
6f0c39e2
C
137}
138
69818c93 139function listVideoLanguages (req: express.Request, res: express.Response, next: express.NextFunction) {
65fcc311 140 res.json(VIDEO_LANGUAGES)
3092476e
C
141}
142
ed04d94f
C
143// Wrapper to video add that retry the function if there is a database error
144// We need this because we run the transaction in SERIALIZABLE isolation that can fail
69818c93 145function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
146 const options = {
147 arguments: [ req, res, req.files.videofile[0] ],
148 errorMessage: 'Cannot insert the video with many retries.'
149 }
ed04d94f 150
6fcd19ba
C
151 retryTransactionWrapper(addVideo, options)
152 .then(() => {
153 // TODO : include Location of the new video -> 201
154 res.type('json').status(204).end()
155 })
156 .catch(err => next(err))
ed04d94f
C
157}
158
93e1258c 159function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
4771e000 160 const videoInfos: VideoCreate = req.body
9f10b292 161
6fcd19ba
C
162 return db.sequelize.transaction(t => {
163 const user = res.locals.oauth.token.User
7920c273 164
6fcd19ba
C
165 const name = user.username
166 // null because it is OUR pod
167 const podId = null
168 const userId = user.id
feb4bdfd 169
6fcd19ba
C
170 return db.Author.findOrCreateAuthor(name, podId, userId, t)
171 .then(author => {
172 const tags = videoInfos.tags
173 if (!tags) return { author, tagInstances: undefined }
4712081f 174
6fcd19ba 175 return db.Tag.findOrCreateTags(tags, t).then(tagInstances => ({ author, tagInstances }))
7920c273 176 })
6fcd19ba
C
177 .then(({ author, tagInstances }) => {
178 const videoData = {
179 name: videoInfos.name,
0a6658fd 180 remote: false,
93e1258c 181 extname: extname(videoPhysicalFile.filename),
6fcd19ba
C
182 category: videoInfos.category,
183 licence: videoInfos.licence,
184 language: videoInfos.language,
185 nsfw: videoInfos.nsfw,
186 description: videoInfos.description,
93e1258c 187 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
6fcd19ba
C
188 authorId: author.id
189 }
190
191 const video = db.Video.build(videoData)
192 return { author, tagInstances, video }
feb4bdfd 193 })
6fcd19ba 194 .then(({ author, tagInstances, video }) => {
93e1258c
C
195 const videoFileData = {
196 extname: extname(videoPhysicalFile.filename),
197 resolution: 0, // TODO: improve readability,
198 size: videoPhysicalFile.size
199 }
200
201 const videoFile = db.VideoFile.build(videoFileData)
202 return { author, tagInstances, video, videoFile }
203 })
204 .then(({ author, 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
C
212 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
213 return { author, tagInstances, video, videoFile }
6fcd19ba 214 })
558d7c23 215 })
93e1258c
C
216 .then(({ author, tagInstances, video, videoFile }) => {
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(
232 JobScheduler.Instance.createJob(t, 'videoTranscoder', dataInput)
233 )
234 }
235
236 return Promise.all(tasks).then(() => ({ author, tagInstances, video, videoFile }))
237 })
238 .then(({ author, tagInstances, video, videoFile }) => {
6fcd19ba 239 const options = { transaction: t }
7920c273 240
6fcd19ba
C
241 return video.save(options)
242 .then(videoCreated => {
243 // Do not forget to add Author informations to the created video
244 videoCreated.Author = author
feb4bdfd 245
93e1258c 246 return { tagInstances, video: videoCreated, videoFile }
6fcd19ba 247 })
3a8a8b51 248 })
93e1258c
C
249 .then(({ tagInstances, video, videoFile }) => {
250 const options = { transaction: t }
251 videoFile.videoId = video.id
252
253 return videoFile.save(options)
254 .then(() => video.VideoFiles = [ videoFile ])
255 .then(() => ({ tagInstances, video }))
256 })
6fcd19ba
C
257 .then(({ tagInstances, video }) => {
258 if (!tagInstances) return video
7920c273 259
6fcd19ba
C
260 const options = { transaction: t }
261 return video.setTags(tagInstances, options)
262 .then(() => {
263 video.Tags = tagInstances
264 return video
265 })
7920c273 266 })
6fcd19ba
C
267 .then(video => {
268 // Let transcoding job send the video to friends because the videofile extension might change
269 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
270
271 return video.toAddRemoteJSON()
272 .then(remoteVideo => {
273 // Now we'll add the video's meta data to our friends
274 return addVideoToFriends(remoteVideo, t)
275 })
528a9efa 276 })
6fcd19ba
C
277 })
278 .then(() => logger.info('Video with name %s created.', videoInfos.name))
279 .catch((err: Error) => {
93e1258c 280 logger.debug('Cannot insert the video.', err)
6fcd19ba 281 throw err
7b1f49de
C
282 })
283}
284
69818c93 285function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
286 const options = {
287 arguments: [ req, res ],
288 errorMessage: 'Cannot update the video with many retries.'
289 }
ed04d94f 290
6fcd19ba
C
291 retryTransactionWrapper(updateVideo, options)
292 .then(() => {
293 // TODO : include Location of the new video -> 201
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()
4771e000 302 const videoInfosToUpdate: VideoUpdate = req.body
7b1f49de 303
6fcd19ba
C
304 return db.sequelize.transaction(t => {
305 let tagsPromise: Promise<TagInstance[]>
306 if (!videoInfosToUpdate.tags) {
307 tagsPromise = Promise.resolve(null)
308 } else {
309 tagsPromise = db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t)
310 }
7b1f49de 311
6fcd19ba
C
312 return tagsPromise
313 .then(tagInstances => {
314 const options = {
315 transaction: t
316 }
7b1f49de 317
6fcd19ba
C
318 if (videoInfosToUpdate.name !== undefined) videoInstance.set('name', videoInfosToUpdate.name)
319 if (videoInfosToUpdate.category !== undefined) videoInstance.set('category', videoInfosToUpdate.category)
320 if (videoInfosToUpdate.licence !== undefined) videoInstance.set('licence', videoInfosToUpdate.licence)
321 if (videoInfosToUpdate.language !== undefined) videoInstance.set('language', videoInfosToUpdate.language)
322 if (videoInfosToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfosToUpdate.nsfw)
323 if (videoInfosToUpdate.description !== undefined) videoInstance.set('description', videoInfosToUpdate.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(() => {
c3d19a49 346 logger.info('Video with name %s updated.', videoInstance.name)
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
69818c93 363function getVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
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
818f7987 389 res.json(videoInstance.toFormatedJSON())
9f10b292 390}
8c308c2b 391
69818c93 392function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
6fcd19ba
C
393 db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
394 .then(result => res.json(getFormatedObjects(result.data, result.total)))
395 .catch(err => next(err))
9f10b292 396}
c45f7f84 397
69818c93 398function removeVideo (req: express.Request, res: express.Response, next: express.NextFunction) {
818f7987 399 const videoInstance = res.locals.video
8c308c2b 400
6fcd19ba
C
401 videoInstance.destroy()
402 .then(() => res.type('json').status(204).end())
403 .catch(err => {
ad0997ad 404 logger.error('Errors when removed the video.', err)
807df9e6 405 return next(err)
6fcd19ba 406 })
9f10b292 407}
8c308c2b 408
69818c93 409function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
6fcd19ba
C
410 db.Video.searchAndPopulateAuthorAndPodAndTags(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort)
411 .then(result => res.json(getFormatedObjects(result.data, result.total)))
412 .catch(err => next(err))
9f10b292 413}