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