]>
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' | |
6 | import { ACTIVITY_PUB, REQUEST_TIMEOUT, 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 C |
15 | |
16 | const options = { | |
8fffe21a | 17 | activityPub: true, |
dcd75f78 | 18 | timeout: REQUEST_TIMEOUT |
8fffe21a C |
19 | } |
20 | ||
2ba92871 C |
21 | const startDate = new Date() |
22 | ||
db4b15f2 | 23 | const response = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options) |
8fffe21a C |
24 | const firstBody = response.body |
25 | ||
a1587156 | 26 | const limit = ACTIVITY_PUB.FETCH_PAGE_LIMIT |
8fffe21a C |
27 | let i = 0 |
28 | let nextLink = firstBody.first | |
29 | while (nextLink && i < limit) { | |
ee79b60e | 30 | let body: any |
c0e71e84 | 31 | |
ee79b60e C |
32 | if (typeof nextLink === 'string') { |
33 | // Don't crawl ourselves | |
a1587156 | 34 | const remoteHost = new URL(nextLink).host |
ee79b60e C |
35 | if (remoteHost === WEBSERVER.HOST) continue |
36 | ||
db4b15f2 | 37 | url = nextLink |
ee79b60e | 38 | |
db4b15f2 | 39 | const res = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options) |
ee79b60e C |
40 | body = res.body |
41 | } else { | |
42 | // nextLink is already the object we want | |
43 | body = nextLink | |
44 | } | |
8fffe21a | 45 | |
8fffe21a C |
46 | nextLink = body.next |
47 | i++ | |
48 | ||
49 | if (Array.isArray(body.orderedItems)) { | |
50 | const items = body.orderedItems | |
db4b15f2 | 51 | logger.info('Processing %i ActivityPub items for %s.', items.length, url) |
8fffe21a C |
52 | |
53 | await handler(items) | |
54 | } | |
55 | } | |
2ba92871 C |
56 | |
57 | if (cleaner) await cleaner(startDate) | |
8fffe21a C |
58 | } |
59 | ||
60 | export { | |
61 | crawlCollectionPage | |
62 | } |