1 import express from 'express'
2 import { pickCommonVideoQuery } from '@server/helpers/query'
3 import { doJSONRequest } from '@server/helpers/requests'
4 import { openapiOperationDoc } from '@server/middlewares/doc'
5 import { getServerActor } from '@server/models/application/application'
6 import { guessAdditionalAttributesFromQuery } from '@server/models/video/formatter/video-format-utils'
7 import { MVideoAccountLight } from '@server/types/models'
8 import { HttpStatusCode } from '../../../../shared/models'
9 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
10 import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
11 import { logger } from '../../../helpers/logger'
12 import { getFormattedObjects } from '../../../helpers/utils'
13 import { REMOTE_SCHEME, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
14 import { sequelizeTypescript } from '../../../initializers/database'
15 import { JobQueue } from '../../../lib/job-queue'
16 import { Hooks } from '../../../lib/plugins/hooks'
20 asyncRetryTransactionMiddleware,
22 checkVideoFollowConstraints,
23 commonVideosFiltersValidator,
28 videosCustomGetValidator,
30 videoSourceGetValidator,
31 videosRemoveValidator,
33 } from '../../../middlewares'
34 import { VideoModel } from '../../../models/video/video'
35 import { blacklistRouter } from './blacklist'
36 import { videoCaptionsRouter } from './captions'
37 import { videoCommentRouter } from './comment'
38 import { filesRouter } from './files'
39 import { videoImportsRouter } from './import'
40 import { liveRouter } from './live'
41 import { ownershipVideoRouter } from './ownership'
42 import { rateVideoRouter } from './rate'
43 import { statsRouter } from './stats'
44 import { studioRouter } from './studio'
45 import { tokenRouter } from './token'
46 import { transcodingRouter } from './transcoding'
47 import { updateRouter } from './update'
48 import { uploadRouter } from './upload'
49 import { viewRouter } from './view'
51 const auditLogger = auditLoggerFactory('videos')
52 const videosRouter = express.Router()
54 videosRouter.use(apiRateLimiter)
56 videosRouter.use('/', blacklistRouter)
57 videosRouter.use('/', statsRouter)
58 videosRouter.use('/', rateVideoRouter)
59 videosRouter.use('/', videoCommentRouter)
60 videosRouter.use('/', studioRouter)
61 videosRouter.use('/', videoCaptionsRouter)
62 videosRouter.use('/', videoImportsRouter)
63 videosRouter.use('/', ownershipVideoRouter)
64 videosRouter.use('/', viewRouter)
65 videosRouter.use('/', liveRouter)
66 videosRouter.use('/', uploadRouter)
67 videosRouter.use('/', updateRouter)
68 videosRouter.use('/', filesRouter)
69 videosRouter.use('/', transcodingRouter)
70 videosRouter.use('/', tokenRouter)
72 videosRouter.get('/categories',
73 openapiOperationDoc({ operationId: 'getCategories' }),
76 videosRouter.get('/licences',
77 openapiOperationDoc({ operationId: 'getLicences' }),
80 videosRouter.get('/languages',
81 openapiOperationDoc({ operationId: 'getLanguages' }),
84 videosRouter.get('/privacies',
85 openapiOperationDoc({ operationId: 'getPrivacies' }),
90 openapiOperationDoc({ operationId: 'getVideos' }),
96 commonVideosFiltersValidator,
97 asyncMiddleware(listVideos)
100 // TODO: remove, deprecated in 5.0 now we send the complete description in VideoDetails
101 videosRouter.get('/:id/description',
102 openapiOperationDoc({ operationId: 'getVideoDesc' }),
103 asyncMiddleware(videosGetValidator),
104 asyncMiddleware(getVideoDescription)
107 videosRouter.get('/:id/source',
108 openapiOperationDoc({ operationId: 'getVideoSource' }),
110 asyncMiddleware(videoSourceGetValidator),
114 videosRouter.get('/:id',
115 openapiOperationDoc({ operationId: 'getVideo' }),
116 optionalAuthenticate,
117 asyncMiddleware(videosCustomGetValidator('for-api')),
118 asyncMiddleware(checkVideoFollowConstraints),
119 asyncMiddleware(getVideo)
122 videosRouter.delete('/:id',
123 openapiOperationDoc({ operationId: 'delVideo' }),
125 asyncMiddleware(videosRemoveValidator),
126 asyncRetryTransactionMiddleware(removeVideo)
129 // ---------------------------------------------------------------------------
135 // ---------------------------------------------------------------------------
137 function listVideoCategories (_req: express.Request, res: express.Response) {
138 res.json(VIDEO_CATEGORIES)
141 function listVideoLicences (_req: express.Request, res: express.Response) {
142 res.json(VIDEO_LICENCES)
145 function listVideoLanguages (_req: express.Request, res: express.Response) {
146 res.json(VIDEO_LANGUAGES)
149 function listVideoPrivacies (_req: express.Request, res: express.Response) {
150 res.json(VIDEO_PRIVACIES)
153 async function getVideo (_req: express.Request, res: express.Response) {
154 const videoId = res.locals.videoAPI.id
155 const userId = res.locals.oauth?.token.User.id
157 const video = await Hooks.wrapObject(res.locals.videoAPI, 'filter:api.video.get.result', { id: videoId, userId })
159 if (video.isOutdated()) {
160 JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
163 return res.json(video.toFormattedDetailsJSON())
166 async function getVideoDescription (req: express.Request, res: express.Response) {
167 const videoInstance = res.locals.videoAll
169 const description = videoInstance.isOwned()
170 ? videoInstance.description
171 : await fetchRemoteVideoDescription(videoInstance)
173 return res.json({ description })
176 function getVideoSource (req: express.Request, res: express.Response) {
177 return res.json(res.locals.videoSource.toFormattedJSON())
180 async function listVideos (req: express.Request, res: express.Response) {
181 const serverActor = await getServerActor()
183 const query = pickCommonVideoQuery(req.query)
184 const countVideos = getCountVideos(req)
186 const apiOptions = await Hooks.wrapObject({
189 displayOnlyForFollower: {
190 actorId: serverActor.id,
193 nsfw: buildNSFWFilter(res, query.nsfw),
194 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
196 }, 'filter:api.videos.list.params')
198 const resultList = await Hooks.wrapPromiseFun(
199 VideoModel.listForApi,
201 'filter:api.videos.list.result'
204 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
207 async function removeVideo (req: express.Request, res: express.Response) {
208 const videoInstance = res.locals.videoAll
210 await sequelizeTypescript.transaction(async t => {
211 await videoInstance.destroy({ transaction: t })
214 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
215 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
217 Hooks.runAction('action:api.video.deleted', { video: videoInstance, req, res })
219 return res.type('json')
220 .status(HttpStatusCode.NO_CONTENT_204)
224 // ---------------------------------------------------------------------------
226 // FIXME: Should not exist, we rely on specific API
227 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
228 const host = video.VideoChannel.Account.Actor.Server.host
229 const path = video.getDescriptionAPIPath()
230 const url = REMOTE_SCHEME.HTTP + '://' + host + path
232 const { body } = await doJSONRequest<any>(url)
233 return body.description || ''