forked from xmppjs/xmpp.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (67 loc) · 1.8 KB
/
index.js
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
"use strict";
const resolve = require("./resolve");
const { promise } = require("@xmpp/events");
async function fetchURIs(domain) {
const result = await resolve(domain, {
srv: [
{
service: "xmpps-client",
protocol: "tcp",
},
{
service: "xmpp-client",
protocol: "tcp",
},
],
});
return [
// Remove duplicates
...new Set(result.map((record) => record.uri)),
];
}
function filterSupportedURIs(entity, uris) {
return uris.filter((uri) => entity._findTransport(uri));
}
async function fallbackConnect(entity, uris) {
if (uris.length === 0) {
throw new Error("Couldn't connect");
}
const uri = uris.shift();
const Transport = entity._findTransport(uri);
if (!Transport) {
return fallbackConnect(entity, uris);
}
entity._status("connecting", uri);
const params = Transport.prototype.socketParameters(uri);
const socket = new Transport.prototype.Socket();
try {
socket.connect(params);
await promise(socket, "connect");
} catch {
return fallbackConnect(entity, uris);
}
entity._attachSocket(socket);
socket.emit("connect");
entity.Transport = Transport;
entity.Socket = Transport.prototype.Socket;
entity.Parser = Transport.prototype.Parser;
}
module.exports = function resolve({ entity }) {
const _connect = entity.connect;
entity.connect = async function connect(service) {
if (!service || /:\/\//.test(service)) {
return _connect.call(this, service);
}
const uris = filterSupportedURIs(entity, await fetchURIs(service));
if (uris.length === 0) {
throw new Error("No compatible transport found.");
}
try {
await fallbackConnect(entity, uris);
} catch (err) {
entity._reset();
entity._status("disconnect");
throw err;
}
};
};