]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Merge branch 'release/4.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
1 import express from 'express'
2 import { pickCommonVideoQuery } from '@server/helpers/query'
3 import { doJSONRequest } from '@server/helpers/requests'
4 import { VideoViews } from '@server/lib/video-views'
5 import { openapiOperationDoc } from '@server/middlewares/doc'
6 import { getServerActor } from '@server/models/application/application'
7 import { guessAdditionalAttributesFromQuery } from '@server/models/video/formatter/video-format-utils'
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 {
20 asyncMiddleware,
21 asyncRetryTransactionMiddleware,
22 authenticate,
23 checkVideoFollowConstraints,
24 commonVideosFiltersValidator,
25 optionalAuthenticate,
26 paginationValidator,
27 setDefaultPagination,
28 setDefaultVideosSort,
29 videosCustomGetValidator,
30 videosGetValidator,
31 videosRemoveValidator,
32 videosSortValidator
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 { editorRouter } from './editor'
39 import { filesRouter } from './files'
40 import { videoImportsRouter } from './import'
41 import { liveRouter } from './live'
42 import { ownershipVideoRouter } from './ownership'
43 import { rateVideoRouter } from './rate'
44 import { transcodingRouter } from './transcoding'
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('/', editorRouter)
56 videosRouter.use('/', videoCaptionsRouter)
57 videosRouter.use('/', videoImportsRouter)
58 videosRouter.use('/', ownershipVideoRouter)
59 videosRouter.use('/', watchingRouter)
60 videosRouter.use('/', liveRouter)
61 videosRouter.use('/', uploadRouter)
62 videosRouter.use('/', updateRouter)
63 videosRouter.use('/', filesRouter)
64 videosRouter.use('/', transcodingRouter)
65
66 videosRouter.get('/categories',
67 openapiOperationDoc({ operationId: 'getCategories' }),
68 listVideoCategories
69 )
70 videosRouter.get('/licences',
71 openapiOperationDoc({ operationId: 'getLicences' }),
72 listVideoLicences
73 )
74 videosRouter.get('/languages',
75 openapiOperationDoc({ operationId: 'getLanguages' }),
76 listVideoLanguages
77 )
78 videosRouter.get('/privacies',
79 openapiOperationDoc({ operationId: 'getPrivacies' }),
80 listVideoPrivacies
81 )
82
83 videosRouter.get('/',
84 openapiOperationDoc({ operationId: 'getVideos' }),
85 paginationValidator,
86 videosSortValidator,
87 setDefaultVideosSort,
88 setDefaultPagination,
89 optionalAuthenticate,
90 commonVideosFiltersValidator,
91 asyncMiddleware(listVideos)
92 )
93
94 videosRouter.get('/:id/description',
95 openapiOperationDoc({ operationId: 'getVideoDesc' }),
96 asyncMiddleware(videosGetValidator),
97 asyncMiddleware(getVideoDescription)
98 )
99 videosRouter.get('/:id',
100 openapiOperationDoc({ operationId: 'getVideo' }),
101 optionalAuthenticate,
102 asyncMiddleware(videosCustomGetValidator('for-api')),
103 asyncMiddleware(checkVideoFollowConstraints),
104 getVideo
105 )
106 videosRouter.post('/:id/views',
107 openapiOperationDoc({ operationId: 'addView' }),
108 asyncMiddleware(videosCustomGetValidator('only-video')),
109 asyncMiddleware(viewVideo)
110 )
111
112 videosRouter.delete('/:id',
113 openapiOperationDoc({ operationId: 'delVideo' }),
114 authenticate,
115 asyncMiddleware(videosRemoveValidator),
116 asyncRetryTransactionMiddleware(removeVideo)
117 )
118
119 // ---------------------------------------------------------------------------
120
121 export {
122 videosRouter
123 }
124
125 // ---------------------------------------------------------------------------
126
127 function listVideoCategories (_req: express.Request, res: express.Response) {
128 res.json(VIDEO_CATEGORIES)
129 }
130
131 function listVideoLicences (_req: express.Request, res: express.Response) {
132 res.json(VIDEO_LICENCES)
133 }
134
135 function listVideoLanguages (_req: express.Request, res: express.Response) {
136 res.json(VIDEO_LANGUAGES)
137 }
138
139 function listVideoPrivacies (_req: express.Request, res: express.Response) {
140 res.json(VIDEO_PRIVACIES)
141 }
142
143 function getVideo (_req: express.Request, res: express.Response) {
144 const video = res.locals.videoAPI
145
146 if (video.isOutdated()) {
147 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
148 }
149
150 return res.json(video.toFormattedDetailsJSON())
151 }
152
153 async function viewVideo (req: express.Request, res: express.Response) {
154 const video = res.locals.onlyVideo
155
156 const ip = req.ip
157 const success = await VideoViews.Instance.processView({ video, ip })
158
159 if (success) {
160 const serverActor = await getServerActor()
161 await sendView(serverActor, video, undefined)
162
163 Hooks.runAction('action:api.video.viewed', { video: video, ip, req, res })
164 }
165
166 return res.status(HttpStatusCode.NO_CONTENT_204).end()
167 }
168
169 async function getVideoDescription (req: express.Request, res: express.Response) {
170 const videoInstance = res.locals.videoAll
171
172 const description = videoInstance.isOwned()
173 ? videoInstance.description
174 : await fetchRemoteVideoDescription(videoInstance)
175
176 return res.json({ description })
177 }
178
179 async function listVideos (req: express.Request, res: express.Response) {
180 const serverActor = await getServerActor()
181
182 const query = pickCommonVideoQuery(req.query)
183 const countVideos = getCountVideos(req)
184
185 const apiOptions = await Hooks.wrapObject({
186 ...query,
187
188 displayOnlyForFollower: {
189 actorId: serverActor.id,
190 orLocalVideos: true
191 },
192 nsfw: buildNSFWFilter(res, query.nsfw),
193 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
194 countVideos
195 }, 'filter:api.videos.list.params')
196
197 const resultList = await Hooks.wrapPromiseFun(
198 VideoModel.listForApi,
199 apiOptions,
200 'filter:api.videos.list.result'
201 )
202
203 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
204 }
205
206 async function removeVideo (req: express.Request, res: express.Response) {
207 const videoInstance = res.locals.videoAll
208
209 await sequelizeTypescript.transaction(async t => {
210 await videoInstance.destroy({ transaction: t })
211 })
212
213 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
214 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
215
216 Hooks.runAction('action:api.video.deleted', { video: videoInstance, req, res })
217
218 return res.type('json')
219 .status(HttpStatusCode.NO_CONTENT_204)
220 .end()
221 }
222
223 // ---------------------------------------------------------------------------
224
225 // FIXME: Should not exist, we rely on specific API
226 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
227 const host = video.VideoChannel.Account.Actor.Server.host
228 const path = video.getDescriptionAPIPath()
229 const url = REMOTE_SCHEME.HTTP + '://' + host + path
230
231 const { body } = await doJSONRequest<any>(url)
232 return body.description || ''
233 }