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