]>
Commit | Line | Data |
---|---|---|
edb4ffc7 | 1 | import * as Bluebird from 'bluebird' |
a1587156 | 2 | import { URL } from 'url' |
db4b15f2 C |
3 | import { ActivityPubOrderedCollection } from '../../../shared/models/activitypub' |
4 | import { logger } from '../../helpers/logger' | |
5 | import { doJSONRequest } from '../../helpers/requests' | |
7500d6c9 | 6 | import { ACTIVITY_PUB, WEBSERVER } from '../../initializers/constants' |
8fffe21a | 7 | |
2ba92871 C |
8 | type HandlerFunction<T> = (items: T[]) => (Promise<any> | Bluebird<any>) |
9 | type CleanerFunction = (startedDate: Date) => (Promise<any> | Bluebird<any>) | |
10 | ||
db4b15f2 C |
11 | async function crawlCollectionPage <T> (argUrl: string, handler: HandlerFunction<T>, cleaner?: CleanerFunction) { |
12 | let url = argUrl | |
13 | ||
14 | logger.info('Crawling ActivityPub data on %s.', url) | |
8fffe21a | 15 | |
7500d6c9 | 16 | const options = { activityPub: true } |
8fffe21a | 17 | |
2ba92871 C |
18 | const startDate = new Date() |
19 | ||
db4b15f2 | 20 | const response = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options) |
8fffe21a C |
21 | const firstBody = response.body |
22 | ||
a1587156 | 23 | const limit = ACTIVITY_PUB.FETCH_PAGE_LIMIT |
8fffe21a C |
24 | let i = 0 |
25 | let nextLink = firstBody.first | |
26 | while (nextLink && i < limit) { | |
ee79b60e | 27 | let body: any |
c0e71e84 | 28 | |
ee79b60e C |
29 | if (typeof nextLink === 'string') { |
30 | // Don't crawl ourselves | |
a1587156 | 31 | const remoteHost = new URL(nextLink).host |
ee79b60e C |
32 | if (remoteHost === WEBSERVER.HOST) continue |
33 | ||
db4b15f2 | 34 | url = nextLink |
ee79b60e | 35 | |
db4b15f2 | 36 | const res = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options) |
ee79b60e C |
37 | body = res.body |
38 | } else { | |
39 | // nextLink is already the object we want | |
40 | body = nextLink | |
41 | } | |
8fffe21a | 42 | |
8fffe21a C |
43 | nextLink = body.next |
44 | i++ | |
45 | ||
46 | if (Array.isArray(body.orderedItems)) { | |
47 | const items = body.orderedItems | |
db4b15f2 | 48 | logger.info('Processing %i ActivityPub items for %s.', items.length, url) |
8fffe21a C |
49 | |
50 | await handler(items) | |
51 | } | |
52 | } | |
2ba92871 C |
53 | |
54 | if (cleaner) await cleaner(startDate) | |
8fffe21a C |
55 | } |
56 | ||
57 | export { | |
58 | crawlCollectionPage | |
59 | } |