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'
11 resetSequelizeInstance,
12 retryTransactionWrapper
13 } from '../../../helpers'
14 import { CONFIG, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_MIMETYPE_EXT, VIDEO_PRIVACIES } from '../../../initializers'
15 import { database as db } from '../../../initializers/database'
16 import { sendAddVideo } from '../../../lib/activitypub/send/send-add'
17 import { sendUpdateVideo } from '../../../lib/activitypub/send/send-update'
18 import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
28 videosRemoveValidator,
29 videosSearchValidator,
32 } from '../../../middlewares'
33 import { VideoInstance } from '../../../models'
34 import { abuseVideoRouter } from './abuse'
35 import { blacklistRouter } from './blacklist'
36 import { videoChannelRouter } from './channel'
37 import { rateVideoRouter } from './rate'
38 import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
39 import { shareVideoByServer } from '../../../lib/activitypub/share'
40 import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
42 const videosRouter = express.Router()
44 // multer configuration
45 const storage = multer.diskStorage({
46 destination: (req, file, cb) => {
47 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
50 filename: async (req, file, cb) => {
51 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
55 randomString = await generateRandomString(16)
57 logger.error('Cannot generate random string for file name.', err)
58 randomString = 'fake-random-string'
61 cb(null, randomString + extension)
65 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
67 videosRouter.use('/', abuseVideoRouter)
68 videosRouter.use('/', blacklistRouter)
69 videosRouter.use('/', rateVideoRouter)
70 videosRouter.use('/', videoChannelRouter)
72 videosRouter.get('/categories', listVideoCategories)
73 videosRouter.get('/licences', listVideoLicences)
74 videosRouter.get('/languages', listVideoLanguages)
75 videosRouter.get('/privacies', listVideoPrivacies)
82 asyncMiddleware(listVideos)
84 videosRouter.put('/:id',
86 videosUpdateValidator,
87 asyncMiddleware(updateVideoRetryWrapper)
89 videosRouter.post('/upload',
93 asyncMiddleware(addVideoRetryWrapper)
96 videosRouter.get('/:id/description',
98 asyncMiddleware(getVideoDescription)
100 videosRouter.get('/:id',
105 videosRouter.delete('/:id',
107 videosRemoveValidator,
108 asyncMiddleware(removeVideoRetryWrapper)
111 videosRouter.get('/search/:value',
112 videosSearchValidator,
118 asyncMiddleware(searchVideos)
121 // ---------------------------------------------------------------------------
127 // ---------------------------------------------------------------------------
129 function listVideoCategories (req: express.Request, res: express.Response) {
130 res.json(VIDEO_CATEGORIES)
133 function listVideoLicences (req: express.Request, res: express.Response) {
134 res.json(VIDEO_LICENCES)
137 function listVideoLanguages (req: express.Request, res: express.Response) {
138 res.json(VIDEO_LANGUAGES)
141 function listVideoPrivacies (req: express.Request, res: express.Response) {
142 res.json(VIDEO_PRIVACIES)
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
147 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
149 arguments: [ req, res, req.files['videofile'][0] ],
150 errorMessage: 'Cannot insert the video with many retries.'
153 await retryTransactionWrapper(addVideo, options)
155 // TODO : include Location of the new video -> 201
156 res.type('json').status(204).end()
159 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
160 const videoInfo: VideoCreate = req.body
163 await db.sequelize.transaction(async t => {
164 const sequelizeOptions = { transaction: t }
167 name: videoInfo.name,
169 extname: extname(videoPhysicalFile.filename),
170 category: videoInfo.category,
171 licence: videoInfo.licence,
172 language: videoInfo.language,
173 nsfw: videoInfo.nsfw,
174 description: videoInfo.description,
175 privacy: videoInfo.privacy,
176 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
177 channelId: res.locals.videoChannel.id
179 const video = db.Video.build(videoData)
180 video.url = getVideoActivityPubUrl(video)
182 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
183 const videoFileHeight = await getVideoFileHeight(videoFilePath)
185 const videoFileData = {
186 extname: extname(videoPhysicalFile.filename),
187 resolution: videoFileHeight,
188 size: videoPhysicalFile.size
190 const videoFile = db.VideoFile.build(videoFileData)
191 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
192 const source = join(videoDir, videoPhysicalFile.filename)
193 const destination = join(videoDir, video.getVideoFilename(videoFile))
195 await renamePromise(source, destination)
196 // This is important in case if there is another attempt in the retry process
197 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
202 video.createTorrentAndSetInfoHash(videoFile),
203 video.createThumbnail(videoFile),
204 video.createPreview(videoFile)
207 if (CONFIG.TRANSCODING.ENABLED === true) {
208 // Put uuid because we don't have id auto incremented for now
210 videoUUID: video.uuid
214 transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
217 await Promise.all(tasks)
219 const videoCreated = await video.save(sequelizeOptions)
220 // Do not forget to add video channel information to the created video
221 videoCreated.VideoChannel = res.locals.videoChannel
222 videoUUID = videoCreated.uuid
224 videoFile.videoId = video.id
226 await videoFile.save(sequelizeOptions)
227 video.VideoFiles = [videoFile]
229 if (videoInfo.tags) {
230 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
232 await video.setTags(tagInstances, sequelizeOptions)
233 video.Tags = tagInstances
236 // Let transcoding job send the video to friends because the video file extension might change
237 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
238 // Don't send video to remote servers, it is private
239 if (video.privacy === VideoPrivacy.PRIVATE) return undefined
241 await sendAddVideo(video, t)
242 await shareVideoByServer(video, t)
245 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
248 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
250 arguments: [ req, res ],
251 errorMessage: 'Cannot update the video with many retries.'
254 await retryTransactionWrapper(updateVideo, options)
256 return res.type('json').status(204).end()
259 async function updateVideo (req: express.Request, res: express.Response) {
260 const videoInstance: VideoInstance = res.locals.video
261 const videoFieldsSave = videoInstance.toJSON()
262 const videoInfoToUpdate: VideoUpdate = req.body
263 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
266 await db.sequelize.transaction(async t => {
267 const sequelizeOptions = {
271 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
272 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
273 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
274 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
275 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
276 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', videoInfoToUpdate.privacy)
277 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
279 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
281 if (videoInfoToUpdate.tags) {
282 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
284 await videoInstance.setTags(tagInstances, sequelizeOptions)
285 videoInstance.Tags = tagInstances
288 // Now we'll update the video's meta data to our friends
289 if (wasPrivateVideo === false) {
290 await sendUpdateVideo(videoInstanceUpdated, t)
293 // Video is not private anymore, send a create action to remote servers
294 if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) {
295 await sendAddVideo(videoInstance, t)
296 await shareVideoByServer(videoInstance, t)
300 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
302 // Force fields we want to update
303 // If the transaction is retried, sequelize will think the object has not changed
304 // So it will skip the SQL request, even if the last one was ROLLBACKed!
305 resetSequelizeInstance(videoInstance, videoFieldsSave)
311 async function getVideo (req: express.Request, res: express.Response) {
312 const videoInstance = res.locals.video
314 if (videoInstance.isOwned()) {
315 // The increment is done directly in the database, not using the instance value
316 // FIXME: make a real view system
317 // For example, only add a view when a user watch a video during 30s etc
318 videoInstance.increment('views')
320 // TODO: send to followers a notification
322 .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err))
324 // TODO: send view event to followers
327 // Do not wait the view system
328 return res.json(videoInstance.toFormattedDetailsJSON())
331 async function getVideoDescription (req: express.Request, res: express.Response) {
332 const videoInstance = res.locals.video
335 if (videoInstance.isOwned()) {
336 description = videoInstance.description
338 description = await fetchRemoteVideoDescription(videoInstance)
341 return res.json({ description })
344 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
345 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
347 return res.json(getFormattedObjects(resultList.data, resultList.total))
350 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
352 arguments: [ req, res ],
353 errorMessage: 'Cannot remove the video with many retries.'
356 await retryTransactionWrapper(removeVideo, options)
358 return res.type('json').status(204).end()
361 async function removeVideo (req: express.Request, res: express.Response) {
362 const videoInstance: VideoInstance = res.locals.video
364 await db.sequelize.transaction(async t => {
365 await videoInstance.destroy({ transaction: t })
368 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
371 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
372 const resultList = await db.Video.searchAndPopulateAccountAndServerAndTags(
380 return res.json(getFormattedObjects(resultList.data, resultList.total))