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