keanu-weblite/src/services/matrix.service.js

525 lines
23 KiB
JavaScript
Raw Normal View History

2020-11-09 10:26:56 +01:00
global.Olm = require("olm");
import sdk from "matrix-js-sdk";
import util from "../plugins/utils";
import User from "../models/user";
import config from "../assets/config";
2020-11-09 10:26:56 +01:00
const LocalStorageCryptoStore = require("matrix-js-sdk/lib/crypto/store/localStorage-crypto-store")
.LocalStorageCryptoStore;
sdk.setCryptoStoreFactory(
() => new LocalStorageCryptoStore(window.localStorage)
);
export default {
install(Vue, options) {
if (!options || !options.store) {
throw new Error('Please initialise plugin with a Vuex store.')
}
2020-11-09 10:26:56 +01:00
const store = options.store;
2020-11-09 10:26:56 +01:00
const matrixService = new Vue({
store,
2020-11-09 10:26:56 +01:00
data() {
return {
matrixClient: null,
2020-11-19 22:48:08 +01:00
matrixClientReady: false,
rooms: [],
userDisplayName: null,
userAvatar: null,
2020-12-15 17:06:26 +01:00
currentRoom: null,
notificationCount: 0
}
},
mounted() {
console.log("Matrix service mounted");
},
2020-11-09 10:26:56 +01:00
computed: {
ready() {
2020-11-25 10:02:24 +01:00
return this.matrixClient != null && this.matrixClientReady;
},
2020-11-09 10:26:56 +01:00
currentUser() {
return this.$store.state.auth.user;
},
2020-11-25 14:42:50 +01:00
currentUserId() {
const user = this.currentUser || {}
return user.user_id;
},
currentUserDisplayName() {
if (this.ready) {
const user = this.matrixClient.getUser(this.currentUserId) || {}
return user.displayName;
}
return null;
},
currentRoomId() {
return this.$store.state.currentRoomId;
},
2020-12-15 17:06:26 +01:00
},
2020-11-25 10:02:24 +01:00
2020-12-15 17:06:26 +01:00
watch: {
currentRoomId: {
immediate: true,
handler(roomId) {
this.currentRoom = this.getRoom(roomId);
}
},
},
methods: {
login(user) {
const tempMatrixClient = sdk.createClient(User.homeServerUrl(user.home_server));
2020-11-25 10:02:24 +01:00
var promiseLogin;
if (user.is_guest && !user.access_token) {
2021-01-20 09:42:13 +01:00
// Generate random username and password. We don't user REAL matrix
// guest accounts because 1. They are not allowed to post media, 2. They
// can not use avatars and 3. They can not seamlessly be upgraded to real accounts.
//
// Instead, we use an ILAG approach, Improved Landing as Guest.
const user = util.randomUser();
const pass = util.randomPass();
2020-11-25 10:02:24 +01:00
promiseLogin = tempMatrixClient
2021-01-20 09:42:13 +01:00
.register(user, pass, null, {
type: "m.login.dummy",
2021-01-28 22:13:08 +01:00
})
2020-11-25 10:02:24 +01:00
.then((response) => {
console.log("Response", response);
2021-01-20 09:42:13 +01:00
response.password = pass;
2020-11-25 10:02:24 +01:00
response.is_guest = true;
localStorage.setItem('user', JSON.stringify(response));
return response;
})
} else if (!user.is_guest && user.access_token) {
// Logged in on "real" account
promiseLogin = Promise.resolve(user);
2020-11-25 10:02:24 +01:00
} else {
var data = { user: User.localPart(user.user_id), password: user.password, type: "m.login.password" };
if (user.device_id) {
data.device_id = user.device_id;
}
2020-11-25 10:02:24 +01:00
promiseLogin = tempMatrixClient
.login("m.login.password", data)
2020-11-25 10:02:24 +01:00
.then((response) => {
var u = response;
if (user.is_guest) {
// Copy over needed properties
u = Object.assign(user, response);
}
localStorage.setItem('user', JSON.stringify(u));
2020-11-25 10:02:24 +01:00
return response;
})
}
return promiseLogin
.then(user => {
return this.getMatrixClient(user);
})
},
clearCryptoStore() {
// Clear crypto related data
// TODO - for some reason "clearStores" called in "logout" only clears the "account" crypto
// data item, not all sessions etc. Why? We need to do that manually here!
const toRemove = [];
for (let i = 0; i < localStorage.length; ++i) {
const key = localStorage.key(i);
if (key.startsWith("crypto.")) toRemove.push(key);
}
for (const key of toRemove) {
localStorage.removeItem(key);
}
},
logout() {
if (this.matrixClient) {
this.removeMatrixClientListeners(this.matrixClient);
this.matrixClient.stopClient();
this.matrixClient.clearStores().then(() => {
this.clearCryptoStore()
})
this.matrixClient = null;
2020-11-19 22:48:08 +01:00
this.matrixClientReady = false;
} else {
this.clearCryptoStore();
}
localStorage.removeItem('user');
this.$store.commit("setCurrentRoomId", null);
},
/**
* Upgrade a guest account into a "normal" account. For now, use random user and pass...
*/
upgradeGuestAccount() {
if (!this.matrixClient || !this.currentUser || !this.currentUser.is_guest) {
return Promise.reject("Invalid params");
}
const randomPassword = util.randomPass();
2021-01-20 09:42:13 +01:00
const self = this;
return this.matrixClient.register(this.matrixClient.getUserIdLocalpart(), randomPassword, null, {
type: "m.login.dummy",
2021-01-28 22:13:08 +01:00
}, undefined, this.currentUser.access_token)
.then((response) => {
console.log("Response", response);
response.is_guest = false;
2021-01-20 09:42:13 +01:00
response.password = randomPassword;
self.currentUser = response;
localStorage.setItem('user', JSON.stringify(response)); // Update local storage as well.
self.logout();
return self.currentUser;
});
},
initClient() {
this.reloadRooms();
2020-11-19 22:48:08 +01:00
this.matrixClientReady = true;
this.matrixClient.emit('Matrix.initialized', this.matrixClient);
this.matrixClient.getProfileInfo(this.currentUserId)
.then(info => {
console.log("Got user profile: " + JSON.stringify(info));
this.userDisplayName = info.displayname;
this.userAvatar = info.avatar_url;
})
.catch(err => {
console.log("Failed to get user profile: ", err);
})
},
async getMatrixClient(user) {
if (user === undefined) {
user = this.$store.state.auth.user;
}
2020-11-25 10:02:24 +01:00
if (this.matrixClientReady) {
return new Promise((resolve, ignoredreject) => {
2020-11-25 10:02:24 +01:00
resolve(user);
})
} else if (this.matrixClient) {
return new Promise((resolve, ignoredreject) => {
2020-11-25 10:02:24 +01:00
this.matrixClient.once('Matrix.initialized', (ignoredclient) => {
resolve(user);
});
})
}
const matrixStore = new sdk.MemoryStore(window.localStorage);
const webStorageSessionStore = new sdk.WebStorageSessionStore(
window.localStorage
);
var homeServer = user.home_server;
if (!homeServer.startsWith("https://")) {
homeServer = "https://" + homeServer;
}
var opts = {
baseUrl: homeServer,
userId: user.user_id,
store: matrixStore,
sessionStore: webStorageSessionStore,
deviceId: user.device_id,
accessToken: user.access_token,
2020-11-25 10:02:24 +01:00
timelineSupport: true,
2021-01-20 09:42:13 +01:00
unstableClientRelationAggregation: true,
//useAuthorizationHeader: true
}
this.matrixClient = sdk.createClient(opts);
2021-01-20 09:42:13 +01:00
// if (user.is_guest) {
// this.matrixClient.setGuest(true);
// }
return this.matrixClient
.initCrypto()
.then(() => {
console.log("Crypto initialized");
this.addMatrixClientListeners(this.matrixClient);
this.matrixClient.startClient();
return this.matrixClient;
})
.then(matrixClient => {
if (matrixClient.isInitialSyncComplete()) {
console.log("Initial sync done already!");
return matrixClient;
} else {
return new Promise((resolve, reject) => {
matrixClient.once(
"sync",
function (state, ignoredprevState, ignoredres) {
console.log(state); // state will be 'PREPARED' when the client is ready to use
if (state == "PREPARED") {
resolve(matrixClient);
} else if (state == "ERROR") {
reject("Error syncing");
}
}
)
});
2020-11-09 10:26:56 +01:00
}
2020-11-25 10:02:24 +01:00
})
.then(() => {
// Ready to use! Start by loading rooms.
this.initClient();
return user;
})
},
2020-11-09 10:26:56 +01:00
addMatrixClientListeners(client) {
if (client) {
client.on("event", this.onEvent);
2020-11-25 15:07:51 +01:00
client.on("Room", this.onRoom);
2021-01-20 09:42:13 +01:00
client.on("Session.logged_out", this.onSessionLoggedOut);
}
},
2020-11-09 10:26:56 +01:00
removeMatrixClientListeners(client) {
if (client) {
client.off("event", this.onEvent);
2020-11-25 15:07:51 +01:00
client.off("Room", this.onRoom);
2021-01-20 09:42:13 +01:00
client.off("Session.logged_out", this.onSessionLoggedOut);
}
},
onEvent(event) {
switch (event.getType()) {
case "m.room.topic": {
const room = this.matrixClient.getRoom(event.getRoomId());
if (room) {
Vue.set(room, "topic", event.getContent().topic);
}
}
2020-11-25 10:02:24 +01:00
break;
case "m.room.avatar": {
const room = this.matrixClient.getRoom(event.getRoomId());
if (room) {
Vue.set(room, "avatar", room.getAvatarUrl(this.matrixClient.getHomeserverUrl(), 80, 80, "scale", true));
}
}
2020-11-25 10:02:24 +01:00
break;
}
this.updateNotificationCount();
},
2020-11-09 10:26:56 +01:00
2020-11-25 15:07:51 +01:00
onRoom(ignoredroom) {
console.log("Got room: " + ignoredroom);
2020-11-25 15:07:51 +01:00
this.reloadRooms();
this.updateNotificationCount();
2020-11-25 15:07:51 +01:00
},
2021-01-20 09:42:13 +01:00
onSessionLoggedOut() {
console.log("Logged out!");
if (this.matrixClient) {
this.removeMatrixClientListeners(this.matrixClient);
this.matrixClient.stopClient();
this.matrixClient = null;
this.matrixClientReady = false;
}
this.$store.commit("setCurrentRoomId", null);
2021-01-28 22:13:08 +01:00
// Clear the access token
var user = JSON.parse(localStorage.getItem('user'));
if (user) {
delete user.access_token;
}
localStorage.setItem('user', JSON.stringify(user));
this.$navigation.push({ name: "Login" }, -1);
2021-01-20 09:42:13 +01:00
},
2020-11-25 15:07:51 +01:00
reloadRooms() {
2021-01-28 22:13:08 +01:00
// TODO - do incremental update instead of replacing the whole array
// each time!
var updatedRooms = this.matrixClient.getVisibleRooms();
updatedRooms = updatedRooms.filter(room => {
return room._selfMembership && (room._selfMembership == "invite" || room._selfMembership == "join");
});
2021-01-28 22:13:08 +01:00
updatedRooms.forEach(room => {
if (!room.avatar) {
Vue.set(room, "avatar", room.getAvatarUrl(this.matrixClient.getHomeserverUrl(), 80, 80, "scale", true));
}
});
console.log("Reload rooms", updatedRooms);
2021-01-28 22:13:08 +01:00
Vue.set(this, "rooms", updatedRooms);
const currentRoom = this.getRoom(this.$store.state.currentRoomId);
2021-01-28 22:13:08 +01:00
if (this.currentRoom != currentRoom) {
this.currentRoom = currentRoom;
2020-11-25 15:07:51 +01:00
}
},
setCurrentRoomId(roomId) {
this.$store.commit("setCurrentRoomId", roomId);
2021-01-28 22:13:08 +01:00
this.currentRoom = this.getRoom(roomId);
},
getRoom(roomId) {
2020-12-15 17:06:26 +01:00
if (!roomId) {
return null;
}
2021-01-28 22:13:08 +01:00
var room = null;
if (this.matrixClient) {
const visibleRooms = this.matrixClient.getRooms();
room = visibleRooms.find(room => {
if (roomId.startsWith("#")) {
return room.getCanonicalAlias() == roomId;
}
return room.roomId == roomId;
});
2020-11-25 15:07:51 +01:00
}
2021-01-11 17:42:58 +01:00
return room || null;
},
2021-01-28 22:13:08 +01:00
leaveRoom(roomId) {
return this.matrixClient.leave(roomId, undefined)
.then(() => {
this.rooms = this.rooms.filter(room => {
room.roomId != roomId;
});
this.matrixClient.store.removeRoom(roomId);
//this.matrixClient.forget(roomId, true, undefined);
2021-01-28 22:13:08 +01:00
})
},
on(event, handler) {
if (this.matrixClient) {
this.matrixClient.on(event, handler);
}
},
off(event, handler) {
if (this.matrixClient) {
this.matrixClient.off(event, handler);
}
2020-11-17 20:02:42 +01:00
},
uploadFile(file, opts) {
return this.matrixClient.uploadContent(file, opts);
},
2020-12-16 15:57:44 +01:00
getPublicRoomInfo(roomId) {
if (!roomId) {
return Promise.reject("Invalid parameters");
}
const parts = roomId.split(':');
if (parts.length != 2) {
return Promise.reject("Unknown room server");
}
const server = parts[1];
var clientPromise;
if (this.matrixClient) {
clientPromise = this.getMatrixClient().then(() => {
return this.matrixClient;
})
} else {
const tempMatrixClient = sdk.createClient(config.defaultServer);
var tempUserString = localStorage.getItem('tempuser');
var tempUser = null;
if (tempUserString) {
tempUser = JSON.parse(tempUserString);
}
// Need to create an account?
//
if (tempUser) {
clientPromise = Promise.resolve(tempUser);
} else {
const user = util.randomUser();
const pass = util.randomPass();
clientPromise = tempMatrixClient
.register(user, pass, null, {
type: "m.login.dummy",
})
.then((response) => {
console.log("Response", response);
response.password = pass;
response.is_guest = true;
localStorage.setItem('tempuser', JSON.stringify(response));
return response;
});
}
// Get an access token
clientPromise = clientPromise.then(user => {
var data = { user: User.localPart(user.user_id), password: user.password, type: "m.login.password" };
if (user.device_id) {
data.device_id = user.device_id;
}
return tempMatrixClient.login("m.login.password", data)
})
// Then login
//
// Create a slimmed down client, without crypto. This one is
// Only used to get public room info from.
clientPromise = clientPromise.then(user => {
var opts = {
baseUrl: config.defaultServer,
userId: user.user_id,
accessToken: user.access_token,
timelineSupport: false,
}
var matrixClient = sdk.createClient(opts);
matrixClient.startClient();
return matrixClient;
});
}
const findOrGetMore = function _findOrGetMore(client, response) {
2020-12-16 15:57:44 +01:00
for (var room of response.chunk) {
2021-01-28 22:13:08 +01:00
if ((roomId.startsWith("#") && room.canonical_alias == roomId) || (roomId.startsWith("!") && room.room_id == roomId)) {
if (room.avatar_url) {
room.avatar = client.mxcUrlToHttp(room.avatar_url, 80, 80, 'scale', true);
}
2020-12-16 15:57:44 +01:00
return Promise.resolve(room);
}
}
if (response.next_batch) {
return client.publicRooms({ server: server, limit: 1000, since: response.next_batch })
2021-01-28 22:13:08 +01:00
.then(response => {
return _findOrGetMore(client, response);
2021-01-28 22:13:08 +01:00
})
.catch(err => {
return Promise.reject("Failed to find room: " + err);
});
2020-12-16 15:57:44 +01:00
} else {
return Promise.reject("No more data");
}
};
var matrixClient;
return clientPromise
.then(client => {
matrixClient = client;
return matrixClient.publicRooms({ server: server, limit: 1000 })
})
2021-01-28 22:13:08 +01:00
.then(response => {
return findOrGetMore(matrixClient, response);
2021-01-28 22:13:08 +01:00
})
.catch(err => {
return Promise.reject("Failed to find room: " + err);
});
},
updateNotificationCount() {
var count = 0;
this.rooms.forEach(room => {
count += room.getUnreadNotificationCount('total') || 0;
});
this.notificationCount = count;
2020-12-16 15:57:44 +01:00
}
}
})
Vue.prototype.$matrix = matrixService;
}
}