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