]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-channel.ts
023ebbedfabf8e3e7090b48ecb949950a9e97325
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
1 import * as express from 'express'
2 import { getFormattedObjects } from '../../helpers/utils'
3 import {
4 asyncMiddleware,
5 asyncRetryTransactionMiddleware,
6 authenticate,
7 commonVideosFiltersValidator,
8 optionalAuthenticate,
9 paginationValidator,
10 setDefaultPagination,
11 setDefaultSort,
12 videoChannelsAddValidator,
13 videoChannelsGetValidator,
14 videoChannelsRemoveValidator,
15 videoChannelsSortValidator,
16 videoChannelsUpdateValidator
17 } from '../../middlewares'
18 import { VideoChannelModel } from '../../models/video/video-channel'
19 import { videosSortValidator } from '../../middlewares/validators'
20 import { sendUpdateActor } from '../../lib/activitypub/send'
21 import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
22 import { createVideoChannel } from '../../lib/video-channel'
23 import { buildNSFWFilter, createReqFiles } from '../../helpers/express-utils'
24 import { setAsyncActorKeys } from '../../lib/activitypub'
25 import { AccountModel } from '../../models/account/account'
26 import { CONFIG, IMAGE_MIMETYPE_EXT, sequelizeTypescript } from '../../initializers'
27 import { logger } from '../../helpers/logger'
28 import { VideoModel } from '../../models/video/video'
29 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
30 import { updateActorAvatarFile } from '../../lib/avatar'
31 import { auditLoggerFactory, VideoChannelAuditView } from '../../helpers/audit-logger'
32 import { resetSequelizeInstance } from '../../helpers/database-utils'
33
34 const auditLogger = auditLoggerFactory('channels')
35 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
36
37 const videoChannelRouter = express.Router()
38
39 videoChannelRouter.get('/',
40 paginationValidator,
41 videoChannelsSortValidator,
42 setDefaultSort,
43 setDefaultPagination,
44 asyncMiddleware(listVideoChannels)
45 )
46
47 videoChannelRouter.post('/',
48 authenticate,
49 videoChannelsAddValidator,
50 asyncRetryTransactionMiddleware(addVideoChannel)
51 )
52
53 videoChannelRouter.post('/:id/avatar/pick',
54 authenticate,
55 reqAvatarFile,
56 // Check the rights
57 asyncMiddleware(videoChannelsUpdateValidator),
58 updateAvatarValidator,
59 asyncMiddleware(updateVideoChannelAvatar)
60 )
61
62 videoChannelRouter.put('/:id',
63 authenticate,
64 asyncMiddleware(videoChannelsUpdateValidator),
65 asyncRetryTransactionMiddleware(updateVideoChannel)
66 )
67
68 videoChannelRouter.delete('/:id',
69 authenticate,
70 asyncMiddleware(videoChannelsRemoveValidator),
71 asyncRetryTransactionMiddleware(removeVideoChannel)
72 )
73
74 videoChannelRouter.get('/:id',
75 asyncMiddleware(videoChannelsGetValidator),
76 asyncMiddleware(getVideoChannel)
77 )
78
79 videoChannelRouter.get('/:id/videos',
80 asyncMiddleware(videoChannelsGetValidator),
81 paginationValidator,
82 videosSortValidator,
83 setDefaultSort,
84 setDefaultPagination,
85 optionalAuthenticate,
86 commonVideosFiltersValidator,
87 asyncMiddleware(listVideoChannelVideos)
88 )
89
90 // ---------------------------------------------------------------------------
91
92 export {
93 videoChannelRouter
94 }
95
96 // ---------------------------------------------------------------------------
97
98 async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
99 const resultList = await VideoChannelModel.listForApi(req.query.start, req.query.count, req.query.sort)
100
101 return res.json(getFormattedObjects(resultList.data, resultList.total))
102 }
103
104 async 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
124 async 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
149 async 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
189 async 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
205 async 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
211 async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
212 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
213
214 const resultList = await VideoModel.listForApi({
215 start: req.query.start,
216 count: req.query.count,
217 sort: req.query.sort,
218 categoryOneOf: req.query.categoryOneOf,
219 licenceOneOf: req.query.licenceOneOf,
220 languageOneOf: req.query.languageOneOf,
221 tagsOneOf: req.query.tagsOneOf,
222 tagsAllOf: req.query.tagsAllOf,
223 nsfw: buildNSFWFilter(res, req.query.nsfw),
224 withFiles: false,
225 videoChannelId: videoChannelInstance.id
226 })
227
228 return res.json(getFormattedObjects(resultList.data, resultList.total))
229 }