]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-channel.ts
03617dc8d37a680ef306328bf15f152969c0ae48
[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 { MChannelAccountDefault } from '@server/types/models'
5 import { VideoChannelCreate, VideoChannelUpdate } 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 { deleteLocalActorAvatarFile, updateLocalActorAvatarFile } from '../../lib/avatar'
17 import { JobQueue } from '../../lib/job-queue'
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 { videoChannelsNameWithHostValidator, videoChannelsOwnSearchValidator, videosSortValidator } from '../../middlewares/validators'
36 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
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
46 const videoChannelRouter = express.Router()
47
48 videoChannelRouter.get('/',
49 paginationValidator,
50 videoChannelsSortValidator,
51 setDefaultSort,
52 setDefaultPagination,
53 videoChannelsOwnSearchValidator,
54 asyncMiddleware(listVideoChannels)
55 )
56
57 videoChannelRouter.post('/',
58 authenticate,
59 asyncMiddleware(videoChannelsAddValidator),
60 asyncRetryTransactionMiddleware(addVideoChannel)
61 )
62
63 videoChannelRouter.post('/:nameWithHost/avatar/pick',
64 authenticate,
65 reqAvatarFile,
66 // Check the rights
67 asyncMiddleware(videoChannelsUpdateValidator),
68 updateAvatarValidator,
69 asyncMiddleware(updateVideoChannelAvatar)
70 )
71
72 videoChannelRouter.delete('/:nameWithHost/avatar',
73 authenticate,
74 // Check the rights
75 asyncMiddleware(videoChannelsUpdateValidator),
76 asyncMiddleware(deleteVideoChannelAvatar)
77 )
78
79 videoChannelRouter.put('/:nameWithHost',
80 authenticate,
81 asyncMiddleware(videoChannelsUpdateValidator),
82 asyncRetryTransactionMiddleware(updateVideoChannel)
83 )
84
85 videoChannelRouter.delete('/:nameWithHost',
86 authenticate,
87 asyncMiddleware(videoChannelsRemoveValidator),
88 asyncRetryTransactionMiddleware(removeVideoChannel)
89 )
90
91 videoChannelRouter.get('/:nameWithHost',
92 asyncMiddleware(videoChannelsNameWithHostValidator),
93 asyncMiddleware(getVideoChannel)
94 )
95
96 videoChannelRouter.get('/:nameWithHost/video-playlists',
97 asyncMiddleware(videoChannelsNameWithHostValidator),
98 paginationValidator,
99 videoPlaylistsSortValidator,
100 setDefaultSort,
101 setDefaultPagination,
102 commonVideoPlaylistFiltersValidator,
103 asyncMiddleware(listVideoChannelPlaylists)
104 )
105
106 videoChannelRouter.get('/:nameWithHost/videos',
107 asyncMiddleware(videoChannelsNameWithHostValidator),
108 paginationValidator,
109 videosSortValidator,
110 setDefaultVideosSort,
111 setDefaultPagination,
112 optionalAuthenticate,
113 commonVideosFiltersValidator,
114 asyncMiddleware(listVideoChannelVideos)
115 )
116
117 // ---------------------------------------------------------------------------
118
119 export {
120 videoChannelRouter
121 }
122
123 // ---------------------------------------------------------------------------
124
125 async function listVideoChannels (req: express.Request, res: express.Response) {
126 const serverActor = await getServerActor()
127 const resultList = await VideoChannelModel.listForApi({
128 actorId: serverActor.id,
129 start: req.query.start,
130 count: req.query.count,
131 sort: req.query.sort
132 })
133
134 return res.json(getFormattedObjects(resultList.data, resultList.total))
135 }
136
137 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
138 const avatarPhysicalFile = req.files['avatarfile'][0]
139 const videoChannel = res.locals.videoChannel
140 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
141
142 const avatar = await updateLocalActorAvatarFile(videoChannel, avatarPhysicalFile)
143
144 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
145
146 return res
147 .json({
148 avatar: avatar.toFormattedJSON()
149 })
150 .end()
151 }
152
153 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
154 const videoChannel = res.locals.videoChannel
155
156 await deleteLocalActorAvatarFile(videoChannel)
157
158 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
159 }
160
161 async function addVideoChannel (req: express.Request, res: express.Response) {
162 const videoChannelInfo: VideoChannelCreate = req.body
163
164 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
165 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
166
167 return createLocalVideoChannel(videoChannelInfo, account, t)
168 })
169
170 const payload = { actorId: videoChannelCreated.actorId }
171 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
172
173 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
174 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
175
176 return res.json({
177 videoChannel: {
178 id: videoChannelCreated.id
179 }
180 }).end()
181 }
182
183 async function updateVideoChannel (req: express.Request, res: express.Response) {
184 const videoChannelInstance = res.locals.videoChannel
185 const videoChannelFieldsSave = videoChannelInstance.toJSON()
186 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
187 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
188 let doBulkVideoUpdate = false
189
190 try {
191 await sequelizeTypescript.transaction(async t => {
192 const sequelizeOptions = {
193 transaction: t
194 }
195
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 }
208
209 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelAccountDefault
210 await sendUpdateActor(videoChannelInstanceUpdated, t)
211
212 auditLogger.update(
213 getAuditIdFromRes(res),
214 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
215 oldVideoChannelAuditKeys
216 )
217
218 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
219 })
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 }
230
231 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
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 }
237 }
238
239 async function removeVideoChannel (req: express.Request, res: express.Response) {
240 const videoChannelInstance = res.locals.videoChannel
241
242 await sequelizeTypescript.transaction(async t => {
243 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
244
245 await videoChannelInstance.destroy({ transaction: t })
246
247 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
248 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
249 })
250
251 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
252 }
253
254 async function getVideoChannel (req: express.Request, res: express.Response) {
255 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
256
257 if (videoChannelWithVideos.isOutdated()) {
258 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
259 }
260
261 return res.json(videoChannelWithVideos.toFormattedJSON())
262 }
263
264 async 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,
272 videoChannelId: res.locals.videoChannel.id,
273 type: req.query.playlistType
274 })
275
276 return res.json(getFormattedObjects(resultList.data, resultList.total))
277 }
278
279 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
280 const videoChannelInstance = res.locals.videoChannel
281 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
282 const countVideos = getCountVideos(req)
283
284 const apiOptions = await Hooks.wrapObject({
285 followerActorId,
286 start: req.query.start,
287 count: req.query.count,
288 sort: req.query.sort,
289 includeLocalVideos: true,
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,
295 filter: req.query.filter,
296 nsfw: buildNSFWFilter(res, req.query.nsfw),
297 withFiles: false,
298 videoChannelId: videoChannelInstance.id,
299 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
300 countVideos
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 )
308
309 return res.json(getFormattedObjects(resultList.data, resultList.total))
310 }