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