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 { getVideoActivityPubUrl, shareVideoByServer } 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 } from '../../../lib/activitypub/send/send-add'
19 import { sendUpdateVideo } from '../../../lib/activitypub/send/send-update'
20 import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
30 videosRemoveValidator,
31 videosSearchValidator,
34 } from '../../../middlewares'
35 import { VideoInstance } from '../../../models'
36 import { abuseVideoRouter } from './abuse'
37 import { blacklistRouter } from './blacklist'
38 import { videoChannelRouter } from './channel'
39 import { rateVideoRouter } from './rate'
41 const videosRouter = express.Router()
43 // multer configuration
44 const storage = multer.diskStorage({
45 destination: (req, file, cb) => {
46 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
49 filename: async (req, file, cb) => {
50 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
54 randomString = await generateRandomString(16)
56 logger.error('Cannot generate random string for file name.', err)
57 randomString = 'fake-random-string'
60 cb(null, randomString + extension)
64 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
66 videosRouter.use('/', abuseVideoRouter)
67 videosRouter.use('/', blacklistRouter)
68 videosRouter.use('/', rateVideoRouter)
69 videosRouter.use('/', videoChannelRouter)
71 videosRouter.get('/categories', listVideoCategories)
72 videosRouter.get('/licences', listVideoLicences)
73 videosRouter.get('/languages', listVideoLanguages)
74 videosRouter.get('/privacies', listVideoPrivacies)
81 asyncMiddleware(listVideos)
83 videosRouter.put('/:id',
85 videosUpdateValidator,
86 asyncMiddleware(updateVideoRetryWrapper)
88 videosRouter.post('/upload',
92 asyncMiddleware(addVideoRetryWrapper)
95 videosRouter.get('/:id/description',
97 asyncMiddleware(getVideoDescription)
99 videosRouter.get('/:id',
104 videosRouter.delete('/:id',
106 videosRemoveValidator,
107 asyncMiddleware(removeVideoRetryWrapper)
110 videosRouter.get('/search/:value',
111 videosSearchValidator,
117 asyncMiddleware(searchVideos)
120 // ---------------------------------------------------------------------------
126 // ---------------------------------------------------------------------------
128 function listVideoCategories (req: express.Request, res: express.Response) {
129 res.json(VIDEO_CATEGORIES)
132 function listVideoLicences (req: express.Request, res: express.Response) {
133 res.json(VIDEO_LICENCES)
136 function listVideoLanguages (req: express.Request, res: express.Response) {
137 res.json(VIDEO_LANGUAGES)
140 function listVideoPrivacies (req: express.Request, res: express.Response) {
141 res.json(VIDEO_PRIVACIES)
144 // Wrapper to video add that retry the function if there is a database error
145 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
146 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
148 arguments: [ req, res, req.files['videofile'][0] ],
149 errorMessage: 'Cannot insert the video with many retries.'
152 await retryTransactionWrapper(addVideo, options)
154 // TODO : include Location of the new video -> 201
155 res.type('json').status(204).end()
158 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
159 const videoInfo: VideoCreate = req.body
162 await db.sequelize.transaction(async t => {
163 const sequelizeOptions = { transaction: t }
166 name: videoInfo.name,
168 extname: extname(videoPhysicalFile.filename),
169 category: videoInfo.category,
170 licence: videoInfo.licence,
171 language: videoInfo.language,
172 nsfw: videoInfo.nsfw,
173 description: videoInfo.description,
174 privacy: videoInfo.privacy,
175 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
176 channelId: res.locals.videoChannel.id
178 const video = db.Video.build(videoData)
179 video.url = getVideoActivityPubUrl(video)
181 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
182 const videoFileHeight = await getVideoFileHeight(videoFilePath)
184 const videoFileData = {
185 extname: extname(videoPhysicalFile.filename),
186 resolution: videoFileHeight,
187 size: videoPhysicalFile.size
189 const videoFile = db.VideoFile.build(videoFileData)
190 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
191 const source = join(videoDir, videoPhysicalFile.filename)
192 const destination = join(videoDir, video.getVideoFilename(videoFile))
194 await renamePromise(source, destination)
195 // This is important in case if there is another attempt in the retry process
196 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
201 video.createTorrentAndSetInfoHash(videoFile),
202 video.createThumbnail(videoFile),
203 video.createPreview(videoFile)
206 if (CONFIG.TRANSCODING.ENABLED === true) {
207 // Put uuid because we don't have id auto incremented for now
209 videoUUID: video.uuid
213 transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
216 await Promise.all(tasks)
218 const videoCreated = await video.save(sequelizeOptions)
219 // Do not forget to add video channel information to the created video
220 videoCreated.VideoChannel = res.locals.videoChannel
221 videoUUID = videoCreated.uuid
223 videoFile.videoId = video.id
225 await videoFile.save(sequelizeOptions)
226 video.VideoFiles = [videoFile]
228 if (videoInfo.tags) {
229 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
231 await video.setTags(tagInstances, sequelizeOptions)
232 video.Tags = tagInstances
235 // Let transcoding job send the video to friends because the video file extension might change
236 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
237 // Don't send video to remote servers, it is private
238 if (video.privacy === VideoPrivacy.PRIVATE) return undefined
240 await sendAddVideo(video, t)
241 await shareVideoByServer(video, t)
244 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
247 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
249 arguments: [ req, res ],
250 errorMessage: 'Cannot update the video with many retries.'
253 await retryTransactionWrapper(updateVideo, options)
255 return res.type('json').status(204).end()
258 async function updateVideo (req: express.Request, res: express.Response) {
259 const videoInstance: VideoInstance = res.locals.video
260 const videoFieldsSave = videoInstance.toJSON()
261 const videoInfoToUpdate: VideoUpdate = req.body
262 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
265 await db.sequelize.transaction(async t => {
266 const sequelizeOptions = {
270 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
271 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
272 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
273 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
274 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
275 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', videoInfoToUpdate.privacy)
276 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
278 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
280 if (videoInfoToUpdate.tags) {
281 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
283 await videoInstance.setTags(tagInstances, sequelizeOptions)
284 videoInstance.Tags = tagInstances
287 // Now we'll update the video's meta data to our friends
288 if (wasPrivateVideo === false) {
289 await sendUpdateVideo(videoInstanceUpdated, t)
292 // Video is not private anymore, send a create action to remote servers
293 if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) {
294 await sendAddVideo(videoInstance, t)
295 await shareVideoByServer(videoInstance, t)
299 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
301 // Force fields we want to update
302 // If the transaction is retried, sequelize will think the object has not changed
303 // So it will skip the SQL request, even if the last one was ROLLBACKed!
304 resetSequelizeInstance(videoInstance, videoFieldsSave)
310 async function getVideo (req: express.Request, res: express.Response) {
311 const videoInstance = res.locals.video
313 if (videoInstance.isOwned()) {
314 // The increment is done directly in the database, not using the instance value
315 // FIXME: make a real view system
316 // For example, only add a view when a user watch a video during 30s etc
317 videoInstance.increment('views')
319 // TODO: send to followers a notification
321 .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err))
323 // TODO: send view event to followers
326 // Do not wait the view system
327 return res.json(videoInstance.toFormattedDetailsJSON())
330 async function getVideoDescription (req: express.Request, res: express.Response) {
331 const videoInstance = res.locals.video
334 if (videoInstance.isOwned()) {
335 description = videoInstance.description
337 description = await fetchRemoteVideoDescription(videoInstance)
340 return res.json({ description })
343 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
344 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
346 return res.json(getFormattedObjects(resultList.data, resultList.total))
349 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
351 arguments: [ req, res ],
352 errorMessage: 'Cannot remove the video with many retries.'
355 await retryTransactionWrapper(removeVideo, options)
357 return res.type('json').status(204).end()
360 async function removeVideo (req: express.Request, res: express.Response) {
361 const videoInstance: VideoInstance = res.locals.video
363 await db.sequelize.transaction(async t => {
364 await videoInstance.destroy({ transaction: t })
367 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
370 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
371 const resultList = await db.Video.searchAndPopulateAccountAndServerAndTags(
379 return res.json(getFormattedObjects(resultList.data, resultList.total))