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