]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/channel.ts
315469115ebbc2b08e71f99fb8a393822f2e8e35
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / channel.ts
1 import * as express from 'express'
2 import { VideoChannelCreate, VideoChannelUpdate } from '../../../../shared'
3 import { getFormattedObjects, logger, resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers'
4 import { sequelizeTypescript } from '../../../initializers'
5 import { createVideoChannel } from '../../../lib'
6 import { sendUpdateVideoChannel } from '../../../lib/activitypub/send/send-update'
7 import {
8 asyncMiddleware,
9 authenticate,
10 listVideoAccountChannelsValidator,
11 paginationValidator,
12 setPagination,
13 setVideoChannelsSort,
14 videoChannelsAddValidator,
15 videoChannelsGetValidator,
16 videoChannelsRemoveValidator,
17 videoChannelsSortValidator,
18 videoChannelsUpdateValidator
19 } from '../../../middlewares'
20 import { AccountModel } from '../../../models/account/account'
21 import { VideoChannelModel } from '../../../models/video/video-channel'
22
23 const videoChannelRouter = express.Router()
24
25 videoChannelRouter.get('/channels',
26 paginationValidator,
27 videoChannelsSortValidator,
28 setVideoChannelsSort,
29 setPagination,
30 asyncMiddleware(listVideoChannels)
31 )
32
33 videoChannelRouter.get('/accounts/:accountId/channels',
34 asyncMiddleware(listVideoAccountChannelsValidator),
35 asyncMiddleware(listVideoAccountChannels)
36 )
37
38 videoChannelRouter.post('/channels',
39 authenticate,
40 videoChannelsAddValidator,
41 asyncMiddleware(addVideoChannelRetryWrapper)
42 )
43
44 videoChannelRouter.put('/channels/:id',
45 authenticate,
46 asyncMiddleware(videoChannelsUpdateValidator),
47 updateVideoChannelRetryWrapper
48 )
49
50 videoChannelRouter.delete('/channels/:id',
51 authenticate,
52 asyncMiddleware(videoChannelsRemoveValidator),
53 asyncMiddleware(removeVideoChannelRetryWrapper)
54 )
55
56 videoChannelRouter.get('/channels/:id',
57 asyncMiddleware(videoChannelsGetValidator),
58 asyncMiddleware(getVideoChannel)
59 )
60
61 // ---------------------------------------------------------------------------
62
63 export {
64 videoChannelRouter
65 }
66
67 // ---------------------------------------------------------------------------
68
69 async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
70 const resultList = await VideoChannelModel.listForApi(req.query.start, req.query.count, req.query.sort)
71
72 return res.json(getFormattedObjects(resultList.data, resultList.total))
73 }
74
75 async function listVideoAccountChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
76 const resultList = await VideoChannelModel.listByAccount(res.locals.account.id)
77
78 return res.json(getFormattedObjects(resultList.data, resultList.total))
79 }
80
81 // Wrapper to video channel add that retry the async function if there is a database error
82 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
83 async function addVideoChannelRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
84 const options = {
85 arguments: [ req, res ],
86 errorMessage: 'Cannot insert the video video channel with many retries.'
87 }
88
89 await retryTransactionWrapper(addVideoChannel, options)
90
91 // TODO : include Location of the new video channel -> 201
92 return res.type('json').status(204).end()
93 }
94
95 function addVideoChannel (req: express.Request, res: express.Response) {
96 const videoChannelInfo: VideoChannelCreate = req.body
97 const account: AccountModel = res.locals.oauth.token.User.Account
98
99 return sequelizeTypescript.transaction(async t => {
100 const videoChannelCreated = await createVideoChannel(videoChannelInfo, account, t)
101
102 logger.info('Video channel with uuid %s created.', videoChannelCreated.uuid)
103 })
104 }
105
106 async function updateVideoChannelRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
107 const options = {
108 arguments: [ req, res ],
109 errorMessage: 'Cannot update the video with many retries.'
110 }
111
112 await retryTransactionWrapper(updateVideoChannel, options)
113
114 return res.type('json').status(204).end()
115 }
116
117 async function updateVideoChannel (req: express.Request, res: express.Response) {
118 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
119 const videoChannelFieldsSave = videoChannelInstance.toJSON()
120 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
121
122 try {
123 await sequelizeTypescript.transaction(async t => {
124 const sequelizeOptions = {
125 transaction: t
126 }
127
128 if (videoChannelInfoToUpdate.name !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.name)
129 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
130
131 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
132
133 await sendUpdateVideoChannel(videoChannelInstanceUpdated, t)
134 })
135
136 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.uuid)
137 } catch (err) {
138 logger.debug('Cannot update the video channel.', err)
139
140 // Force fields we want to update
141 // If the transaction is retried, sequelize will think the object has not changed
142 // So it will skip the SQL request, even if the last one was ROLLBACKed!
143 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
144
145 throw err
146 }
147 }
148
149 async function removeVideoChannelRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
150 const options = {
151 arguments: [ req, res ],
152 errorMessage: 'Cannot remove the video channel with many retries.'
153 }
154
155 await retryTransactionWrapper(removeVideoChannel, options)
156
157 return res.type('json').status(204).end()
158 }
159
160 async function removeVideoChannel (req: express.Request, res: express.Response) {
161 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
162
163 await sequelizeTypescript.transaction(async t => {
164 await videoChannelInstance.destroy({ transaction: t })
165 })
166
167 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.uuid)
168 }
169
170 async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
171 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
172
173 return res.json(videoChannelWithVideos.toFormattedJSON())
174 }