video-channel.ts 10 KB

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