summaryrefslogtreecommitdiff
path: root/src/remote/activitypub/resolver.ts
blob: 113b2c4e4f6b6ed0fd2db1e88c2c564c885ab5cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import * as request from 'request-promise-native';
import { IObject } from './type';
import config from '../../config';
import { apLogger } from './logger';

export const logger = apLogger.createSubLogger('resolver');

export default class Resolver {
	private history: Set<string>;
	private timeout = 10 * 1000;

	constructor() {
		this.history = new Set();
	}

	public async resolveCollection(value: any) {
		const collection = typeof value === 'string'
			? await this.resolve(value)
			: value;

		switch (collection.type) {
			case 'Collection': {
				collection.objects = collection.items;
				break;
			}

			case 'OrderedCollection': {
				collection.objects = collection.orderedItems;
				break;
			}

			default: {
				logger.error(`unknown collection type: ${collection.type}`);
				throw new Error(`unknown collection type: ${collection.type}`);
			}
		}

		return collection;
	}

	public async resolve(value: any): Promise<IObject> {
		if (value == null) {
			logger.error('resolvee is null (or undefined)');
			throw new Error('resolvee is null (or undefined)');
		}

		if (typeof value !== 'string') {
			return value;
		}

		if (this.history.has(value)) {
			logger.error(`cannot resolve already resolved one`);
			throw new Error('cannot resolve already resolved one');
		}

		this.history.add(value);

		const object = await request({
			url: value,
			proxy: config.proxy,
			timeout: this.timeout,
			headers: {
				'User-Agent': config.userAgent,
				Accept: 'application/activity+json, application/ld+json'
			},
			json: true
		}).catch(e => {
			logger.error(`request error: ${e.message}`);
			throw new Error(`request error: ${e.message}`);
		});

		if (object === null || (
			Array.isArray(object['@context']) ?
				!object['@context'].includes('https://www.w3.org/ns/activitystreams') :
				object['@context'] !== 'https://www.w3.org/ns/activitystreams'
		)) {
			logger.error(`invalid response: ${value}`);
			throw new Error('invalid response');
		}

		return object;
	}
}