summaryrefslogtreecommitdiff
path: root/src/remote/activitypub/resolver.ts
blob: ebfe25fe7ea3ff2fd5b258a19074e33d1985661f (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import RemoteUserObject from '../../models/remote-user-object';
import { IObject } from './type';
const request = require('request-promise-native');

type IResult = {
  resolver: Resolver;
  object: IObject;
};

export default class Resolver {
	private requesting: Set<string>;

	constructor(iterable?: Iterable<string>) {
		this.requesting = new Set(iterable);
	}

	private async resolveUnrequestedOne(value) {
		if (typeof value !== 'string') {
			return { resolver: this, object: value };
		}

		const resolver = new Resolver(this.requesting);

		resolver.requesting.add(value);

		const object = await request({
			url: value,
			headers: {
				Accept: 'application/activity+json, application/ld+json'
			},
			json: true
		});

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

		return { resolver, object };
	}

	private async resolveCollection(value) {
		if (Array.isArray(value)) {
			return value;
		}

		const resolved = typeof value === 'string' ?
			await this.resolveUnrequestedOne(value) :
			value;

		switch (resolved.type) {
		case 'Collection':
			return resolved.items;

		case 'OrderedCollection':
			return resolved.orderedItems;

		default:
			return [resolved];
		}
	}

	public async resolve(value): Promise<Array<Promise<IResult>>> {
		const collection = await this.resolveCollection(value);

		return collection
			.filter(element => !this.requesting.has(element))
			.map(this.resolveUnrequestedOne.bind(this));
	}

	public resolveOne(value) {
		if (this.requesting.has(value)) {
			throw new Error();
		}

		return this.resolveUnrequestedOne(value);
	}

	public async resolveRemoteUserObjects(value) {
		const collection = await this.resolveCollection(value);

		return collection.filter(element => !this.requesting.has(element)).map(element => {
			if (typeof element === 'string') {
				const object = RemoteUserObject.findOne({ uri: element });

				if (object !== null) {
					return object;
				}
			}

			return this.resolveUnrequestedOne(element);
		});
	}
}