]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/schedulers/auto-follow-index-instances.ts
Merge branch 'release/3.2.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / auto-follow-index-instances.ts
CommitLineData
6f1b4fa4 1import { chunk } from 'lodash'
db4b15f2 2import { doJSONRequest } from '@server/helpers/requests'
6f1b4fa4 3import { JobQueue } from '@server/lib/job-queue'
7d9ba5c0 4import { ActorFollowModel } from '@server/models/actor/actor-follow'
8dc8a34e 5import { getServerActor } from '@server/models/application/application'
2ca154da
C
6import { logger } from '../../helpers/logger'
7import { CONFIG } from '../../initializers/config'
8import { SCHEDULER_INTERVALS_MS, SERVER_ACTOR_NAME } from '../../initializers/constants'
9import { AbstractScheduler } from './abstract-scheduler'
6f1b4fa4
C
10
11export 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
db4b15f2
C
37 const searchParams = { count: 1000 }
38 if (this.lastCheck) Object.assign(searchParams, { since: this.lastCheck.toISOString() })
92ce6233 39
6f1b4fa4
C
40 this.lastCheck = new Date()
41
db4b15f2 42 const { body } = await doJSONRequest<any>(indexUrl, { searchParams })
95cd31f1 43 if (!body.data || Array.isArray(body.data) === false) {
2ca154da 44 logger.error('Cannot auto follow instances of index %s. Please check the auto follow URL.', indexUrl, { body })
95cd31f1
C
45 return
46 }
6f1b4fa4
C
47
48 const hosts: string[] = body.data.map(o => o.host)
49 const chunks = chunk(hosts, 20)
50
51 for (const chunk of chunks) {
52 const unfollowedHosts = await ActorFollowModel.keepUnfollowedInstance(chunk)
53
54 for (const unfollowedHost of unfollowedHosts) {
55 const payload = {
56 host: unfollowedHost,
57 name: SERVER_ACTOR_NAME,
58 followerActorId: serverActor.id,
59 isAutoFollow: true
60 }
61
a1587156 62 JobQueue.Instance.createJob({ type: 'activitypub-follow', payload })
6f1b4fa4
C
63 }
64 }
65
66 } catch (err) {
67 logger.error('Cannot auto follow hosts of index %s.', indexUrl, { err })
68 }
69
70 }
71
72 static get Instance () {
73 return this.instance || (this.instance = new this())
74 }
75}