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