]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-channel.ts
Add get subscription endpoint
[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 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 } 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 import { resetSequelizeInstance } from '../../helpers/database-utils'
32
33 const auditLogger = auditLoggerFactory('channels')
34 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
35
36 const videoChannelRouter = express.Router()
37
38 videoChannelRouter.get('/',
39 paginationValidator,
40 videoChannelsSortValidator,
41 setDefaultSort,
42 setDefaultPagination,
43 asyncMiddleware(listVideoChannels)
44 )
45
46 videoChannelRouter.post('/',
47 authenticate,
48 videoChannelsAddValidator,
49 asyncRetryTransactionMiddleware(addVideoChannel)
50 )
51
52 videoChannelRouter.post('/:nameWithHost/avatar/pick',
53 authenticate,
54 reqAvatarFile,
55 // Check the rights
56 asyncMiddleware(videoChannelsUpdateValidator),
57 updateAvatarValidator,
58 asyncMiddleware(updateVideoChannelAvatar)
59 )
60
61 videoChannelRouter.put('/:nameWithHost',
62 authenticate,
63 asyncMiddleware(videoChannelsUpdateValidator),
64 asyncRetryTransactionMiddleware(updateVideoChannel)
65 )
66
67 videoChannelRouter.delete('/:nameWithHost',
68 authenticate,
69 asyncMiddleware(videoChannelsRemoveValidator),
70 asyncRetryTransactionMiddleware(removeVideoChannel)
71 )
72
73 videoChannelRouter.get('/:nameWithHost',
74 asyncMiddleware(videoChannelsNameWithHostValidator),
75 asyncMiddleware(getVideoChannel)
76 )
77
78 videoChannelRouter.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
91 export {
92 videoChannelRouter
93 }
94
95 // ---------------------------------------------------------------------------
96
97 async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
98 const resultList = await VideoChannelModel.listForApi(req.query.start, req.query.count, req.query.sort)
99
100 return res.json(getFormattedObjects(resultList.data, resultList.total))
101 }
102
103 async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
104 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
105 const videoChannel = res.locals.videoChannel as VideoChannelModel
106 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
107
108 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel.Actor, videoChannel)
109
110 auditLogger.update(
111 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
112 new VideoChannelAuditView(videoChannel.toFormattedJSON()),
113 oldVideoChannelAuditKeys
114 )
115
116 return res
117 .json({
118 avatar: avatar.toFormattedJSON()
119 })
120 .end()
121 }
122
123 async function addVideoChannel (req: express.Request, res: express.Response) {
124 const videoChannelInfo: VideoChannelCreate = req.body
125 const account: AccountModel = res.locals.oauth.token.User.Account
126
127 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
128 return createVideoChannel(videoChannelInfo, account, t)
129 })
130
131 setAsyncActorKeys(videoChannelCreated.Actor)
132 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
133
134 auditLogger.create(
135 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
136 new VideoChannelAuditView(videoChannelCreated.toFormattedJSON())
137 )
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 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
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(
195 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
196 new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
197 )
198 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
199 })
200
201 return res.type('json').status(204).end()
202 }
203
204 async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
205 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
206
207 return res.json(videoChannelWithVideos.toFormattedJSON())
208 }
209
210 async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
211 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
212
213 const resultList = await VideoModel.listForApi({
214 start: req.query.start,
215 count: req.query.count,
216 sort: req.query.sort,
217 includeLocalVideos: true,
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 }