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