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