]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/video-channel.ts
Remove traefik docker support
[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
C
3import { getServerActor } from '@server/models/application/application'
4import { MChannelAccountDefault } from '@server/types/models'
5import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
6import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
7import { resetSequelizeInstance } from '../../helpers/database-utils'
8import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
9import { logger } from '../../helpers/logger'
e1c55031 10import { getFormattedObjects } from '../../helpers/utils'
8054669f
C
11import { CONFIG } from '../../initializers/config'
12import { MIMETYPES } from '../../initializers/constants'
13import { sequelizeTypescript } from '../../initializers/database'
14import { setAsyncActorKeys } from '../../lib/activitypub/actor'
15import { sendUpdateActor } from '../../lib/activitypub/send'
16import { updateActorAvatarFile } from '../../lib/avatar'
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
C
35import { videoChannelsNameWithHostValidator, videoChannelsOwnSearchValidator, videosSortValidator } from '../../middlewares/validators'
36import { updateAvatarValidator } from '../../middlewares/validators/avatar'
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'
2d53be02 42import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
4bbfc6c6 43
80e36cd9 44const auditLogger = auditLoggerFactory('channels')
14e2014a 45const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: 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
8a19bee1 73videoChannelRouter.put('/:nameWithHost',
cc918ac3
C
74 authenticate,
75 asyncMiddleware(videoChannelsUpdateValidator),
90d4bb81 76 asyncRetryTransactionMiddleware(updateVideoChannel)
cc918ac3
C
77)
78
8a19bee1 79videoChannelRouter.delete('/:nameWithHost',
cc918ac3
C
80 authenticate,
81 asyncMiddleware(videoChannelsRemoveValidator),
90d4bb81 82 asyncRetryTransactionMiddleware(removeVideoChannel)
cc918ac3
C
83)
84
8a19bee1
C
85videoChannelRouter.get('/:nameWithHost',
86 asyncMiddleware(videoChannelsNameWithHostValidator),
cc918ac3
C
87 asyncMiddleware(getVideoChannel)
88)
89
418d092a
C
90videoChannelRouter.get('/:nameWithHost/video-playlists',
91 asyncMiddleware(videoChannelsNameWithHostValidator),
92 paginationValidator,
93 videoPlaylistsSortValidator,
94 setDefaultSort,
95 setDefaultPagination,
df0b219d 96 commonVideoPlaylistFiltersValidator,
418d092a
C
97 asyncMiddleware(listVideoChannelPlaylists)
98)
99
8a19bee1
C
100videoChannelRouter.get('/:nameWithHost/videos',
101 asyncMiddleware(videoChannelsNameWithHostValidator),
cc918ac3
C
102 paginationValidator,
103 videosSortValidator,
8054669f 104 setDefaultVideosSort,
cc918ac3
C
105 setDefaultPagination,
106 optionalAuthenticate,
d525fc39 107 commonVideosFiltersValidator,
cc918ac3
C
108 asyncMiddleware(listVideoChannelVideos)
109)
110
48dce1c9
C
111// ---------------------------------------------------------------------------
112
113export {
114 videoChannelRouter
115}
116
117// ---------------------------------------------------------------------------
118
dae86118 119async function listVideoChannels (req: express.Request, res: express.Response) {
f37dc0dd 120 const serverActor = await getServerActor()
bc99dfe5
RK
121 const resultList = await VideoChannelModel.listForApi({
122 actorId: serverActor.id,
123 start: req.query.start,
124 count: req.query.count,
4f5d0459 125 sort: req.query.sort
bc99dfe5 126 })
48dce1c9
C
127
128 return res.json(getFormattedObjects(resultList.data, resultList.total))
129}
cc918ac3 130
dae86118 131async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
a1587156 132 const avatarPhysicalFile = req.files['avatarfile'][0]
dae86118 133 const videoChannel = res.locals.videoChannel
80e36cd9 134 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
4bbfc6c6 135
f201a749 136 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
4bbfc6c6 137
f201a749 138 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
80e36cd9 139
4bbfc6c6
C
140 return res
141 .json({
142 avatar: avatar.toFormattedJSON()
143 })
144 .end()
145}
146
cc918ac3
C
147async function addVideoChannel (req: express.Request, res: express.Response) {
148 const videoChannelInfo: VideoChannelCreate = req.body
cc918ac3 149
453e83ea 150 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
dae86118 151 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
91411dba 152
1ca9f7c3 153 return createLocalVideoChannel(videoChannelInfo, account, t)
cc918ac3
C
154 })
155
156 setAsyncActorKeys(videoChannelCreated.Actor)
57cfff78 157 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.url, { err }))
cc918ac3 158
91411dba 159 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
57cfff78 160 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
cc918ac3 161
90d4bb81
C
162 return res.json({
163 videoChannel: {
57cfff78 164 id: videoChannelCreated.id
90d4bb81
C
165 }
166 }).end()
cc918ac3
C
167}
168
169async function updateVideoChannel (req: express.Request, res: express.Response) {
dae86118 170 const videoChannelInstance = res.locals.videoChannel
cc918ac3 171 const videoChannelFieldsSave = videoChannelInstance.toJSON()
80e36cd9 172 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
cc918ac3 173 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
7d14d4d2 174 let doBulkVideoUpdate = false
cc918ac3
C
175
176 try {
177 await sequelizeTypescript.transaction(async t => {
178 const sequelizeOptions = {
179 transaction: t
180 }
181
7d14d4d2
C
182 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
183 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
184
185 if (videoChannelInfoToUpdate.support !== undefined) {
186 const oldSupportField = videoChannelInstance.support
187 videoChannelInstance.support = videoChannelInfoToUpdate.support
188
189 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
190 doBulkVideoUpdate = true
191 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
192 }
193 }
cc918ac3 194
b5fecbf4 195 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelAccountDefault
cc918ac3 196 await sendUpdateActor(videoChannelInstanceUpdated, t)
cc918ac3 197
80e36cd9 198 auditLogger.update(
993cef4b 199 getAuditIdFromRes(res),
80e36cd9
AB
200 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
201 oldVideoChannelAuditKeys
202 )
7d14d4d2 203
57cfff78 204 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
80e36cd9 205 })
cc918ac3
C
206 } catch (err) {
207 logger.debug('Cannot update the video channel.', { err })
208
209 // Force fields we want to update
210 // If the transaction is retried, sequelize will think the object has not changed
211 // So it will skip the SQL request, even if the last one was ROLLBACKed!
212 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
213
214 throw err
215 }
cc918ac3 216
2d53be02 217 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
7d14d4d2
C
218
219 // Don't process in a transaction, and after the response because it could be long
220 if (doBulkVideoUpdate) {
221 await federateAllVideosOfChannel(videoChannelInstance)
222 }
cc918ac3
C
223}
224
225async function removeVideoChannel (req: express.Request, res: express.Response) {
dae86118 226 const videoChannelInstance = res.locals.videoChannel
cc918ac3 227
90d4bb81 228 await sequelizeTypescript.transaction(async t => {
df0b219d
C
229 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
230
cc918ac3
C
231 await videoChannelInstance.destroy({ transaction: t })
232
993cef4b 233 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
57cfff78 234 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
cc918ac3
C
235 })
236
2d53be02 237 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
cc918ac3
C
238}
239
dae86118 240async function getVideoChannel (req: express.Request, res: express.Response) {
cc918ac3
C
241 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
242
744d0eca
C
243 if (videoChannelWithVideos.isOutdated()) {
244 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
744d0eca
C
245 }
246
cc918ac3
C
247 return res.json(videoChannelWithVideos.toFormattedJSON())
248}
249
418d092a
C
250async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
251 const serverActor = await getServerActor()
252
253 const resultList = await VideoPlaylistModel.listForApi({
254 followerActorId: serverActor.id,
255 start: req.query.start,
256 count: req.query.count,
257 sort: req.query.sort,
df0b219d
C
258 videoChannelId: res.locals.videoChannel.id,
259 type: req.query.playlistType
418d092a
C
260 })
261
262 return res.json(getFormattedObjects(resultList.data, resultList.total))
263}
264
dae86118
C
265async function listVideoChannelVideos (req: express.Request, res: express.Response) {
266 const videoChannelInstance = res.locals.videoChannel
4e74e803 267 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
fe987656 268 const countVideos = getCountVideos(req)
cc918ac3 269
38267c0c 270 const apiOptions = await Hooks.wrapObject({
4e74e803 271 followerActorId,
cc918ac3
C
272 start: req.query.start,
273 count: req.query.count,
274 sort: req.query.sort,
8a19bee1 275 includeLocalVideos: true,
d525fc39
C
276 categoryOneOf: req.query.categoryOneOf,
277 licenceOneOf: req.query.licenceOneOf,
278 languageOneOf: req.query.languageOneOf,
279 tagsOneOf: req.query.tagsOneOf,
280 tagsAllOf: req.query.tagsAllOf,
1cd3facc 281 filter: req.query.filter,
d525fc39 282 nsfw: buildNSFWFilter(res, req.query.nsfw),
cc918ac3 283 withFiles: false,
1cd3facc 284 videoChannelId: videoChannelInstance.id,
fe987656
C
285 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
286 countVideos
38267c0c
C
287 }, 'filter:api.video-channels.videos.list.params')
288
289 const resultList = await Hooks.wrapPromiseFun(
290 VideoModel.listForApi,
291 apiOptions,
292 'filter:api.video-channels.videos.list.result'
293 )
cc918ac3
C
294
295 return res.json(getFormattedObjects(resultList.data, resultList.total))
296}