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