1 import { chunk } from 'lodash'
2 import { doJSONRequest } from '@server/helpers/requests'
3 import { JobQueue } from '@server/lib/job-queue'
4 import { ActorFollowModel } from '@server/models/activitypub/actor-follow'
5 import { getServerActor } from '@server/models/application/application'
6 import { logger } from '../../helpers/logger'
7 import { CONFIG } from '../../initializers/config'
8 import { SCHEDULER_INTERVALS_MS, SERVER_ACTOR_NAME } from '../../initializers/constants'
9 import { AbstractScheduler } from './abstract-scheduler'
11 export class AutoFollowIndexInstances extends AbstractScheduler {
13 private static instance: AbstractScheduler
15 protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.autoFollowIndexInstances
17 private lastCheck: Date
19 private constructor () {
23 protected async internalExecute () {
24 return this.autoFollow()
27 private async autoFollow () {
28 if (CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_INDEX.ENABLED === false) return
30 const indexUrl = CONFIG.FOLLOWINGS.INSTANCE.AUTO_FOLLOW_INDEX.INDEX_URL
32 logger.info('Auto follow instances of index %s.', indexUrl)
35 const serverActor = await getServerActor()
37 const searchParams = { count: 1000 }
38 if (this.lastCheck) Object.assign(searchParams, { since: this.lastCheck.toISOString() })
40 this.lastCheck = new Date()
42 const { body } = await doJSONRequest<any>(indexUrl, { searchParams })
43 if (!body.data || Array.isArray(body.data) === false) {
44 logger.error('Cannot auto follow instances of index %s. Please check the auto follow URL.', indexUrl, { body })
48 const hosts: string[] = body.data.map(o => o.host)
49 const chunks = chunk(hosts, 20)
51 for (const chunk of chunks) {
52 const unfollowedHosts = await ActorFollowModel.keepUnfollowedInstance(chunk)
54 for (const unfollowedHost of unfollowedHosts) {
57 name: SERVER_ACTOR_NAME,
58 followerActorId: serverActor.id,
62 JobQueue.Instance.createJob({ type: 'activitypub-follow', payload })
67 logger.error('Cannot auto follow hosts of index %s.', indexUrl, { err })
72 static get Instance () {
73 return this.instance || (this.instance = new this())