50 lines
1.6 KiB
JavaScript
50 lines
1.6 KiB
JavaScript
"use strict";
|
|
|
|
let usimp = {};
|
|
|
|
usimp.lookup = function (domain_name) {
|
|
return fetch(`https://${domain_name}/.well-known/usimp.json`, {
|
|
redirect: "manual",
|
|
});
|
|
}
|
|
|
|
usimp.chooseDomainServer = function (domainServers, invalidDomainServers = []) {
|
|
if (domainServers.length === 0) throw Error("No domain servers specified");
|
|
|
|
domainServers.filter(srv => invalidDomainServers.map(srv => srv.id).includes(srv.id));
|
|
if (domainServers.length === 0) throw Error("No domain servers reachable");
|
|
if (domainServers.length === 1) return domainServers[0];
|
|
|
|
let priority = domainServers.reduce((min, srv) => Math.min(min, srv.priority), Infinity);
|
|
domainServers = domainServers.filter(srv => srv.priority === priority);
|
|
if (domainServers.length === 1) return domainServers[0];
|
|
|
|
let totalWeight = domainServers.reduce((total, srv) => total + srv.weight, 0);
|
|
let w = Math.floor(Math.random() * totalWeight);
|
|
|
|
let accumulator = 0;
|
|
for (let srv of domainServers) {
|
|
accumulator += srv.weight;
|
|
if (w < accumulator) return srv;
|
|
}
|
|
|
|
console.warn("Domain server selection not worked correctly");
|
|
return domainServers[0];
|
|
}
|
|
|
|
usimp.login = function (domainServer, domain, account, password) {
|
|
return fetch(`http://${domainServer.host}:${domainServer.protocols.http}/_usimp/authenticate`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'To-Domain': domain,
|
|
'From-Domain': domain
|
|
},
|
|
body: JSON.stringify({
|
|
type: "password",
|
|
name: account,
|
|
password: password,
|
|
}),
|
|
});
|
|
}
|