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 { getServerActor } from '../../../helpers/utils'
23 } from '../../../initializers'
25 fetchRemoteVideoDescription,
26 getVideoActivityPubUrl,
27 shareVideoByServerAndChannel
28 } from '../../../lib/activitypub'
29 import { sendCreateVideo, sendCreateViewToOrigin, sendCreateViewToVideoFollowers, sendUpdateVideo } from '../../../lib/activitypub/send'
30 import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler'
39 videosRemoveValidator,
40 videosSearchValidator,
43 } from '../../../middlewares'
44 import { TagModel } from '../../../models/video/tag'
45 import { VideoModel } from '../../../models/video/video'
46 import { VideoFileModel } from '../../../models/video/video-file'
47 import { abuseVideoRouter } from './abuse'
48 import { blacklistRouter } from './blacklist'
49 import { videoChannelRouter } from './channel'
50 import { rateVideoRouter } from './rate'
52 const videosRouter = express.Router()
54 // multer configuration
55 const storage = multer.diskStorage({
56 destination: (req, file, cb) => {
57 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
60 filename: async (req, file, cb) => {
61 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
65 randomString = await generateRandomString(16)
67 logger.error('Cannot generate random string for file name.', err)
68 randomString = 'fake-random-string'
71 cb(null, randomString + extension)
75 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
77 videosRouter.use('/', abuseVideoRouter)
78 videosRouter.use('/', blacklistRouter)
79 videosRouter.use('/', rateVideoRouter)
80 videosRouter.use('/', videoChannelRouter)
82 videosRouter.get('/categories', listVideoCategories)
83 videosRouter.get('/licences', listVideoLicences)
84 videosRouter.get('/languages', listVideoLanguages)
85 videosRouter.get('/privacies', listVideoPrivacies)
92 asyncMiddleware(listVideos)
94 videosRouter.get('/search',
95 videosSearchValidator,
100 asyncMiddleware(searchVideos)
102 videosRouter.put('/:id',
104 asyncMiddleware(videosUpdateValidator),
105 asyncMiddleware(updateVideoRetryWrapper)
107 videosRouter.post('/upload',
110 asyncMiddleware(videosAddValidator),
111 asyncMiddleware(addVideoRetryWrapper)
114 videosRouter.get('/:id/description',
115 asyncMiddleware(videosGetValidator),
116 asyncMiddleware(getVideoDescription)
118 videosRouter.get('/:id',
119 asyncMiddleware(videosGetValidator),
122 videosRouter.post('/:id/views',
123 asyncMiddleware(videosGetValidator),
124 asyncMiddleware(viewVideo)
127 videosRouter.delete('/:id',
129 asyncMiddleware(videosRemoveValidator),
130 asyncMiddleware(removeVideoRetryWrapper)
133 // ---------------------------------------------------------------------------
139 // ---------------------------------------------------------------------------
141 function listVideoCategories (req: express.Request, res: express.Response) {
142 res.json(VIDEO_CATEGORIES)
145 function listVideoLicences (req: express.Request, res: express.Response) {
146 res.json(VIDEO_LICENCES)
149 function listVideoLanguages (req: express.Request, res: express.Response) {
150 res.json(VIDEO_LANGUAGES)
153 function listVideoPrivacies (req: express.Request, res: express.Response) {
154 res.json(VIDEO_PRIVACIES)
157 // Wrapper to video add that retry the function if there is a database error
158 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
159 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
161 arguments: [ req, res, req.files['videofile'][0] ],
162 errorMessage: 'Cannot insert the video with many retries.'
165 const video = await retryTransactionWrapper(addVideo, options)
175 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
176 const videoInfo: VideoCreate = req.body
178 // Prepare data so we don't block the transaction
180 name: videoInfo.name,
182 extname: extname(videoPhysicalFile.filename),
183 category: videoInfo.category,
184 licence: videoInfo.licence,
185 language: videoInfo.language,
186 nsfw: videoInfo.nsfw,
187 description: videoInfo.description,
188 privacy: videoInfo.privacy,
189 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
190 channelId: res.locals.videoChannel.id
192 const video = new VideoModel(videoData)
193 video.url = getVideoActivityPubUrl(video)
195 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
196 const videoFileHeight = await getVideoFileHeight(videoFilePath)
198 const videoFileData = {
199 extname: extname(videoPhysicalFile.filename),
200 resolution: videoFileHeight,
201 size: videoPhysicalFile.size
203 const videoFile = new VideoFileModel(videoFileData)
204 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
205 const source = join(videoDir, videoPhysicalFile.filename)
206 const destination = join(videoDir, video.getVideoFilename(videoFile))
208 await renamePromise(source, destination)
209 // This is important in case if there is another attempt in the retry process
210 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
215 video.createTorrentAndSetInfoHash(videoFile),
216 video.createThumbnail(videoFile),
217 video.createPreview(videoFile)
219 await Promise.all(tasks)
221 return sequelizeTypescript.transaction(async t => {
222 const sequelizeOptions = { transaction: t }
224 if (CONFIG.TRANSCODING.ENABLED === true) {
225 // Put uuid because we don't have id auto incremented for now
227 videoUUID: video.uuid
230 await transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
233 const videoCreated = await video.save(sequelizeOptions)
234 // Do not forget to add video channel information to the created video
235 videoCreated.VideoChannel = res.locals.videoChannel
237 videoFile.videoId = video.id
238 await videoFile.save(sequelizeOptions)
240 video.VideoFiles = [ videoFile ]
242 if (videoInfo.tags) {
243 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
245 await video.$set('Tags', tagInstances, sequelizeOptions)
246 video.Tags = tagInstances
249 // Let transcoding job send the video to friends because the video file extension might change
250 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
251 // Don't send video to remote servers, it is private
252 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
254 await sendCreateVideo(video, t)
255 // TODO: share by video channel
256 await shareVideoByServerAndChannel(video, t)
258 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
264 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
266 arguments: [ req, res ],
267 errorMessage: 'Cannot update the video with many retries.'
270 await retryTransactionWrapper(updateVideo, options)
272 return res.type('json').status(204).end()
275 async function updateVideo (req: express.Request, res: express.Response) {
276 const videoInstance: VideoModel = res.locals.video
277 const videoFieldsSave = videoInstance.toJSON()
278 const videoInfoToUpdate: VideoUpdate = req.body
279 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
282 await sequelizeTypescript.transaction(async t => {
283 const sequelizeOptions = {
287 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
288 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
289 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
290 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
291 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
292 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', parseInt(videoInfoToUpdate.privacy.toString(), 10))
293 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
295 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
297 if (videoInfoToUpdate.tags) {
298 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
300 await videoInstance.$set('Tags', tagInstances, sequelizeOptions)
301 videoInstance.Tags = tagInstances
304 // Now we'll update the video's meta data to our friends
305 if (wasPrivateVideo === false) {
306 await sendUpdateVideo(videoInstanceUpdated, t)
309 // Video is not private anymore, send a create action to remote servers
310 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
311 await sendCreateVideo(videoInstanceUpdated, t)
312 // TODO: Send by video channel
313 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
317 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
319 // Force fields we want to update
320 // If the transaction is retried, sequelize will think the object has not changed
321 // So it will skip the SQL request, even if the last one was ROLLBACKed!
322 resetSequelizeInstance(videoInstance, videoFieldsSave)
328 function getVideo (req: express.Request, res: express.Response) {
329 const videoInstance = res.locals.video
331 return res.json(videoInstance.toFormattedDetailsJSON())
334 async function viewVideo (req: express.Request, res: express.Response) {
335 const videoInstance = res.locals.video
337 await videoInstance.increment('views')
338 const serverAccount = await getServerActor()
340 if (videoInstance.isOwned()) {
341 await sendCreateViewToVideoFollowers(serverAccount, videoInstance, undefined)
343 await sendCreateViewToOrigin(serverAccount, videoInstance, undefined)
346 return res.status(204).end()
349 async function getVideoDescription (req: express.Request, res: express.Response) {
350 const videoInstance = res.locals.video
353 if (videoInstance.isOwned()) {
354 description = videoInstance.description
356 description = await fetchRemoteVideoDescription(videoInstance)
359 return res.json({ description })
362 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
363 const resultList = await VideoModel.listForApi(req.query.start, req.query.count, req.query.sort)
365 return res.json(getFormattedObjects(resultList.data, resultList.total))
368 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
370 arguments: [ req, res ],
371 errorMessage: 'Cannot remove the video with many retries.'
374 await retryTransactionWrapper(removeVideo, options)
376 return res.type('json').status(204).end()
379 async function removeVideo (req: express.Request, res: express.Response) {
380 const videoInstance: VideoModel = res.locals.video
382 await sequelizeTypescript.transaction(async t => {
383 await videoInstance.destroy({ transaction: t })
386 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
389 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
390 const resultList = await VideoModel.searchAndPopulateAccountAndServerAndTags(
397 return res.json(getFormattedObjects(resultList.data, resultList.total))