update-videos-scheduler.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { logger } from '../../helpers/logger'
  2. import { AbstractScheduler } from './abstract-scheduler'
  3. import { ScheduleVideoUpdateModel } from '../../models/video/schedule-video-update'
  4. import { retryTransactionWrapper } from '../../helpers/database-utils'
  5. import { federateVideoIfNeeded } from '../activitypub'
  6. import { SCHEDULER_INTERVALS_MS, sequelizeTypescript } from '../../initializers'
  7. import { VideoPrivacy } from '../../../shared/models/videos'
  8. export class UpdateVideosScheduler extends AbstractScheduler {
  9. private static instance: AbstractScheduler
  10. protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.updateVideos
  11. private isRunning = false
  12. private constructor () {
  13. super()
  14. }
  15. async execute () {
  16. if (this.isRunning === true) return
  17. this.isRunning = true
  18. try {
  19. await retryTransactionWrapper(this.updateVideos.bind(this))
  20. } catch (err) {
  21. logger.error('Cannot execute update videos scheduler.', { err })
  22. } finally {
  23. this.isRunning = false
  24. }
  25. }
  26. private async updateVideos () {
  27. if (!await ScheduleVideoUpdateModel.areVideosToUpdate()) return undefined
  28. return sequelizeTypescript.transaction(async t => {
  29. const schedules = await ScheduleVideoUpdateModel.listVideosToUpdate(t)
  30. for (const schedule of schedules) {
  31. const video = schedule.Video
  32. logger.info('Executing scheduled video update on %s.', video.uuid)
  33. if (schedule.privacy) {
  34. const oldPrivacy = video.privacy
  35. const isNewVideo = oldPrivacy === VideoPrivacy.PRIVATE
  36. video.privacy = schedule.privacy
  37. if (isNewVideo === true) video.publishedAt = new Date()
  38. await video.save({ transaction: t })
  39. await federateVideoIfNeeded(video, isNewVideo, t)
  40. }
  41. await schedule.destroy({ transaction: t })
  42. }
  43. })
  44. }
  45. static get Instance () {
  46. return this.instance || (this.instance = new this())
  47. }
  48. }