]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/video-channel.ts
Refactor video playlist middlewares
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
CommitLineData
48dce1c9 1import * as express from 'express'
f37dc0dd 2import { getFormattedObjects, getServerActor } from '../../helpers/utils'
48dce1c9
C
3import {
4 asyncMiddleware,
90d4bb81 5 asyncRetryTransactionMiddleware,
06215f15
C
6 authenticate,
7 commonVideosFiltersValidator,
cc918ac3 8 optionalAuthenticate,
48dce1c9
C
9 paginationValidator,
10 setDefaultPagination,
11 setDefaultSort,
cc918ac3 12 videoChannelsAddValidator,
cc918ac3
C
13 videoChannelsRemoveValidator,
14 videoChannelsSortValidator,
418d092a
C
15 videoChannelsUpdateValidator,
16 videoPlaylistsSortValidator
48dce1c9
C
17} from '../../middlewares'
18import { VideoChannelModel } from '../../models/video/video-channel'
8a19bee1 19import { videoChannelsNameWithHostValidator, videosSortValidator } from '../../middlewares/validators'
cc918ac3
C
20import { sendUpdateActor } from '../../lib/activitypub/send'
21import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
22import { createVideoChannel } from '../../lib/video-channel'
687d638c 23import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
cc918ac3 24import { setAsyncActorKeys } from '../../lib/activitypub'
cc918ac3 25import { AccountModel } from '../../models/account/account'
14e2014a 26import { CONFIG, MIMETYPES, sequelizeTypescript } from '../../initializers'
cc918ac3
C
27import { logger } from '../../helpers/logger'
28import { VideoModel } from '../../models/video/video'
4bbfc6c6
C
29import { updateAvatarValidator } from '../../middlewares/validators/avatar'
30import { updateActorAvatarFile } from '../../lib/avatar'
993cef4b 31import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
06215f15 32import { resetSequelizeInstance } from '../../helpers/database-utils'
91411dba 33import { UserModel } from '../../models/account/user'
744d0eca 34import { JobQueue } from '../../lib/job-queue'
418d092a 35import { VideoPlaylistModel } from '../../models/video/video-playlist'
df0b219d 36import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
4bbfc6c6 37
80e36cd9 38const auditLogger = auditLoggerFactory('channels')
14e2014a 39const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
48dce1c9
C
40
41const videoChannelRouter = express.Router()
42
43videoChannelRouter.get('/',
44 paginationValidator,
45 videoChannelsSortValidator,
46 setDefaultSort,
47 setDefaultPagination,
48 asyncMiddleware(listVideoChannels)
49)
50
cc918ac3
C
51videoChannelRouter.post('/',
52 authenticate,
601527d7 53 asyncMiddleware(videoChannelsAddValidator),
90d4bb81 54 asyncRetryTransactionMiddleware(addVideoChannel)
cc918ac3
C
55)
56
8a19bee1 57videoChannelRouter.post('/:nameWithHost/avatar/pick',
4bbfc6c6
C
58 authenticate,
59 reqAvatarFile,
60 // Check the rights
61 asyncMiddleware(videoChannelsUpdateValidator),
62 updateAvatarValidator,
4a534352 63 asyncMiddleware(updateVideoChannelAvatar)
4bbfc6c6
C
64)
65
8a19bee1 66videoChannelRouter.put('/:nameWithHost',
cc918ac3
C
67 authenticate,
68 asyncMiddleware(videoChannelsUpdateValidator),
90d4bb81 69 asyncRetryTransactionMiddleware(updateVideoChannel)
cc918ac3
C
70)
71
8a19bee1 72videoChannelRouter.delete('/:nameWithHost',
cc918ac3
C
73 authenticate,
74 asyncMiddleware(videoChannelsRemoveValidator),
90d4bb81 75 asyncRetryTransactionMiddleware(removeVideoChannel)
cc918ac3
C
76)
77
8a19bee1
C
78videoChannelRouter.get('/:nameWithHost',
79 asyncMiddleware(videoChannelsNameWithHostValidator),
cc918ac3
C
80 asyncMiddleware(getVideoChannel)
81)
82
418d092a
C
83videoChannelRouter.get('/:nameWithHost/video-playlists',
84 asyncMiddleware(videoChannelsNameWithHostValidator),
85 paginationValidator,
86 videoPlaylistsSortValidator,
87 setDefaultSort,
88 setDefaultPagination,
df0b219d 89 commonVideoPlaylistFiltersValidator,
418d092a
C
90 asyncMiddleware(listVideoChannelPlaylists)
91)
92
8a19bee1
C
93videoChannelRouter.get('/:nameWithHost/videos',
94 asyncMiddleware(videoChannelsNameWithHostValidator),
cc918ac3
C
95 paginationValidator,
96 videosSortValidator,
97 setDefaultSort,
98 setDefaultPagination,
99 optionalAuthenticate,
d525fc39 100 commonVideosFiltersValidator,
cc918ac3
C
101 asyncMiddleware(listVideoChannelVideos)
102)
103
48dce1c9
C
104// ---------------------------------------------------------------------------
105
106export {
107 videoChannelRouter
108}
109
110// ---------------------------------------------------------------------------
111
112async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
f37dc0dd
C
113 const serverActor = await getServerActor()
114 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
48dce1c9
C
115
116 return res.json(getFormattedObjects(resultList.data, resultList.total))
117}
cc918ac3 118
4bbfc6c6
C
119async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
120 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
80e36cd9
AB
121 const videoChannel = res.locals.videoChannel as VideoChannelModel
122 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
4bbfc6c6 123
f201a749 124 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
4bbfc6c6 125
f201a749 126 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
80e36cd9 127
4bbfc6c6
C
128 return res
129 .json({
130 avatar: avatar.toFormattedJSON()
131 })
132 .end()
133}
134
cc918ac3
C
135async function addVideoChannel (req: express.Request, res: express.Response) {
136 const videoChannelInfo: VideoChannelCreate = req.body
cc918ac3
C
137
138 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
91411dba
C
139 const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t)
140
cc918ac3
C
141 return createVideoChannel(videoChannelInfo, account, t)
142 })
143
144 setAsyncActorKeys(videoChannelCreated.Actor)
145 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
146
91411dba 147 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
cc918ac3
C
148 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
149
90d4bb81
C
150 return res.json({
151 videoChannel: {
152 id: videoChannelCreated.id,
153 uuid: videoChannelCreated.Actor.uuid
154 }
155 }).end()
cc918ac3
C
156}
157
158async function updateVideoChannel (req: express.Request, res: express.Response) {
159 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
160 const videoChannelFieldsSave = videoChannelInstance.toJSON()
80e36cd9 161 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
cc918ac3
C
162 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
163
164 try {
165 await sequelizeTypescript.transaction(async t => {
166 const sequelizeOptions = {
167 transaction: t
168 }
169
08c1efbe 170 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
cc918ac3
C
171 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
172 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
173
174 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
175 await sendUpdateActor(videoChannelInstanceUpdated, t)
cc918ac3 176
80e36cd9 177 auditLogger.update(
993cef4b 178 getAuditIdFromRes(res),
80e36cd9
AB
179 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
180 oldVideoChannelAuditKeys
181 )
182 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
183 })
cc918ac3
C
184 } catch (err) {
185 logger.debug('Cannot update the video channel.', { err })
186
187 // Force fields we want to update
188 // If the transaction is retried, sequelize will think the object has not changed
189 // So it will skip the SQL request, even if the last one was ROLLBACKed!
190 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
191
192 throw err
193 }
cc918ac3
C
194
195 return res.type('json').status(204).end()
196}
197
198async function removeVideoChannel (req: express.Request, res: express.Response) {
199 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
200
90d4bb81 201 await sequelizeTypescript.transaction(async t => {
df0b219d
C
202 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
203
cc918ac3
C
204 await videoChannelInstance.destroy({ transaction: t })
205
993cef4b 206 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
cc918ac3
C
207 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
208 })
209
90d4bb81 210 return res.type('json').status(204).end()
cc918ac3
C
211}
212
213async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
214 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
215
744d0eca
C
216 if (videoChannelWithVideos.isOutdated()) {
217 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
218 .catch(err => logger.error('Cannot create AP refresher job for actor %s.', videoChannelWithVideos.Actor.url, { err }))
219 }
220
cc918ac3
C
221 return res.json(videoChannelWithVideos.toFormattedJSON())
222}
223
418d092a
C
224async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
225 const serverActor = await getServerActor()
226
227 const resultList = await VideoPlaylistModel.listForApi({
228 followerActorId: serverActor.id,
229 start: req.query.start,
230 count: req.query.count,
231 sort: req.query.sort,
df0b219d
C
232 videoChannelId: res.locals.videoChannel.id,
233 type: req.query.playlistType
418d092a
C
234 })
235
236 return res.json(getFormattedObjects(resultList.data, resultList.total))
237}
238
cc918ac3
C
239async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
240 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
4e74e803 241 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
cc918ac3
C
242
243 const resultList = await VideoModel.listForApi({
4e74e803 244 followerActorId,
cc918ac3
C
245 start: req.query.start,
246 count: req.query.count,
247 sort: req.query.sort,
8a19bee1 248 includeLocalVideos: true,
d525fc39
C
249 categoryOneOf: req.query.categoryOneOf,
250 licenceOneOf: req.query.licenceOneOf,
251 languageOneOf: req.query.languageOneOf,
252 tagsOneOf: req.query.tagsOneOf,
253 tagsAllOf: req.query.tagsAllOf,
1cd3facc 254 filter: req.query.filter,
d525fc39 255 nsfw: buildNSFWFilter(res, req.query.nsfw),
cc918ac3 256 withFiles: false,
1cd3facc 257 videoChannelId: videoChannelInstance.id,
7ad9b984 258 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
cc918ac3
C
259 })
260
261 return res.json(getFormattedObjects(resultList.data, resultList.total))
262}