2017-05-27 05:08:24 +00:00
|
|
|
var request = require('request');
|
|
|
|
var log = require("../util/LogService");
|
2017-08-27 05:49:27 +00:00
|
|
|
var dns = require("dns-then");
|
|
|
|
var Promise = require("bluebird");
|
2017-05-27 05:08:24 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Represents a lightweight matrix client with minimal functionality
|
|
|
|
*/
|
|
|
|
class MatrixLiteClient {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a new matrix client
|
|
|
|
* @param {OpenID} openId the open ID to use
|
|
|
|
*/
|
|
|
|
constructor(openId) {
|
|
|
|
this._openId = openId;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the Matrix User ID that owns this open ID
|
|
|
|
* @return {Promise<string>} resolves to the mxid
|
|
|
|
*/
|
|
|
|
getSelfMxid() {
|
2017-09-12 02:58:57 +00:00
|
|
|
return this._do("GET", "/_matrix/federation/v1/openid/userinfo", /*qs=*/null, /*body=*/null, /*allowSelfSigned=*/true).then((response, body) => {
|
2017-05-27 05:08:24 +00:00
|
|
|
var json = JSON.parse(response.body);
|
|
|
|
return json['sub'];
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-09-12 02:58:57 +00:00
|
|
|
_do(method, endpoint, qs = null, body = null, allowSelfSigned = false) {
|
2017-09-09 03:12:26 +00:00
|
|
|
var serverName = this._openId.matrix_server_name;
|
2017-08-27 05:49:27 +00:00
|
|
|
// HACK: We have to wrap the dns promise in a Bluebird promise just to make sure it works
|
2017-09-09 03:12:26 +00:00
|
|
|
var dnsPromise = dns.resolveSrv("_matrix._tcp." + serverName);
|
2017-08-27 05:49:27 +00:00
|
|
|
return Promise.resolve(dnsPromise).then(records => {
|
|
|
|
if (records && records.length > 0)
|
2017-09-09 03:12:26 +00:00
|
|
|
serverName = records[0].name + ":" + records[0].port;
|
2017-08-27 05:49:27 +00:00
|
|
|
}, err => {
|
2017-09-09 03:12:26 +00:00
|
|
|
log.warn("MatrixLiteClient", "Failed to lookup SRV for " + serverName + " - assuming none available.");
|
2017-08-27 05:49:27 +00:00
|
|
|
log.warn("MatrixLiteClient", err);
|
|
|
|
}).then(() => {
|
2017-09-09 03:12:26 +00:00
|
|
|
var url = "https://" + serverName + endpoint;
|
2017-08-27 05:49:27 +00:00
|
|
|
|
|
|
|
log.verbose("MatrixLiteClient", "Performing request: " + url);
|
|
|
|
|
|
|
|
if (!qs) qs = {};
|
|
|
|
qs['access_token'] = this._openId.access_token;
|
|
|
|
|
|
|
|
var params = {
|
|
|
|
url: url,
|
|
|
|
method: method,
|
|
|
|
form: body,
|
2017-09-12 02:58:57 +00:00
|
|
|
qs: qs,
|
|
|
|
rejectUnauthorized: !allowSelfSigned
|
2017-08-27 05:49:27 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
request(params, (err, response, body) => {
|
|
|
|
if (err) {
|
|
|
|
log.error("MatrixLiteClient", err);
|
|
|
|
reject(err);
|
|
|
|
} else resolve(response, body);
|
|
|
|
});
|
2017-05-27 05:08:24 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = MatrixLiteClient;
|