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