]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Fix CLI build
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
8054669f 2import toInt from 'validator/lib/toInt'
304a84d5 3import { doJSONRequest } from '@server/helpers/requests'
7a4ea932 4import { LiveManager } from '@server/lib/live-manager'
e030bfb5 5import { docMiddleware } from '@server/middlewares/doc'
8054669f 6import { getServerActor } from '@server/models/application/application'
304a84d5 7import { MVideoAccountLight } from '@server/types/models'
c158a5fa 8import { VideosCommonQuery } from '../../../../shared'
f6d6e7f8 9import { HttpStatusCode } from '../../../../shared/core-utils/miscs'
8054669f 10import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
c158a5fa
C
11import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
12import { logger } from '../../../helpers/logger'
8dc8a34e 13import { getFormattedObjects } from '../../../helpers/utils'
304a84d5 14import { REMOTE_SCHEME, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
8054669f
C
15import { sequelizeTypescript } from '../../../initializers/database'
16import { sendView } from '../../../lib/activitypub/send/send-view'
94a5ff8a 17import { JobQueue } from '../../../lib/job-queue'
8054669f 18import { Hooks } from '../../../lib/plugins/hooks'
b5c0e955 19import { Redis } from '../../../lib/redis'
65fcc311 20import {
ac81d1a0 21 asyncMiddleware,
90d4bb81 22 asyncRetryTransactionMiddleware,
ac81d1a0 23 authenticate,
8d427346 24 checkVideoFollowConstraints,
d525fc39 25 commonVideosFiltersValidator,
0883b324 26 optionalAuthenticate,
ac81d1a0
C
27 paginationValidator,
28 setDefaultPagination,
8054669f 29 setDefaultVideosSort,
d57d1d83 30 videoFileMetadataGetValidator,
09209296 31 videosCustomGetValidator,
ac81d1a0
C
32 videosGetValidator,
33 videosRemoveValidator,
c158a5fa 34 videosSortValidator
65fcc311 35} from '../../../middlewares'
3fd3ab2d
C
36import { VideoModel } from '../../../models/video/video'
37import { VideoFileModel } from '../../../models/video/video-file'
65fcc311 38import { blacklistRouter } from './blacklist'
40e87e9e 39import { videoCaptionsRouter } from './captions'
8054669f 40import { videoCommentRouter } from './comment'
fbad87b0 41import { videoImportsRouter } from './import'
c6c0fa6c 42import { liveRouter } from './live'
8054669f
C
43import { ownershipVideoRouter } from './ownership'
44import { rateVideoRouter } from './rate'
c158a5fa
C
45import { updateRouter } from './update'
46import { uploadRouter } from './upload'
6e46de09 47import { watchingRouter } from './watching'
65fcc311 48
80e36cd9 49const auditLogger = auditLoggerFactory('videos')
65fcc311 50const videosRouter = express.Router()
8c308c2b 51
65fcc311
C
52videosRouter.use('/', blacklistRouter)
53videosRouter.use('/', rateVideoRouter)
bf1f6508 54videosRouter.use('/', videoCommentRouter)
40e87e9e 55videosRouter.use('/', videoCaptionsRouter)
fbad87b0 56videosRouter.use('/', videoImportsRouter)
74d63469 57videosRouter.use('/', ownershipVideoRouter)
6e46de09 58videosRouter.use('/', watchingRouter)
c6c0fa6c 59videosRouter.use('/', liveRouter)
c158a5fa
C
60videosRouter.use('/', uploadRouter)
61videosRouter.use('/', updateRouter)
d33242b0 62
65fcc311
C
63videosRouter.get('/categories', listVideoCategories)
64videosRouter.get('/licences', listVideoLicences)
65videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 66videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 67
65fcc311
C
68videosRouter.get('/',
69 paginationValidator,
70 videosSortValidator,
8054669f 71 setDefaultVideosSort,
f05a1c30 72 setDefaultPagination,
0883b324 73 optionalAuthenticate,
d525fc39 74 commonVideosFiltersValidator,
eb080476 75 asyncMiddleware(listVideos)
fbf1134e 76)
f6d6e7f8 77
9567011b 78videosRouter.get('/:id/description',
a2431b7d 79 asyncMiddleware(videosGetValidator),
9567011b
C
80 asyncMiddleware(getVideoDescription)
81)
8319d6ae
RK
82videosRouter.get('/:id/metadata/:videoFileId',
83 asyncMiddleware(videoFileMetadataGetValidator),
84 asyncMiddleware(getVideoFileMetadata)
85)
65fcc311 86videosRouter.get('/:id',
e030bfb5 87 docMiddleware('https://docs.joinpeertube.org/api-rest-reference.html#operation/getVideo'),
6e46de09 88 optionalAuthenticate,
09209296 89 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
8d427346 90 asyncMiddleware(checkVideoFollowConstraints),
09209296 91 asyncMiddleware(getVideo)
fbf1134e 92)
1f3e9fec 93videosRouter.post('/:id/views',
2c8776fc 94 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
1f3e9fec
C
95 asyncMiddleware(viewVideo)
96)
198b205c 97
65fcc311 98videosRouter.delete('/:id',
e030bfb5 99 docMiddleware('https://docs.joinpeertube.org/api-rest-reference.html#operation/delVideo'),
65fcc311 100 authenticate,
a2431b7d 101 asyncMiddleware(videosRemoveValidator),
90d4bb81 102 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 103)
198b205c 104
9f10b292 105// ---------------------------------------------------------------------------
c45f7f84 106
65fcc311
C
107export {
108 videosRouter
109}
c45f7f84 110
9f10b292 111// ---------------------------------------------------------------------------
c45f7f84 112
f6d6e7f8 113function listVideoCategories (_req: express.Request, res: express.Response) {
65fcc311 114 res.json(VIDEO_CATEGORIES)
6e07c3de
C
115}
116
f6d6e7f8 117function listVideoLicences (_req: express.Request, res: express.Response) {
65fcc311 118 res.json(VIDEO_LICENCES)
6f0c39e2
C
119}
120
f6d6e7f8 121function listVideoLanguages (_req: express.Request, res: express.Response) {
65fcc311 122 res.json(VIDEO_LANGUAGES)
3092476e
C
123}
124
f6d6e7f8 125function listVideoPrivacies (_req: express.Request, res: express.Response) {
fd45e8f4
C
126 res.json(VIDEO_PRIVACIES)
127}
128
c158a5fa 129async function getVideo (_req: express.Request, res: express.Response) {
09209296
C
130 // We need more attributes
131 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 132
89cd1275
C
133 const video = await Hooks.wrapPromiseFun(
134 VideoModel.loadForGetAPI,
453e83ea 135 { id: res.locals.onlyVideoWithRights.id, userId },
b4055e1c
C
136 'filter:api.video.get.result'
137 )
1f3e9fec 138
09209296
C
139 if (video.isOutdated()) {
140 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
04b8c3fb
C
141 }
142
09209296 143 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
144}
145
146async function viewVideo (req: express.Request, res: express.Response) {
e4bf7856 147 const immutableVideoAttrs = res.locals.onlyImmutableVideo
9e167724 148
490b595a 149 const ip = req.ip
e4bf7856 150 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
b5c0e955 151 if (exists) {
e4bf7856 152 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
76148b27 153 return res.status(HttpStatusCode.NO_CONTENT_204).end()
b5c0e955
C
154 }
155
e4bf7856 156 const video = await VideoModel.load(immutableVideoAttrs.id)
b5c0e955 157
e4bf7856
C
158 const promises: Promise<any>[] = [
159 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
160 ]
9e167724 161
e4bf7856 162 let federateView = true
b4055e1c 163
e4bf7856
C
164 // Increment our live manager
165 if (video.isLive && video.isOwned()) {
166 LiveManager.Instance.addViewTo(video.id)
167
168 // Views of our local live will be sent by our live manager
169 federateView = false
170 }
171
172 // Increment our video views cache counter
173 if (!video.isLive) {
174 promises.push(Redis.Instance.addVideoView(video.id))
175 }
176
177 if (federateView) {
178 const serverActor = await getServerActor()
179 promises.push(sendView(serverActor, video, undefined))
180 }
181
182 await Promise.all(promises)
183
184 Hooks.runAction('action:api.video.viewed', { video, ip })
185
76148b27 186 return res.status(HttpStatusCode.NO_CONTENT_204).end()
9f10b292 187}
8c308c2b 188
9567011b 189async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 190 const videoInstance = res.locals.videoAll
9567011b 191
c158a5fa
C
192 const description = videoInstance.isOwned()
193 ? videoInstance.description
194 : await fetchRemoteVideoDescription(videoInstance)
9567011b
C
195
196 return res.json({ description })
197}
198
8319d6ae
RK
199async function getVideoFileMetadata (req: express.Request, res: express.Response) {
200 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
583eb04b 201
8319d6ae
RK
202 return res.json(videoFile.metadata)
203}
204
04b8c3fb 205async function listVideos (req: express.Request, res: express.Response) {
1fd61899 206 const query = req.query as VideosCommonQuery
fe987656
C
207 const countVideos = getCountVideos(req)
208
b4055e1c 209 const apiOptions = await Hooks.wrapObject({
1fd61899
C
210 start: query.start,
211 count: query.count,
212 sort: query.sort,
06a05d5f 213 includeLocalVideos: true,
1fd61899
C
214 categoryOneOf: query.categoryOneOf,
215 licenceOneOf: query.licenceOneOf,
216 languageOneOf: query.languageOneOf,
217 tagsOneOf: query.tagsOneOf,
218 tagsAllOf: query.tagsAllOf,
219 nsfw: buildNSFWFilter(res, query.nsfw),
220 isLive: query.isLive,
221 filter: query.filter,
6e46de09 222 withFiles: false,
fe987656
C
223 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
224 countVideos
b4055e1c
C
225 }, 'filter:api.videos.list.params')
226
89cd1275
C
227 const resultList = await Hooks.wrapPromiseFun(
228 VideoModel.listForApi,
229 apiOptions,
b4055e1c
C
230 'filter:api.videos.list.result'
231 )
eb080476
C
232
233 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 234}
c45f7f84 235
c158a5fa 236async function removeVideo (_req: express.Request, res: express.Response) {
453e83ea 237 const videoInstance = res.locals.videoAll
91f6f169 238
3fd3ab2d 239 await sequelizeTypescript.transaction(async t => {
eb080476 240 await videoInstance.destroy({ transaction: t })
91f6f169 241 })
eb080476 242
993cef4b 243 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 244 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 245
b4055e1c
C
246 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
247
2d53be02
RK
248 return res.type('json')
249 .status(HttpStatusCode.NO_CONTENT_204)
250 .end()
9f10b292 251}
304a84d5
C
252
253// ---------------------------------------------------------------------------
254
255// FIXME: Should not exist, we rely on specific API
256async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
257 const host = video.VideoChannel.Account.Actor.Server.host
258 const path = video.getDescriptionAPIPath()
259 const url = REMOTE_SCHEME.HTTP + '://' + host + path
260
261 const { body } = await doJSONRequest<any>(url)
262 return body.description || ''
263}