]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/api/video-channel.ts
Fix overview cache
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
... / ...
CommitLineData
1import * as express from 'express'
2import { getFormattedObjects, getServerActor } from '../../helpers/utils'
3import {
4 asyncMiddleware,
5 asyncRetryTransactionMiddleware,
6 authenticate,
7 commonVideosFiltersValidator,
8 optionalAuthenticate,
9 paginationValidator,
10 setDefaultPagination,
11 setDefaultSort,
12 videoChannelsAddValidator,
13 videoChannelsRemoveValidator,
14 videoChannelsSortValidator,
15 videoChannelsUpdateValidator
16} from '../../middlewares'
17import { VideoChannelModel } from '../../models/video/video-channel'
18import { videoChannelsNameWithHostValidator, videosSortValidator } from '../../middlewares/validators'
19import { sendUpdateActor } from '../../lib/activitypub/send'
20import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
21import { createVideoChannel } from '../../lib/video-channel'
22import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
23import { setAsyncActorKeys } from '../../lib/activitypub'
24import { AccountModel } from '../../models/account/account'
25import { CONFIG, IMAGE_MIMETYPE_EXT, sequelizeTypescript } from '../../initializers'
26import { logger } from '../../helpers/logger'
27import { VideoModel } from '../../models/video/video'
28import { updateAvatarValidator } from '../../middlewares/validators/avatar'
29import { updateActorAvatarFile } from '../../lib/avatar'
30import { auditLoggerFactory, VideoChannelAuditView } from '../../helpers/audit-logger'
31import { resetSequelizeInstance } from '../../helpers/database-utils'
32
33const auditLogger = auditLoggerFactory('channels')
34const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
35
36const videoChannelRouter = express.Router()
37
38videoChannelRouter.get('/',
39 paginationValidator,
40 videoChannelsSortValidator,
41 setDefaultSort,
42 setDefaultPagination,
43 asyncMiddleware(listVideoChannels)
44)
45
46videoChannelRouter.post('/',
47 authenticate,
48 videoChannelsAddValidator,
49 asyncRetryTransactionMiddleware(addVideoChannel)
50)
51
52videoChannelRouter.post('/:nameWithHost/avatar/pick',
53 authenticate,
54 reqAvatarFile,
55 // Check the rights
56 asyncMiddleware(videoChannelsUpdateValidator),
57 updateAvatarValidator,
58 asyncMiddleware(updateVideoChannelAvatar)
59)
60
61videoChannelRouter.put('/:nameWithHost',
62 authenticate,
63 asyncMiddleware(videoChannelsUpdateValidator),
64 asyncRetryTransactionMiddleware(updateVideoChannel)
65)
66
67videoChannelRouter.delete('/:nameWithHost',
68 authenticate,
69 asyncMiddleware(videoChannelsRemoveValidator),
70 asyncRetryTransactionMiddleware(removeVideoChannel)
71)
72
73videoChannelRouter.get('/:nameWithHost',
74 asyncMiddleware(videoChannelsNameWithHostValidator),
75 asyncMiddleware(getVideoChannel)
76)
77
78videoChannelRouter.get('/:nameWithHost/videos',
79 asyncMiddleware(videoChannelsNameWithHostValidator),
80 paginationValidator,
81 videosSortValidator,
82 setDefaultSort,
83 setDefaultPagination,
84 optionalAuthenticate,
85 commonVideosFiltersValidator,
86 asyncMiddleware(listVideoChannelVideos)
87)
88
89// ---------------------------------------------------------------------------
90
91export {
92 videoChannelRouter
93}
94
95// ---------------------------------------------------------------------------
96
97async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
98 const serverActor = await getServerActor()
99 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
100
101 return res.json(getFormattedObjects(resultList.data, resultList.total))
102}
103
104async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
105 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
106 const videoChannel = res.locals.videoChannel as VideoChannelModel
107 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
108
109 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel.Actor, videoChannel)
110
111 auditLogger.update(
112 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
113 new VideoChannelAuditView(videoChannel.toFormattedJSON()),
114 oldVideoChannelAuditKeys
115 )
116
117 return res
118 .json({
119 avatar: avatar.toFormattedJSON()
120 })
121 .end()
122}
123
124async function addVideoChannel (req: express.Request, res: express.Response) {
125 const videoChannelInfo: VideoChannelCreate = req.body
126 const account: AccountModel = res.locals.oauth.token.User.Account
127
128 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
129 return createVideoChannel(videoChannelInfo, account, t)
130 })
131
132 setAsyncActorKeys(videoChannelCreated.Actor)
133 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
134
135 auditLogger.create(
136 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
137 new VideoChannelAuditView(videoChannelCreated.toFormattedJSON())
138 )
139 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
140
141 return res.json({
142 videoChannel: {
143 id: videoChannelCreated.id,
144 uuid: videoChannelCreated.Actor.uuid
145 }
146 }).end()
147}
148
149async function updateVideoChannel (req: express.Request, res: express.Response) {
150 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
151 const videoChannelFieldsSave = videoChannelInstance.toJSON()
152 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
153 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
154
155 try {
156 await sequelizeTypescript.transaction(async t => {
157 const sequelizeOptions = {
158 transaction: t
159 }
160
161 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
162 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
163 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
164
165 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
166 await sendUpdateActor(videoChannelInstanceUpdated, t)
167
168 auditLogger.update(
169 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
170 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
171 oldVideoChannelAuditKeys
172 )
173 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
174 })
175 } catch (err) {
176 logger.debug('Cannot update the video channel.', { err })
177
178 // Force fields we want to update
179 // If the transaction is retried, sequelize will think the object has not changed
180 // So it will skip the SQL request, even if the last one was ROLLBACKed!
181 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
182
183 throw err
184 }
185
186 return res.type('json').status(204).end()
187}
188
189async function removeVideoChannel (req: express.Request, res: express.Response) {
190 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
191
192 await sequelizeTypescript.transaction(async t => {
193 await videoChannelInstance.destroy({ transaction: t })
194
195 auditLogger.delete(
196 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
197 new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
198 )
199 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
200 })
201
202 return res.type('json').status(204).end()
203}
204
205async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
206 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
207
208 return res.json(videoChannelWithVideos.toFormattedJSON())
209}
210
211async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
212 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
213 const actorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
214
215 const resultList = await VideoModel.listForApi({
216 actorId,
217 start: req.query.start,
218 count: req.query.count,
219 sort: req.query.sort,
220 includeLocalVideos: true,
221 categoryOneOf: req.query.categoryOneOf,
222 licenceOneOf: req.query.licenceOneOf,
223 languageOneOf: req.query.languageOneOf,
224 tagsOneOf: req.query.tagsOneOf,
225 tagsAllOf: req.query.tagsAllOf,
226 nsfw: buildNSFWFilter(res, req.query.nsfw),
227 withFiles: false,
228 videoChannelId: videoChannelInstance.id
229 })
230
231 return res.json(getFormattedObjects(resultList.data, resultList.total))
232}