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