From c57d32c450f0cf44ad3f2bd09495387f0a0b90bd Mon Sep 17 00:00:00 2001 From: adb Date: Wed, 10 Mar 2021 01:50:38 +0100 Subject: [PATCH] add matrixHandler and cookieHandler --- src/lib/cookieHandler.js | 36 ++++++++++++++++++++++++++++++++++++ src/lib/matrixHandler.js | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 src/lib/cookieHandler.js create mode 100644 src/lib/matrixHandler.js diff --git a/src/lib/cookieHandler.js b/src/lib/cookieHandler.js new file mode 100644 index 0000000..62fa832 --- /dev/null +++ b/src/lib/cookieHandler.js @@ -0,0 +1,36 @@ +export class cookieHandler { + constructor(expires) { + this.expires = expires; + this.reload(); + } + getCookie(key){ + let cookie = this.cookies.find(cookie => cookie.split('=')[0] === key); + return cookie ? cookie.split('=')[1] : false; + } + setCookie(object){ + object.forEach((value, key) => { + this.cookies[key] = value; + }) + } + parseCookie(string){ + let cookies; + string.replace(/ /g, '').split(';').forEach(cookie => { + let arr = cookie.split('='); + cookies[arr[0]] = arr[1]; + }) + return cookies; + } + reload(){ + this.cookies = this.parseCookie(document.cookie) + } + store(){ + document.cookie = this.toString(); + } + toString(cookies = this.cookies){ + let string = ''; + cookies.forEach((value, key) => { + string += `${key}=${value}; `; + }) + return string; + } +} diff --git a/src/lib/matrixHandler.js b/src/lib/matrixHandler.js new file mode 100644 index 0000000..f7f5c45 --- /dev/null +++ b/src/lib/matrixHandler.js @@ -0,0 +1,38 @@ +import matrix from 'matrix-js-sdk'; +import {cookieHandler} from '@/lib/cookieHandler.js'; + +export class MatrixHandler { + constructor(clientDisplayName = 'matrix-chat') { + this.clientDisplayName = clientDisplayName; + this.accessToken; + let cookie = new cookieHandler().getCookie(); + this.client = undefined; + if (cookie.baseUrl && cookie.accessToken && cookie.userId) + this.tokenLogin(cookie.baseUrl, cookie.accessToken, cookie.userId); + } + login(user, password, baseUrl, onError){ + if (this.client){ console.log('there is already an active session'); return; } + this.client = new matrix.createClient({ + baseUrl: baseUrl + }); + this.client.login('m.login.password', { + user: user, + password: password, + initial_device_display_name: this.clientDisplayName, + }).then((response) => { + console.log(`access token => ${response.access_token}`); + if (response.error) { + console.log(`login error => ${response.error}`); + onError(response.error); + } + }) + } + tokenLogin(baseUrl, accessToken, userId){ + if (this.client){ console.log('there is already an active session'); return; } + this.client = new matrix.createClient({baseUrl, accessToken, userId}); + this.client.startClient(); + this.client.once('sync', (state) => { + console.log(state); + }); + } +} \ No newline at end of file