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'
5 import { renamePromise } from '../../../helpers/core-utils'
6 import { retryTransactionWrapper } from '../../../helpers/database-utils'
7 import { getVideoFileHeight } from '../../../helpers/ffmpeg-utils'
8 import { logger } from '../../../helpers/logger'
9 import { generateRandomString, getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
11 CONFIG, sequelizeTypescript, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_MIMETYPE_EXT,
13 } from '../../../initializers'
14 import { fetchRemoteVideoDescription, getVideoActivityPubUrl, shareVideoByServerAndChannel } from '../../../lib/activitypub'
15 import { sendCreateVideo, sendCreateViewToOrigin, sendCreateViewToVideoFollowers, sendUpdateVideo } from '../../../lib/activitypub/send'
16 import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler'
18 asyncMiddleware, authenticate, paginationValidator, setPagination, setVideosSort, videosAddValidator, videosGetValidator,
19 videosRemoveValidator, videosSearchValidator, videosSortValidator, videosUpdateValidator
20 } from '../../../middlewares'
21 import { TagModel } from '../../../models/video/tag'
22 import { VideoModel } from '../../../models/video/video'
23 import { VideoFileModel } from '../../../models/video/video-file'
24 import { abuseVideoRouter } from './abuse'
25 import { blacklistRouter } from './blacklist'
26 import { videoChannelRouter } from './channel'
27 import { videoCommentRouter } from './comment'
28 import { rateVideoRouter } from './rate'
30 const videosRouter = express.Router()
32 // multer configuration
33 const storage = multer.diskStorage({
34 destination: (req, file, cb) => {
35 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
38 filename: async (req, file, cb) => {
39 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
43 randomString = await generateRandomString(16)
45 logger.error('Cannot generate random string for file name.', err)
46 randomString = 'fake-random-string'
49 cb(null, randomString + extension)
53 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
55 videosRouter.use('/', abuseVideoRouter)
56 videosRouter.use('/', blacklistRouter)
57 videosRouter.use('/', rateVideoRouter)
58 videosRouter.use('/', videoChannelRouter)
59 videosRouter.use('/', videoCommentRouter)
61 videosRouter.get('/categories', listVideoCategories)
62 videosRouter.get('/licences', listVideoLicences)
63 videosRouter.get('/languages', listVideoLanguages)
64 videosRouter.get('/privacies', listVideoPrivacies)
71 asyncMiddleware(listVideos)
73 videosRouter.get('/search',
74 videosSearchValidator,
79 asyncMiddleware(searchVideos)
81 videosRouter.put('/:id',
83 asyncMiddleware(videosUpdateValidator),
84 asyncMiddleware(updateVideoRetryWrapper)
86 videosRouter.post('/upload',
89 asyncMiddleware(videosAddValidator),
90 asyncMiddleware(addVideoRetryWrapper)
93 videosRouter.get('/:id/description',
94 asyncMiddleware(videosGetValidator),
95 asyncMiddleware(getVideoDescription)
97 videosRouter.get('/:id',
98 asyncMiddleware(videosGetValidator),
101 videosRouter.post('/:id/views',
102 asyncMiddleware(videosGetValidator),
103 asyncMiddleware(viewVideo)
106 videosRouter.delete('/:id',
108 asyncMiddleware(videosRemoveValidator),
109 asyncMiddleware(removeVideoRetryWrapper)
112 // ---------------------------------------------------------------------------
118 // ---------------------------------------------------------------------------
120 function listVideoCategories (req: express.Request, res: express.Response) {
121 res.json(VIDEO_CATEGORIES)
124 function listVideoLicences (req: express.Request, res: express.Response) {
125 res.json(VIDEO_LICENCES)
128 function listVideoLanguages (req: express.Request, res: express.Response) {
129 res.json(VIDEO_LANGUAGES)
132 function listVideoPrivacies (req: express.Request, res: express.Response) {
133 res.json(VIDEO_PRIVACIES)
136 // Wrapper to video add that retry the function if there is a database error
137 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
138 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
140 arguments: [ req, res, req.files['videofile'][0] ],
141 errorMessage: 'Cannot insert the video with many retries.'
144 const video = await retryTransactionWrapper(addVideo, options)
154 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
155 const videoInfo: VideoCreate = req.body
157 // Prepare data so we don't block the transaction
159 name: videoInfo.name,
161 extname: extname(videoPhysicalFile.filename),
162 category: videoInfo.category,
163 licence: videoInfo.licence,
164 language: videoInfo.language,
165 nsfw: videoInfo.nsfw,
166 description: videoInfo.description,
167 privacy: videoInfo.privacy,
168 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
169 channelId: res.locals.videoChannel.id
171 const video = new VideoModel(videoData)
172 video.url = getVideoActivityPubUrl(video)
174 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
175 const videoFileHeight = await getVideoFileHeight(videoFilePath)
177 const videoFileData = {
178 extname: extname(videoPhysicalFile.filename),
179 resolution: videoFileHeight,
180 size: videoPhysicalFile.size
182 const videoFile = new VideoFileModel(videoFileData)
183 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
184 const source = join(videoDir, videoPhysicalFile.filename)
185 const destination = join(videoDir, video.getVideoFilename(videoFile))
187 await renamePromise(source, destination)
188 // This is important in case if there is another attempt in the retry process
189 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
194 video.createTorrentAndSetInfoHash(videoFile),
195 video.createThumbnail(videoFile),
196 video.createPreview(videoFile)
198 await Promise.all(tasks)
200 return sequelizeTypescript.transaction(async t => {
201 const sequelizeOptions = { transaction: t }
203 if (CONFIG.TRANSCODING.ENABLED === true) {
204 // Put uuid because we don't have id auto incremented for now
206 videoUUID: video.uuid
209 await transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
212 const videoCreated = await video.save(sequelizeOptions)
213 // Do not forget to add video channel information to the created video
214 videoCreated.VideoChannel = res.locals.videoChannel
216 videoFile.videoId = video.id
217 await videoFile.save(sequelizeOptions)
219 video.VideoFiles = [ videoFile ]
221 if (videoInfo.tags) {
222 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
224 await video.$set('Tags', tagInstances, sequelizeOptions)
225 video.Tags = tagInstances
228 // Let transcoding job send the video to friends because the video file extension might change
229 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
230 // Don't send video to remote servers, it is private
231 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
233 await sendCreateVideo(video, t)
234 await shareVideoByServerAndChannel(video, t)
236 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
242 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
244 arguments: [ req, res ],
245 errorMessage: 'Cannot update the video with many retries.'
248 await retryTransactionWrapper(updateVideo, options)
250 return res.type('json').status(204).end()
253 async function updateVideo (req: express.Request, res: express.Response) {
254 const videoInstance: VideoModel = res.locals.video
255 const videoFieldsSave = videoInstance.toJSON()
256 const videoInfoToUpdate: VideoUpdate = req.body
257 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
260 await sequelizeTypescript.transaction(async t => {
261 const sequelizeOptions = {
265 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
266 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
267 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
268 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
269 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
270 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', parseInt(videoInfoToUpdate.privacy.toString(), 10))
271 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
273 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
275 if (videoInfoToUpdate.tags) {
276 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
278 await videoInstance.$set('Tags', tagInstances, sequelizeOptions)
279 videoInstance.Tags = tagInstances
282 // Now we'll update the video's meta data to our friends
283 if (wasPrivateVideo === false) {
284 await sendUpdateVideo(videoInstanceUpdated, t)
287 // Video is not private anymore, send a create action to remote servers
288 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
289 await sendCreateVideo(videoInstanceUpdated, t)
290 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
294 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
296 // Force fields we want to update
297 // If the transaction is retried, sequelize will think the object has not changed
298 // So it will skip the SQL request, even if the last one was ROLLBACKed!
299 resetSequelizeInstance(videoInstance, videoFieldsSave)
305 function getVideo (req: express.Request, res: express.Response) {
306 const videoInstance = res.locals.video
308 return res.json(videoInstance.toFormattedDetailsJSON())
311 async function viewVideo (req: express.Request, res: express.Response) {
312 const videoInstance = res.locals.video
314 await videoInstance.increment('views')
315 const serverAccount = await getServerActor()
317 if (videoInstance.isOwned()) {
318 await sendCreateViewToVideoFollowers(serverAccount, videoInstance, undefined)
320 await sendCreateViewToOrigin(serverAccount, videoInstance, undefined)
323 return res.status(204).end()
326 async function getVideoDescription (req: express.Request, res: express.Response) {
327 const videoInstance = res.locals.video
330 if (videoInstance.isOwned()) {
331 description = videoInstance.description
333 description = await fetchRemoteVideoDescription(videoInstance)
336 return res.json({ description })
339 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
340 const resultList = await VideoModel.listForApi(req.query.start, req.query.count, req.query.sort)
342 return res.json(getFormattedObjects(resultList.data, resultList.total))
345 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
347 arguments: [ req, res ],
348 errorMessage: 'Cannot remove the video with many retries.'
351 await retryTransactionWrapper(removeVideo, options)
353 return res.type('json').status(204).end()
356 async function removeVideo (req: express.Request, res: express.Response) {
357 const videoInstance: VideoModel = res.locals.video
359 await sequelizeTypescript.transaction(async t => {
360 await videoInstance.destroy({ transaction: t })
363 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
366 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
367 const resultList = await VideoModel.searchAndPopulateAccountAndServerAndTags(
374 return res.json(getFormattedObjects(resultList.data, resultList.total))