]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/api/video-channel.ts
Add test regarding tmp directory
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
... / ...
CommitLineData
1import * as express from 'express'
2import { getFormattedObjects, getServerActor } from '../../helpers/utils'
3import {
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} from '../../middlewares'
17import { VideoChannelModel } from '../../models/video/video-channel'
18import { videoChannelsNameWithHostValidator, videosSortValidator } from '../../middlewares/validators'
19import { sendUpdateActor } from '../../lib/activitypub/send'
20import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
21import { createVideoChannel } from '../../lib/video-channel'
22import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
23import { setAsyncActorKeys } from '../../lib/activitypub'
24import { AccountModel } from '../../models/account/account'
25import { CONFIG, IMAGE_MIMETYPE_EXT, sequelizeTypescript } from '../../initializers'
26import { logger } from '../../helpers/logger'
27import { VideoModel } from '../../models/video/video'
28import { updateAvatarValidator } from '../../middlewares/validators/avatar'
29import { updateActorAvatarFile } from '../../lib/avatar'
30import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
31import { resetSequelizeInstance } from '../../helpers/database-utils'
32import { UserModel } from '../../models/account/user'
33
34const auditLogger = auditLoggerFactory('channels')
35const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
36
37const videoChannelRouter = express.Router()
38
39videoChannelRouter.get('/',
40 paginationValidator,
41 videoChannelsSortValidator,
42 setDefaultSort,
43 setDefaultPagination,
44 asyncMiddleware(listVideoChannels)
45)
46
47videoChannelRouter.post('/',
48 authenticate,
49 asyncMiddleware(videoChannelsAddValidator),
50 asyncRetryTransactionMiddleware(addVideoChannel)
51)
52
53videoChannelRouter.post('/:nameWithHost/avatar/pick',
54 authenticate,
55 reqAvatarFile,
56 // Check the rights
57 asyncMiddleware(videoChannelsUpdateValidator),
58 updateAvatarValidator,
59 asyncMiddleware(updateVideoChannelAvatar)
60)
61
62videoChannelRouter.put('/:nameWithHost',
63 authenticate,
64 asyncMiddleware(videoChannelsUpdateValidator),
65 asyncRetryTransactionMiddleware(updateVideoChannel)
66)
67
68videoChannelRouter.delete('/:nameWithHost',
69 authenticate,
70 asyncMiddleware(videoChannelsRemoveValidator),
71 asyncRetryTransactionMiddleware(removeVideoChannel)
72)
73
74videoChannelRouter.get('/:nameWithHost',
75 asyncMiddleware(videoChannelsNameWithHostValidator),
76 asyncMiddleware(getVideoChannel)
77)
78
79videoChannelRouter.get('/:nameWithHost/videos',
80 asyncMiddleware(videoChannelsNameWithHostValidator),
81 paginationValidator,
82 videosSortValidator,
83 setDefaultSort,
84 setDefaultPagination,
85 optionalAuthenticate,
86 commonVideosFiltersValidator,
87 asyncMiddleware(listVideoChannelVideos)
88)
89
90// ---------------------------------------------------------------------------
91
92export {
93 videoChannelRouter
94}
95
96// ---------------------------------------------------------------------------
97
98async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
99 const serverActor = await getServerActor()
100 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
101
102 return res.json(getFormattedObjects(resultList.data, resultList.total))
103}
104
105async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
106 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
107 const videoChannel = res.locals.videoChannel as VideoChannelModel
108 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
109
110 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
111
112 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
113
114 return res
115 .json({
116 avatar: avatar.toFormattedJSON()
117 })
118 .end()
119}
120
121async function addVideoChannel (req: express.Request, res: express.Response) {
122 const videoChannelInfo: VideoChannelCreate = req.body
123
124 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
125 const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t)
126
127 return createVideoChannel(videoChannelInfo, account, t)
128 })
129
130 setAsyncActorKeys(videoChannelCreated.Actor)
131 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
132
133 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
134 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
135
136 return res.json({
137 videoChannel: {
138 id: videoChannelCreated.id,
139 uuid: videoChannelCreated.Actor.uuid
140 }
141 }).end()
142}
143
144async function updateVideoChannel (req: express.Request, res: express.Response) {
145 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
146 const videoChannelFieldsSave = videoChannelInstance.toJSON()
147 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
148 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
149
150 try {
151 await sequelizeTypescript.transaction(async t => {
152 const sequelizeOptions = {
153 transaction: t
154 }
155
156 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
157 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
158 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
159
160 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
161 await sendUpdateActor(videoChannelInstanceUpdated, t)
162
163 auditLogger.update(
164 getAuditIdFromRes(res),
165 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
166 oldVideoChannelAuditKeys
167 )
168 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
169 })
170 } catch (err) {
171 logger.debug('Cannot update the video channel.', { err })
172
173 // Force fields we want to update
174 // If the transaction is retried, sequelize will think the object has not changed
175 // So it will skip the SQL request, even if the last one was ROLLBACKed!
176 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
177
178 throw err
179 }
180
181 return res.type('json').status(204).end()
182}
183
184async function removeVideoChannel (req: express.Request, res: express.Response) {
185 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
186
187 await sequelizeTypescript.transaction(async t => {
188 await videoChannelInstance.destroy({ transaction: t })
189
190 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
191 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
192 })
193
194 return res.type('json').status(204).end()
195}
196
197async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
198 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
199
200 return res.json(videoChannelWithVideos.toFormattedJSON())
201}
202
203async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
204 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
205 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
206
207 const resultList = await VideoModel.listForApi({
208 followerActorId,
209 start: req.query.start,
210 count: req.query.count,
211 sort: req.query.sort,
212 includeLocalVideos: true,
213 categoryOneOf: req.query.categoryOneOf,
214 licenceOneOf: req.query.licenceOneOf,
215 languageOneOf: req.query.languageOneOf,
216 tagsOneOf: req.query.tagsOneOf,
217 tagsAllOf: req.query.tagsAllOf,
218 filter: req.query.filter,
219 nsfw: buildNSFWFilter(res, req.query.nsfw),
220 withFiles: false,
221 videoChannelId: videoChannelInstance.id,
222 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
223 })
224
225 return res.json(getFormattedObjects(resultList.data, resultList.total))
226}