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