]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-channel.ts
8fc34022430bb61dc3aff14ced7164581d71fda2
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
1 import * as express from 'express'
2 import { getFormattedObjects, getServerActor } from '../../helpers/utils'
3 import {
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'
17 import { VideoChannelModel } from '../../models/video/video-channel'
18 import { videoChannelsNameWithHostValidator, 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 { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } 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, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
31 import { resetSequelizeInstance } from '../../helpers/database-utils'
32 import { UserModel } from '../../models/account/user'
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('/:nameWithHost/avatar/pick',
54 authenticate,
55 reqAvatarFile,
56 // Check the rights
57 asyncMiddleware(videoChannelsUpdateValidator),
58 updateAvatarValidator,
59 asyncMiddleware(updateVideoChannelAvatar)
60 )
61
62 videoChannelRouter.put('/:nameWithHost',
63 authenticate,
64 asyncMiddleware(videoChannelsUpdateValidator),
65 asyncRetryTransactionMiddleware(updateVideoChannel)
66 )
67
68 videoChannelRouter.delete('/:nameWithHost',
69 authenticate,
70 asyncMiddleware(videoChannelsRemoveValidator),
71 asyncRetryTransactionMiddleware(removeVideoChannel)
72 )
73
74 videoChannelRouter.get('/:nameWithHost',
75 asyncMiddleware(videoChannelsNameWithHostValidator),
76 asyncMiddleware(getVideoChannel)
77 )
78
79 videoChannelRouter.get('/:nameWithHost/videos',
80 asyncMiddleware(videoChannelsNameWithHostValidator),
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 serverActor = await getServerActor()
100 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
101
102 return res.json(getFormattedObjects(resultList.data, resultList.total))
103 }
104
105 async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
106 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
107 const videoChannel = res.locals.videoChannel as VideoChannelModel
108 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
109
110 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel.Actor, videoChannel)
111
112 auditLogger.update(
113 getAuditIdFromRes(res),
114 new VideoChannelAuditView(videoChannel.toFormattedJSON()),
115 oldVideoChannelAuditKeys
116 )
117
118 return res
119 .json({
120 avatar: avatar.toFormattedJSON()
121 })
122 .end()
123 }
124
125 async function addVideoChannel (req: express.Request, res: express.Response) {
126 const videoChannelInfo: VideoChannelCreate = req.body
127
128 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
129 const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t)
130
131 return createVideoChannel(videoChannelInfo, account, t)
132 })
133
134 setAsyncActorKeys(videoChannelCreated.Actor)
135 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
136
137 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
138 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
139
140 return res.json({
141 videoChannel: {
142 id: videoChannelCreated.id,
143 uuid: videoChannelCreated.Actor.uuid
144 }
145 }).end()
146 }
147
148 async function updateVideoChannel (req: express.Request, res: express.Response) {
149 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
150 const videoChannelFieldsSave = videoChannelInstance.toJSON()
151 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
152 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
153
154 try {
155 await sequelizeTypescript.transaction(async t => {
156 const sequelizeOptions = {
157 transaction: t
158 }
159
160 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
161 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
162 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
163
164 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
165 await sendUpdateActor(videoChannelInstanceUpdated, t)
166
167 auditLogger.update(
168 getAuditIdFromRes(res),
169 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
170 oldVideoChannelAuditKeys
171 )
172 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
173 })
174 } catch (err) {
175 logger.debug('Cannot update the video channel.', { err })
176
177 // Force fields we want to update
178 // If the transaction is retried, sequelize will think the object has not changed
179 // So it will skip the SQL request, even if the last one was ROLLBACKed!
180 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
181
182 throw err
183 }
184
185 return res.type('json').status(204).end()
186 }
187
188 async function removeVideoChannel (req: express.Request, res: express.Response) {
189 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
190
191 await sequelizeTypescript.transaction(async t => {
192 await videoChannelInstance.destroy({ transaction: t })
193
194 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
195 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
196 })
197
198 return res.type('json').status(204).end()
199 }
200
201 async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
202 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
203
204 return res.json(videoChannelWithVideos.toFormattedJSON())
205 }
206
207 async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
208 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
209 const actorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
210
211 const resultList = await VideoModel.listForApi({
212 actorId,
213 start: req.query.start,
214 count: req.query.count,
215 sort: req.query.sort,
216 includeLocalVideos: true,
217 categoryOneOf: req.query.categoryOneOf,
218 licenceOneOf: req.query.licenceOneOf,
219 languageOneOf: req.query.languageOneOf,
220 tagsOneOf: req.query.tagsOneOf,
221 tagsAllOf: req.query.tagsAllOf,
222 nsfw: buildNSFWFilter(res, req.query.nsfw),
223 withFiles: false,
224 videoChannelId: videoChannelInstance.id
225 })
226
227 return res.json(getFormattedObjects(resultList.data, resultList.total))
228 }