]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Prevent broken transcoding with audio only input
[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 videosRouter.get('/:id/description',
98 openapiOperationDoc({ operationId: 'getVideoDesc' }),
99 asyncMiddleware(videosGetValidator),
100 asyncMiddleware(getVideoDescription)
101 )
102
103 videosRouter.get('/:id/source',
104 openapiOperationDoc({ operationId: 'getVideoSource' }),
105 authenticate,
106 asyncMiddleware(videoSourceGetValidator),
107 getVideoSource
108 )
109
110 videosRouter.get('/:id',
111 openapiOperationDoc({ operationId: 'getVideo' }),
112 optionalAuthenticate,
113 asyncMiddleware(videosCustomGetValidator('for-api')),
114 asyncMiddleware(checkVideoFollowConstraints),
115 asyncMiddleware(getVideo)
116 )
117
118 videosRouter.delete('/:id',
119 openapiOperationDoc({ operationId: 'delVideo' }),
120 authenticate,
121 asyncMiddleware(videosRemoveValidator),
122 asyncRetryTransactionMiddleware(removeVideo)
123 )
124
125 // ---------------------------------------------------------------------------
126
127 export {
128 videosRouter
129 }
130
131 // ---------------------------------------------------------------------------
132
133 function listVideoCategories (_req: express.Request, res: express.Response) {
134 res.json(VIDEO_CATEGORIES)
135 }
136
137 function listVideoLicences (_req: express.Request, res: express.Response) {
138 res.json(VIDEO_LICENCES)
139 }
140
141 function listVideoLanguages (_req: express.Request, res: express.Response) {
142 res.json(VIDEO_LANGUAGES)
143 }
144
145 function listVideoPrivacies (_req: express.Request, res: express.Response) {
146 res.json(VIDEO_PRIVACIES)
147 }
148
149 async function getVideo (_req: express.Request, res: express.Response) {
150 const videoId = res.locals.videoAPI.id
151 const userId = res.locals.oauth?.token.User.id
152
153 const video = await Hooks.wrapObject(res.locals.videoAPI, 'filter:api.video.get.result', { id: videoId, userId })
154
155 if (video.isOutdated()) {
156 JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
157 }
158
159 return res.json(video.toFormattedDetailsJSON())
160 }
161
162 async function getVideoDescription (req: express.Request, res: express.Response) {
163 const videoInstance = res.locals.videoAll
164
165 const description = videoInstance.isOwned()
166 ? videoInstance.description
167 : await fetchRemoteVideoDescription(videoInstance)
168
169 return res.json({ description })
170 }
171
172 function getVideoSource (req: express.Request, res: express.Response) {
173 return res.json(res.locals.videoSource.toFormattedJSON())
174 }
175
176 async function listVideos (req: express.Request, res: express.Response) {
177 const serverActor = await getServerActor()
178
179 const query = pickCommonVideoQuery(req.query)
180 const countVideos = getCountVideos(req)
181
182 const apiOptions = await Hooks.wrapObject({
183 ...query,
184
185 displayOnlyForFollower: {
186 actorId: serverActor.id,
187 orLocalVideos: true
188 },
189 nsfw: buildNSFWFilter(res, query.nsfw),
190 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
191 countVideos
192 }, 'filter:api.videos.list.params')
193
194 const resultList = await Hooks.wrapPromiseFun(
195 VideoModel.listForApi,
196 apiOptions,
197 'filter:api.videos.list.result'
198 )
199
200 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
201 }
202
203 async function removeVideo (req: express.Request, res: express.Response) {
204 const videoInstance = res.locals.videoAll
205
206 await sequelizeTypescript.transaction(async t => {
207 await videoInstance.destroy({ transaction: t })
208 })
209
210 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
211 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
212
213 Hooks.runAction('action:api.video.deleted', { video: videoInstance, req, res })
214
215 return res.type('json')
216 .status(HttpStatusCode.NO_CONTENT_204)
217 .end()
218 }
219
220 // ---------------------------------------------------------------------------
221
222 // FIXME: Should not exist, we rely on specific API
223 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
224 const host = video.VideoChannel.Account.Actor.Server.host
225 const path = video.getDescriptionAPIPath()
226 const url = REMOTE_SCHEME.HTTP + '://' + host + path
227
228 const { body } = await doJSONRequest<any>(url)
229 return body.description || ''
230 }