1 import * as express from 'express'
2 import toInt from 'validator/lib/toInt'
3 import { LiveManager } from '@server/lib/live-manager'
4 import { getServerActor } from '@server/models/application/application'
5 import { VideosCommonQuery } from '../../../../shared'
6 import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
7 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
8 import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
9 import { logger } from '../../../helpers/logger'
10 import { getFormattedObjects } from '../../../helpers/utils'
11 import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
12 import { sequelizeTypescript } from '../../../initializers/database'
13 import { sendView } from '../../../lib/activitypub/send/send-view'
14 import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
15 import { JobQueue } from '../../../lib/job-queue'
16 import { Hooks } from '../../../lib/plugins/hooks'
17 import { Redis } from '../../../lib/redis'
20 asyncRetryTransactionMiddleware,
22 checkVideoFollowConstraints,
23 commonVideosFiltersValidator,
28 videoFileMetadataGetValidator,
29 videosCustomGetValidator,
31 videosRemoveValidator,
33 } from '../../../middlewares'
34 import { VideoModel } from '../../../models/video/video'
35 import { VideoFileModel } from '../../../models/video/video-file'
36 import { blacklistRouter } from './blacklist'
37 import { videoCaptionsRouter } from './captions'
38 import { videoCommentRouter } from './comment'
39 import { videoImportsRouter } from './import'
40 import { liveRouter } from './live'
41 import { ownershipVideoRouter } from './ownership'
42 import { rateVideoRouter } from './rate'
43 import { updateRouter } from './update'
44 import { uploadRouter } from './upload'
45 import { watchingRouter } from './watching'
47 const auditLogger = auditLoggerFactory('videos')
48 const videosRouter = express.Router()
50 videosRouter.use('/', blacklistRouter)
51 videosRouter.use('/', rateVideoRouter)
52 videosRouter.use('/', videoCommentRouter)
53 videosRouter.use('/', videoCaptionsRouter)
54 videosRouter.use('/', videoImportsRouter)
55 videosRouter.use('/', ownershipVideoRouter)
56 videosRouter.use('/', watchingRouter)
57 videosRouter.use('/', liveRouter)
58 videosRouter.use('/', uploadRouter)
59 videosRouter.use('/', updateRouter)
61 videosRouter.get('/categories', listVideoCategories)
62 videosRouter.get('/licences', listVideoLicences)
63 videosRouter.get('/languages', listVideoLanguages)
64 videosRouter.get('/privacies', listVideoPrivacies)
72 commonVideosFiltersValidator,
73 asyncMiddleware(listVideos)
76 videosRouter.get('/:id/description',
77 asyncMiddleware(videosGetValidator),
78 asyncMiddleware(getVideoDescription)
80 videosRouter.get('/:id/metadata/:videoFileId',
81 asyncMiddleware(videoFileMetadataGetValidator),
82 asyncMiddleware(getVideoFileMetadata)
84 videosRouter.get('/:id',
86 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
87 asyncMiddleware(checkVideoFollowConstraints),
88 asyncMiddleware(getVideo)
90 videosRouter.post('/:id/views',
91 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
92 asyncMiddleware(viewVideo)
95 videosRouter.delete('/:id',
97 asyncMiddleware(videosRemoveValidator),
98 asyncRetryTransactionMiddleware(removeVideo)
101 // ---------------------------------------------------------------------------
107 // ---------------------------------------------------------------------------
109 function listVideoCategories (_req: express.Request, res: express.Response) {
110 res.json(VIDEO_CATEGORIES)
113 function listVideoLicences (_req: express.Request, res: express.Response) {
114 res.json(VIDEO_LICENCES)
117 function listVideoLanguages (_req: express.Request, res: express.Response) {
118 res.json(VIDEO_LANGUAGES)
121 function listVideoPrivacies (_req: express.Request, res: express.Response) {
122 res.json(VIDEO_PRIVACIES)
125 async function getVideo (_req: express.Request, res: express.Response) {
126 // We need more attributes
127 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
129 const video = await Hooks.wrapPromiseFun(
130 VideoModel.loadForGetAPI,
131 { id: res.locals.onlyVideoWithRights.id, userId },
132 'filter:api.video.get.result'
135 if (video.isOutdated()) {
136 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
139 return res.json(video.toFormattedDetailsJSON())
142 async function viewVideo (req: express.Request, res: express.Response) {
143 const immutableVideoAttrs = res.locals.onlyImmutableVideo
146 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
148 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
149 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
152 const video = await VideoModel.load(immutableVideoAttrs.id)
154 const promises: Promise<any>[] = [
155 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
158 let federateView = true
160 // Increment our live manager
161 if (video.isLive && video.isOwned()) {
162 LiveManager.Instance.addViewTo(video.id)
164 // Views of our local live will be sent by our live manager
168 // Increment our video views cache counter
170 promises.push(Redis.Instance.addVideoView(video.id))
174 const serverActor = await getServerActor()
175 promises.push(sendView(serverActor, video, undefined))
178 await Promise.all(promises)
180 Hooks.runAction('action:api.video.viewed', { video, ip })
182 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
185 async function getVideoDescription (req: express.Request, res: express.Response) {
186 const videoInstance = res.locals.videoAll
188 const description = videoInstance.isOwned()
189 ? videoInstance.description
190 : await fetchRemoteVideoDescription(videoInstance)
192 return res.json({ description })
195 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
196 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
198 return res.json(videoFile.metadata)
201 async function listVideos (req: express.Request, res: express.Response) {
202 const query = req.query as VideosCommonQuery
203 const countVideos = getCountVideos(req)
205 const apiOptions = await Hooks.wrapObject({
209 includeLocalVideos: true,
210 categoryOneOf: query.categoryOneOf,
211 licenceOneOf: query.licenceOneOf,
212 languageOneOf: query.languageOneOf,
213 tagsOneOf: query.tagsOneOf,
214 tagsAllOf: query.tagsAllOf,
215 nsfw: buildNSFWFilter(res, query.nsfw),
216 isLive: query.isLive,
217 filter: query.filter,
219 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
221 }, 'filter:api.videos.list.params')
223 const resultList = await Hooks.wrapPromiseFun(
224 VideoModel.listForApi,
226 'filter:api.videos.list.result'
229 return res.json(getFormattedObjects(resultList.data, resultList.total))
232 async function removeVideo (_req: express.Request, res: express.Response) {
233 const videoInstance = res.locals.videoAll
235 await sequelizeTypescript.transaction(async t => {
236 await videoInstance.destroy({ transaction: t })
239 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
240 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
242 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
244 return res.type('json')
245 .status(HttpStatusCode.NO_CONTENT_204)