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 { getServerAccount } from '../../../helpers/utils'
15 import { CONFIG, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_MIMETYPE_EXT, VIDEO_PRIVACIES } from '../../../initializers'
16 import { database as db } from '../../../initializers/database'
17 import { sendAddVideo } from '../../../lib/activitypub/send/send-add'
18 import { sendCreateViewToOrigin } from '../../../lib/activitypub/send/send-create'
19 import { sendUpdateVideo } from '../../../lib/activitypub/send/send-update'
20 import { shareVideoByServer } from '../../../lib/activitypub/share'
21 import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
22 import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
23 import { sendCreateViewToVideoFollowers } from '../../../lib/index'
24 import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
33 videosRemoveValidator,
34 videosSearchValidator,
37 } from '../../../middlewares'
38 import { VideoInstance } from '../../../models'
39 import { abuseVideoRouter } from './abuse'
40 import { blacklistRouter } from './blacklist'
41 import { videoChannelRouter } from './channel'
42 import { rateVideoRouter } from './rate'
44 const videosRouter = express.Router()
46 // multer configuration
47 const storage = multer.diskStorage({
48 destination: (req, file, cb) => {
49 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
52 filename: async (req, file, cb) => {
53 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
57 randomString = await generateRandomString(16)
59 logger.error('Cannot generate random string for file name.', err)
60 randomString = 'fake-random-string'
63 cb(null, randomString + extension)
67 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
69 videosRouter.use('/', abuseVideoRouter)
70 videosRouter.use('/', blacklistRouter)
71 videosRouter.use('/', rateVideoRouter)
72 videosRouter.use('/', videoChannelRouter)
74 videosRouter.get('/categories', listVideoCategories)
75 videosRouter.get('/licences', listVideoLicences)
76 videosRouter.get('/languages', listVideoLanguages)
77 videosRouter.get('/privacies', listVideoPrivacies)
84 asyncMiddleware(listVideos)
86 videosRouter.get('/search',
87 videosSearchValidator,
92 asyncMiddleware(searchVideos)
94 videosRouter.put('/:id',
96 asyncMiddleware(videosUpdateValidator),
97 asyncMiddleware(updateVideoRetryWrapper)
99 videosRouter.post('/upload',
103 asyncMiddleware(addVideoRetryWrapper)
106 videosRouter.get('/:id/description',
107 asyncMiddleware(videosGetValidator),
108 asyncMiddleware(getVideoDescription)
110 videosRouter.get('/:id',
111 asyncMiddleware(videosGetValidator),
114 videosRouter.post('/:id/views',
115 asyncMiddleware(videosGetValidator),
116 asyncMiddleware(viewVideo)
119 videosRouter.delete('/:id',
121 asyncMiddleware(videosRemoveValidator),
122 asyncMiddleware(removeVideoRetryWrapper)
125 // ---------------------------------------------------------------------------
131 // ---------------------------------------------------------------------------
133 function listVideoCategories (req: express.Request, res: express.Response) {
134 res.json(VIDEO_CATEGORIES)
137 function listVideoLicences (req: express.Request, res: express.Response) {
138 res.json(VIDEO_LICENCES)
141 function listVideoLanguages (req: express.Request, res: express.Response) {
142 res.json(VIDEO_LANGUAGES)
145 function listVideoPrivacies (req: express.Request, res: express.Response) {
146 res.json(VIDEO_PRIVACIES)
149 // Wrapper to video add that retry the function if there is a database error
150 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
151 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
153 arguments: [ req, res, req.files['videofile'][0] ],
154 errorMessage: 'Cannot insert the video with many retries.'
157 const video = await retryTransactionWrapper(addVideo, options)
167 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
168 const videoInfo: VideoCreate = req.body
170 // Prepare data so we don't block the transaction
172 name: videoInfo.name,
174 extname: extname(videoPhysicalFile.filename),
175 category: videoInfo.category,
176 licence: videoInfo.licence,
177 language: videoInfo.language,
178 nsfw: videoInfo.nsfw,
179 description: videoInfo.description,
180 privacy: videoInfo.privacy,
181 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
182 channelId: res.locals.videoChannel.id
184 const video = db.Video.build(videoData)
185 video.url = getVideoActivityPubUrl(video)
187 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
188 const videoFileHeight = await getVideoFileHeight(videoFilePath)
190 const videoFileData = {
191 extname: extname(videoPhysicalFile.filename),
192 resolution: videoFileHeight,
193 size: videoPhysicalFile.size
195 const videoFile = db.VideoFile.build(videoFileData)
196 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
197 const source = join(videoDir, videoPhysicalFile.filename)
198 const destination = join(videoDir, video.getVideoFilename(videoFile))
200 await renamePromise(source, destination)
201 // This is important in case if there is another attempt in the retry process
202 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
207 video.createTorrentAndSetInfoHash(videoFile),
208 video.createThumbnail(videoFile),
209 video.createPreview(videoFile)
211 await Promise.all(tasks)
213 return db.sequelize.transaction(async t => {
214 const sequelizeOptions = { transaction: t }
216 if (CONFIG.TRANSCODING.ENABLED === true) {
217 // Put uuid because we don't have id auto incremented for now
219 videoUUID: video.uuid
222 await transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
225 const videoCreated = await video.save(sequelizeOptions)
226 // Do not forget to add video channel information to the created video
227 videoCreated.VideoChannel = res.locals.videoChannel
229 videoFile.videoId = video.id
230 await videoFile.save(sequelizeOptions)
232 video.VideoFiles = [ videoFile ]
234 if (videoInfo.tags) {
235 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
237 await video.setTags(tagInstances, sequelizeOptions)
238 video.Tags = tagInstances
241 // Let transcoding job send the video to friends because the video file extension might change
242 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
243 // Don't send video to remote servers, it is private
244 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
246 await sendAddVideo(video, t)
247 await shareVideoByServer(video, t)
249 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
255 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
257 arguments: [ req, res ],
258 errorMessage: 'Cannot update the video with many retries.'
261 await retryTransactionWrapper(updateVideo, options)
263 return res.type('json').status(204).end()
266 async function updateVideo (req: express.Request, res: express.Response) {
267 const videoInstance: VideoInstance = res.locals.video
268 const videoFieldsSave = videoInstance.toJSON()
269 const videoInfoToUpdate: VideoUpdate = req.body
270 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
273 await db.sequelize.transaction(async t => {
274 const sequelizeOptions = {
278 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
279 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
280 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
281 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
282 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
283 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', parseInt(videoInfoToUpdate.privacy.toString(), 10))
284 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
286 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
288 if (videoInfoToUpdate.tags) {
289 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
291 await videoInstance.setTags(tagInstances, sequelizeOptions)
292 videoInstance.Tags = tagInstances
295 // Now we'll update the video's meta data to our friends
296 if (wasPrivateVideo === false) {
297 await sendUpdateVideo(videoInstanceUpdated, t)
300 // Video is not private anymore, send a create action to remote servers
301 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
302 await sendAddVideo(videoInstanceUpdated, t)
303 await shareVideoByServer(videoInstanceUpdated, t)
307 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
309 // Force fields we want to update
310 // If the transaction is retried, sequelize will think the object has not changed
311 // So it will skip the SQL request, even if the last one was ROLLBACKed!
312 resetSequelizeInstance(videoInstance, videoFieldsSave)
318 function getVideo (req: express.Request, res: express.Response) {
319 const videoInstance = res.locals.video
321 return res.json(videoInstance.toFormattedDetailsJSON())
324 async function viewVideo (req: express.Request, res: express.Response) {
325 const videoInstance = res.locals.video
327 await videoInstance.increment('views')
328 const serverAccount = await getServerAccount()
330 if (videoInstance.isOwned()) {
331 await sendCreateViewToVideoFollowers(serverAccount, videoInstance, undefined)
333 await sendCreateViewToOrigin(serverAccount, videoInstance, undefined)
336 return res.status(204).end()
339 async function getVideoDescription (req: express.Request, res: express.Response) {
340 const videoInstance = res.locals.video
343 if (videoInstance.isOwned()) {
344 description = videoInstance.description
346 description = await fetchRemoteVideoDescription(videoInstance)
349 return res.json({ description })
352 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
353 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
355 return res.json(getFormattedObjects(resultList.data, resultList.total))
358 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
360 arguments: [ req, res ],
361 errorMessage: 'Cannot remove the video with many retries.'
364 await retryTransactionWrapper(removeVideo, options)
366 return res.type('json').status(204).end()
369 async function removeVideo (req: express.Request, res: express.Response) {
370 const videoInstance: VideoInstance = res.locals.video
372 await db.sequelize.transaction(async t => {
373 await videoInstance.destroy({ transaction: t })
376 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
379 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
380 const resultList = await db.Video.searchAndPopulateAccountAndServerAndTags(
387 return res.json(getFormattedObjects(resultList.data, resultList.total))