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