]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/update-videos-scheduler.ts
Refactor schedule update
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / update-videos-scheduler.ts
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/videos'
6 import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants'
7 import { Notifier } from '../notifier'
8 import { sequelizeTypescript } from '../../initializers/database'
9 import { MVideoFullLight } from '@server/types/models'
10 import { VideoModel } from '@server/models/video/video'
11
12 export class UpdateVideosScheduler extends AbstractScheduler {
13
14 private static instance: AbstractScheduler
15
16 protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.updateVideos
17
18 private constructor () {
19 super()
20 }
21
22 protected async internalExecute () {
23 return retryTransactionWrapper(this.updateVideos.bind(this))
24 }
25
26 private async updateVideos () {
27 if (!await ScheduleVideoUpdateModel.areVideosToUpdate()) return undefined
28
29 const schedules = await ScheduleVideoUpdateModel.listVideosToUpdate()
30 const publishedVideos: MVideoFullLight[] = []
31
32 for (const schedule of schedules) {
33 await sequelizeTypescript.transaction(async t => {
34 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(schedule.videoId, t)
35
36 logger.info('Executing scheduled video update on %s.', video.uuid)
37
38 if (schedule.privacy) {
39 const wasConfidentialVideo = video.isConfidential()
40 const isNewVideo = video.isNewVideo(schedule.privacy)
41
42 video.setPrivacy(schedule.privacy)
43 await video.save({ transaction: t })
44 await federateVideoIfNeeded(video, isNewVideo, t)
45
46 if (wasConfidentialVideo) {
47 publishedVideos.push(video)
48 }
49 }
50
51 await schedule.destroy({ transaction: t })
52 })
53 }
54
55 for (const v of publishedVideos) {
56 Notifier.Instance.notifyOnNewVideoIfNeeded(v)
57 Notifier.Instance.notifyOnVideoPublishedAfterScheduledUpdate(v)
58 }
59 }
60
61 static get Instance () {
62 return this.instance || (this.instance = new this())
63 }
64 }