Create a login before joining

This allows us to get room avatar and name for public rooms, at least if they are on the same server as our account (config.defaultServer). Issue #45.
This commit is contained in:
N-Pex 2021-03-12 14:57:36 +01:00
parent 988e27a56c
commit 4c1de61ff4
2 changed files with 163 additions and 83 deletions

View file

@ -218,8 +218,10 @@ export default {
if (!this.currentUser || !this.currentUser.userId) { if (!this.currentUser || !this.currentUser.userId) {
return null; return null;
} }
return (this.userDisplayName || this.currentUser.userId.substring(1)).substring(0, 1).toUpperCase(); return (this.userDisplayName || this.currentUser.userId.substring(1))
} .substring(0, 1)
.toUpperCase();
},
}, },
watch: { watch: {
roomId: { roomId: {
@ -232,11 +234,12 @@ export default {
"Join: Current room changed to " + (value ? value : "null") "Join: Current room changed to " + (value ? value : "null")
); );
this.roomName = this.roomId; this.roomName = this.roomId;
if (this.currentUser) {
this.waitingForMembership = true; this.waitingForInfo = true;
const self = this; const self = this;
this.$matrix this.waitingForMembership = true;
.login(this.currentUser) if (this.currentUser) {
this.getLoginPromise()
.then(() => { .then(() => {
self.$matrix.setCurrentRoomId(self.roomAliasOrId); // Go to this room, now or when joined. self.$matrix.setCurrentRoomId(self.roomAliasOrId); // Go to this room, now or when joined.
const room = self.$matrix.getRoom(self.roomAliasOrId); const room = self.$matrix.getRoom(self.roomAliasOrId);
@ -256,12 +259,34 @@ export default {
); );
return; return;
} }
this.waitingForMembership = false;
}) })
.catch((ignoredErr) => { .catch(err => {
console.log("Error logging in: ", err)
})
.finally(() => {
this.waitingForMembership = false; this.waitingForMembership = false;
this.getRoomInfo();
}); });
} else {
this.waitingForMembership = false;
this.getRoomInfo();
} }
}
},
},
methods: {
/**
* Returns a promise that will log us into the Matrix.
*
* Will use a real account, if we have one, otherwise will create
* a random account.
*/
getLoginPromise() {
return this.$store.dispatch("auth/login", this.currentUser || this.guestUser);
},
getRoomInfo() {
if (this.roomId.startsWith("#")) { if (this.roomId.startsWith("#")) {
this.$matrix this.$matrix
.getPublicRoomInfo(this.roomId) .getPublicRoomInfo(this.roomId)
@ -269,10 +294,11 @@ export default {
console.log("Found room:", room); console.log("Found room:", room);
this.roomName = room.name; this.roomName = room.name;
this.roomAvatar = room.avatar; this.roomAvatar = room.avatar;
this.waitingForInfo = false;
}) })
.catch((err) => { .catch((err) => {
console.log("Could not find room info", err); console.log("Could not find room info", err);
})
.finally(() => {
this.waitingForInfo = false; this.waitingForInfo = false;
}); });
} else { } else {
@ -284,10 +310,7 @@ export default {
this.waitingForInfo = false; this.waitingForInfo = false;
} }
}, },
},
},
methods: {
onMyMembership(room, membership, ignoredprevMembership) { onMyMembership(room, membership, ignoredprevMembership) {
if (room && room.roomId == this.roomId && membership == "join") { if (room && room.roomId == this.roomId && membership == "join") {
this.$nextTick(() => { this.$nextTick(() => {
@ -313,13 +336,7 @@ export default {
handleJoin() { handleJoin() {
this.loading = true; this.loading = true;
this.loadingMessage = "Logging in..."; this.loadingMessage = "Logging in...";
var clientPromise; return this.getLoginPromise()
if (this.currentUser) {
clientPromise = this.$matrix.login(this.currentUser);
} else {
clientPromise = this.$store.dispatch("auth/login", this.guestUser);
}
return clientPromise
.then( .then(
function (user) { function (user) {
if (!this.hasChangedDisplayName) { if (!this.hasChangedDisplayName) {

View file

@ -2,6 +2,7 @@ global.Olm = require("olm");
import sdk from "matrix-js-sdk"; import sdk from "matrix-js-sdk";
import util from "../plugins/utils"; import util from "../plugins/utils";
import User from "../models/user"; import User from "../models/user";
import config from "../assets/config";
const LocalStorageCryptoStore = require("matrix-js-sdk/lib/crypto/store/localStorage-crypto-store") const LocalStorageCryptoStore = require("matrix-js-sdk/lib/crypto/store/localStorage-crypto-store")
.LocalStorageCryptoStore; .LocalStorageCryptoStore;
@ -402,22 +403,80 @@ export default {
if (parts.length != 2) { if (parts.length != 2) {
return Promise.reject("Unknown room server"); return Promise.reject("Unknown room server");
} }
const server = parts[1]; const server = parts[1];
const tempMatrixClient = sdk.createClient("https://" + server);
const findOrGetMore = function _findOrGetMore(response) { 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) {
for (var room of response.chunk) { for (var room of response.chunk) {
if ((roomId.startsWith("#") && room.canonical_alias == roomId) || (roomId.startsWith("!") && room.room_id == roomId)) { if ((roomId.startsWith("#") && room.canonical_alias == roomId) || (roomId.startsWith("!") && room.room_id == roomId)) {
room.avatar = tempMatrixClient.mxcUrlToHttp(room.avatar_url, 80, 80, 'scale', true); if (room.avatar_url) {
room.avatar = client.mxcUrlToHttp(room.avatar_url, 80, 80, 'scale', true);
}
return Promise.resolve(room); return Promise.resolve(room);
} }
} }
if (response.next_batch) { if (response.next_batch) {
return tempMatrixClient._http.request(undefined, "GET", "/publicRooms", { limit: 1000, since: response.next_batch }) return client.publicRooms({ server: server, limit: 1000, since: response.next_batch })
//return tempMatrixClient.publicRooms({limit:1,next_batch:response.next_batch})
.then(response => { .then(response => {
return _findOrGetMore(response); return _findOrGetMore(client, response);
}) })
.catch(err => { .catch(err => {
return Promise.reject("Failed to find room: " + err); return Promise.reject("Failed to find room: " + err);
@ -427,10 +486,14 @@ export default {
} }
}; };
return tempMatrixClient._http.request(undefined, "GET", "/publicRooms", { limit: 1000 }) var matrixClient;
//return tempMatrixClient.publicRooms({limit:1}) return clientPromise
.then(client => {
matrixClient = client;
return matrixClient.publicRooms({ server: server, limit: 1000 })
})
.then(response => { .then(response => {
return findOrGetMore(response); return findOrGetMore(matrixClient, response);
}) })
.catch(err => { .catch(err => {
return Promise.reject("Failed to find room: " + err); return Promise.reject("Failed to find room: " + err);