]>
Commit | Line | Data |
---|---|---|
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' | |
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 searchParams = { count: 1000 } | |
38 | if (this.lastCheck) Object.assign(searchParams, { since: this.lastCheck.toISOString() }) | |
39 | ||
40 | this.lastCheck = new Date() | |
41 | ||
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 }) | |
45 | return | |
46 | } | |
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 | ||
62 | JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) | |
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 | } |