feathermost/main.js

412 lines
11 KiB
JavaScript
Raw Normal View History

2020-03-25 17:05:25 +01:00
"use strict";
2020-03-24 22:47:39 +01:00
2020-03-25 17:05:25 +01:00
function byId(id, nullOk=false) {
const el = document.getElementById(id);
if (!el && !nullOk) {
console.error(`No element #${id}`);
2020-03-24 22:47:39 +01:00
}
2020-03-25 17:05:25 +01:00
return el;
2020-03-24 22:47:39 +01:00
}
2020-03-26 16:01:09 +01:00
const LOCALSTORAGE_KEY_SERVER = "mattermostServer";
const RE_SERVER_ITEM = new RegExp(`^${LOCALSTORAGE_KEY_SERVER}_(.*)\$`, "");
const Storage = {
2020-03-26 16:01:09 +01:00
getServers() {
let servers = [];
for (var i = 0; i < window.localStorage.length; i++) {
const key = window.localStorage.key(i);
const matches = key.match(RE_SERVER_ITEM);
if (matches) {
const endpoint = matches[1];
console.debug(`Found logged in endpoint ${endpoint}`);
let stored = JSON.parse(window.localStorage.getItem(Storage._key_for(endpoint)));
servers.push({...stored, endpoint});
2020-03-26 16:01:09 +01:00
}
}
return servers;
},
2020-03-26 16:01:09 +01:00
_key_for(endpoint) {
return `${LOCALSTORAGE_KEY_SERVER}_${endpoint}`;
},
2020-03-26 16:01:09 +01:00
clear(endpoint) {
window.localStorage.removeItem(Storage._key_for(endpoint));
},
2020-03-26 16:01:09 +01:00
store(endpoint, login_id, token) {
window.localStorage.setItem(Storage._key_for(endpoint), JSON.stringify({login_id, token}));
},
2020-03-26 16:01:09 +01:00
get(endpoint) {
return JSON.parse(window.localStorage.getItem(Storage._key_for(endpoint)) || "null");
2020-03-26 16:01:09 +01:00
}
}
2020-03-26 16:01:09 +01:00
2020-03-25 17:05:25 +01:00
class MattermostApi {
constructor(endpoint) {
2020-03-26 16:01:09 +01:00
this._endpoint = endpoint;
2020-03-24 22:47:39 +01:00
}
2020-03-26 16:01:09 +01:00
get id() {
return this._endpoint;
}
2020-03-29 00:40:47 +01:00
async get(path, token, queryParams) {
2020-03-26 16:01:09 +01:00
const headers = token ? {"Authorization": `Bearer ${token}`} : {};
2020-03-29 00:40:47 +01:00
const response = await ajax.getJson(`${this._endpoint}${path}`, {headers, queryParams});
if (!response.ok) {
throw response;
}
return response;
2020-03-25 17:05:25 +01:00
}
2020-03-24 22:47:39 +01:00
2020-03-29 00:40:47 +01:00
async post(path, token, data) {
2020-03-26 16:01:09 +01:00
const headers = token ? {"Authorization": `Bearer ${token}`} : {};
const response = await ajax.postJson(`${this._endpoint}${path}`, data, {headers});
if (!response.ok) {
throw response;
}
return response;
2020-03-24 22:47:39 +01:00
}
}
2020-03-26 16:01:09 +01:00
class MattermostClient {
constructor (api, storage) {
this.api = api;
this.storage = storage;
}
async logIn(login_id, password) {
2020-03-29 00:40:47 +01:00
const response = await this.api.post("/users/login", undefined, {login_id, password});
2020-03-26 16:01:09 +01:00
const token = response.getResponseHeader("Token");
if (!token) {
throw Error("No Token header in response to log in request");
}
this.storage.store(this.api.id, login_id, token);
return response.responseJson;
}
async logOut() {
2020-03-26 17:46:22 +01:00
const stored = this.storage.get(this.api.id);
if (!stored || !stored.token) {
throw Error("No token stored");
}
2020-03-29 00:40:47 +01:00
const response = await this.api.post("/users/logout", stored.token);
// Verify that the token is now invalidated
let tokenWorks;
try {
const meResponse = await this.usersMe();
tokenWorks = true;
} catch (e) {
if (e instanceof ajax.NotOkError && e.xhr.status == 401) {
tokenWorks = false;
} else {
throw e;
}
}
if (tokenWorks) {
throw new Error("Failed to log out: token still works after trying to log out");
}
this.storage.clear(this.api.id);
2020-03-26 16:01:09 +01:00
return response.responseJson;
}
async usersMe() {
const stored = this.storage.get(this.api.id);
if (!stored || !stored.token) {
throw Error("No token stored");
}
const response = await this.api.get("/users/me", stored.token);
return response.responseJson;
}
async myTeams() {
const stored = this.storage.get(this.api.id);
const response = await this.api.get("/users/me/teams", stored.token);
return response.responseJson;
}
async myChannels(team_id) {
const stored = this.storage.get(this.api.id);
const response = await this.api.get(`/users/me/teams/${team_id}/channels`, stored.token);
return response.responseJson;
}
2020-03-29 00:40:47 +01:00
async channelPosts(channel_id, beforePost=null, afterPost=null, since=null) {
const stored = this.storage.get(this.api.id);
const response = await this.api.get(`/channels/${channel_id}/posts`, stored.token, {
before: beforePost, after: afterPost, since
});
return response.responseJson;
}
2020-03-26 16:01:09 +01:00
}
/**
* Return an endpoint URL that has a protocol, domain and path
*/
function normalizedEndpoint(endpoint) {
let matches = endpoint.match(/^(https?:\/\/)?([^\/]+)(\/.*)?$/i);
if (!matches) throw Error("Invalid endpoint URL");
let protocol = matches[1] || "https://";
let domain = matches[2];
let path = matches[3] || "/api/v4";
return `${protocol}${domain}${path}`;
}
function humanReadableEndpoint(endpoint) {
let matches = endpoint.match(/^(https?:\/\/.+)\/api\/v4$/i);
if (!matches) throw Error("Invalid endpoint URL");
return matches[1];
}
2020-03-26 16:01:09 +01:00
function createClient(endpoint) {
const api = new MattermostApi(normalizedEndpoint(endpoint));
return new MattermostClient(api, Storage);
2020-03-26 16:01:09 +01:00
}
function buttonDisable(element, text) {
if (!element.dataset.originalText) {
element.dataset.originalText = element.innerText;
}
element.innerText = text;
2020-03-26 16:01:09 +01:00
element.disabled = true;
}
function buttonEnable(element) {
element.innerText = element.dataset.originalText;
2020-03-26 16:01:09 +01:00
element.disabled = false;
}
function populateServerSelectionList() {
const servers = Storage.getServers();
let nodes = [];
for (let server of servers) {
const li = document.createElement("li");
const endpoint = humanReadableEndpoint(server.endpoint);
li.innerText = `${server.login_id}@${endpoint} `;
2020-03-24 22:47:39 +01:00
const logoutButton = document.createElement("button");
logoutButton.className = "logout";
logoutButton.innerText = "Log out";
logoutButton.addEventListener("click", e => logOut(endpoint, e.currentTarget));
li.appendChild(logoutButton);
nodes.push(li);
}
byId("server_selection_list").innerHTML = "";
byId("server_selection_list").append(...nodes);
}
populateServerSelectionList();
function populateChannelList() {
async function addChannelItems(endpoint) {
const client = createClient(endpoint);
const teams = await client.myTeams();
console.log(teams);
for (let team of teams) {
let nodes = [];
const channels = await client.myChannels(team.id);
console.log(channels);
for (let channel of channels) {
const li = document.createElement("li");
const a = document.createElement("a");
a.href = "javascript:void(0)";
2020-03-29 18:54:49 +02:00
const titleAndElements = channelNameElements(team, channel);
if (!titleAndElements) continue;
a.title = titleAndElements[0];
a.append(...titleAndElements[1]);
a.addEventListener("click", () => switchToChannel(client, team, channel));
li.appendChild(a);
2020-03-29 18:54:49 +02:00
li.dataset["id"] = channel.id;
nodes.push(li);
}
byId("channel_list").append(...nodes);
}
}
2020-03-26 16:01:09 +01:00
const servers = Storage.getServers();
2020-03-26 16:01:09 +01:00
byId("channel_list").innerHTML = "";
for (let server of servers) {
addChannelItems(server.endpoint);
}
}
populateChannelList();
2020-03-29 00:40:47 +01:00
function populateChannelContents(contents) {
byId("channel_contents").innerHTML = "";
let nodes = [];
for (let id of contents.order) {
const post = contents.posts[id];
const isThreadReply = !!post.parent_id;
const messageDiv = document.createElement("div");
messageDiv.className = "message";
messageDiv.innerText = post.message;
const createAt = new Date(post.create_at);
const createAtDiv = document.createElement("time");
createAtDiv.className = "create_at";
createAtDiv.innerText = createAt.toLocaleString("nl-BE");
createAtDiv.dateTime = createAt.toISOString();
const authorDiv = document.createElement("div");
authorDiv.className = "author";
authorDiv.innerText = `Auteur: ${post.user_id}`;
const postDiv = document.createElement("div");
postDiv.className = "post";
2020-03-29 18:54:49 +02:00
postDiv.dataset["id"] = id;
2020-03-29 00:40:47 +01:00
postDiv.appendChild(authorDiv);
postDiv.appendChild(createAtDiv);
postDiv.appendChild(messageDiv);
nodes.unshift(postDiv);
}
byId("channel_contents").append(...nodes);
}
function logIn() {
const client = createClient(byId("login_server").value);
buttonDisable(byId("login_button"), "Logging in...");
client.logIn(byId("login_login_id").value, byId("login_password").value)
2020-03-26 16:01:09 +01:00
.then(json => {
buttonEnable(byId("login_button"));
2020-03-26 16:01:09 +01:00
byId("login_message").innerText = "";
byId("channel_list").innerText = `Logged in as ${json.username}`;
window.location = "#";
populateServerSelectionList();
populateChannelList();
2020-03-26 16:01:09 +01:00
})
.catch(error => {
console.error(error);
buttonEnable(byId("login_button"));
2020-03-26 16:01:09 +01:00
byId("login_message").innerText = `${error}`;
});
}
function logOut(endpoint, button) {
const client = createClient(endpoint);
2020-03-26 16:01:09 +01:00
buttonDisable(button, "Logging out...");
2020-03-26 16:01:09 +01:00
client.logOut()
.then(response => {
console.info("Succesfully logged out");
populateServerSelectionList();
populateChannelList();
2020-03-26 16:01:09 +01:00
})
.catch(error => {
console.error(error);
const span = document.createElement("span");
span.innerText = `Failed to log out: ${error.message}`;
button.parentElement.appendChild(span);
buttonEnable(button);
2020-03-26 16:01:09 +01:00
});
2020-03-25 17:05:25 +01:00
}
2020-03-29 18:54:49 +02:00
function channelNameElements(team, channel) {
let icon = "";
let teamName = team.name;
let channelName = channel.name;
let title = "";
switch (channel.type) {
case "O": // Public channel
title = `${channel.name} in team ${team.name} (public)`;
break;
case "P": // Private channel
icon = "🔒";
title = `${channel.name} in team ${team.name} (private)`;
break;
case "D": // Direct message
return undefined;
teamName = "";
channelName = `👤 ...`;
title = `Direct message`;
break;
case "G": // Group chat
teamName = "";
channelName = `👥 ${channel.display_name}`;
title = `Group chat with ${channel.display_name}`;
break;
default: // Unsupported
icon = channel.type;
title = `${channel.name} in team ${team.name} (type ${channel.type})`;
break;
}
let elements = [];
if (teamName) {
const teamElement = document.createElement("span");
teamElement.className = "team-name";
teamElement.innerText = teamName;
elements.push(teamElement);
const separatorElement = document.createElement("span");
separatorElement.className = "separator";
separatorElement.innerText = "/";
elements.push(separatorElement);
}
const channelElement = document.createElement("span");
channelElement.className = "channel-name";
channelElement.innerText = channelName;
elements.push(channelElement);
return [title, elements];
}
function switchToChannel(client, team, channel) {
for (let el of byId("channel_list").childNodes) {
if (el.dataset["id"] == channel.id) {
el.className = "active";
} else {
el.className = "";
}
}
const [title, elements] = channelNameElements(team, channel);
byId("channel_header").innerHTML = "";
byId("channel_header").append(...elements);
2020-03-29 00:40:47 +01:00
byId("channel_contents").innerText = "Loading…";
2020-03-29 18:54:49 +02:00
client.channelPosts(channel.id)
2020-03-29 00:40:47 +01:00
.then(response => {
2020-03-29 18:54:49 +02:00
console.info(`Got channel contents of ${channel.id} (${channel.name})`);
2020-03-29 00:40:47 +01:00
populateChannelContents(response);
2020-03-29 18:54:49 +02:00
})
.catch(error => {
console.error(error);
byId("channel_contents").innerText = `Failed to get channel contents:\n${error.message}`;
2020-03-29 00:40:47 +01:00
});
}
2020-03-29 18:54:49 +02:00
function updateComposeHeight() {
byId("compose").style.height = "";
byId("compose").style.height = (byId("compose").scrollHeight + 1) + "px";
}
byId("compose").addEventListener("input", updateComposeHeight);
updateComposeHeight();
byId("login_button").addEventListener("click", logIn);