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