1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
4 import { renamePromise } from '../../../helpers/core-utils'
5 import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
6 import { processImage } from '../../../helpers/image-utils'
7 import { logger } from '../../../helpers/logger'
8 import { auditLoggerFactory, VideoAuditView } from '../../../helpers/audit-logger'
9 import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
21 } from '../../../initializers'
23 changeVideoChannelShare,
24 federateVideoIfNeeded,
25 fetchRemoteVideoDescription,
26 getVideoActivityPubUrl
27 } from '../../../lib/activitypub'
28 import { sendCreateView } from '../../../lib/activitypub/send'
29 import { JobQueue } from '../../../lib/job-queue'
30 import { Redis } from '../../../lib/redis'
33 asyncRetryTransactionMiddleware,
35 commonVideosFiltersValidator,
42 videosRemoveValidator,
45 } from '../../../middlewares'
46 import { TagModel } from '../../../models/video/tag'
47 import { VideoModel } from '../../../models/video/video'
48 import { VideoFileModel } from '../../../models/video/video-file'
49 import { abuseVideoRouter } from './abuse'
50 import { blacklistRouter } from './blacklist'
51 import { videoCommentRouter } from './comment'
52 import { rateVideoRouter } from './rate'
53 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
54 import { createReqFiles, buildNSFWFilter } from '../../../helpers/express-utils'
55 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
56 import { videoCaptionsRouter } from './captions'
58 const auditLogger = auditLoggerFactory('videos')
59 const videosRouter = express.Router()
61 const reqVideoFileAdd = createReqFiles(
62 [ 'videofile', 'thumbnailfile', 'previewfile' ],
63 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
65 videofile: CONFIG.STORAGE.VIDEOS_DIR,
66 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
67 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
70 const reqVideoFileUpdate = createReqFiles(
71 [ 'thumbnailfile', 'previewfile' ],
74 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
75 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
79 videosRouter.use('/', abuseVideoRouter)
80 videosRouter.use('/', blacklistRouter)
81 videosRouter.use('/', rateVideoRouter)
82 videosRouter.use('/', videoCommentRouter)
83 videosRouter.use('/', videoCaptionsRouter)
85 videosRouter.get('/categories', listVideoCategories)
86 videosRouter.get('/licences', listVideoLicences)
87 videosRouter.get('/languages', listVideoLanguages)
88 videosRouter.get('/privacies', listVideoPrivacies)
96 commonVideosFiltersValidator,
97 asyncMiddleware(listVideos)
99 videosRouter.put('/:id',
102 asyncMiddleware(videosUpdateValidator),
103 asyncRetryTransactionMiddleware(updateVideo)
105 videosRouter.post('/upload',
108 asyncMiddleware(videosAddValidator),
109 asyncRetryTransactionMiddleware(addVideo)
112 videosRouter.get('/:id/description',
113 asyncMiddleware(videosGetValidator),
114 asyncMiddleware(getVideoDescription)
116 videosRouter.get('/:id',
117 asyncMiddleware(videosGetValidator),
120 videosRouter.post('/:id/views',
121 asyncMiddleware(videosGetValidator),
122 asyncMiddleware(viewVideo)
125 videosRouter.delete('/:id',
127 asyncMiddleware(videosRemoveValidator),
128 asyncRetryTransactionMiddleware(removeVideo)
131 // ---------------------------------------------------------------------------
137 // ---------------------------------------------------------------------------
139 function listVideoCategories (req: express.Request, res: express.Response) {
140 res.json(VIDEO_CATEGORIES)
143 function listVideoLicences (req: express.Request, res: express.Response) {
144 res.json(VIDEO_LICENCES)
147 function listVideoLanguages (req: express.Request, res: express.Response) {
148 res.json(VIDEO_LANGUAGES)
151 function listVideoPrivacies (req: express.Request, res: express.Response) {
152 res.json(VIDEO_PRIVACIES)
155 async function addVideo (req: express.Request, res: express.Response) {
156 const videoPhysicalFile = req.files['videofile'][0]
157 const videoInfo: VideoCreate = req.body
159 // Prepare data so we don't block the transaction
161 name: videoInfo.name,
163 extname: extname(videoPhysicalFile.filename),
164 category: videoInfo.category,
165 licence: videoInfo.licence,
166 language: videoInfo.language,
167 commentsEnabled: videoInfo.commentsEnabled || false,
168 waitTranscoding: videoInfo.waitTranscoding || false,
169 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
170 nsfw: videoInfo.nsfw || false,
171 description: videoInfo.description,
172 support: videoInfo.support,
173 privacy: videoInfo.privacy,
174 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
175 channelId: res.locals.videoChannel.id
177 const video = new VideoModel(videoData)
178 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
180 // Build the file object
181 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
182 const fps = await getVideoFileFPS(videoPhysicalFile.path)
184 const videoFileData = {
185 extname: extname(videoPhysicalFile.filename),
186 resolution: videoFileResolution,
187 size: videoPhysicalFile.size,
190 const videoFile = new VideoFileModel(videoFileData)
192 // Move physical file
193 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
194 const destination = join(videoDir, video.getVideoFilename(videoFile))
195 await renamePromise(videoPhysicalFile.path, destination)
196 // This is important in case if there is another attempt in the retry process
197 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
198 videoPhysicalFile.path = destination
200 // Process thumbnail or create it from the video
201 const thumbnailField = req.files['thumbnailfile']
202 if (thumbnailField) {
203 const thumbnailPhysicalFile = thumbnailField[0]
204 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
206 await video.createThumbnail(videoFile)
209 // Process preview or create it from the video
210 const previewField = req.files['previewfile']
212 const previewPhysicalFile = previewField[0]
213 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
215 await video.createPreview(videoFile)
218 // Create the torrent file
219 await video.createTorrentAndSetInfoHash(videoFile)
221 const videoCreated = await sequelizeTypescript.transaction(async t => {
222 const sequelizeOptions = { transaction: t }
224 const videoCreated = await video.save(sequelizeOptions)
225 // Do not forget to add video channel information to the created video
226 videoCreated.VideoChannel = res.locals.videoChannel
228 videoFile.videoId = video.id
229 await videoFile.save(sequelizeOptions)
231 video.VideoFiles = [ videoFile ]
234 if (videoInfo.tags !== undefined) {
235 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
237 await video.$set('Tags', tagInstances, sequelizeOptions)
238 video.Tags = tagInstances
241 // Schedule an update in the future?
242 if (videoInfo.scheduleUpdate) {
243 await ScheduleVideoUpdateModel.create({
245 updateAt: videoInfo.scheduleUpdate.updateAt,
246 privacy: videoInfo.scheduleUpdate.privacy || null
247 }, { transaction: t })
250 await federateVideoIfNeeded(video, true, t)
252 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
253 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
258 if (video.state === VideoState.TO_TRANSCODE) {
259 // Put uuid because we don't have id auto incremented for now
261 videoUUID: videoCreated.uuid,
265 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
271 uuid: videoCreated.uuid
276 async function updateVideo (req: express.Request, res: express.Response) {
277 const videoInstance: VideoModel = res.locals.video
278 const videoFieldsSave = videoInstance.toJSON()
279 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
280 const videoInfoToUpdate: VideoUpdate = req.body
281 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
283 // Process thumbnail or create it from the video
284 if (req.files && req.files['thumbnailfile']) {
285 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
286 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
289 // Process preview or create it from the video
290 if (req.files && req.files['previewfile']) {
291 const previewPhysicalFile = req.files['previewfile'][0]
292 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
296 await sequelizeTypescript.transaction(async t => {
297 const sequelizeOptions = {
300 const oldVideoChannel = videoInstance.VideoChannel
302 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
303 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
304 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
305 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
306 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
307 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
308 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
309 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
310 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
311 if (videoInfoToUpdate.privacy !== undefined) {
312 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
313 videoInstance.set('privacy', newPrivacy)
315 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
316 videoInstance.set('publishedAt', new Date())
320 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
322 // Video tags update?
323 if (videoInfoToUpdate.tags !== undefined) {
324 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
326 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
327 videoInstanceUpdated.Tags = tagInstances
330 // Video channel update?
331 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
332 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
333 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
335 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
338 // Schedule an update in the future?
339 if (videoInfoToUpdate.scheduleUpdate) {
340 await ScheduleVideoUpdateModel.upsert({
341 videoId: videoInstanceUpdated.id,
342 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
343 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
344 }, { transaction: t })
345 } else if (videoInfoToUpdate.scheduleUpdate === null) {
346 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
349 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
350 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
353 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
354 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
357 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
360 // Force fields we want to update
361 // If the transaction is retried, sequelize will think the object has not changed
362 // So it will skip the SQL request, even if the last one was ROLLBACKed!
363 resetSequelizeInstance(videoInstance, videoFieldsSave)
368 return res.type('json').status(204).end()
371 function getVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
374 return res.json(videoInstance.toFormattedDetailsJSON())
377 async function viewVideo (req: express.Request, res: express.Response) {
378 const videoInstance = res.locals.video
381 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
383 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
384 return res.status(204).end()
387 await videoInstance.increment('views')
388 await Redis.Instance.setView(ip, videoInstance.uuid)
390 const serverAccount = await getServerActor()
392 await sendCreateView(serverAccount, videoInstance, undefined)
394 return res.status(204).end()
397 async function getVideoDescription (req: express.Request, res: express.Response) {
398 const videoInstance = res.locals.video
401 if (videoInstance.isOwned()) {
402 description = videoInstance.description
404 description = await fetchRemoteVideoDescription(videoInstance)
407 return res.json({ description })
410 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
411 const resultList = await VideoModel.listForApi({
412 start: req.query.start,
413 count: req.query.count,
414 sort: req.query.sort,
415 categoryOneOf: req.query.categoryOneOf,
416 licenceOneOf: req.query.licenceOneOf,
417 languageOneOf: req.query.languageOneOf,
418 tagsOneOf: req.query.tagsOneOf,
419 tagsAllOf: req.query.tagsAllOf,
420 nsfw: buildNSFWFilter(res, req.query.nsfw),
421 filter: req.query.filter as VideoFilter,
425 return res.json(getFormattedObjects(resultList.data, resultList.total))
428 async function removeVideo (req: express.Request, res: express.Response) {
429 const videoInstance: VideoModel = res.locals.video
431 await sequelizeTypescript.transaction(async t => {
432 await videoInstance.destroy({ transaction: t })
435 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
436 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
438 return res.type('json').status(204).end()