video-channel.ts 10 KB

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