1 import * as express from 'express'
2 import * as multer from 'multer'
3 import { extname, join } from 'path'
4 import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared'
6 fetchRemoteVideoDescription,
12 resetSequelizeInstance,
13 retryTransactionWrapper
14 } from '../../../helpers'
15 import { getActivityPubUrl } from '../../../helpers/activitypub'
16 import { CONFIG, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_MIMETYPE_EXT, VIDEO_PRIVACIES } from '../../../initializers'
17 import { database as db } from '../../../initializers/database'
18 import { sendAddVideo, sendUpdateVideoChannel } from '../../../lib/activitypub/send-request'
19 import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
29 videosRemoveValidator,
30 videosSearchValidator,
33 } from '../../../middlewares'
34 import { VideoInstance } from '../../../models'
35 import { abuseVideoRouter } from './abuse'
36 import { blacklistRouter } from './blacklist'
37 import { videoChannelRouter } from './channel'
38 import { rateVideoRouter } from './rate'
40 const videosRouter = express.Router()
42 // multer configuration
43 const storage = multer.diskStorage({
44 destination: (req, file, cb) => {
45 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
48 filename: async (req, file, cb) => {
49 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
53 randomString = await generateRandomString(16)
55 logger.error('Cannot generate random string for file name.', err)
56 randomString = 'fake-random-string'
59 cb(null, randomString + '.' + extension)
63 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
65 videosRouter.use('/', abuseVideoRouter)
66 videosRouter.use('/', blacklistRouter)
67 videosRouter.use('/', rateVideoRouter)
68 videosRouter.use('/', videoChannelRouter)
70 videosRouter.get('/categories', listVideoCategories)
71 videosRouter.get('/licences', listVideoLicences)
72 videosRouter.get('/languages', listVideoLanguages)
73 videosRouter.get('/privacies', listVideoPrivacies)
80 asyncMiddleware(listVideos)
82 videosRouter.put('/:id',
84 videosUpdateValidator,
85 asyncMiddleware(updateVideoRetryWrapper)
87 videosRouter.post('/upload',
91 asyncMiddleware(addVideoRetryWrapper)
94 videosRouter.get('/:id/description',
96 asyncMiddleware(getVideoDescription)
98 videosRouter.get('/:id',
103 videosRouter.delete('/:id',
105 videosRemoveValidator,
106 asyncMiddleware(removeVideoRetryWrapper)
109 videosRouter.get('/search/:value',
110 videosSearchValidator,
116 asyncMiddleware(searchVideos)
119 // ---------------------------------------------------------------------------
125 // ---------------------------------------------------------------------------
127 function listVideoCategories (req: express.Request, res: express.Response) {
128 res.json(VIDEO_CATEGORIES)
131 function listVideoLicences (req: express.Request, res: express.Response) {
132 res.json(VIDEO_LICENCES)
135 function listVideoLanguages (req: express.Request, res: express.Response) {
136 res.json(VIDEO_LANGUAGES)
139 function listVideoPrivacies (req: express.Request, res: express.Response) {
140 res.json(VIDEO_PRIVACIES)
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
145 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
147 arguments: [ req, res, req.files['videofile'][0] ],
148 errorMessage: 'Cannot insert the video with many retries.'
151 await retryTransactionWrapper(addVideo, options)
153 // TODO : include Location of the new video -> 201
154 res.type('json').status(204).end()
157 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
158 const videoInfo: VideoCreate = req.body
161 await db.sequelize.transaction(async t => {
162 const sequelizeOptions = { transaction: t }
165 name: videoInfo.name,
167 extname: extname(videoPhysicalFile.filename),
168 category: videoInfo.category,
169 licence: videoInfo.licence,
170 language: videoInfo.language,
171 nsfw: videoInfo.nsfw,
172 description: videoInfo.description,
173 privacy: videoInfo.privacy,
174 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
175 channelId: res.locals.videoChannel.id
177 const video = db.Video.build(videoData)
178 video.url = getActivityPubUrl('video', video.uuid)
180 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
181 const videoFileHeight = await getVideoFileHeight(videoFilePath)
183 const videoFileData = {
184 extname: extname(videoPhysicalFile.filename),
185 resolution: videoFileHeight,
186 size: videoPhysicalFile.size
188 const videoFile = db.VideoFile.build(videoFileData)
189 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
190 const source = join(videoDir, videoPhysicalFile.filename)
191 const destination = join(videoDir, video.getVideoFilename(videoFile))
193 await renamePromise(source, destination)
194 // This is important in case if there is another attempt in the retry process
195 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
200 video.createTorrentAndSetInfoHash(videoFile),
201 video.createThumbnail(videoFile),
202 video.createPreview(videoFile)
205 if (CONFIG.TRANSCODING.ENABLED === true) {
206 // Put uuid because we don't have id auto incremented for now
208 videoUUID: video.uuid
212 transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
215 await Promise.all(tasks)
217 const videoCreated = await video.save(sequelizeOptions)
218 // Do not forget to add video channel information to the created video
219 videoCreated.VideoChannel = res.locals.videoChannel
220 videoUUID = videoCreated.uuid
222 videoFile.videoId = video.id
224 await videoFile.save(sequelizeOptions)
225 video.VideoFiles = [videoFile]
227 if (videoInfo.tags) {
228 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
230 await video.setTags(tagInstances, sequelizeOptions)
231 video.Tags = tagInstances
234 // Let transcoding job send the video to friends because the video file extension might change
235 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
236 // Don't send video to remote servers, it is private
237 if (video.privacy === VideoPrivacy.PRIVATE) return undefined
239 await sendAddVideo(video, t)
242 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
245 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
247 arguments: [ req, res ],
248 errorMessage: 'Cannot update the video with many retries.'
251 await retryTransactionWrapper(updateVideo, options)
253 return res.type('json').status(204).end()
256 async function updateVideo (req: express.Request, res: express.Response) {
257 const videoInstance = res.locals.video
258 const videoFieldsSave = videoInstance.toJSON()
259 const videoInfoToUpdate: VideoUpdate = req.body
260 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
263 await db.sequelize.transaction(async t => {
264 const sequelizeOptions = {
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.privacy !== undefined) videoInstance.set('privacy', videoInfoToUpdate.privacy)
274 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
276 await videoInstance.save(sequelizeOptions)
278 if (videoInfoToUpdate.tags) {
279 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
281 await videoInstance.setTags(tagInstances, sequelizeOptions)
282 videoInstance.Tags = tagInstances
285 // Now we'll update the video's meta data to our friends
286 if (wasPrivateVideo === false) {
287 await sendUpdateVideoChannel(videoInstance, t)
290 // Video is not private anymore, send a create action to remote servers
291 if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) {
292 await sendAddVideo(videoInstance, t)
296 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
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!
301 resetSequelizeInstance(videoInstance, videoFieldsSave)
307 async function getVideo (req: express.Request, res: express.Response) {
308 const videoInstance = res.locals.video
310 if (videoInstance.isOwned()) {
311 // The increment is done directly in the database, not using the instance value
312 // FIXME: make a real view system
313 // For example, only add a view when a user watch a video during 30s etc
314 videoInstance.increment('views')
316 // TODO: send to followers a notification
318 .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err))
320 // TODO: send view event to followers
323 // Do not wait the view system
324 return res.json(videoInstance.toFormattedDetailsJSON())
327 async function getVideoDescription (req: express.Request, res: express.Response) {
328 const videoInstance = res.locals.video
331 if (videoInstance.isOwned()) {
332 description = videoInstance.description
334 description = await fetchRemoteVideoDescription(videoInstance)
337 return res.json({ description })
340 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
341 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
343 return res.json(getFormattedObjects(resultList.data, resultList.total))
346 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
348 arguments: [ req, res ],
349 errorMessage: 'Cannot remove the video with many retries.'
352 await retryTransactionWrapper(removeVideo, options)
354 return res.type('json').status(204).end()
357 async function removeVideo (req: express.Request, res: express.Response) {
358 const videoInstance: VideoInstance = res.locals.video
360 await db.sequelize.transaction(async t => {
361 await videoInstance.destroy({ transaction: t })
364 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
367 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
368 const resultList = await db.Video.searchAndPopulateAccountAndServerAndTags(
376 return res.json(getFormattedObjects(resultList.data, resultList.total))