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