]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Use separate queries for video files
[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'
1c627fd8 5import { openapiOperationDoc } 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
c756bae0
RK
63videosRouter.get('/categories',
64 openapiOperationDoc({ operationId: 'getCategories' }),
65 listVideoCategories
66)
67videosRouter.get('/licences',
68 openapiOperationDoc({ operationId: 'getLicences' }),
69 listVideoLicences
70)
71videosRouter.get('/languages',
72 openapiOperationDoc({ operationId: 'getLanguages' }),
73 listVideoLanguages
74)
75videosRouter.get('/privacies',
76 openapiOperationDoc({ operationId: 'getPrivacies' }),
77 listVideoPrivacies
78)
6e07c3de 79
65fcc311 80videosRouter.get('/',
c756bae0 81 openapiOperationDoc({ operationId: 'getVideos' }),
65fcc311
C
82 paginationValidator,
83 videosSortValidator,
8054669f 84 setDefaultVideosSort,
f05a1c30 85 setDefaultPagination,
0883b324 86 optionalAuthenticate,
d525fc39 87 commonVideosFiltersValidator,
eb080476 88 asyncMiddleware(listVideos)
fbf1134e 89)
f6d6e7f8 90
9567011b 91videosRouter.get('/:id/description',
c756bae0 92 openapiOperationDoc({ operationId: 'getVideoDesc' }),
a2431b7d 93 asyncMiddleware(videosGetValidator),
9567011b
C
94 asyncMiddleware(getVideoDescription)
95)
8319d6ae
RK
96videosRouter.get('/:id/metadata/:videoFileId',
97 asyncMiddleware(videoFileMetadataGetValidator),
98 asyncMiddleware(getVideoFileMetadata)
99)
65fcc311 100videosRouter.get('/:id',
1c627fd8 101 openapiOperationDoc({ operationId: 'getVideo' }),
6e46de09 102 optionalAuthenticate,
09209296 103 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
8d427346 104 asyncMiddleware(checkVideoFollowConstraints),
09209296 105 asyncMiddleware(getVideo)
fbf1134e 106)
1f3e9fec 107videosRouter.post('/:id/views',
c756bae0 108 openapiOperationDoc({ operationId: 'addView' }),
2c8776fc 109 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
1f3e9fec
C
110 asyncMiddleware(viewVideo)
111)
198b205c 112
65fcc311 113videosRouter.delete('/:id',
1c627fd8 114 openapiOperationDoc({ operationId: 'delVideo' }),
65fcc311 115 authenticate,
a2431b7d 116 asyncMiddleware(videosRemoveValidator),
90d4bb81 117 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 118)
198b205c 119
9f10b292 120// ---------------------------------------------------------------------------
c45f7f84 121
65fcc311
C
122export {
123 videosRouter
124}
c45f7f84 125
9f10b292 126// ---------------------------------------------------------------------------
c45f7f84 127
f6d6e7f8 128function listVideoCategories (_req: express.Request, res: express.Response) {
65fcc311 129 res.json(VIDEO_CATEGORIES)
6e07c3de
C
130}
131
f6d6e7f8 132function listVideoLicences (_req: express.Request, res: express.Response) {
65fcc311 133 res.json(VIDEO_LICENCES)
6f0c39e2
C
134}
135
f6d6e7f8 136function listVideoLanguages (_req: express.Request, res: express.Response) {
65fcc311 137 res.json(VIDEO_LANGUAGES)
3092476e
C
138}
139
f6d6e7f8 140function listVideoPrivacies (_req: express.Request, res: express.Response) {
fd45e8f4
C
141 res.json(VIDEO_PRIVACIES)
142}
143
c158a5fa 144async function getVideo (_req: express.Request, res: express.Response) {
09209296
C
145 // We need more attributes
146 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
b4055e1c 147
89cd1275
C
148 const video = await Hooks.wrapPromiseFun(
149 VideoModel.loadForGetAPI,
1d43c3a6 150 { id: _req.params.id, userId },
b4055e1c
C
151 'filter:api.video.get.result'
152 )
1f3e9fec 153
09209296
C
154 if (video.isOutdated()) {
155 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
04b8c3fb
C
156 }
157
09209296 158 return res.json(video.toFormattedDetailsJSON())
1f3e9fec
C
159}
160
161async function viewVideo (req: express.Request, res: express.Response) {
e4bf7856 162 const immutableVideoAttrs = res.locals.onlyImmutableVideo
9e167724 163
490b595a 164 const ip = req.ip
e4bf7856 165 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
b5c0e955 166 if (exists) {
e4bf7856 167 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
76148b27 168 return res.status(HttpStatusCode.NO_CONTENT_204).end()
b5c0e955
C
169 }
170
e4bf7856 171 const video = await VideoModel.load(immutableVideoAttrs.id)
b5c0e955 172
e4bf7856
C
173 const promises: Promise<any>[] = [
174 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
175 ]
9e167724 176
e4bf7856 177 let federateView = true
b4055e1c 178
e4bf7856
C
179 // Increment our live manager
180 if (video.isLive && video.isOwned()) {
181 LiveManager.Instance.addViewTo(video.id)
182
183 // Views of our local live will be sent by our live manager
184 federateView = false
185 }
186
187 // Increment our video views cache counter
188 if (!video.isLive) {
189 promises.push(Redis.Instance.addVideoView(video.id))
190 }
191
192 if (federateView) {
193 const serverActor = await getServerActor()
194 promises.push(sendView(serverActor, video, undefined))
195 }
196
197 await Promise.all(promises)
198
199 Hooks.runAction('action:api.video.viewed', { video, ip })
200
76148b27 201 return res.status(HttpStatusCode.NO_CONTENT_204).end()
9f10b292 202}
8c308c2b 203
9567011b 204async function getVideoDescription (req: express.Request, res: express.Response) {
453e83ea 205 const videoInstance = res.locals.videoAll
9567011b 206
c158a5fa
C
207 const description = videoInstance.isOwned()
208 ? videoInstance.description
209 : await fetchRemoteVideoDescription(videoInstance)
9567011b
C
210
211 return res.json({ description })
212}
213
8319d6ae
RK
214async function getVideoFileMetadata (req: express.Request, res: express.Response) {
215 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
583eb04b 216
8319d6ae
RK
217 return res.json(videoFile.metadata)
218}
219
04b8c3fb 220async function listVideos (req: express.Request, res: express.Response) {
1fd61899 221 const query = req.query as VideosCommonQuery
fe987656
C
222 const countVideos = getCountVideos(req)
223
b4055e1c 224 const apiOptions = await Hooks.wrapObject({
1fd61899
C
225 start: query.start,
226 count: query.count,
227 sort: query.sort,
06a05d5f 228 includeLocalVideos: true,
1fd61899
C
229 categoryOneOf: query.categoryOneOf,
230 licenceOneOf: query.licenceOneOf,
231 languageOneOf: query.languageOneOf,
232 tagsOneOf: query.tagsOneOf,
233 tagsAllOf: query.tagsAllOf,
234 nsfw: buildNSFWFilter(res, query.nsfw),
235 isLive: query.isLive,
236 filter: query.filter,
6e46de09 237 withFiles: false,
fe987656
C
238 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
239 countVideos
b4055e1c
C
240 }, 'filter:api.videos.list.params')
241
89cd1275
C
242 const resultList = await Hooks.wrapPromiseFun(
243 VideoModel.listForApi,
244 apiOptions,
b4055e1c
C
245 'filter:api.videos.list.result'
246 )
eb080476
C
247
248 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 249}
c45f7f84 250
c158a5fa 251async function removeVideo (_req: express.Request, res: express.Response) {
453e83ea 252 const videoInstance = res.locals.videoAll
91f6f169 253
3fd3ab2d 254 await sequelizeTypescript.transaction(async t => {
eb080476 255 await videoInstance.destroy({ transaction: t })
91f6f169 256 })
eb080476 257
993cef4b 258 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
eb080476 259 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81 260
b4055e1c
C
261 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
262
2d53be02
RK
263 return res.type('json')
264 .status(HttpStatusCode.NO_CONTENT_204)
265 .end()
9f10b292 266}
304a84d5
C
267
268// ---------------------------------------------------------------------------
269
270// FIXME: Should not exist, we rely on specific API
271async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
272 const host = video.VideoChannel.Account.Actor.Server.host
273 const path = video.getDescriptionAPIPath()
274 const url = REMOTE_SCHEME.HTTP + '://' + host + path
275
276 const { body } = await doJSONRequest<any>(url)
277 return body.description || ''
278}