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