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

343 lines
14 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";
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: [],
2020-12-15 17:06:26 +01:00
currentRoom: null,
}
},
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;
},
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.server);
2020-11-25 10:02:24 +01:00
var promiseLogin;
if (user.is_guest) {
promiseLogin = tempMatrixClient
.registerGuest({}, undefined)
.then((response) => {
console.log("Response", response);
response.is_guest = true;
localStorage.setItem('user', JSON.stringify(response));
return response;
})
} else {
promiseLogin = tempMatrixClient
.login("m.login.password", { user: user.username, password: user.password, type: "m.login.password" })
.then((response) => {
localStorage.setItem('user', JSON.stringify(response));
return response;
})
}
return promiseLogin
.then(user => {
return this.getMatrixClient(user);
})
},
logout() {
if (this.matrixClient) {
this.removeMatrixClientListeners(this.matrixClient);
this.matrixClient.stopClient();
this.matrixClient = null;
2020-11-19 22:48:08 +01:00
this.matrixClientReady = false;
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 randomUsername = util.randomUser();
const randomPassword = util.randomPass();
const data = {
username:randomUsername,
password:randomPassword,
guest_access_token:this.currentUser.access_token
};
return this.matrixClient.registerRequest(data, undefined, undefined)
.then((response) => {
console.log("Response", response);
response.is_guest = false;
localStorage.setItem('user', JSON.stringify(response));
return response;
});
},
initClient() {
this.reloadRooms();
2020-11-19 22:48:08 +01:00
this.matrixClientReady = true;
2020-12-15 17:06:26 +01:00
this.currentRoom = null;
this.currentRoom = this.getRoom(this.currentRoomId);
2020-11-19 22:48:08 +01:00
this.matrixClient.emit('Matrix.initialized', this.matrixClient);
},
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,
unstableClientRelationAggregation: true
}
this.matrixClient = sdk.createClient(opts);
2020-11-25 10:02:24 +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);
}
},
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);
}
},
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;
}
},
2020-11-09 10:26:56 +01:00
2020-11-25 15:07:51 +01:00
onRoom(ignoredroom) {
this.reloadRooms();
},
reloadRooms() {
this.rooms = this.matrixClient.getVisibleRooms();
this.rooms.forEach(room => {
Vue.set(room, "avatar", room.getAvatarUrl(this.matrixClient.getHomeserverUrl(), 80, 80, "scale", true));
});
},
2020-11-09 10:26:56 +01:00
2020-11-25 15:07:51 +01:00
setCurrentRoom(room) {
// If we don't know about this room yet (e.g. we just joined)
// add it to our list.
if (!this.getRoom(room.roomId)) {
this.rooms.push(room);
}
this.setCurrentRoomId(room.roomId);
},
setCurrentRoomId(roomId) {
this.$store.commit("setCurrentRoomId", roomId);
},
getRoom(roomId) {
2020-12-15 17:06:26 +01:00
if (!roomId) {
return null;
}
var room = this.rooms.find(room => {
if (roomId.startsWith("#")) {
return room.getCanonicalAlias() == roomId;
}
return room.roomId == roomId;
});
2020-11-25 15:07:51 +01:00
if (!room && this.matrixClient) {
room = this.matrixClient.getRoom(roomId);
}
return room;
},
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];
const tempMatrixClient = sdk.createClient("https://" + server);
const findOrGetMore = function _findOrGetMore(response) {
for (var room of response.chunk) {
if ((roomId.startsWith("#") && room.canonical_alias == roomId) || (roomId.startsWith("!") && room.room_id == roomId)){
room.avatar = tempMatrixClient.mxcUrlToHttp(room.avatar_url, 80, 80, 'scale', true);
return Promise.resolve(room);
}
}
if (response.next_batch) {
return tempMatrixClient._http.request(undefined, "GET", "/publicRooms", {limit:1000, next_batch:response.next_batch})
//return tempMatrixClient.publicRooms({limit:1,next_batch:response.next_batch})
.then(response => {
return _findOrGetMore(response);
})
} else {
return Promise.reject("No more data");
}
};
return tempMatrixClient._http.request(undefined, "GET", "/publicRooms", {limit:1000})
//return tempMatrixClient.publicRooms({limit:1})
.then(response => {
return findOrGetMore(response);
});
}
}
})
Vue.prototype.$matrix = matrixService;
}
}