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