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