vector-im-hydrogen-web/src/matrix/hs-api.js

125 lines
3.8 KiB
JavaScript
Raw Normal View History

import {
HomeServerError,
2019-03-08 12:26:59 +01:00
RequestAbortError,
NetworkError
} from "./error.js";
2019-02-10 21:25:29 +01:00
2019-02-04 23:26:24 +01:00
class RequestWrapper {
2018-12-21 14:35:24 +01:00
constructor(promise, controller) {
if (!controller) {
const abortPromise = new Promise((_, reject) => {
this._controller = {
abort() {
const err = new Error("fetch request aborted");
err.name = "AbortError";
reject(err);
}
};
});
this._promise = Promise.race([promise, abortPromise]);
} else {
this._promise = promise;
this._controller = controller;
}
2018-12-21 14:35:24 +01:00
}
abort() {
this._controller.abort();
}
2019-02-04 23:26:24 +01:00
response() {
2018-12-21 14:35:24 +01:00
return this._promise;
}
}
2019-02-07 01:25:12 +01:00
export default class HomeServerApi {
2018-12-21 14:35:24 +01:00
constructor(homeserver, accessToken) {
2019-03-08 20:03:47 +01:00
// store these both in a closure somehow so it's harder to get at in case of XSS?
// one could change the homeserver as well so the token gets sent there, so both must be protected from read/write
this._homeserver = homeserver;
2018-12-21 14:35:24 +01:00
this._accessToken = accessToken;
}
_url(csPath) {
2019-02-04 23:26:24 +01:00
return `${this._homeserver}/_matrix/client/r0${csPath}`;
2018-12-21 14:35:24 +01:00
}
2019-02-04 23:26:24 +01:00
_request(method, csPath, queryParams = {}, body) {
2018-12-21 14:35:24 +01:00
const queryString = Object.entries(queryParams)
2019-05-12 20:26:20 +02:00
.filter(([, value]) => value !== undefined)
2019-02-04 23:26:24 +01:00
.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`)
2018-12-21 14:35:24 +01:00
.join("&");
const url = this._url(`${csPath}?${queryString}`);
2019-02-04 23:26:24 +01:00
let bodyString;
const headers = new Headers();
if (this._accessToken) {
headers.append("Authorization", `Bearer ${this._accessToken}`);
}
2018-12-21 14:35:24 +01:00
headers.append("Accept", "application/json");
2019-02-04 23:26:24 +01:00
if (body) {
2018-12-21 14:35:24 +01:00
headers.append("Content-Type", "application/json");
2019-02-04 23:26:24 +01:00
bodyString = JSON.stringify(body);
2018-12-21 14:35:24 +01:00
}
const controller = typeof AbortController === "function" ? new AbortController() : null;
2018-12-21 14:35:24 +01:00
// TODO: set authenticated headers with second arguments, cache them
2019-02-04 23:26:24 +01:00
let promise = fetch(url, {
method,
headers,
body: bodyString,
signal: controller && controller.signal
2019-02-04 23:26:24 +01:00
});
2019-02-10 21:25:29 +01:00
promise = promise.then(async (response) => {
2018-12-21 14:35:24 +01:00
if (response.ok) {
2019-02-10 21:25:29 +01:00
return await response.json();
2018-12-21 14:35:24 +01:00
} else {
switch (response.status) {
default:
2019-02-10 21:25:29 +01:00
throw new HomeServerError(method, url, await response.json())
2018-12-21 14:35:24 +01:00
}
}
}, err => {
2019-03-08 12:26:59 +01:00
if (err.name === "AbortError") {
throw new RequestAbortError();
} else if (err instanceof TypeError) {
// Network errors are reported as TypeErrors, see
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
// this can either mean user is offline, server is offline, or a CORS error (server misconfiguration).
//
// One could check navigator.onLine to rule out the first
// but the 2 later ones are indistinguishable from javascript.
throw new NetworkError(err.message);
}
throw err;
2018-12-21 14:35:24 +01:00
});
2019-02-04 23:26:24 +01:00
return new RequestWrapper(promise, controller);
}
_post(csPath, queryParams, body) {
return this._request("POST", csPath, queryParams, body);
}
_get(csPath, queryParams, body) {
return this._request("GET", csPath, queryParams, body);
2018-12-21 14:35:24 +01:00
}
2019-02-10 21:25:29 +01:00
sync(since, filter, timeout) {
return this._get("/sync", {since, timeout, filter});
2019-02-04 23:26:24 +01:00
}
2019-03-09 00:41:06 +01:00
// params is from, dir and optionally to, limit, filter.
messages(roomId, params) {
return this._get(`/rooms/${roomId}/messages`, params);
}
2019-02-04 23:26:24 +01:00
passwordLogin(username, password) {
return this._post("/login", undefined, {
"type": "m.login.password",
"identifier": {
"type": "m.id.user",
"user": username
},
"password": password
});
2018-12-21 14:35:24 +01:00
}
2019-03-08 12:26:59 +01:00
}