Add matrix service to $matrix and move room handling to that

This commit is contained in:
N-Pex 2020-11-09 15:08:36 +01:00
parent 2ca7dd3655
commit c88931e00c
7 changed files with 239 additions and 213 deletions

View file

@ -1,12 +1,12 @@
<template> <template>
<v-app> <v-app>
<v-app-bar app dark> <v-app-bar app dark flat color="#008860">
<v-app-bar-nav-icon @click.stop="openDrawer = !openDrawer"> <v-app-bar-nav-icon @click.stop="openDrawer = !openDrawer">
<v-icon>menu</v-icon> <v-icon>menu</v-icon>
</v-app-bar-nav-icon> </v-app-bar-nav-icon>
<v-toolbar-title <v-toolbar-title
>Keanu{{ room ? " - " + room.name : "" }}</v-toolbar-title >Keanu{{ $matrix.currentRoom ? (" - " + $matrix.currentRoom.summary.info.title) : "" }}</v-toolbar-title
> >
<v-spacer></v-spacer> <v-spacer></v-spacer>
@ -39,8 +39,7 @@
<v-navigation-drawer app v-model="openDrawer"> <v-navigation-drawer app v-model="openDrawer">
<v-list nav dense> <v-list nav dense>
<RoomList <RoomList
v-if="$matrixClient != null" v-if="$matrix.ready"
v-on:onCurrentRoomChanged="onCurrentRoomChanged"
/> />
</v-list> </v-list>
</v-navigation-drawer> </v-navigation-drawer>
@ -54,7 +53,6 @@
</template> </template>
<script> <script>
import Vue from "vue";
import RoomList from "./components/RoomList"; import RoomList from "./components/RoomList";
export default { export default {
@ -64,7 +62,6 @@ export default {
}, },
data: () => ({ data: () => ({
openDrawer: false, openDrawer: false,
currentRoom: null,
}), }),
mounted() { mounted() {
this.$router.replace("/"); this.$router.replace("/");
@ -76,28 +73,22 @@ export default {
logOut() { logOut() {
this.$store.dispatch("auth/logout"); this.$store.dispatch("auth/logout");
this.$router.replace("/login"); this.$router.replace("/login");
this.$store.commit("setCurrentRoom", null);
},
onCurrentRoomChanged(room) {
this.$store.commit("setCurrentRoom", room);
}, },
}, },
computed: { computed: {
currentUser() { currentUser() {
return this.$store.state.auth.user; return this.$store.state.auth.user;
}, },
room() {
return this.$store.state.currentRoom;
},
}, },
watch: { watch: {
currentUser: { currentUser: {
immediate: true, immediate: true,
handler(ignorednewVal, ignoredoldVal) { handler(ignorednewVal, ignoredoldVal) {
if (this.loggedIn) { if (this.loggedIn) {
const self = this;
this.$matrix.getMatrixClient(this.currentUser) this.$matrix.getMatrixClient(this.currentUser)
.then((matrixClient) => { .then(() => {
Vue.prototype.$matrixClient = matrixClient; self.$matrix.initClient();
}) })
.catch((error) => { .catch((error) => {
console.log("Error creating client", error); console.log("Error creating client", error);

View file

@ -1,4 +1,4 @@
$chat-background: #f5fdf5; $chat-background: #008860;
$chat-standard-padding: 32px; $chat-standard-padding: 32px;
$chat-standard-padding-s: 16px; $chat-standard-padding-s: 16px;
$chat-standard-padding-xs: 8px; $chat-standard-padding-xs: 8px;

View file

@ -10,7 +10,7 @@
<div <div
class="messageJoin" class="messageJoin"
v-if=" v-if="
event.event.state_key != myAddress && event.event.state_key != myUserId &&
event.getContent().membership == 'join' && event.getContent().membership == 'join' &&
event.getType() == 'm.room.member' event.getType() == 'm.room.member'
" "
@ -22,7 +22,7 @@
<div <div
class="messageJoin" class="messageJoin"
v-if=" v-if="
event.event.state_key != myAddress && event.event.state_key != myUserId &&
event.getContent().membership == 'leave' && event.getContent().membership == 'leave' &&
event.getType() == 'm.room.member' event.getType() == 'm.room.member'
" "
@ -34,7 +34,7 @@
<div <div
class="messageJoin" class="messageJoin"
v-if=" v-if="
event.event.state_key != myAddress && event.event.state_key != myUserId &&
event.getContent().membership == 'invite' && event.getContent().membership == 'invite' &&
event.getType() == 'm.room.member' event.getType() == 'm.room.member'
" "
@ -44,7 +44,7 @@
<div <div
v-else-if=" v-else-if="
event.getSender() != myAddress && event.getSender() != myUserId &&
event.getType() == 'm.room.message' event.getType() == 'm.room.message'
" "
> >
@ -108,46 +108,50 @@ export default {
}), }),
computed: { computed: {
room() { myUserId() {
return this.$store.state.currentRoom; return this.$store.state.auth.user.user_id;
}, },
roomId() { roomId() {
return this.room != null ? this.room.roomId : null; return this.$matrix.currentRoomId;
}, },
sendButtonDisabled() { sendButtonDisabled() {
return this.currentInput.length == 0; return this.currentInput.length == 0;
}, },
myAddress() {
// TODO
return "@npex2:neo.keanu.im";
},
}, },
watch: { watch: {
room() { roomId() {
console.log("Chat: Current room changed"); console.log("Chat: Current room changed");
// Clear old events // Clear old events
this.events = []; this.events = [];
// Remove all old room listeners // Remove all old room listeners
this.$matrixClient.removeAllListeners("Room.timeline"); this.$matrix.off("Room.timeline", this.onEvent);
this.$matrixClient.removeAllListeners("RoomMember.typing"); this.$matrix.off("RoomMember.typing", this.onUserTyping);
this.contactIsTyping = false; this.contactIsTyping = false;
if (!this.room) { if (!this.roomId) {
return; // no room return; // no room
} }
const room = this.$matrix.getRoom(this.roomId);
if (!room) {
return; // Not found
}
this.room.timeline.forEach((event) => { room.timeline.forEach((event) => {
this.handleMatrixEvent(event); this.handleMatrixEvent(event);
}); });
// Add event listener for this room // Add event listener for this room
this.$matrixClient.on( this.$matrix.on("Room.timeline", this.onEvent);
"Room.timeline", this.$matrix.on("RoomMember.typing", this.onUserTyping);
function (event, ignoredroom, ignoredtoStartOfTimeline) { },
},
methods: {
onEvent(event) {
if (event.getRoomId() !== this.roomId) { if (event.getRoomId() !== this.roomId) {
return; // Not for this room return; // Not for this room
} }
@ -155,8 +159,7 @@ export default {
this.$nextTick(function () { this.$nextTick(function () {
const container = this.$refs.chatContainer; const container = this.$refs.chatContainer;
if (container.children.length > 0) { if (container.children.length > 0) {
const lastChild = const lastChild = container.children[container.children.length - 1];
container.children[container.children.length - 1];
console.log("Scroll into view", lastChild); console.log("Scroll into view", lastChild);
window.requestAnimationFrame(() => { window.requestAnimationFrame(() => {
lastChild.scrollIntoView({ lastChild.scrollIntoView({
@ -168,21 +171,13 @@ export default {
} }
}); });
} }
}.bind(this)
);
this.$matrixClient.on(
"RoomMember.typing",
function (event, member) {
if (member.userId == this.contactAddress) {
this.contactIsTyping = member.typing;
}
}.bind(this)
);
},
}, },
methods: { onUserTyping(event) {
//TODO
console.log("Typing:", event);
},
/** /**
* Handle a matrix event. Add it to our array if valid type. * Handle a matrix event. Add it to our array if valid type.
* @returns True if the event was added, false otherwise. * @returns True if the event was added, false otherwise.

View file

@ -1,8 +1,8 @@
<template> <template>
<v-list flat> <v-list flat>
<v-subheader>ROOMS</v-subheader> <v-subheader>ROOMS</v-subheader>
<v-list-item-group v-model="currentRoomIndex" color="primary"> <v-list-item-group v-model="currentRoomId" color="primary">
<v-list-item v-for="(room, i) in rooms" :key="i"> <v-list-item v-for="room in $matrix.rooms" :key="room.roomId" :value="room.roomId">
<v-list-item-icon> <v-list-item-icon>
<v-icon v-text="room.icon"></v-icon> <v-icon v-text="room.icon"></v-icon>
</v-list-item-icon> </v-list-item-icon>
@ -11,12 +11,11 @@
v-text="room.summary.info.title" v-text="room.summary.info.title"
></v-list-item-title> ></v-list-item-title>
<v-list-item-content <v-list-item-content
>Topic: {{ room.summary.info.desc }}</v-list-item-content >Topic: {{ room.topic }}</v-list-item-content
> >
</v-list-item-content> </v-list-item-content>
</v-list-item> </v-list-item>
</v-list-item-group> </v-list-item-group>
<v-btn @click="reloadRooms">Refresh</v-btn>
</v-list> </v-list>
</template> </template>
@ -25,68 +24,12 @@ export default {
name: "RoomList", name: "RoomList",
data: () => ({ data: () => ({
rooms: [], currentRoomId: -1,
currentRoomIndex: -1,
}), }),
mounted() {
this.reloadRooms();
this.$matrixClient.on("Room.name", this.onRoomNameChanged);
this.$matrixClient.on("event", this.onEvent);
},
destroyed() {
this.$matrixClient.off("Room.name", this.onRoomNameChanged);
this.$matrixClient.off("event", this.onEvent);
},
watch: { watch: {
currentRoomIndex() { currentRoomId() {
var currentRoom = this.$matrix.setCurrentRoomId(this.currentRoomId);
this.currentRoomIndex >= 0 && this.currentRoomIndex < this.rooms.length
? this.rooms[this.currentRoomIndex]
: null;
this.$emit("onCurrentRoomChanged", currentRoom);
},
},
methods: {
onEvent(event) {
if (event.getType() == "m.room.topic") {
const room = this.rooms.find((r) => {
return (r.roomId == event.getRoomId());
})
if (room) {
room.summary.info.desc = event.getContent().topic;
}
return;
}
const allowedEvents = [
"m.room.message"
];
if (allowedEvents.includes(event.getType())) {
// TODO - find "last message"...
}
},
onRoomNameChanged(room) {
console.log("New name for room: " + room.name);
},
reloadRooms() {
var rooms = this.$matrixClient.getVisibleRooms();
rooms.forEach((room) => {
console.log("Room", room);
});
this.rooms = rooms;
// Default to first room if available
if (this.rooms.length > 0 && this.currentRoomIndex == -1) {
this.currentRoomIndex = 0;
} else if (this.rooms.length == 0) {
this.currentRoomIndex = -1;
}
}, },
}, },
}; };

View file

@ -9,6 +9,8 @@ import 'material-design-icons-iconfont/dist/material-design-icons.css'
Vue.config.productionTip = false Vue.config.productionTip = false
Vue.use(matrix, {store: store});
new Vue({ new Vue({
vuetify, vuetify,
router, router,

View file

@ -1,6 +1,5 @@
global.Olm = require("olm"); global.Olm = require("olm");
import sdk from "matrix-js-sdk"; import sdk from "matrix-js-sdk";
import Vue from 'vue';
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;
@ -8,24 +7,80 @@ sdk.setCryptoStoreFactory(
() => new LocalStorageCryptoStore(window.localStorage) () => new LocalStorageCryptoStore(window.localStorage)
); );
class MatrixService { export default {
constructor() { install(Vue, options) {
this.matrixClient = null; if (!options || !options.store) {
throw new Error('Please initialise plugin with a Vuex store.')
} }
const store = options.store;
const matrixService = new Vue({
store,
data() {
return {
matrixClient: null,
rooms: [],
}
},
mounted() {
console.log("Matrix service mounted");
},
computed: {
ready() {
return this.matrixClient != null;
},
currentUser() {
return this.$store.state.auth.user;
},
currentRoomId() {
return this.$store.state.currentRoomId;
},
currentRoom() {
return this.getRoom(this.currentRoomId);
},
},
methods: {
login(user) { login(user) {
const tempMatrixClient = sdk.createClient(user.server); const tempMatrixClient = sdk.createClient(user.server);
var retUser;
return tempMatrixClient return tempMatrixClient
.login("m.login.password", { user: user.username, password: user.password, type: "m.login.password" }) .login("m.login.password", { user: user.username, password: user.password, type: "m.login.password" })
.then((response) => { .then((response) => {
localStorage.setItem('user', JSON.stringify(response)); localStorage.setItem('user', JSON.stringify(response));
return response; return response;
}) })
} .then(user => {
retUser = user;
return this.getMatrixClient(user);
})
.then(() => {
// Ready to use! Start by loading rooms.
this.initClient();
return retUser;
})
},
logout() { logout() {
if (this.matrixClient) {
this.removeMatrixClientListeners(this.matrixClient);
this.matrixClient.stopClient();
this.matrixClient = null;
localStorage.removeItem('user'); localStorage.removeItem('user');
} }
this.$store.commit("setCurrentRoomId", null);
},
initClient() {
this.reloadRooms();
},
async getMatrixClient(user) { async getMatrixClient(user) {
const matrixStore = new sdk.MemoryStore(window.localStorage); const matrixStore = new sdk.MemoryStore(window.localStorage);
@ -46,13 +101,16 @@ class MatrixService {
deviceId: user.device_id, deviceId: user.device_id,
accessToken: user.access_token accessToken: user.access_token
} }
user.matrixClient = sdk.createClient(opts); this.matrixClient = sdk.createClient(opts);
return user.matrixClient return this.matrixClient
.initCrypto() .initCrypto()
.then(() => { .then(() => {
console.log("Crypto initialized"); console.log("Crypto initialized");
user.matrixClient.startClient();
return user.matrixClient; this.addMatrixClientListeners(this.matrixClient);
this.matrixClient.startClient();
return this.matrixClient;
}) })
.then(matrixClient => { .then(matrixClient => {
if (matrixClient.isInitialSyncComplete()) { if (matrixClient.isInitialSyncComplete()) {
@ -74,22 +132,59 @@ class MatrixService {
}); });
} }
}); });
},
addMatrixClientListeners(client) {
if (client) {
client.on("event", this.onEvent);
}
},
removeMatrixClientListeners(client) {
if (client) {
client.off("event", this.onEvent);
}
},
onEvent(event) {
if (event.getType() == "m.room.topic") {
const room = this.matrixClient.getRoom(event.getRoomId());
if (room) {
Vue.set(room, "topic", event.getContent().topic);
}
return;
}
},
reloadRooms() {
this.rooms = this.matrixClient.getVisibleRooms();
},
setCurrentRoomId(roomId) {
this.$store.commit("setCurrentRoomId", roomId);
},
getRoom(roomId) {
if (this.matrixClient) {
return this.matrixClient.getRoom(roomId);
}
return null;
},
on(event, handler) {
if (this.matrixClient) {
this.matrixClient.on(event, handler);
}
},
off(event, handler) {
if (this.matrixClient) {
this.matrixClient.off(event, handler);
} }
} }
const matrixService = new MatrixService();
const matrixServicePlugin = {}
matrixServicePlugin.install = function (Vue, ignoredOptions) {
Vue.prototype.$matrix = matrixService;
Vue.mixin({
mounted: function () {
// Store the VUE instance root in our own $root variable.
matrixService.$root = this.$root;
} }
}) })
Vue.prototype.$matrix = matrixService;
}
} }
Vue.use(matrixServicePlugin);
export default MatrixService;

View file

@ -7,11 +7,11 @@ Vue.use(Vuex)
export default new Vuex.Store({ export default new Vuex.Store({
state: { state: {
currentRoom: null currentRoomId: null
}, },
mutations: { mutations: {
setCurrentRoom(state, room) { setCurrentRoomId(state, roomId) {
state.currentRoom = room; state.currentRoomId = roomId;
}, },
}, },
actions: { actions: {