]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/video-channel.ts
Add data directory for plugins and some helpers
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
CommitLineData
48dce1c9 1import * as express from 'express'
38267c0c 2import { Hooks } from '@server/lib/plugins/hooks'
8054669f 3import { getServerActor } from '@server/models/application/application'
2cb03dc1
C
4import { MChannelBannerAccountDefault } from '@server/types/models'
5import { ActorImageType, VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
8795d6f2 6import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
8054669f
C
7import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
8import { resetSequelizeInstance } from '../../helpers/database-utils'
9import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
10import { logger } from '../../helpers/logger'
e1c55031 11import { getFormattedObjects } from '../../helpers/utils'
8054669f
C
12import { CONFIG } from '../../initializers/config'
13import { MIMETYPES } from '../../initializers/constants'
14import { sequelizeTypescript } from '../../initializers/database'
8054669f 15import { sendUpdateActor } from '../../lib/activitypub/send'
2cb03dc1 16import { deleteLocalActorImageFile, updateLocalActorImageFile } from '../../lib/actor-image'
8054669f
C
17import { JobQueue } from '../../lib/job-queue'
18import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
48dce1c9
C
19import {
20 asyncMiddleware,
90d4bb81 21 asyncRetryTransactionMiddleware,
06215f15
C
22 authenticate,
23 commonVideosFiltersValidator,
cc918ac3 24 optionalAuthenticate,
48dce1c9
C
25 paginationValidator,
26 setDefaultPagination,
27 setDefaultSort,
8054669f 28 setDefaultVideosSort,
cc918ac3 29 videoChannelsAddValidator,
cc918ac3
C
30 videoChannelsRemoveValidator,
31 videoChannelsSortValidator,
418d092a
C
32 videoChannelsUpdateValidator,
33 videoPlaylistsSortValidator
48dce1c9 34} from '../../middlewares'
8054669f 35import { videoChannelsNameWithHostValidator, videoChannelsOwnSearchValidator, videosSortValidator } from '../../middlewares/validators'
213e30ef 36import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
8054669f 37import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
cc918ac3 38import { AccountModel } from '../../models/account/account'
cc918ac3 39import { VideoModel } from '../../models/video/video'
8054669f 40import { VideoChannelModel } from '../../models/video/video-channel'
418d092a 41import { VideoPlaylistModel } from '../../models/video/video-playlist'
4bbfc6c6 42
80e36cd9 43const auditLogger = auditLoggerFactory('channels')
14e2014a 44const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
2cb03dc1 45const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { bannerfile: CONFIG.STORAGE.TMP_DIR })
48dce1c9
C
46
47const videoChannelRouter = express.Router()
48
49videoChannelRouter.get('/',
50 paginationValidator,
51 videoChannelsSortValidator,
52 setDefaultSort,
53 setDefaultPagination,
bc99dfe5 54 videoChannelsOwnSearchValidator,
48dce1c9
C
55 asyncMiddleware(listVideoChannels)
56)
57
cc918ac3
C
58videoChannelRouter.post('/',
59 authenticate,
601527d7 60 asyncMiddleware(videoChannelsAddValidator),
90d4bb81 61 asyncRetryTransactionMiddleware(addVideoChannel)
cc918ac3
C
62)
63
8a19bee1 64videoChannelRouter.post('/:nameWithHost/avatar/pick',
4bbfc6c6
C
65 authenticate,
66 reqAvatarFile,
67 // Check the rights
68 asyncMiddleware(videoChannelsUpdateValidator),
69 updateAvatarValidator,
4a534352 70 asyncMiddleware(updateVideoChannelAvatar)
4bbfc6c6
C
71)
72
2cb03dc1
C
73videoChannelRouter.post('/:nameWithHost/banner/pick',
74 authenticate,
75 reqBannerFile,
76 // Check the rights
77 asyncMiddleware(videoChannelsUpdateValidator),
78 updateBannerValidator,
79 asyncMiddleware(updateVideoChannelBanner)
80)
81
1ea7da81
RK
82videoChannelRouter.delete('/:nameWithHost/avatar',
83 authenticate,
84 // Check the rights
85 asyncMiddleware(videoChannelsUpdateValidator),
86 asyncMiddleware(deleteVideoChannelAvatar)
87)
88
2cb03dc1
C
89videoChannelRouter.delete('/:nameWithHost/banner',
90 authenticate,
91 // Check the rights
92 asyncMiddleware(videoChannelsUpdateValidator),
93 asyncMiddleware(deleteVideoChannelBanner)
94)
95
8a19bee1 96videoChannelRouter.put('/:nameWithHost',
cc918ac3
C
97 authenticate,
98 asyncMiddleware(videoChannelsUpdateValidator),
90d4bb81 99 asyncRetryTransactionMiddleware(updateVideoChannel)
cc918ac3
C
100)
101
8a19bee1 102videoChannelRouter.delete('/:nameWithHost',
cc918ac3
C
103 authenticate,
104 asyncMiddleware(videoChannelsRemoveValidator),
90d4bb81 105 asyncRetryTransactionMiddleware(removeVideoChannel)
cc918ac3
C
106)
107
8a19bee1
C
108videoChannelRouter.get('/:nameWithHost',
109 asyncMiddleware(videoChannelsNameWithHostValidator),
cc918ac3
C
110 asyncMiddleware(getVideoChannel)
111)
112
418d092a
C
113videoChannelRouter.get('/:nameWithHost/video-playlists',
114 asyncMiddleware(videoChannelsNameWithHostValidator),
115 paginationValidator,
116 videoPlaylistsSortValidator,
117 setDefaultSort,
118 setDefaultPagination,
df0b219d 119 commonVideoPlaylistFiltersValidator,
418d092a
C
120 asyncMiddleware(listVideoChannelPlaylists)
121)
122
8a19bee1
C
123videoChannelRouter.get('/:nameWithHost/videos',
124 asyncMiddleware(videoChannelsNameWithHostValidator),
cc918ac3
C
125 paginationValidator,
126 videosSortValidator,
8054669f 127 setDefaultVideosSort,
cc918ac3
C
128 setDefaultPagination,
129 optionalAuthenticate,
d525fc39 130 commonVideosFiltersValidator,
cc918ac3
C
131 asyncMiddleware(listVideoChannelVideos)
132)
133
48dce1c9
C
134// ---------------------------------------------------------------------------
135
136export {
137 videoChannelRouter
138}
139
140// ---------------------------------------------------------------------------
141
dae86118 142async function listVideoChannels (req: express.Request, res: express.Response) {
f37dc0dd 143 const serverActor = await getServerActor()
bc99dfe5
RK
144 const resultList = await VideoChannelModel.listForApi({
145 actorId: serverActor.id,
146 start: req.query.start,
147 count: req.query.count,
4f5d0459 148 sort: req.query.sort
bc99dfe5 149 })
48dce1c9
C
150
151 return res.json(getFormattedObjects(resultList.data, resultList.total))
152}
cc918ac3 153
2cb03dc1
C
154async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
155 const bannerPhysicalFile = req.files['bannerfile'][0]
156 const videoChannel = res.locals.videoChannel
157 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
158
159 const banner = await updateLocalActorImageFile(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
160
161 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
162
163 return res.json({ banner: banner.toFormattedJSON() })
164}
dae86118 165async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
a1587156 166 const avatarPhysicalFile = req.files['avatarfile'][0]
dae86118 167 const videoChannel = res.locals.videoChannel
80e36cd9 168 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
4bbfc6c6 169
2cb03dc1 170 const avatar = await updateLocalActorImageFile(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
4bbfc6c6 171
f201a749 172 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
80e36cd9 173
2cb03dc1 174 return res.json({ avatar: avatar.toFormattedJSON() })
4bbfc6c6
C
175}
176
1ea7da81
RK
177async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
178 const videoChannel = res.locals.videoChannel
179
2cb03dc1
C
180 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
181
182 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
183}
184
185async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
186 const videoChannel = res.locals.videoChannel
187
188 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
1ea7da81
RK
189
190 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
191}
192
cc918ac3
C
193async function addVideoChannel (req: express.Request, res: express.Response) {
194 const videoChannelInfo: VideoChannelCreate = req.body
cc918ac3 195
453e83ea 196 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
dae86118 197 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
91411dba 198
1ca9f7c3 199 return createLocalVideoChannel(videoChannelInfo, account, t)
cc918ac3
C
200 })
201
8795d6f2
C
202 const payload = { actorId: videoChannelCreated.actorId }
203 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
cc918ac3 204
91411dba 205 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
57cfff78 206 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
cc918ac3 207
90d4bb81
C
208 return res.json({
209 videoChannel: {
57cfff78 210 id: videoChannelCreated.id
90d4bb81 211 }
2cb03dc1 212 })
cc918ac3
C
213}
214
215async function updateVideoChannel (req: express.Request, res: express.Response) {
dae86118 216 const videoChannelInstance = res.locals.videoChannel
cc918ac3 217 const videoChannelFieldsSave = videoChannelInstance.toJSON()
80e36cd9 218 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
cc918ac3 219 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
7d14d4d2 220 let doBulkVideoUpdate = false
cc918ac3
C
221
222 try {
223 await sequelizeTypescript.transaction(async t => {
224 const sequelizeOptions = {
225 transaction: t
226 }
227
7d14d4d2
C
228 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
229 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
230
231 if (videoChannelInfoToUpdate.support !== undefined) {
232 const oldSupportField = videoChannelInstance.support
233 videoChannelInstance.support = videoChannelInfoToUpdate.support
234
235 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
236 doBulkVideoUpdate = true
237 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
238 }
239 }
cc918ac3 240
2cb03dc1 241 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelBannerAccountDefault
cc918ac3 242 await sendUpdateActor(videoChannelInstanceUpdated, t)
cc918ac3 243
80e36cd9 244 auditLogger.update(
993cef4b 245 getAuditIdFromRes(res),
80e36cd9
AB
246 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
247 oldVideoChannelAuditKeys
248 )
7d14d4d2 249
57cfff78 250 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
80e36cd9 251 })
cc918ac3
C
252 } catch (err) {
253 logger.debug('Cannot update the video channel.', { err })
254
255 // Force fields we want to update
256 // If the transaction is retried, sequelize will think the object has not changed
257 // So it will skip the SQL request, even if the last one was ROLLBACKed!
258 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
259
260 throw err
261 }
cc918ac3 262
2d53be02 263 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
7d14d4d2
C
264
265 // Don't process in a transaction, and after the response because it could be long
266 if (doBulkVideoUpdate) {
267 await federateAllVideosOfChannel(videoChannelInstance)
268 }
cc918ac3
C
269}
270
271async function removeVideoChannel (req: express.Request, res: express.Response) {
dae86118 272 const videoChannelInstance = res.locals.videoChannel
cc918ac3 273
90d4bb81 274 await sequelizeTypescript.transaction(async t => {
df0b219d
C
275 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
276
cc918ac3
C
277 await videoChannelInstance.destroy({ transaction: t })
278
993cef4b 279 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
57cfff78 280 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
cc918ac3
C
281 })
282
2d53be02 283 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
cc918ac3
C
284}
285
dae86118 286async function getVideoChannel (req: express.Request, res: express.Response) {
2cb03dc1 287 const videoChannel = res.locals.videoChannel
cc918ac3 288
2cb03dc1
C
289 if (videoChannel.isOutdated()) {
290 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
744d0eca
C
291 }
292
2cb03dc1 293 return res.json(videoChannel.toFormattedJSON())
cc918ac3
C
294}
295
418d092a
C
296async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
297 const serverActor = await getServerActor()
298
299 const resultList = await VideoPlaylistModel.listForApi({
300 followerActorId: serverActor.id,
301 start: req.query.start,
302 count: req.query.count,
303 sort: req.query.sort,
df0b219d
C
304 videoChannelId: res.locals.videoChannel.id,
305 type: req.query.playlistType
418d092a
C
306 })
307
308 return res.json(getFormattedObjects(resultList.data, resultList.total))
309}
310
dae86118
C
311async function listVideoChannelVideos (req: express.Request, res: express.Response) {
312 const videoChannelInstance = res.locals.videoChannel
4e74e803 313 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
fe987656 314 const countVideos = getCountVideos(req)
cc918ac3 315
38267c0c 316 const apiOptions = await Hooks.wrapObject({
4e74e803 317 followerActorId,
cc918ac3
C
318 start: req.query.start,
319 count: req.query.count,
320 sort: req.query.sort,
8a19bee1 321 includeLocalVideos: true,
d525fc39
C
322 categoryOneOf: req.query.categoryOneOf,
323 licenceOneOf: req.query.licenceOneOf,
324 languageOneOf: req.query.languageOneOf,
325 tagsOneOf: req.query.tagsOneOf,
326 tagsAllOf: req.query.tagsAllOf,
1cd3facc 327 filter: req.query.filter,
d525fc39 328 nsfw: buildNSFWFilter(res, req.query.nsfw),
cc918ac3 329 withFiles: false,
1cd3facc 330 videoChannelId: videoChannelInstance.id,
fe987656
C
331 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
332 countVideos
38267c0c
C
333 }, 'filter:api.video-channels.videos.list.params')
334
335 const resultList = await Hooks.wrapPromiseFun(
336 VideoModel.listForApi,
337 apiOptions,
338 'filter:api.video-channels.videos.list.result'
339 )
cc918ac3
C
340
341 return res.json(getFormattedObjects(resultList.data, resultList.total))
342}