1 import Bluebird from 'bluebird'
2 import { URL } from 'url'
3 import { retryTransactionWrapper } from '@server/helpers/database-utils'
4 import { ActivityPubOrderedCollection } from '../../../shared/models/activitypub'
5 import { logger } from '../../helpers/logger'
6 import { doJSONRequest } from '../../helpers/requests'
7 import { ACTIVITY_PUB, WEBSERVER } from '../../initializers/constants'
9 type HandlerFunction<T> = (items: T[]) => (Promise<any> | Bluebird<any>)
10 type CleanerFunction = (startedDate: Date) => Promise<any>
12 async function crawlCollectionPage <T> (argUrl: string, handler: HandlerFunction<T>, cleaner?: CleanerFunction) {
15 logger.info('Crawling ActivityPub data on %s.', url)
17 const options = { activityPub: true }
19 const startDate = new Date()
21 const response = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options)
22 const firstBody = response.body
24 const limit = ACTIVITY_PUB.FETCH_PAGE_LIMIT
26 let nextLink = firstBody.first
27 while (nextLink && i < limit) {
30 if (typeof nextLink === 'string') {
31 // Don't crawl ourselves
32 const remoteHost = new URL(nextLink).host
33 if (remoteHost === WEBSERVER.HOST) continue
37 const res = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options)
40 // nextLink is already the object we want
47 if (Array.isArray(body.orderedItems)) {
48 const items = body.orderedItems
49 logger.info('Processing %i ActivityPub items for %s.', items.length, url)
55 if (cleaner) await retryTransactionWrapper(cleaner, startDate)