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