misskey/src/remote/activitypub/resolver.ts

70 lines
1.5 KiB
TypeScript
Raw Normal View History

2018-03-31 12:55:00 +02:00
const request = require('request-promise-native');
2018-04-01 14:56:11 +02:00
export default class Resolver {
private requesting: Set<string>;
constructor(iterable?: Iterable<string>) {
this.requesting = new Set(iterable);
2018-03-31 12:55:00 +02:00
}
2018-04-01 14:56:11 +02:00
private async resolveUnrequestedOne(value) {
if (typeof value !== 'string') {
return { resolver: this, object: value };
}
2018-03-31 12:55:00 +02:00
2018-04-01 14:56:11 +02:00
const resolver = new Resolver(this.requesting);
2018-03-31 12:55:00 +02:00
2018-04-01 14:56:11 +02:00
resolver.requesting.add(value);
2018-03-31 12:55:00 +02:00
2018-04-01 14:56:11 +02:00
const object = await request({
url: value,
headers: {
Accept: 'application/activity+json, application/ld+json'
},
json: true
});
2018-03-31 12:55:00 +02:00
2018-04-01 14:56:11 +02:00
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();
}
2018-03-31 12:55:00 +02:00
2018-04-01 14:56:11 +02:00
return { resolver, object };
2018-03-31 12:55:00 +02:00
}
public async resolveCollection(value) {
2018-04-01 14:56:11 +02:00
const resolved = typeof value === 'string' ?
await this.resolveUnrequestedOne(value) :
{ resolver: this, object: value };
2018-03-31 12:55:00 +02:00
switch (resolved.object.type) {
2018-04-01 14:56:11 +02:00
case 'Collection':
resolved.object = resolved.object.items;
break;
2018-03-31 12:55:00 +02:00
2018-04-01 14:56:11 +02:00
case 'OrderedCollection':
resolved.object = resolved.object.orderedItems;
break;
2018-03-31 12:55:00 +02:00
2018-04-01 14:56:11 +02:00
default:
if (!Array.isArray(value)) {
resolved.object = [resolved.object];
}
break;
2018-04-01 14:56:11 +02:00
}
return resolved;
2018-03-31 12:55:00 +02:00
}
2018-04-01 14:24:25 +02:00
public resolveOne(value) {
2018-03-31 12:55:00 +02:00
if (this.requesting.has(value)) {
2018-04-01 14:24:25 +02:00
throw new Error();
2018-03-31 12:55:00 +02:00
}
2018-04-01 14:56:11 +02:00
return this.resolveUnrequestedOne(value);
2018-03-31 12:55:00 +02:00
}
}