]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/video-channel.ts
Merge branch 'release/4.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
CommitLineData
41fb13c3 1import express from 'express'
d6886027 2import { pickCommonVideoQuery } from '@server/helpers/query'
d0800f76 3import { getBiggestActorImage } from '@server/lib/actor-image'
38267c0c 4import { Hooks } from '@server/lib/plugins/hooks'
4beda9e1 5import { ActorFollowModel } from '@server/models/actor/actor-follow'
8054669f 6import { getServerActor } from '@server/models/application/application'
2760b454 7import { guessAdditionalAttributesFromQuery } from '@server/models/video/formatter/video-format-utils'
2cb03dc1 8import { MChannelBannerAccountDefault } from '@server/types/models'
d17c7b4e 9import { ActorImageType, HttpStatusCode, VideoChannelCreate, VideoChannelUpdate } from '@shared/models'
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 { MIMETYPES } from '../../initializers/constants'
16import { sequelizeTypescript } from '../../initializers/database'
8054669f 17import { sendUpdateActor } from '../../lib/activitypub/send'
8054669f 18import { JobQueue } from '../../lib/job-queue'
d0800f76 19import { deleteLocalActorImageFile, updateLocalActorImageFiles } 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')
d3d3deaa
C
53const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
54const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
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
d0800f76 189 const banners = await updateLocalActorImageFiles(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
2cb03dc1
C
190
191 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
192
d0800f76 193 return res.json({
194 // TODO: remove, deprecated in 4.2
195 banner: getBiggestActorImage(banners).toFormattedJSON(),
196 banners: banners.map(b => b.toFormattedJSON())
197 })
2cb03dc1 198}
c158a5fa 199
dae86118 200async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
a1587156 201 const avatarPhysicalFile = req.files['avatarfile'][0]
dae86118 202 const videoChannel = res.locals.videoChannel
80e36cd9 203 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
4bbfc6c6 204
d0800f76 205 const avatars = await updateLocalActorImageFiles(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
f201a749 206 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
80e36cd9 207
d0800f76 208 return res.json({
209 // TODO: remove, deprecated in 4.2
210 avatar: getBiggestActorImage(avatars).toFormattedJSON(),
211 avatars: avatars.map(a => a.toFormattedJSON())
212 })
4bbfc6c6
C
213}
214
1ea7da81
RK
215async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
216 const videoChannel = res.locals.videoChannel
217
2cb03dc1
C
218 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
219
76148b27 220 return res.status(HttpStatusCode.NO_CONTENT_204).end()
2cb03dc1
C
221}
222
223async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
224 const videoChannel = res.locals.videoChannel
225
226 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
1ea7da81 227
76148b27 228 return res.status(HttpStatusCode.NO_CONTENT_204).end()
1ea7da81
RK
229}
230
cc918ac3
C
231async function addVideoChannel (req: express.Request, res: express.Response) {
232 const videoChannelInfo: VideoChannelCreate = req.body
cc918ac3 233
453e83ea 234 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
dae86118 235 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
91411dba 236
1ca9f7c3 237 return createLocalVideoChannel(videoChannelInfo, account, t)
cc918ac3
C
238 })
239
8795d6f2
C
240 const payload = { actorId: videoChannelCreated.actorId }
241 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
cc918ac3 242
91411dba 243 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
57cfff78 244 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
cc918ac3 245
90d4bb81
C
246 return res.json({
247 videoChannel: {
57cfff78 248 id: videoChannelCreated.id
90d4bb81 249 }
2cb03dc1 250 })
cc918ac3
C
251}
252
253async function updateVideoChannel (req: express.Request, res: express.Response) {
dae86118 254 const videoChannelInstance = res.locals.videoChannel
cc918ac3 255 const videoChannelFieldsSave = videoChannelInstance.toJSON()
80e36cd9 256 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
cc918ac3 257 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
7d14d4d2 258 let doBulkVideoUpdate = false
cc918ac3
C
259
260 try {
261 await sequelizeTypescript.transaction(async t => {
7d14d4d2
C
262 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
263 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
264
265 if (videoChannelInfoToUpdate.support !== undefined) {
266 const oldSupportField = videoChannelInstance.support
267 videoChannelInstance.support = videoChannelInfoToUpdate.support
268
269 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
270 doBulkVideoUpdate = true
271 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
272 }
273 }
cc918ac3 274
c158a5fa 275 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
cc918ac3 276 await sendUpdateActor(videoChannelInstanceUpdated, t)
cc918ac3 277
80e36cd9 278 auditLogger.update(
993cef4b 279 getAuditIdFromRes(res),
80e36cd9
AB
280 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
281 oldVideoChannelAuditKeys
282 )
7d14d4d2 283
57cfff78 284 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
80e36cd9 285 })
cc918ac3
C
286 } catch (err) {
287 logger.debug('Cannot update the video channel.', { err })
288
289 // Force fields we want to update
290 // If the transaction is retried, sequelize will think the object has not changed
291 // So it will skip the SQL request, even if the last one was ROLLBACKed!
292 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
293
294 throw err
295 }
cc918ac3 296
2d53be02 297 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
7d14d4d2
C
298
299 // Don't process in a transaction, and after the response because it could be long
300 if (doBulkVideoUpdate) {
301 await federateAllVideosOfChannel(videoChannelInstance)
302 }
cc918ac3
C
303}
304
305async function removeVideoChannel (req: express.Request, res: express.Response) {
dae86118 306 const videoChannelInstance = res.locals.videoChannel
cc918ac3 307
90d4bb81 308 await sequelizeTypescript.transaction(async t => {
df0b219d
C
309 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
310
cc918ac3
C
311 await videoChannelInstance.destroy({ transaction: t })
312
993cef4b 313 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
57cfff78 314 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
cc918ac3
C
315 })
316
2d53be02 317 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
cc918ac3
C
318}
319
98ab5dc8 320function getVideoChannel (req: express.Request, res: express.Response) {
2cb03dc1 321 const videoChannel = res.locals.videoChannel
cc918ac3 322
2cb03dc1
C
323 if (videoChannel.isOutdated()) {
324 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
744d0eca
C
325 }
326
2cb03dc1 327 return res.json(videoChannel.toFormattedJSON())
cc918ac3
C
328}
329
418d092a
C
330async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
331 const serverActor = await getServerActor()
332
333 const resultList = await VideoPlaylistModel.listForApi({
334 followerActorId: serverActor.id,
335 start: req.query.start,
336 count: req.query.count,
337 sort: req.query.sort,
df0b219d
C
338 videoChannelId: res.locals.videoChannel.id,
339 type: req.query.playlistType
418d092a
C
340 })
341
342 return res.json(getFormattedObjects(resultList.data, resultList.total))
343}
344
dae86118 345async function listVideoChannelVideos (req: express.Request, res: express.Response) {
2760b454
C
346 const serverActor = await getServerActor()
347
dae86118 348 const videoChannelInstance = res.locals.videoChannel
2760b454
C
349
350 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
351 ? null
352 : {
353 actorId: serverActor.id,
354 orLocalVideos: true
355 }
356
fe987656 357 const countVideos = getCountVideos(req)
d6886027 358 const query = pickCommonVideoQuery(req.query)
cc918ac3 359
38267c0c 360 const apiOptions = await Hooks.wrapObject({
d6886027
C
361 ...query,
362
2760b454 363 displayOnlyForFollower,
1fd61899 364 nsfw: buildNSFWFilter(res, query.nsfw),
1cd3facc 365 videoChannelId: videoChannelInstance.id,
fe987656
C
366 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
367 countVideos
38267c0c
C
368 }, 'filter:api.video-channels.videos.list.params')
369
370 const resultList = await Hooks.wrapPromiseFun(
371 VideoModel.listForApi,
372 apiOptions,
373 'filter:api.video-channels.videos.list.result'
374 )
cc918ac3 375
2760b454 376 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
cc918ac3 377}
4beda9e1
C
378
379async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
380 const channel = res.locals.videoChannel
381
382 const resultList = await ActorFollowModel.listFollowersForApi({
383 actorIds: [ channel.actorId ],
384 start: req.query.start,
385 count: req.query.count,
386 sort: req.query.sort,
387 search: req.query.search,
906f46d0 388 state: 'accepted'
4beda9e1
C
389 })
390
391 return res.json(getFormattedObjects(resultList.data, resultList.total))
392}