From 289a230207a2e1651c0ce6b732aba4b04ff77953 Mon Sep 17 00:00:00 2001 From: adb Date: Wed, 7 Apr 2021 23:16:51 +0200 Subject: [PATCH] add NotificationHandler and listen to pushEvents --- src/lib/NotificationHandler.js | 28 ++++++++++++++++++++++++++++ src/lib/matrixHandler.js | 15 ++++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 src/lib/NotificationHandler.js diff --git a/src/lib/NotificationHandler.js b/src/lib/NotificationHandler.js new file mode 100644 index 0000000..3d17dfe --- /dev/null +++ b/src/lib/NotificationHandler.js @@ -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}`); + } +} \ No newline at end of file diff --git a/src/lib/matrixHandler.js b/src/lib/matrixHandler.js index 7a39894..3bd68a0 100644 --- a/src/lib/matrixHandler.js +++ b/src/lib/matrixHandler.js @@ -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){