]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
49490f79b13c3579918f0f47d337d47cd88f97d1
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
1 import * as express from 'express'
2 import toInt from 'validator/lib/toInt'
3 import { pickCommonVideoQuery } from '@server/helpers/query'
4 import { doJSONRequest } from '@server/helpers/requests'
5 import { LiveManager } from '@server/lib/live'
6 import { openapiOperationDoc } from '@server/middlewares/doc'
7 import { getServerActor } from '@server/models/application/application'
8 import { MVideoAccountLight } from '@server/types/models'
9 import { HttpStatusCode } from '../../../../shared/models'
10 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
11 import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils'
12 import { logger } from '../../../helpers/logger'
13 import { getFormattedObjects } from '../../../helpers/utils'
14 import { REMOTE_SCHEME, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
15 import { sequelizeTypescript } from '../../../initializers/database'
16 import { sendView } from '../../../lib/activitypub/send/send-view'
17 import { JobQueue } from '../../../lib/job-queue'
18 import { Hooks } from '../../../lib/plugins/hooks'
19 import { Redis } from '../../../lib/redis'
20 import {
21 asyncMiddleware,
22 asyncRetryTransactionMiddleware,
23 authenticate,
24 checkVideoFollowConstraints,
25 commonVideosFiltersValidator,
26 optionalAuthenticate,
27 paginationValidator,
28 setDefaultPagination,
29 setDefaultVideosSort,
30 videoFileMetadataGetValidator,
31 videosCustomGetValidator,
32 videosGetValidator,
33 videosRemoveValidator,
34 videosSortValidator
35 } from '../../../middlewares'
36 import { VideoModel } from '../../../models/video/video'
37 import { VideoFileModel } from '../../../models/video/video-file'
38 import { blacklistRouter } from './blacklist'
39 import { videoCaptionsRouter } from './captions'
40 import { videoCommentRouter } from './comment'
41 import { videoImportsRouter } from './import'
42 import { liveRouter } from './live'
43 import { ownershipVideoRouter } from './ownership'
44 import { rateVideoRouter } from './rate'
45 import { updateRouter } from './update'
46 import { uploadRouter } from './upload'
47 import { watchingRouter } from './watching'
48
49 const auditLogger = auditLoggerFactory('videos')
50 const videosRouter = express.Router()
51
52 videosRouter.use('/', blacklistRouter)
53 videosRouter.use('/', rateVideoRouter)
54 videosRouter.use('/', videoCommentRouter)
55 videosRouter.use('/', videoCaptionsRouter)
56 videosRouter.use('/', videoImportsRouter)
57 videosRouter.use('/', ownershipVideoRouter)
58 videosRouter.use('/', watchingRouter)
59 videosRouter.use('/', liveRouter)
60 videosRouter.use('/', uploadRouter)
61 videosRouter.use('/', updateRouter)
62
63 videosRouter.get('/categories',
64 openapiOperationDoc({ operationId: 'getCategories' }),
65 listVideoCategories
66 )
67 videosRouter.get('/licences',
68 openapiOperationDoc({ operationId: 'getLicences' }),
69 listVideoLicences
70 )
71 videosRouter.get('/languages',
72 openapiOperationDoc({ operationId: 'getLanguages' }),
73 listVideoLanguages
74 )
75 videosRouter.get('/privacies',
76 openapiOperationDoc({ operationId: 'getPrivacies' }),
77 listVideoPrivacies
78 )
79
80 videosRouter.get('/',
81 openapiOperationDoc({ operationId: 'getVideos' }),
82 paginationValidator,
83 videosSortValidator,
84 setDefaultVideosSort,
85 setDefaultPagination,
86 optionalAuthenticate,
87 commonVideosFiltersValidator,
88 asyncMiddleware(listVideos)
89 )
90
91 videosRouter.get('/:id/description',
92 openapiOperationDoc({ operationId: 'getVideoDesc' }),
93 asyncMiddleware(videosGetValidator),
94 asyncMiddleware(getVideoDescription)
95 )
96 videosRouter.get('/:id/metadata/:videoFileId',
97 asyncMiddleware(videoFileMetadataGetValidator),
98 asyncMiddleware(getVideoFileMetadata)
99 )
100 videosRouter.get('/:id',
101 openapiOperationDoc({ operationId: 'getVideo' }),
102 optionalAuthenticate,
103 asyncMiddleware(videosCustomGetValidator('for-api')),
104 asyncMiddleware(checkVideoFollowConstraints),
105 asyncMiddleware(getVideo)
106 )
107 videosRouter.post('/:id/views',
108 openapiOperationDoc({ operationId: 'addView' }),
109 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
110 asyncMiddleware(viewVideo)
111 )
112
113 videosRouter.delete('/:id',
114 openapiOperationDoc({ operationId: 'delVideo' }),
115 authenticate,
116 asyncMiddleware(videosRemoveValidator),
117 asyncRetryTransactionMiddleware(removeVideo)
118 )
119
120 // ---------------------------------------------------------------------------
121
122 export {
123 videosRouter
124 }
125
126 // ---------------------------------------------------------------------------
127
128 function listVideoCategories (_req: express.Request, res: express.Response) {
129 res.json(VIDEO_CATEGORIES)
130 }
131
132 function listVideoLicences (_req: express.Request, res: express.Response) {
133 res.json(VIDEO_LICENCES)
134 }
135
136 function listVideoLanguages (_req: express.Request, res: express.Response) {
137 res.json(VIDEO_LANGUAGES)
138 }
139
140 function listVideoPrivacies (_req: express.Request, res: express.Response) {
141 res.json(VIDEO_PRIVACIES)
142 }
143
144 async function getVideo (_req: express.Request, res: express.Response) {
145 const video = res.locals.videoAPI
146
147 if (video.isOutdated()) {
148 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
149 }
150
151 return res.json(video.toFormattedDetailsJSON())
152 }
153
154 async function viewVideo (req: express.Request, res: express.Response) {
155 const immutableVideoAttrs = res.locals.onlyImmutableVideo
156
157 const ip = req.ip
158 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
159 if (exists) {
160 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
161 return res.status(HttpStatusCode.NO_CONTENT_204).end()
162 }
163
164 const video = await VideoModel.load(immutableVideoAttrs.id)
165
166 const promises: Promise<any>[] = [
167 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
168 ]
169
170 let federateView = true
171
172 // Increment our live manager
173 if (video.isLive && video.isOwned()) {
174 LiveManager.Instance.addViewTo(video.id)
175
176 // Views of our local live will be sent by our live manager
177 federateView = false
178 }
179
180 // Increment our video views cache counter
181 if (!video.isLive) {
182 promises.push(Redis.Instance.addVideoView(video.id))
183 }
184
185 if (federateView) {
186 const serverActor = await getServerActor()
187 promises.push(sendView(serverActor, video, undefined))
188 }
189
190 await Promise.all(promises)
191
192 Hooks.runAction('action:api.video.viewed', { video, ip })
193
194 return res.status(HttpStatusCode.NO_CONTENT_204).end()
195 }
196
197 async function getVideoDescription (req: express.Request, res: express.Response) {
198 const videoInstance = res.locals.videoAll
199
200 const description = videoInstance.isOwned()
201 ? videoInstance.description
202 : await fetchRemoteVideoDescription(videoInstance)
203
204 return res.json({ description })
205 }
206
207 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
208 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
209
210 return res.json(videoFile.metadata)
211 }
212
213 async function listVideos (req: express.Request, res: express.Response) {
214 const query = pickCommonVideoQuery(req.query)
215 const countVideos = getCountVideos(req)
216
217 const apiOptions = await Hooks.wrapObject({
218 ...query,
219
220 includeLocalVideos: true,
221 nsfw: buildNSFWFilter(res, query.nsfw),
222 withFiles: false,
223 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
224 countVideos
225 }, 'filter:api.videos.list.params')
226
227 const resultList = await Hooks.wrapPromiseFun(
228 VideoModel.listForApi,
229 apiOptions,
230 'filter:api.videos.list.result'
231 )
232
233 return res.json(getFormattedObjects(resultList.data, resultList.total))
234 }
235
236 async function removeVideo (_req: express.Request, res: express.Response) {
237 const videoInstance = res.locals.videoAll
238
239 await sequelizeTypescript.transaction(async t => {
240 await videoInstance.destroy({ transaction: t })
241 })
242
243 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
244 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
245
246 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
247
248 return res.type('json')
249 .status(HttpStatusCode.NO_CONTENT_204)
250 .end()
251 }
252
253 // ---------------------------------------------------------------------------
254
255 // FIXME: Should not exist, we rely on specific API
256 async 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 }