]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webfinger.ts
Speed up overviews route
[github/Chocobozzz/PeerTube.git] / server / helpers / webfinger.ts
1 import * as WebFinger from 'webfinger.js'
2 import { WebFingerData } from '../../shared'
3 import { ActorModel } from '../models/activitypub/actor'
4 import { isTestInstance } from './core-utils'
5 import { isActivityPubUrlValid } from './custom-validators/activitypub/misc'
6 import { CONFIG } from '../initializers'
7
8 const webfinger = new WebFinger({
9 webfist_fallback: false,
10 tls_only: isTestInstance(),
11 uri_fallback: false,
12 request_timeout: 3000
13 })
14
15 async function loadActorUrlOrGetFromWebfinger (uri: string) {
16 const [ name, host ] = uri.split('@')
17 let actor: ActorModel
18
19 if (host === CONFIG.WEBSERVER.HOST) {
20 actor = await ActorModel.loadLocalByName(name)
21 } else {
22 actor = await ActorModel.loadByNameAndHost(name, host)
23 }
24
25 if (actor) return actor.url
26
27 return getUrlFromWebfinger(uri)
28 }
29
30 async function getUrlFromWebfinger (uri: string) {
31 const webfingerData: WebFingerData = await webfingerLookup(uri)
32 return getLinkOrThrow(webfingerData)
33 }
34
35 // ---------------------------------------------------------------------------
36
37 export {
38 getUrlFromWebfinger,
39 loadActorUrlOrGetFromWebfinger
40 }
41
42 // ---------------------------------------------------------------------------
43
44 function getLinkOrThrow (webfingerData: WebFingerData) {
45 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
46
47 const selfLink = webfingerData.links.find(l => l.rel === 'self')
48 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
49 throw new Error('Cannot find self link or href is not a valid URL.')
50 }
51
52 return selfLink.href
53 }
54
55 function webfingerLookup (nameWithHost: string) {
56 return new Promise<WebFingerData>((res, rej) => {
57 webfinger.lookup(nameWithHost, (err, p) => {
58 if (err) return rej(err)
59
60 return res(p.object)
61 })
62 })
63 }