Split types and typings
[oweals/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
11 export class UpdateVideosScheduler extends AbstractScheduler {
12
13   private static instance: AbstractScheduler
14
15   protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.updateVideos
16
17   private constructor () {
18     super()
19   }
20
21   protected async internalExecute () {
22     return retryTransactionWrapper(this.updateVideos.bind(this))
23   }
24
25   private async updateVideos () {
26     if (!await ScheduleVideoUpdateModel.areVideosToUpdate()) return undefined
27
28     const publishedVideos = await sequelizeTypescript.transaction(async t => {
29       const schedules = await ScheduleVideoUpdateModel.listVideosToUpdate(t)
30       const publishedVideos: MVideoFullLight[] = []
31
32       for (const schedule of schedules) {
33         const video = schedule.Video
34         logger.info('Executing scheduled video update on %s.', video.uuid)
35
36         if (schedule.privacy) {
37           const wasConfidentialVideo = video.isConfidential()
38           const isNewVideo = video.isNewVideo(schedule.privacy)
39
40           video.setPrivacy(schedule.privacy)
41           await video.save({ transaction: t })
42           await federateVideoIfNeeded(video, isNewVideo, t)
43
44           if (wasConfidentialVideo) {
45             const videoToPublish: MVideoFullLight = Object.assign(video, { ScheduleVideoUpdate: schedule, UserVideoHistories: [] })
46             publishedVideos.push(videoToPublish)
47           }
48         }
49
50         await schedule.destroy({ transaction: t })
51       }
52
53       return publishedVideos
54     })
55
56     for (const v of publishedVideos) {
57       Notifier.Instance.notifyOnNewVideoIfNeeded(v)
58       Notifier.Instance.notifyOnVideoPublishedAfterScheduledUpdate(v)
59     }
60   }
61
62   static get Instance () {
63     return this.instance || (this.instance = new this())
64   }
65 }