add NotificationHandler and listen to pushEvents

matrix-chat-native
adb 3 years ago
parent fda133486a
commit 289a230207

@ -0,0 +1,28 @@
import {getMxcFromUserId, getAvatarUrl} from '@/lib/getMxc';
import {calcUserName} from '@/lib/matrixUtils';
import {getRoom} from '@/lib/matrixUtils';
import {router} from '@/router';
export class NotificationHandler{
constructor() {
this.activateNotification();
}
async activateNotification(){
if (!window.Notification){
console.log('notifications are unsupported')
return false;
}
if (Notification.permission === 'granted') return true;
return await Notification.requestPermission()
.then(permission => {return permission === 'granted'});
}
showNotification(event){
if (Notification.permission !== 'granted') return false;
console.log(event);
let mxc = getMxcFromUserId(event.sender);
new Notification(`${calcUserName(event.sender)} in ${getRoom(event.room_id).name}`, {
body: event.content.body,
icon: mxc?getAvatarUrl(mxc):undefined
}).onclick = ()=>router.push(`/rooms/${event.room_id}`);
}
}

@ -1,4 +1,5 @@
import matrix from 'matrix-js-sdk';
import {NotificationHandler} from "@/lib/NotificationHandler";
export class MatrixHandler {
constructor(clientDisplayName = 'matrix-chat') {
@ -9,6 +10,7 @@ export class MatrixHandler {
this.loading = undefined;
this.user = undefined;
this.baseUrl = undefined;
this.notify = new NotificationHandler();
}
login(user, password, baseUrl, onError, callback = ()=>{}){
if (this.client){ console.log('there is already an active session'); return; }
@ -57,15 +59,22 @@ export class MatrixHandler {
await this.client.stopClient();
this.client = undefined;
}
startSync(callback = ()=>{}){
async startSync(callback = ()=>{}){
this.loading = true;
this.client.startClient();
await this.client.startClient();
this.client.once('sync', (state) => {
console.log(state);
this.rooms = this.client.getRooms();
console.log(this.rooms)
this.loading = false;
callback();
this.listenToPushEvents()
});
}
listenToPushEvents(){
this.client.on('event', event => {
if (this.client.getPushActionsForEvent(event).notify){
this.notify.showNotification(event.event);
}
});
}
async sendEvent({content, type}, roomId, replyTo = undefined){

Loading…
Cancel
Save