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'
57 import { videoImportsRouter } from './import'
59 const auditLogger = auditLoggerFactory('videos')
60 const videosRouter = express.Router()
62 const reqVideoFileAdd = createReqFiles(
63 [ 'videofile', 'thumbnailfile', 'previewfile' ],
64 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
66 videofile: CONFIG.STORAGE.VIDEOS_DIR,
67 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
68 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
71 const reqVideoFileUpdate = createReqFiles(
72 [ 'thumbnailfile', 'previewfile' ],
75 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
76 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
80 videosRouter.use('/', abuseVideoRouter)
81 videosRouter.use('/', blacklistRouter)
82 videosRouter.use('/', rateVideoRouter)
83 videosRouter.use('/', videoCommentRouter)
84 videosRouter.use('/', videoCaptionsRouter)
85 videosRouter.use('/', videoImportsRouter)
87 videosRouter.get('/categories', listVideoCategories)
88 videosRouter.get('/licences', listVideoLicences)
89 videosRouter.get('/languages', listVideoLanguages)
90 videosRouter.get('/privacies', listVideoPrivacies)
98 commonVideosFiltersValidator,
99 asyncMiddleware(listVideos)
101 videosRouter.put('/:id',
104 asyncMiddleware(videosUpdateValidator),
105 asyncRetryTransactionMiddleware(updateVideo)
107 videosRouter.post('/upload',
110 asyncMiddleware(videosAddValidator),
111 asyncRetryTransactionMiddleware(addVideo)
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 asyncRetryTransactionMiddleware(removeVideo)
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 async function addVideo (req: express.Request, res: express.Response) {
158 const videoPhysicalFile = req.files['videofile'][0]
159 const videoInfo: VideoCreate = req.body
161 // Prepare data so we don't block the transaction
163 name: videoInfo.name,
165 category: videoInfo.category,
166 licence: videoInfo.licence,
167 language: videoInfo.language,
168 commentsEnabled: videoInfo.commentsEnabled || false,
169 waitTranscoding: videoInfo.waitTranscoding || false,
170 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
171 nsfw: videoInfo.nsfw || false,
172 description: videoInfo.description,
173 support: videoInfo.support,
174 privacy: videoInfo.privacy,
175 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
176 channelId: res.locals.videoChannel.id
178 const video = new VideoModel(videoData)
179 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
181 // Build the file object
182 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
183 const fps = await getVideoFileFPS(videoPhysicalFile.path)
185 const videoFileData = {
186 extname: extname(videoPhysicalFile.filename),
187 resolution: videoFileResolution,
188 size: videoPhysicalFile.size,
191 const videoFile = new VideoFileModel(videoFileData)
193 // Move physical file
194 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
195 const destination = join(videoDir, video.getVideoFilename(videoFile))
196 await renamePromise(videoPhysicalFile.path, destination)
197 // This is important in case if there is another attempt in the retry process
198 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
199 videoPhysicalFile.path = destination
201 // Process thumbnail or create it from the video
202 const thumbnailField = req.files['thumbnailfile']
203 if (thumbnailField) {
204 const thumbnailPhysicalFile = thumbnailField[0]
205 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
207 await video.createThumbnail(videoFile)
210 // Process preview or create it from the video
211 const previewField = req.files['previewfile']
213 const previewPhysicalFile = previewField[0]
214 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
216 await video.createPreview(videoFile)
219 // Create the torrent file
220 await video.createTorrentAndSetInfoHash(videoFile)
222 const videoCreated = await sequelizeTypescript.transaction(async t => {
223 const sequelizeOptions = { transaction: t }
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 ]
235 if (videoInfo.tags !== undefined) {
236 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
238 await video.$set('Tags', tagInstances, sequelizeOptions)
239 video.Tags = tagInstances
242 // Schedule an update in the future?
243 if (videoInfo.scheduleUpdate) {
244 await ScheduleVideoUpdateModel.create({
246 updateAt: videoInfo.scheduleUpdate.updateAt,
247 privacy: videoInfo.scheduleUpdate.privacy || null
248 }, { transaction: t })
251 await federateVideoIfNeeded(video, true, t)
253 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
254 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
259 if (video.state === VideoState.TO_TRANSCODE) {
260 // Put uuid because we don't have id auto incremented for now
262 videoUUID: videoCreated.uuid,
266 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
272 uuid: videoCreated.uuid
277 async function updateVideo (req: express.Request, res: express.Response) {
278 const videoInstance: VideoModel = res.locals.video
279 const videoFieldsSave = videoInstance.toJSON()
280 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
281 const videoInfoToUpdate: VideoUpdate = req.body
282 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
284 // Process thumbnail or create it from the video
285 if (req.files && req.files['thumbnailfile']) {
286 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
287 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
290 // Process preview or create it from the video
291 if (req.files && req.files['previewfile']) {
292 const previewPhysicalFile = req.files['previewfile'][0]
293 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
297 await sequelizeTypescript.transaction(async t => {
298 const sequelizeOptions = {
301 const oldVideoChannel = videoInstance.VideoChannel
303 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
304 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
305 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
306 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
307 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
308 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
309 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
310 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
311 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
312 if (videoInfoToUpdate.privacy !== undefined) {
313 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
314 videoInstance.set('privacy', newPrivacy)
316 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
317 videoInstance.set('publishedAt', new Date())
321 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
323 // Video tags update?
324 if (videoInfoToUpdate.tags !== undefined) {
325 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
327 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
328 videoInstanceUpdated.Tags = tagInstances
331 // Video channel update?
332 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
333 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
334 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
336 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
339 // Schedule an update in the future?
340 if (videoInfoToUpdate.scheduleUpdate) {
341 await ScheduleVideoUpdateModel.upsert({
342 videoId: videoInstanceUpdated.id,
343 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
344 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
345 }, { transaction: t })
346 } else if (videoInfoToUpdate.scheduleUpdate === null) {
347 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
350 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
351 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
354 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
355 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
358 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
361 // Force fields we want to update
362 // If the transaction is retried, sequelize will think the object has not changed
363 // So it will skip the SQL request, even if the last one was ROLLBACKed!
364 resetSequelizeInstance(videoInstance, videoFieldsSave)
369 return res.type('json').status(204).end()
372 function getVideo (req: express.Request, res: express.Response) {
373 const videoInstance = res.locals.video
375 return res.json(videoInstance.toFormattedDetailsJSON())
378 async function viewVideo (req: express.Request, res: express.Response) {
379 const videoInstance = res.locals.video
382 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
384 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
385 return res.status(204).end()
388 await videoInstance.increment('views')
389 await Redis.Instance.setView(ip, videoInstance.uuid)
391 const serverAccount = await getServerActor()
393 await sendCreateView(serverAccount, videoInstance, undefined)
395 return res.status(204).end()
398 async function getVideoDescription (req: express.Request, res: express.Response) {
399 const videoInstance = res.locals.video
402 if (videoInstance.isOwned()) {
403 description = videoInstance.description
405 description = await fetchRemoteVideoDescription(videoInstance)
408 return res.json({ description })
411 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
412 const resultList = await VideoModel.listForApi({
413 start: req.query.start,
414 count: req.query.count,
415 sort: req.query.sort,
416 categoryOneOf: req.query.categoryOneOf,
417 licenceOneOf: req.query.licenceOneOf,
418 languageOneOf: req.query.languageOneOf,
419 tagsOneOf: req.query.tagsOneOf,
420 tagsAllOf: req.query.tagsAllOf,
421 nsfw: buildNSFWFilter(res, req.query.nsfw),
422 filter: req.query.filter as VideoFilter,
426 return res.json(getFormattedObjects(resultList.data, resultList.total))
429 async function removeVideo (req: express.Request, res: express.Response) {
430 const videoInstance: VideoModel = res.locals.video
432 await sequelizeTypescript.transaction(async t => {
433 await videoInstance.destroy({ transaction: t })
436 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
437 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
439 return res.type('json').status(204).end()