]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/video-channel.ts
Split check user params tests
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
CommitLineData
41fb13c3 1import express from 'express'
d6886027 2import { pickCommonVideoQuery } from '@server/helpers/query'
38267c0c 3import { Hooks } from '@server/lib/plugins/hooks'
4beda9e1 4import { ActorFollowModel } from '@server/models/actor/actor-follow'
8054669f 5import { getServerActor } from '@server/models/application/application'
2cb03dc1 6import { MChannelBannerAccountDefault } from '@server/types/models'
d6886027 7import { ActorImageType, VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
c0e8b12e 8import { HttpStatusCode } from '../../../shared/models/http/http-error-codes'
8054669f
C
9import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
10import { resetSequelizeInstance } from '../../helpers/database-utils'
11import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
12import { logger } from '../../helpers/logger'
e1c55031 13import { getFormattedObjects } from '../../helpers/utils'
8054669f
C
14import { CONFIG } from '../../initializers/config'
15import { MIMETYPES } from '../../initializers/constants'
16import { sequelizeTypescript } from '../../initializers/database'
8054669f 17import { sendUpdateActor } from '../../lib/activitypub/send'
8054669f 18import { JobQueue } from '../../lib/job-queue'
136d7efd 19import { deleteLocalActorImageFile, updateLocalActorImageFile } from '../../lib/local-actor'
8054669f 20import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
48dce1c9
C
21import {
22 asyncMiddleware,
90d4bb81 23 asyncRetryTransactionMiddleware,
06215f15
C
24 authenticate,
25 commonVideosFiltersValidator,
cc918ac3 26 optionalAuthenticate,
48dce1c9
C
27 paginationValidator,
28 setDefaultPagination,
29 setDefaultSort,
8054669f 30 setDefaultVideosSort,
cc918ac3 31 videoChannelsAddValidator,
cc918ac3
C
32 videoChannelsRemoveValidator,
33 videoChannelsSortValidator,
418d092a
C
34 videoChannelsUpdateValidator,
35 videoPlaylistsSortValidator
48dce1c9 36} from '../../middlewares'
4beda9e1
C
37import {
38 ensureAuthUserOwnsChannelValidator,
39 videoChannelsFollowersSortValidator,
40 videoChannelsListValidator,
41 videoChannelsNameWithHostValidator,
42 videosSortValidator
43} from '../../middlewares/validators'
213e30ef 44import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
8054669f 45import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
cc918ac3 46import { AccountModel } from '../../models/account/account'
cc918ac3 47import { VideoModel } from '../../models/video/video'
8054669f 48import { VideoChannelModel } from '../../models/video/video-channel'
418d092a 49import { VideoPlaylistModel } from '../../models/video/video-playlist'
4bbfc6c6 50
80e36cd9 51const auditLogger = auditLoggerFactory('channels')
14e2014a 52const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
2cb03dc1 53const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { bannerfile: CONFIG.STORAGE.TMP_DIR })
48dce1c9
C
54
55const videoChannelRouter = express.Router()
56
57videoChannelRouter.get('/',
58 paginationValidator,
59 videoChannelsSortValidator,
60 setDefaultSort,
61 setDefaultPagination,
37a44fc9 62 videoChannelsListValidator,
48dce1c9
C
63 asyncMiddleware(listVideoChannels)
64)
65
cc918ac3
C
66videoChannelRouter.post('/',
67 authenticate,
601527d7 68 asyncMiddleware(videoChannelsAddValidator),
90d4bb81 69 asyncRetryTransactionMiddleware(addVideoChannel)
cc918ac3
C
70)
71
8a19bee1 72videoChannelRouter.post('/:nameWithHost/avatar/pick',
4bbfc6c6
C
73 authenticate,
74 reqAvatarFile,
4beda9e1
C
75 asyncMiddleware(videoChannelsNameWithHostValidator),
76 ensureAuthUserOwnsChannelValidator,
4bbfc6c6 77 updateAvatarValidator,
4a534352 78 asyncMiddleware(updateVideoChannelAvatar)
4bbfc6c6
C
79)
80
2cb03dc1
C
81videoChannelRouter.post('/:nameWithHost/banner/pick',
82 authenticate,
83 reqBannerFile,
4beda9e1
C
84 asyncMiddleware(videoChannelsNameWithHostValidator),
85 ensureAuthUserOwnsChannelValidator,
2cb03dc1
C
86 updateBannerValidator,
87 asyncMiddleware(updateVideoChannelBanner)
88)
89
1ea7da81
RK
90videoChannelRouter.delete('/:nameWithHost/avatar',
91 authenticate,
4beda9e1
C
92 asyncMiddleware(videoChannelsNameWithHostValidator),
93 ensureAuthUserOwnsChannelValidator,
1ea7da81
RK
94 asyncMiddleware(deleteVideoChannelAvatar)
95)
96
2cb03dc1
C
97videoChannelRouter.delete('/:nameWithHost/banner',
98 authenticate,
4beda9e1
C
99 asyncMiddleware(videoChannelsNameWithHostValidator),
100 ensureAuthUserOwnsChannelValidator,
2cb03dc1
C
101 asyncMiddleware(deleteVideoChannelBanner)
102)
103
8a19bee1 104videoChannelRouter.put('/:nameWithHost',
cc918ac3 105 authenticate,
4beda9e1
C
106 asyncMiddleware(videoChannelsNameWithHostValidator),
107 ensureAuthUserOwnsChannelValidator,
108 videoChannelsUpdateValidator,
90d4bb81 109 asyncRetryTransactionMiddleware(updateVideoChannel)
cc918ac3
C
110)
111
8a19bee1 112videoChannelRouter.delete('/:nameWithHost',
cc918ac3
C
113 authenticate,
114 asyncMiddleware(videoChannelsRemoveValidator),
90d4bb81 115 asyncRetryTransactionMiddleware(removeVideoChannel)
cc918ac3
C
116)
117
8a19bee1
C
118videoChannelRouter.get('/:nameWithHost',
119 asyncMiddleware(videoChannelsNameWithHostValidator),
98ab5dc8 120 getVideoChannel
cc918ac3
C
121)
122
418d092a
C
123videoChannelRouter.get('/:nameWithHost/video-playlists',
124 asyncMiddleware(videoChannelsNameWithHostValidator),
125 paginationValidator,
126 videoPlaylistsSortValidator,
127 setDefaultSort,
128 setDefaultPagination,
df0b219d 129 commonVideoPlaylistFiltersValidator,
418d092a
C
130 asyncMiddleware(listVideoChannelPlaylists)
131)
132
8a19bee1
C
133videoChannelRouter.get('/:nameWithHost/videos',
134 asyncMiddleware(videoChannelsNameWithHostValidator),
cc918ac3
C
135 paginationValidator,
136 videosSortValidator,
8054669f 137 setDefaultVideosSort,
cc918ac3
C
138 setDefaultPagination,
139 optionalAuthenticate,
d525fc39 140 commonVideosFiltersValidator,
cc918ac3
C
141 asyncMiddleware(listVideoChannelVideos)
142)
143
4beda9e1
C
144videoChannelRouter.get('/:nameWithHost/followers',
145 authenticate,
146 asyncMiddleware(videoChannelsNameWithHostValidator),
147 ensureAuthUserOwnsChannelValidator,
148 paginationValidator,
149 videoChannelsFollowersSortValidator,
150 setDefaultSort,
151 setDefaultPagination,
152 asyncMiddleware(listVideoChannelFollowers)
153)
154
48dce1c9
C
155// ---------------------------------------------------------------------------
156
157export {
158 videoChannelRouter
159}
160
161// ---------------------------------------------------------------------------
162
dae86118 163async function listVideoChannels (req: express.Request, res: express.Response) {
f37dc0dd 164 const serverActor = await getServerActor()
bc99dfe5
RK
165 const resultList = await VideoChannelModel.listForApi({
166 actorId: serverActor.id,
167 start: req.query.start,
168 count: req.query.count,
4f5d0459 169 sort: req.query.sort
bc99dfe5 170 })
48dce1c9
C
171
172 return res.json(getFormattedObjects(resultList.data, resultList.total))
173}
cc918ac3 174
2cb03dc1
C
175async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
176 const bannerPhysicalFile = req.files['bannerfile'][0]
177 const videoChannel = res.locals.videoChannel
178 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
179
180 const banner = await updateLocalActorImageFile(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
181
182 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
183
184 return res.json({ banner: banner.toFormattedJSON() })
185}
c158a5fa 186
dae86118 187async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
a1587156 188 const avatarPhysicalFile = req.files['avatarfile'][0]
dae86118 189 const videoChannel = res.locals.videoChannel
80e36cd9 190 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
4bbfc6c6 191
2cb03dc1 192 const avatar = await updateLocalActorImageFile(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
4bbfc6c6 193
f201a749 194 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
80e36cd9 195
2cb03dc1 196 return res.json({ avatar: avatar.toFormattedJSON() })
4bbfc6c6
C
197}
198
1ea7da81
RK
199async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
200 const videoChannel = res.locals.videoChannel
201
2cb03dc1
C
202 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
203
76148b27 204 return res.status(HttpStatusCode.NO_CONTENT_204).end()
2cb03dc1
C
205}
206
207async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
208 const videoChannel = res.locals.videoChannel
209
210 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
1ea7da81 211
76148b27 212 return res.status(HttpStatusCode.NO_CONTENT_204).end()
1ea7da81
RK
213}
214
cc918ac3
C
215async function addVideoChannel (req: express.Request, res: express.Response) {
216 const videoChannelInfo: VideoChannelCreate = req.body
cc918ac3 217
453e83ea 218 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
dae86118 219 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
91411dba 220
1ca9f7c3 221 return createLocalVideoChannel(videoChannelInfo, account, t)
cc918ac3
C
222 })
223
8795d6f2
C
224 const payload = { actorId: videoChannelCreated.actorId }
225 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
cc918ac3 226
91411dba 227 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
57cfff78 228 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
cc918ac3 229
90d4bb81
C
230 return res.json({
231 videoChannel: {
57cfff78 232 id: videoChannelCreated.id
90d4bb81 233 }
2cb03dc1 234 })
cc918ac3
C
235}
236
237async function updateVideoChannel (req: express.Request, res: express.Response) {
dae86118 238 const videoChannelInstance = res.locals.videoChannel
cc918ac3 239 const videoChannelFieldsSave = videoChannelInstance.toJSON()
80e36cd9 240 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
cc918ac3 241 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
7d14d4d2 242 let doBulkVideoUpdate = false
cc918ac3
C
243
244 try {
245 await sequelizeTypescript.transaction(async t => {
7d14d4d2
C
246 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
247 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
248
249 if (videoChannelInfoToUpdate.support !== undefined) {
250 const oldSupportField = videoChannelInstance.support
251 videoChannelInstance.support = videoChannelInfoToUpdate.support
252
253 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
254 doBulkVideoUpdate = true
255 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
256 }
257 }
cc918ac3 258
c158a5fa 259 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
cc918ac3 260 await sendUpdateActor(videoChannelInstanceUpdated, t)
cc918ac3 261
80e36cd9 262 auditLogger.update(
993cef4b 263 getAuditIdFromRes(res),
80e36cd9
AB
264 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
265 oldVideoChannelAuditKeys
266 )
7d14d4d2 267
57cfff78 268 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
80e36cd9 269 })
cc918ac3
C
270 } catch (err) {
271 logger.debug('Cannot update the video channel.', { err })
272
273 // Force fields we want to update
274 // If the transaction is retried, sequelize will think the object has not changed
275 // So it will skip the SQL request, even if the last one was ROLLBACKed!
276 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
277
278 throw err
279 }
cc918ac3 280
2d53be02 281 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
7d14d4d2
C
282
283 // Don't process in a transaction, and after the response because it could be long
284 if (doBulkVideoUpdate) {
285 await federateAllVideosOfChannel(videoChannelInstance)
286 }
cc918ac3
C
287}
288
289async function removeVideoChannel (req: express.Request, res: express.Response) {
dae86118 290 const videoChannelInstance = res.locals.videoChannel
cc918ac3 291
90d4bb81 292 await sequelizeTypescript.transaction(async t => {
df0b219d
C
293 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
294
cc918ac3
C
295 await videoChannelInstance.destroy({ transaction: t })
296
993cef4b 297 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
57cfff78 298 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
cc918ac3
C
299 })
300
2d53be02 301 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
cc918ac3
C
302}
303
98ab5dc8 304function getVideoChannel (req: express.Request, res: express.Response) {
2cb03dc1 305 const videoChannel = res.locals.videoChannel
cc918ac3 306
2cb03dc1
C
307 if (videoChannel.isOutdated()) {
308 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
744d0eca
C
309 }
310
2cb03dc1 311 return res.json(videoChannel.toFormattedJSON())
cc918ac3
C
312}
313
418d092a
C
314async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
315 const serverActor = await getServerActor()
316
317 const resultList = await VideoPlaylistModel.listForApi({
318 followerActorId: serverActor.id,
319 start: req.query.start,
320 count: req.query.count,
321 sort: req.query.sort,
df0b219d
C
322 videoChannelId: res.locals.videoChannel.id,
323 type: req.query.playlistType
418d092a
C
324 })
325
326 return res.json(getFormattedObjects(resultList.data, resultList.total))
327}
328
dae86118
C
329async function listVideoChannelVideos (req: express.Request, res: express.Response) {
330 const videoChannelInstance = res.locals.videoChannel
4e74e803 331 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
fe987656 332 const countVideos = getCountVideos(req)
d6886027 333 const query = pickCommonVideoQuery(req.query)
cc918ac3 334
38267c0c 335 const apiOptions = await Hooks.wrapObject({
d6886027
C
336 ...query,
337
4e74e803 338 followerActorId,
8a19bee1 339 includeLocalVideos: true,
1fd61899 340 nsfw: buildNSFWFilter(res, query.nsfw),
cc918ac3 341 withFiles: false,
1cd3facc 342 videoChannelId: videoChannelInstance.id,
fe987656
C
343 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
344 countVideos
38267c0c
C
345 }, 'filter:api.video-channels.videos.list.params')
346
347 const resultList = await Hooks.wrapPromiseFun(
348 VideoModel.listForApi,
349 apiOptions,
350 'filter:api.video-channels.videos.list.result'
351 )
cc918ac3
C
352
353 return res.json(getFormattedObjects(resultList.data, resultList.total))
354}
4beda9e1
C
355
356async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
357 const channel = res.locals.videoChannel
358
359 const resultList = await ActorFollowModel.listFollowersForApi({
360 actorIds: [ channel.actorId ],
361 start: req.query.start,
362 count: req.query.count,
363 sort: req.query.sort,
364 search: req.query.search,
906f46d0 365 state: 'accepted'
4beda9e1
C
366 })
367
368 return res.json(getFormattedObjects(resultList.data, resultList.total))
369}