ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

455 lines
16 KiB

  1. import express from 'express'
  2. import {
  3. ActorImageType,
  4. HttpStatusCode,
  5. VideoChannelCreate,
  6. VideoChannelUpdate,
  7. VideosImportInChannelCreate
  8. } from '@peertube/peertube-models'
  9. import { pickCommonVideoQuery } from '@server/helpers/query.js'
  10. import { Hooks } from '@server/lib/plugins/hooks.js'
  11. import { ActorFollowModel } from '@server/models/actor/actor-follow.js'
  12. import { getServerActor } from '@server/models/application/application.js'
  13. import { MChannelBannerAccountDefault } from '@server/types/models/index.js'
  14. import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger.js'
  15. import { resetSequelizeInstance } from '../../helpers/database-utils.js'
  16. import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils.js'
  17. import { logger } from '../../helpers/logger.js'
  18. import { getFormattedObjects } from '../../helpers/utils.js'
  19. import { MIMETYPES } from '../../initializers/constants.js'
  20. import { sequelizeTypescript } from '../../initializers/database.js'
  21. import { sendUpdateActor } from '../../lib/activitypub/send/index.js'
  22. import { JobQueue } from '../../lib/job-queue/index.js'
  23. import { deleteLocalActorImageFile, updateLocalActorImageFiles } from '../../lib/local-actor.js'
  24. import { createLocalVideoChannelWithoutKeys, federateAllVideosOfChannel } from '../../lib/video-channel.js'
  25. import {
  26. apiRateLimiter,
  27. asyncMiddleware,
  28. asyncRetryTransactionMiddleware,
  29. authenticate,
  30. commonVideosFiltersValidator,
  31. ensureCanManageChannelOrAccount,
  32. optionalAuthenticate,
  33. paginationValidator,
  34. setDefaultPagination,
  35. setDefaultSort,
  36. setDefaultVideosSort,
  37. videoChannelsAddValidator,
  38. videoChannelsRemoveValidator,
  39. videoChannelsSortValidator,
  40. videoChannelsUpdateValidator,
  41. videoPlaylistsSortValidator
  42. } from '../../middlewares/index.js'
  43. import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image.js'
  44. import {
  45. ensureChannelOwnerCanUpload,
  46. ensureIsLocalChannel,
  47. videoChannelImportVideosValidator,
  48. videoChannelsFollowersSortValidator,
  49. videoChannelsListValidator,
  50. videoChannelsNameWithHostValidator,
  51. videosSortValidator
  52. } from '../../middlewares/validators/index.js'
  53. import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists.js'
  54. import { AccountModel } from '../../models/account/account.js'
  55. import { guessAdditionalAttributesFromQuery } from '../../models/video/formatter/index.js'
  56. import { VideoChannelModel } from '../../models/video/video-channel.js'
  57. import { VideoPlaylistModel } from '../../models/video/video-playlist.js'
  58. import { VideoModel } from '../../models/video/video.js'
  59. const auditLogger = auditLoggerFactory('channels')
  60. const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
  61. const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
  62. const videoChannelRouter = express.Router()
  63. videoChannelRouter.use(apiRateLimiter)
  64. videoChannelRouter.get('/',
  65. paginationValidator,
  66. videoChannelsSortValidator,
  67. setDefaultSort,
  68. setDefaultPagination,
  69. videoChannelsListValidator,
  70. asyncMiddleware(listVideoChannels)
  71. )
  72. videoChannelRouter.post('/',
  73. authenticate,
  74. asyncMiddleware(videoChannelsAddValidator),
  75. asyncRetryTransactionMiddleware(createVideoChannel)
  76. )
  77. videoChannelRouter.post('/:nameWithHost/avatar/pick',
  78. authenticate,
  79. reqAvatarFile,
  80. asyncMiddleware(videoChannelsNameWithHostValidator),
  81. ensureIsLocalChannel,
  82. ensureCanManageChannelOrAccount,
  83. updateAvatarValidator,
  84. asyncMiddleware(updateVideoChannelAvatar)
  85. )
  86. videoChannelRouter.post('/:nameWithHost/banner/pick',
  87. authenticate,
  88. reqBannerFile,
  89. asyncMiddleware(videoChannelsNameWithHostValidator),
  90. ensureIsLocalChannel,
  91. ensureCanManageChannelOrAccount,
  92. updateBannerValidator,
  93. asyncMiddleware(updateVideoChannelBanner)
  94. )
  95. videoChannelRouter.delete('/:nameWithHost/avatar',
  96. authenticate,
  97. asyncMiddleware(videoChannelsNameWithHostValidator),
  98. ensureIsLocalChannel,
  99. ensureCanManageChannelOrAccount,
  100. asyncMiddleware(deleteVideoChannelAvatar)
  101. )
  102. videoChannelRouter.delete('/:nameWithHost/banner',
  103. authenticate,
  104. asyncMiddleware(videoChannelsNameWithHostValidator),
  105. ensureIsLocalChannel,
  106. ensureCanManageChannelOrAccount,
  107. asyncMiddleware(deleteVideoChannelBanner)
  108. )
  109. videoChannelRouter.put('/:nameWithHost',
  110. authenticate,
  111. asyncMiddleware(videoChannelsNameWithHostValidator),
  112. ensureIsLocalChannel,
  113. ensureCanManageChannelOrAccount,
  114. videoChannelsUpdateValidator,
  115. asyncRetryTransactionMiddleware(updateVideoChannel)
  116. )
  117. videoChannelRouter.delete('/:nameWithHost',
  118. authenticate,
  119. asyncMiddleware(videoChannelsNameWithHostValidator),
  120. ensureIsLocalChannel,
  121. ensureCanManageChannelOrAccount,
  122. asyncMiddleware(videoChannelsRemoveValidator),
  123. asyncRetryTransactionMiddleware(removeVideoChannel)
  124. )
  125. videoChannelRouter.get('/:nameWithHost',
  126. asyncMiddleware(videoChannelsNameWithHostValidator),
  127. asyncMiddleware(getVideoChannel)
  128. )
  129. videoChannelRouter.get('/:nameWithHost/video-playlists',
  130. optionalAuthenticate,
  131. asyncMiddleware(videoChannelsNameWithHostValidator),
  132. paginationValidator,
  133. videoPlaylistsSortValidator,
  134. setDefaultSort,
  135. setDefaultPagination,
  136. commonVideoPlaylistFiltersValidator,
  137. asyncMiddleware(listVideoChannelPlaylists)
  138. )
  139. videoChannelRouter.get('/:nameWithHost/videos',
  140. asyncMiddleware(videoChannelsNameWithHostValidator),
  141. paginationValidator,
  142. videosSortValidator,
  143. setDefaultVideosSort,
  144. setDefaultPagination,
  145. optionalAuthenticate,
  146. commonVideosFiltersValidator,
  147. asyncMiddleware(listVideoChannelVideos)
  148. )
  149. videoChannelRouter.get('/:nameWithHost/followers',
  150. authenticate,
  151. asyncMiddleware(videoChannelsNameWithHostValidator),
  152. ensureCanManageChannelOrAccount,
  153. paginationValidator,
  154. videoChannelsFollowersSortValidator,
  155. setDefaultSort,
  156. setDefaultPagination,
  157. asyncMiddleware(listVideoChannelFollowers)
  158. )
  159. videoChannelRouter.post('/:nameWithHost/import-videos',
  160. authenticate,
  161. asyncMiddleware(videoChannelsNameWithHostValidator),
  162. asyncMiddleware(videoChannelImportVideosValidator),
  163. ensureIsLocalChannel,
  164. ensureCanManageChannelOrAccount,
  165. asyncMiddleware(ensureChannelOwnerCanUpload),
  166. asyncMiddleware(importVideosInChannel)
  167. )
  168. // ---------------------------------------------------------------------------
  169. export {
  170. videoChannelRouter
  171. }
  172. // ---------------------------------------------------------------------------
  173. async function listVideoChannels (req: express.Request, res: express.Response) {
  174. const serverActor = await getServerActor()
  175. const apiOptions = await Hooks.wrapObject({
  176. actorId: serverActor.id,
  177. start: req.query.start,
  178. count: req.query.count,
  179. sort: req.query.sort
  180. }, 'filter:api.video-channels.list.params')
  181. const resultList = await Hooks.wrapPromiseFun(
  182. VideoChannelModel.listForApi.bind(VideoChannelModel),
  183. apiOptions,
  184. 'filter:api.video-channels.list.result'
  185. )
  186. return res.json(getFormattedObjects(resultList.data, resultList.total))
  187. }
  188. async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
  189. const bannerPhysicalFile = req.files['bannerfile'][0]
  190. const videoChannel = res.locals.videoChannel
  191. const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
  192. const banners = await updateLocalActorImageFiles({
  193. accountOrChannel: videoChannel,
  194. imagePhysicalFile: bannerPhysicalFile,
  195. type: ActorImageType.BANNER,
  196. sendActorUpdate: true
  197. })
  198. auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
  199. return res.json({
  200. banners: banners.map(b => b.toFormattedJSON())
  201. })
  202. }
  203. async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
  204. const avatarPhysicalFile = req.files['avatarfile'][0]
  205. const videoChannel = res.locals.videoChannel
  206. const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
  207. const avatars = await updateLocalActorImageFiles({
  208. accountOrChannel: videoChannel,
  209. imagePhysicalFile: avatarPhysicalFile,
  210. type: ActorImageType.AVATAR,
  211. sendActorUpdate: true
  212. })
  213. auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
  214. return res.json({
  215. avatars: avatars.map(a => a.toFormattedJSON())
  216. })
  217. }
  218. async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
  219. const videoChannel = res.locals.videoChannel
  220. await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
  221. return res.status(HttpStatusCode.NO_CONTENT_204).end()
  222. }
  223. async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
  224. const videoChannel = res.locals.videoChannel
  225. await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
  226. return res.status(HttpStatusCode.NO_CONTENT_204).end()
  227. }
  228. async function createVideoChannel (req: express.Request, res: express.Response) {
  229. const videoChannelInfo: VideoChannelCreate = req.body
  230. const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
  231. const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
  232. return createLocalVideoChannelWithoutKeys(videoChannelInfo, account, t)
  233. })
  234. await JobQueue.Instance.createJob({
  235. type: 'actor-keys',
  236. payload: { actorId: videoChannelCreated.actorId }
  237. })
  238. auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
  239. logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
  240. Hooks.runAction('action:api.video-channel.created', { videoChannel: videoChannelCreated, req, res })
  241. return res.json({
  242. videoChannel: {
  243. id: videoChannelCreated.id
  244. }
  245. })
  246. }
  247. async function updateVideoChannel (req: express.Request, res: express.Response) {
  248. const videoChannelInstance = res.locals.videoChannel
  249. const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
  250. const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
  251. let doBulkVideoUpdate = false
  252. try {
  253. await sequelizeTypescript.transaction(async t => {
  254. if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
  255. if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
  256. if (videoChannelInfoToUpdate.support !== undefined) {
  257. const oldSupportField = videoChannelInstance.support
  258. videoChannelInstance.support = videoChannelInfoToUpdate.support
  259. if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
  260. doBulkVideoUpdate = true
  261. await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
  262. }
  263. }
  264. const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
  265. await sendUpdateActor(videoChannelInstanceUpdated, t)
  266. auditLogger.update(
  267. getAuditIdFromRes(res),
  268. new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
  269. oldVideoChannelAuditKeys
  270. )
  271. Hooks.runAction('action:api.video-channel.updated', { videoChannel: videoChannelInstanceUpdated, req, res })
  272. logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
  273. })
  274. } catch (err) {
  275. logger.debug('Cannot update the video channel.', { err })
  276. // If the transaction is retried, sequelize will think the object has not changed
  277. // So we need to restore the previous fields
  278. await resetSequelizeInstance(videoChannelInstance)
  279. throw err
  280. }
  281. res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
  282. // Don't process in a transaction, and after the response because it could be long
  283. if (doBulkVideoUpdate) {
  284. await federateAllVideosOfChannel(videoChannelInstance)
  285. }
  286. }
  287. async function removeVideoChannel (req: express.Request, res: express.Response) {
  288. const videoChannelInstance = res.locals.videoChannel
  289. await sequelizeTypescript.transaction(async t => {
  290. await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
  291. await videoChannelInstance.destroy({ transaction: t })
  292. Hooks.runAction('action:api.video-channel.deleted', { videoChannel: videoChannelInstance, req, res })
  293. auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
  294. logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
  295. })
  296. return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
  297. }
  298. async function getVideoChannel (req: express.Request, res: express.Response) {
  299. const id = res.locals.videoChannel.id
  300. const videoChannel = await Hooks.wrapObject(res.locals.videoChannel, 'filter:api.video-channel.get.result', { id })
  301. if (videoChannel.isOutdated()) {
  302. JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
  303. }
  304. return res.json(videoChannel.toFormattedJSON())
  305. }
  306. async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
  307. const serverActor = await getServerActor()
  308. const resultList = await VideoPlaylistModel.listForApi({
  309. followerActorId: isUserAbleToSearchRemoteURI(res)
  310. ? null
  311. : serverActor.id,
  312. start: req.query.start,
  313. count: req.query.count,
  314. sort: req.query.sort,
  315. videoChannelId: res.locals.videoChannel.id,
  316. type: req.query.playlistType
  317. })
  318. return res.json(getFormattedObjects(resultList.data, resultList.total))
  319. }
  320. async function listVideoChannelVideos (req: express.Request, res: express.Response) {
  321. const serverActor = await getServerActor()
  322. const videoChannelInstance = res.locals.videoChannel
  323. const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
  324. ? null
  325. : {
  326. actorId: serverActor.id,
  327. orLocalVideos: true
  328. }
  329. const countVideos = getCountVideos(req)
  330. const query = pickCommonVideoQuery(req.query)
  331. const apiOptions = await Hooks.wrapObject({
  332. ...query,
  333. displayOnlyForFollower,
  334. nsfw: buildNSFWFilter(res, query.nsfw),
  335. videoChannelId: videoChannelInstance.id,
  336. user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
  337. countVideos
  338. }, 'filter:api.video-channels.videos.list.params')
  339. const resultList = await Hooks.wrapPromiseFun(
  340. VideoModel.listForApi.bind(VideoModel),
  341. apiOptions,
  342. 'filter:api.video-channels.videos.list.result'
  343. )
  344. return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
  345. }
  346. async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
  347. const channel = res.locals.videoChannel
  348. const resultList = await ActorFollowModel.listFollowersForApi({
  349. actorIds: [ channel.actorId ],
  350. start: req.query.start,
  351. count: req.query.count,
  352. sort: req.query.sort,
  353. search: req.query.search,
  354. state: 'accepted'
  355. })
  356. return res.json(getFormattedObjects(resultList.data, resultList.total))
  357. }
  358. async function importVideosInChannel (req: express.Request, res: express.Response) {
  359. const { externalChannelUrl } = req.body as VideosImportInChannelCreate
  360. await JobQueue.Instance.createJob({
  361. type: 'video-channel-import',
  362. payload: {
  363. externalChannelUrl,
  364. videoChannelId: res.locals.videoChannel.id,
  365. partOfChannelSyncId: res.locals.videoChannelSync?.id
  366. }
  367. })
  368. logger.info('Video import job for channel "%s" with url "%s" created.', res.locals.videoChannel.name, externalChannelUrl)
  369. return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
  370. }