]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/auto-follow-index-instances.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / auto-follow-index-instances.ts
1 import { logger } from '../../helpers/logger'
2 import { AbstractScheduler } from './abstract-scheduler'
3 import { INSTANCES_INDEX, SCHEDULER_INTERVALS_MS, SERVER_ACTOR_NAME } from '../../initializers/constants'
4 import { CONFIG } from '../../initializers/config'
5 import { chunk } from 'lodash'
6 import { doRequest } from '@server/helpers/requests'
7 import { ActorFollowModel } from '@server/models/activitypub/actor-follow'
8 import { JobQueue } from '@server/lib/job-queue'
9 import { getServerActor } from '@server/helpers/utils'
10
11 export class AutoFollowIndexInstances extends AbstractScheduler {
12
13 private static instance: AbstractScheduler
14
15 protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.autoFollowIndexInstances
16
17 private lastCheck: Date
18
19 private constructor () {
20 super()
21 }
22
23 protected async internalExecute () {
24 return this.autoFollow()
25 }
26
27 private async autoFollow () {
28 if (CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_INDEX.ENABLED === false) return
29
30 const indexUrl = CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_INDEX.INDEX_URL
31
32 logger.info('Auto follow instances of index %s.', indexUrl)
33
34 try {
35 const serverActor = await getServerActor()
36
37 const uri = indexUrl + INSTANCES_INDEX.HOSTS_PATH
38
39 const qs = { count: 1000 }
40 if (this.lastCheck) Object.assign(qs, { since: this.lastCheck.toISOString() })
41
42 this.lastCheck = new Date()
43
44 const { body } = await doRequest({ uri, qs, json: true })
45
46 const hosts: string[] = body.data.map(o => o.host)
47 const chunks = chunk(hosts, 20)
48
49 for (const chunk of chunks) {
50 const unfollowedHosts = await ActorFollowModel.keepUnfollowedInstance(chunk)
51
52 for (const unfollowedHost of unfollowedHosts) {
53 const payload = {
54 host: unfollowedHost,
55 name: SERVER_ACTOR_NAME,
56 followerActorId: serverActor.id,
57 isAutoFollow: true
58 }
59
60 JobQueue.Instance.createJob({ type: 'activitypub-follow', payload })
61 }
62 }
63
64 } catch (err) {
65 logger.error('Cannot auto follow hosts of index %s.', indexUrl, { err })
66 }
67
68 }
69
70 static get Instance () {
71 return this.instance || (this.instance = new this())
72 }
73 }