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