Improved BaseURL and DM link handling

This commit is contained in:
N Pex 2023-12-01 08:20:03 +00:00
parent b14749c28f
commit dd70e4a576
9 changed files with 373 additions and 322 deletions

View file

@ -15,8 +15,16 @@ export default {
Vue.set(config, key, json[key]);
}
// If default server is not set, default to current server address
if (!json.defaultServer) {
Vue.set(config, "defaultServer", defaultServerFromLocation);
if (!json.defaultBaseUrl) {
if (json.defaultServer) {
// TODO - Only to migrate old values (defaultServer was renamed defaultBaseUrl), can be removed later...
Vue.set(config, "defaultBaseUrl", defaultServerFromLocation);
} else {
Vue.set(config, "defaultBaseUrl", json.defaultServer);
}
}
if (json.useFullyQualifiedDMLinks == undefined) {
Vue.set(config, "useFullyQualifiedDMLinks", true); // Default to true
}
Vue.set(config, "loaded", true);
@ -26,6 +34,24 @@ export default {
}
return config;
});
/**
* If there is an explicit mapping for this MX domain in the config file, return the endpoint URL that it maps to.
* @param {*} domain
* @returns
*/
config.getMatrixDomainPartMapping = (domain) => {
console.log("Get domain endpoint mapping for", domain);
if (config.matrixDomainPartMapping && config.matrixDomainPartMapping[domain]) {
const mapping = config.matrixDomainPartMapping[domain];
if (Array.isArray(mapping)) {
return mapping[0]; //TODO - Use the first one for now, but maybe rotate somehow?
}
return mapping;
}
return undefined;
}
Vue.prototype.$config = config;
}
}

View file

@ -68,8 +68,8 @@ export default {
return null;
},
currentUserHomeServer() {
return this.$config.homeServer ? this.$config.homeServer : User.serverName(this.currentUserId);
currentUserMXDomain() {
return User.domainPart(this.currentUserId) || this.$config.defaultMatrixDomainPart;
},
currentRoomId() {
@ -92,7 +92,7 @@ export default {
return this.rooms.filter((room) => {
return room.selfMembership === "join" || room.selfMembership === "invite";
});
}
},
},
watch: {
@ -110,8 +110,8 @@ export default {
} else {
this.currentRoomIsReadOnlyForUser = false;
}
}
}
},
},
},
methods: {
@ -120,83 +120,88 @@ export default {
return new LocalStorageCryptoStore(this.$store.getters.storage);
},
login(user, registrationFlowHandler, createUser = false) {
const tempMatrixClient = sdk.createClient({baseUrl: user.home_server, idBaseUrl: this.$config.identityServer});
var promiseLogin;
const self = this;
if (user.access_token) {
// Logged in on "real" account
promiseLogin = Promise.resolve(user);
} else if (createUser || (user.is_guest && (!user.user_id || user.registration_session))) {
// 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 userId = (createUser || user.registration_session) ? user.user_id : util.randomUser(this.$config.userIdPrefix);
const pass = (createUser || user.registration_session) ? user.password : util.randomPass();
const extractAndSaveUser = (response) => {
var u = Object.assign({}, response);
u.home_server = tempMatrixClient.baseUrl; // Don't use deprecated field from response.
u.password = pass;
u.is_guest = true;
this.$store.commit("setUser", u);
return u;
};
promiseLogin = tempMatrixClient
.register(userId, pass, user.registration_session || null, {
type: "m.login.dummy",
initial_device_display_name: this.$config.appName,
})
.then((response) => {
return extractAndSaveUser(response);
})
.catch(error => {
if (registrationFlowHandler && error.httpStatus == 401 && error.data) {
const registrationSession = error.data.session;
// Store user, pass and session, so we can resume if network failure occurs etc.
//
var u = {};
u.user_id = userId;
u.home_server = tempMatrixClient.baseUrl; // Don't use deprecated field from response.
u.password = pass;
u.is_guest = true;
u.registration_session = registrationSession;
this.$store.commit("setUser", u);
return registrationFlowHandler(tempMatrixClient, error.data).then((response) => extractAndSaveUser(response));
} else {
console.error(error);
}
throw error;
});
} else {
var data = {
user: User.localPart(user.user_id),
password: user.password,
type: "m.login.password",
initial_device_display_name: this.$config.appName,
};
if (user.device_id) {
data.device_id = user.device_id;
}
promiseLogin = tempMatrixClient.login("m.login.password", data).then((response) => {
var u = Object.assign({}, response);
if (user.is_guest) {
// Copy over needed properties
u = Object.assign(user, response);
}
u.home_server = tempMatrixClient.baseUrl; // Don't use deprecated field from response.
this.$store.commit("setUser", u);
return u;
return util.getMatrixBaseUrl(user, this.$config).then((baseUrl) => {
const tempMatrixClient = sdk.createClient({
baseUrl: baseUrl,
idBaseUrl: this.$config.identityServer,
});
}
var promiseLogin;
return promiseLogin.then((user) => {
return self.getMatrixClient(user);
const self = this;
if (user.access_token) {
// Logged in on "real" account
promiseLogin = Promise.resolve(user);
} else if (createUser || (user.is_guest && (!user.user_id || user.registration_session))) {
// 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 userId =
createUser || user.registration_session ? user.user_id : util.randomUser(this.$config.userIdPrefix);
const pass = createUser || user.registration_session ? user.password : util.randomPass();
const extractAndSaveUser = (response) => {
var u = Object.assign({}, response);
u.password = pass;
u.is_guest = true;
this.$store.commit("setUser", u);
return u;
};
promiseLogin = tempMatrixClient
.register(userId, pass, user.registration_session || null, {
type: "m.login.dummy",
initial_device_display_name: this.$config.appName,
})
.then((response) => {
return extractAndSaveUser(response);
})
.catch((error) => {
if (registrationFlowHandler && error.httpStatus == 401 && error.data) {
const registrationSession = error.data.session;
// Store user, pass and session, so we can resume if network failure occurs etc.
//
var u = {};
u.user_id = userId;
u.password = pass;
u.is_guest = true;
u.registration_session = registrationSession;
this.$store.commit("setUser", u);
return registrationFlowHandler(tempMatrixClient, error.data).then((response) =>
extractAndSaveUser(response)
);
} else {
console.error(error);
}
throw error;
});
} else {
var data = {
user: User.localPart(user.user_id),
password: user.password,
type: "m.login.password",
initial_device_display_name: this.$config.appName,
};
if (user.device_id) {
data.device_id = user.device_id;
}
promiseLogin = tempMatrixClient.login("m.login.password", data).then((response) => {
var u = Object.assign({}, response);
if (user.is_guest) {
// Copy over needed properties
u = Object.assign(user, response);
}
this.$store.commit("setUser", u);
return u;
});
}
return promiseLogin.then((user) => {
return self.getMatrixClient(user);
});
});
},
@ -271,52 +276,54 @@ export default {
const matrixStore = new sdk.MemoryStore(this.$store.getters.storage);
var opts = {
baseUrl: user.home_server,
userId: user.user_id,
store: matrixStore,
deviceId: user.device_id,
accessToken: user.access_token,
timelineSupport: true,
unstableClientRelationAggregation: true,
//useAuthorizationHeader: true
};
this.matrixClient = sdk.createClient(opts);
// if (user.is_guest) {
// this.matrixClient.setGuest(true);
// }
return this.matrixClient
.initCrypto()
.then(() => {
console.log("Crypto initialized");
return util.getMatrixBaseUrl(user, this.$config).then((baseUrl) => {
var opts = {
baseUrl: baseUrl,
userId: user.user_id,
store: matrixStore,
deviceId: user.device_id,
accessToken: user.access_token,
timelineSupport: true,
unstableClientRelationAggregation: true,
//useAuthorizationHeader: true
};
this.matrixClient = sdk.createClient(opts);
// if (user.is_guest) {
// this.matrixClient.setGuest(true);
// }
return this.matrixClient
.initCrypto()
.then(() => {
console.log("Crypto initialized");
this.addMatrixClientListeners(this.matrixClient);
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");
}
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");
}
});
});
});
}
})
.then(() => {
// Ready to use! Start by loading rooms.
this.initClient();
return user;
});
}
})
.then(() => {
// Ready to use! Start by loading rooms.
this.initClient();
return user;
});
});
},
/**
@ -329,7 +336,10 @@ export default {
if (this.ready) {
return Promise.resolve(this.currentUser);
}
return this.$store.dispatch("login", { user: this.currentUser || new User(this.$config.defaultServer, "", "", true), registrationFlowHandler });
return this.$store.dispatch("login", {
user: this.currentUser || new User("", "", true),
registrationFlowHandler,
});
},
addMatrixClientListeners(client) {
@ -376,13 +386,13 @@ export default {
break;
case "m.room.power_levels":
{
if (this.currentRoom && event.getRoomId() == this.currentRoom.roomId) {
this.currentRoomIsReadOnlyForUser = this.isReadOnlyRoomForUser(event.getRoomId(), this.currentUserId);
}
{
if (this.currentRoom && event.getRoomId() == this.currentRoom.roomId) {
this.currentRoomIsReadOnlyForUser = this.isReadOnlyRoomForUser(event.getRoomId(), this.currentUserId);
}
break;
}
break;
case STATE_EVENT_ROOM_DELETED:
{
const room = this.matrixClient.getRoom(event.getRoomId());
@ -394,7 +404,7 @@ export default {
if (event.getSender() !== this.currentUserId) {
this.leaveRoomAndNavigate(room.roomId).then(() => {
this.matrixClient.store.removeRoom(room.roomId);
})
});
}
}
}
@ -406,13 +416,16 @@ export default {
onRoom(room) {
if (room.selfMembership === "invite") {
this.matrixClient.getRoomTags(room.roomId).then(reply => {
if (Object.keys(reply.tags).includes("m.server_notice")) {
Vue.set(room, "isServiceNoticeRoom", true);
}
}).catch((error => {
console.error(error);
}))
this.matrixClient
.getRoomTags(room.roomId)
.then((reply) => {
if (Object.keys(reply.tags).includes("m.server_notice")) {
Vue.set(room, "isServiceNoticeRoom", true);
}
})
.catch((error) => {
console.error(error);
});
}
this.reloadRooms();
this.updateNotificationCount();
@ -476,14 +489,19 @@ export default {
}
});
Vue.set(this, "rooms", updatedRooms);
const resolvedId = (this.currentRoomId && this.currentRoomId.startsWith("#")) ? this.matrixClient.resolveRoomAlias(this.currentRoomId).then(r => r.room_id) : Promise.resolve(this.currentRoomId);
resolvedId.then(roomId => {
const currentRoom = this.getRoom(roomId);
if (this.currentRoom != currentRoom) {
this.currentRoom = currentRoom;
}
}).catch(ignorederror => {});
const resolvedId =
this.currentRoomId && this.currentRoomId.startsWith("#")
? this.matrixClient.resolveRoomAlias(this.currentRoomId).then((r) => r.room_id)
: Promise.resolve(this.currentRoomId);
resolvedId
.then((roomId) => {
const currentRoom = this.getRoom(roomId);
if (this.currentRoom != currentRoom) {
this.currentRoom = currentRoom;
}
})
.catch((ignorederror) => {});
},
setCurrentRoomId(roomId) {
@ -562,26 +580,18 @@ export default {
/**
* Leave the room, and if this is the last room we are in, navigate to the "goodbye" page.
* Otherwise, navigate to home.
* @param roomId
* @param roomId
*/
leaveRoomAndNavigate(roomId) {
const joinedRooms = this.joinedRooms;
const isLastRoomWeAreJoinedTo = (
joinedRooms &&
joinedRooms.length == 1 &&
joinedRooms[0].roomId == roomId
);
return this.leaveRoom(roomId)
.then(() => {
if (isLastRoomWeAreJoinedTo) {
this.$navigation.push({ name: "Goodbye" }, -1);
} else {
this.$navigation.push(
{ name: "Home", params: { roomId: null } },
-1
);
}
})
const isLastRoomWeAreJoinedTo = joinedRooms && joinedRooms.length == 1 && joinedRooms[0].roomId == roomId;
return this.leaveRoom(roomId).then(() => {
if (isLastRoomWeAreJoinedTo) {
this.$navigation.push({ name: "Goodbye" }, -1);
} else {
this.$navigation.push({ name: "Home", params: { roomId: null } }, -1);
}
});
},
kickUser(roomId, userId) {
@ -635,18 +645,20 @@ export default {
/**
* Returns true if the current user is joined to the given room.
* @param roomIdOrAlias
* @param roomIdOrAlias
* @returns Promise<Bool> - Whether the user is joined to the room or not
*/
isJoinedToRoom(roomIdOrAlias) {
if (roomIdOrAlias && this.matrixClient) {
try {
const resolvedRoomId = roomIdOrAlias.startsWith("#") ? this.matrixClient.resolveRoomAlias(roomIdOrAlias).then(res => res.room_id) : Promise.resolve(roomIdOrAlias);
return resolvedRoomId.then(roomId => {
return this.matrixClient.getJoinedRooms().then(rooms => {
const resolvedRoomId = roomIdOrAlias.startsWith("#")
? this.matrixClient.resolveRoomAlias(roomIdOrAlias).then((res) => res.room_id)
: Promise.resolve(roomIdOrAlias);
return resolvedRoomId.then((roomId) => {
return this.matrixClient.getJoinedRooms().then((rooms) => {
return rooms.joined_rooms.includes(roomId);
});
});
});
} catch (ignorederror) {
console.error(ignorederror);
return Promise.resolve(false);
@ -661,7 +673,7 @@ export default {
if (room && room.currentState) {
const powerLevelEvent = room.currentState.getStateEvents("m.room.power_levels", "");
if (powerLevelEvent) {
return powerLevelEvent.getContent().events_default > 0
return powerLevelEvent.getContent().events_default > 0;
}
}
}
@ -672,7 +684,7 @@ export default {
if (this.matrixClient && roomId && userId) {
const room = this.getRoom(roomId);
if (room && room.currentState) {
return !room.currentState.maySendMessage(userId)
return !room.currentState.maySendMessage(userId);
}
}
return false;
@ -686,11 +698,7 @@ export default {
if (powerLevelEvent) {
let content = powerLevelEvent.getContent();
content.events_default = readOnly ? 50 : 0;
this.matrixClient.sendStateEvent(
room.roomId,
"m.room.power_levels",
content
);
this.matrixClient.sendStateEvent(room.roomId, "m.room.power_levels", content);
}
}
}
@ -759,11 +767,7 @@ export default {
});
})
.then(() => {
return this.matrixClient.sendStateEvent(
roomId,
STATE_EVENT_ROOM_DELETED,
{ status: "deleted" }
);
return this.matrixClient.sendStateEvent(roomId, STATE_EVENT_ROOM_DELETED, { status: "deleted" });
})
.then(() => {
//console.log("Purge: create timeline");
@ -849,11 +853,9 @@ export default {
return kickFirstMember(allMembers);
})
.then(() => {
return withRetry(() => this.matrixClient.sendStateEvent(
roomId,
STATE_EVENT_ROOM_DELETED,
{ status: "deleted" }
));
return withRetry(() =>
this.matrixClient.sendStateEvent(roomId, STATE_EVENT_ROOM_DELETED, { status: "deleted" })
);
})
.then(() => {
statusCallback(null);
@ -970,7 +972,7 @@ export default {
return false;
},
/**
/**
* Return true if this room is a direct room with one other user. NOTE: this currently
* only checks number of members, not any is_direct flag.
* @param { } room
@ -979,7 +981,7 @@ export default {
// TODO - Use the is_direct accountData flag (m.direct). WE (as the client)
// apprently need to set this...
if (room && room.getJoinRule() == "invite" && room.getMembers().length == 2) {
return true;
return true;
}
return false;
},
@ -998,7 +1000,10 @@ export default {
setUserDisplayName(name) {
if (this.matrixClient) {
return this.matrixClient.setDisplayName(name || this.user.userId).then(() => this.userDisplayName = name).catch(err => console.err("Failed to set display name", err));
return this.matrixClient
.setDisplayName(name || this.user.userId)
.then(() => (this.userDisplayName = name))
.catch((err) => console.err("Failed to set display name", err));
} else {
return Promise.reject("No matrix client");
}
@ -1043,71 +1048,75 @@ export default {
* @returns A MatrixClient that can be used for public queries
*/
getPublicQueryMatrixClient() {
var clientPromise;
if (this.matrixClient) {
clientPromise = this.getMatrixClient().then(() => {
return this.getMatrixClient().then(() => {
return this.matrixClient;
});
} else {
const tempMatrixClient = sdk.createClient({baseUrl: this.$config.defaultServer});
var tempUserString = this.$store.state.tempuser;
var tempUser = null;
if (tempUserString) {
tempUser = JSON.parse(tempUserString);
}
return util.getMatrixBaseUrl(tempUser, this.$config).then((baseUrl) => {
const tempMatrixClient = sdk.createClient({ baseUrl: baseUrl });
// Need to create an account?
//
if (tempUser) {
clientPromise = Promise.resolve(tempUser);
} else {
const user = util.randomUser(this.$config.userIdPrefix);
const pass = util.randomPass();
clientPromise = tempMatrixClient
.register(user, pass, null, {
type: "m.login.dummy",
initial_device_display_name: this.$config.appName,
})
.then((response) => {
console.log("Response", response);
response.password = pass;
response.is_guest = true;
this.$store.commit("setTempUser", response);
return response;
});
}
var clientPromise;
// Get an access token
clientPromise = clientPromise.then((user) => {
var data = {
user: User.localPart(user.user_id),
password: user.password,
type: "m.login.password",
initial_device_display_name: this.$config.appName,
};
if (user.device_id) {
data.device_id = user.device_id;
// Need to create an account?
//
if (tempUser) {
clientPromise = Promise.resolve(tempUser);
} else {
const user = util.randomUser(this.$config.userIdPrefix);
const pass = util.randomPass();
clientPromise = tempMatrixClient
.register(user, pass, null, {
type: "m.login.dummy",
initial_device_display_name: this.$config.appName,
})
.then((response) => {
console.log("Response", response);
response.password = pass;
response.is_guest = true;
this.$store.commit("setTempUser", response);
return response;
});
}
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: this.$config.defaultServer,
userId: user.user_id,
accessToken: user.access_token,
timelineSupport: false,
};
var matrixClient = sdk.createClient(opts);
matrixClient.startClient();
return matrixClient;
// Get an access token
clientPromise = clientPromise.then((user) => {
var data = {
user: User.localPart(user.user_id),
password: user.password,
type: "m.login.password",
initial_device_display_name: this.$config.appName,
};
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: baseUrl,
userId: user.user_id,
accessToken: user.access_token,
timelineSupport: false,
};
var matrixClient = sdk.createClient(opts);
matrixClient.startClient();
return matrixClient;
});
return clientPromise;
});
}
return clientPromise;
},
getPublicUserInfo(userId) {