Merge branch 'restructure'

# Conflicts:
#	src/components/chatInformation.vue
add-admin-interface
adb 4 years ago
commit e52ea62fe3

@ -0,0 +1,35 @@
module.exports = {
"env": {
"browser": true,
"es6": true
},
"extends": [
"eslint:recommended",
"plugin:vue/essential"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"vue"
],
"rules": {
"indent": [
"warn",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"warn",
"single"
]
}
}

@ -9,47 +9,32 @@
}, },
"dependencies": { "dependencies": {
"@modular-matrix/parse-mxc": "^1.0.1", "@modular-matrix/parse-mxc": "^1.0.1",
"@vue-polkadot/vue-identicon": "^0.0.8",
"core-js": "^3.6.5", "core-js": "^3.6.5",
"jdenticon": "^3.1.0",
"matrix-js-sdk": "^9.1.0", "matrix-js-sdk": "^9.1.0",
"sass": "^1.29.0", "sass": "^1.29.0",
"sass-loader": "^10.1.0",
"v-emoji-picker": "^2.3.1", "v-emoji-picker": "^2.3.1",
"vue": "^2.6.11", "vue": "^2.6.11",
"ws": "^7.3.1" "ws": "^7.3.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.13.0",
"@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3",
"@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-pwa": "~4.5.0",
"@vue/cli-service": "~4.5.0", "@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"babel": "^6.23.0",
"babel-cli": "^6.18.0",
"babel-eslint": "^10.1.0", "babel-eslint": "^10.1.0",
"electron": "^11.0.1", "electron": "^11.0.1",
"eslint": "^7.14.0", "eslint": "^6.7.2",
"eslint-config-airbnb-base": "^14.2.1", "eslint-plugin-vue": "^7.5.0",
"eslint-config-standard": "^16.0.2", "node-sass": "^5.0.0",
"eslint-plugin-import": "^2.22.1", "sass-loader": "^10.1.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-vue": "^7.2.0",
"vue-router": "^3.4.9", "vue-router": "^3.4.9",
"vue-template-compiler": "^2.6.11" "vue-template-compiler": "^2.6.11"
}, }
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
} }

@ -6,27 +6,31 @@
<div class="picBoxBig"><div class="placeholderBig">{{room.name.substr(0,2)}}</div></div> <div class="picBoxBig"><div class="placeholderBig">{{room.name.substr(0,2)}}</div></div>
<div class="roomInformation"> <div class="roomInformation">
<div class="roomName">{{room.name}}</div> <div class="roomName">{{room.name}}</div>
<div class="users">{{room.members.length}} members</div> <div class="users">{{getMembers().length}} members</div>
</div> </div>
</div> </div>
<h2 v-if="room.members.length !== 0">members:</h2> <h2 v-if="getMembers().length !== 0">members:</h2>
<div v-for="member in room.members.slice(0,20)" :key="member.sender" class="contentBox" :title="member.sender"> <div v-for="member in getMembers().slice(0,20)" :key="member" class="contentBox" :title="member">
<userThumbnail :mxcURL="member.content.avatar_url" :userId="member.sender" :username="member.content.displayname" <userThumbnail
width="64" height="64" resizeMethod="scale" class="userThumbnail" /> :mxcURL="getUser(member).avatarUrl"
:fallback="getUser(member).displayName"
class="userThumbnail" :size="3"
/>
<div class="information"> <div class="information">
<div class="userName">{{member.content.displayname?member.content.displayname:member.sender}}</div> <div class="userName">{{getUser(member).displayName || member}}</div>
<div class="status"></div> <div class="status">{{getStatus(getUser(member))}}</div>
</div> </div>
</div> </div>
<p v-if="room.members.length>20">and {{room.members.length-20}} other members</p> <p v-if="getMembers().length>20">and {{getMembers().length-20}} other members</p>
</div> </div>
</div> </div>
<icon class="closeBtn" onclick="this.parentNode.style.display = 'none'" ic="./sym/ic_close_white_24px.svg" /> <icon class="closeBtn" @click.native="closeChatInfo()" ic="./sym/ic_close_white_24px.svg" />
</div> </div>
</template> </template>
<script> <script>
import icon from './icon.vue'; import icon from './icon.vue';
import userThumbnail from './userThumbnail'; import userThumbnail from './userThumbnail';
import {matrix} from "@/main";
export default { export default {
name: "chatInformation", name: "chatInformation",
@ -35,7 +39,18 @@ export default {
userThumbnail userThumbnail
}, },
props:{ props:{
room: {} room: {},
closeChatInfo: Function
},
methods: {
getUser(userId){
return matrix.client.getUser(userId);
},
getMembers(){
return Object.keys(this.room.currentState.members)
},
getStatus(){
}
} }
} }
@ -53,7 +68,6 @@ export default {
box-shadow: 6px 6px 20px #111; box-shadow: 6px 6px 20px #111;
border-radius: 1rem; border-radius: 1rem;
text-align: center; text-align: center;
display: none;
} }
@media (max-width: 30rem) { @media (max-width: 30rem) {
#chatInformation{ #chatInformation{
@ -125,7 +139,8 @@ export default {
position: absolute; position: absolute;
left: 0; left: 0;
top: 0; top: 0;
background-color: #42a7b9; width: 3rem;
height: 3rem;
} }
.information{ .information{
position: absolute; position: absolute;

@ -1,11 +1,9 @@
<template> <template>
<div class="messageContainer"> <div :class="type==='send'?'messageSend':'messageReceive'" class="message">
<div :class=msgClass class="message" :title="time">
<div v-html="solveTextLinks(msg.replace(/</g, '&lt') <div v-html="solveTextLinks(msg.replace(/</g, '&lt')
.replace(/>/g, '&gt'))"></div> .replace(/>/g, '&gt'))"></div>
<div class="time">{{time}}</div> <div class="time">{{time}}</div>
</div> </div>
</div>
</template> </template>
<script> <script>
@ -14,7 +12,7 @@ export default {
props: { props: {
msg: String, msg: String,
time: String, time: String,
msgClass: String type: String
}, },
methods:{ methods:{
solveTextLinks(text){ solveTextLinks(text){
@ -34,31 +32,26 @@ export default {
</script> </script>
<style scoped> <style scoped>
.messageContainer{
position: relative;
margin-top: 0.25rem;
width: calc(100% - 2rem);
left: 1rem;
}
.message{ .message{
position: relative; position: relative;
width: max-content; width: max-content;
min-width: 2rem; min-width: 2rem;
max-width: calc(100% - 3rem); max-width: calc(100% - 5rem);
padding: 0.7rem 1rem 0.45rem 1rem; padding: 0.7rem 1rem 0.45rem 1rem;
right: 0;
background-color: #42a7b9; background-color: #42a7b9;
border-radius: 1rem 1rem 0 1rem; border-radius: 1rem 1rem 0 1rem;
text-align: left; text-align: left;
word-break: break-word; word-break: break-word;
white-space: pre-line; white-space: pre-line;
margin-top: 0.25rem;
} }
.messageReceive{ .messageReceive{
background-color: #42b983; background-color: #42b983;
border-radius: 1rem 1rem 1rem 0; border-radius: 1rem 1rem 1rem 0;
} }
.messageSend{ .messageSend{
margin-left:auto; margin-right:0; margin-left:auto;
margin-right:0;
background-color: #42a7b9; background-color: #42a7b9;
border-radius: 1rem 1rem 0 1rem; border-radius: 1rem 1rem 0 1rem;
} }

@ -1,44 +1,55 @@
<template> <template>
<div class="newMessageBanner"> <form class="newMessageBanner" ref="newMessageBanner" v-on:submit.prevent="sendMessage()">
<form v-on:submit.prevent="sendMessage()">
<label for="newMessageInput"></label> <label for="newMessageInput"></label>
<textarea @keyup.enter.exact="sendMessage()" @input="resizeMessageBanner()" ref="newMessageInput" id="newMessageInput" class="newMessageInput" <textarea
autocomplete="off" rows="1" placeholder="type a message ..." v-model="msg.content.body" /> @keyup.enter.exact="sendMessage()"
<icon type="submit" title="press enter to submit" id="sendMessageBtn" @input="resizeMessageBanner()"
ic="./sym/ic_send_white_24px.svg" /> v-model="msg.content.body"
ref="newMessageInput"
id="newMessageInput"
class="newMessageInput"
autocomplete="off"
rows="1"
placeholder="type a message ..."
/>
<icon
type="submit"
title="press enter to submit"
class="sendMessageBtn"
ic="./sym/ic_send_white_24px.svg"
/>
</form> </form>
</div>
</template> </template>
<script> <script>
import icon from '@/components/icon.vue'; import icon from '@/components/icon.vue';
import main from '@/main.js'; import {matrix} from '@/main.js';
import matrix from '@/matrix.js';
export default { export default {
name: "newMessage", name: "newMessage",
components: { components: {
icon icon
}, },
props: {
onResize: Function,
roomId: String
},
methods: { methods: {
sendMessage(){ async sendMessage(){
if (this.msg.content.body !== "") { if (this.msg.content.body !== "") {
let msgSend = Object.assign({}, this.msg) let msgSend = Object.assign({}, this.msg);
matrix.methods.sendMessage(msgSend) await matrix.sendEvent(msgSend, this.roomId);
this.msg.content.body = "" this.msg.content.body = "";
document.getElementById("messagesContainer").style.height = "calc(100% - 7rem)" let id = this.$refs.newMessageInput;
document.getElementById("newMessageInput").style.height = "1.25rem" id.style.height = "1.25rem";
//let msgContainer = document.getElementById("messagesContainer") this.onResize(id.parentElement.clientHeight);
//msgContainer.scrollTo(0, msgContainer.scrollHeight)
} }
}, },
resizeMessageBanner(){ resizeMessageBanner(){
let id = this.$refs.newMessageInput let id = this.$refs.newMessageInput;
id.style.height = '1.25rem' id.style.height = '1.25rem';
id.style.height = `${id.scrollHeight}px` id.style.height = `${id.scrollHeight}px`;
let msgContainer = document.getElementById("messagesContainer") this.onResize(id.parentElement.clientHeight);
msgContainer.style.height
= `calc(100% - ${id.parentElement.clientHeight}px - 3rem)`
}, },
toggleEmojiPicker() { toggleEmojiPicker() {
this.showEmojiPicker = !this.showEmojiPicker; this.showEmojiPicker = !this.showEmojiPicker;
@ -56,8 +67,6 @@ export default {
msgtype: "m.text" msgtype: "m.text"
} }
}, },
chatroom: main.data().chatroom,
session: matrix.data().session,
showEmojiPicker: false showEmojiPicker: false
} }
} }
@ -71,16 +80,16 @@ export default {
left: 0; left: 0;
width: 100%; width: 100%;
height: min-content; height: min-content;
min-height: 4rem; min-height: 3.5rem;
background-color: #1d1d1d; background-color: #1d1d1d;
border-radius: 1rem 1rem 0 0; border-radius: 1rem 1rem 0 0;
} }
.newMessageInput{ .newMessageInput{
position: relative; position: relative;
margin-top: 1.5rem; margin-top: 1.25rem;
margin-bottom: 1rem; margin-bottom: 0.75rem;
left: 2rem; left: 2rem;
min-height: 1.25rem; min-height: 1.5rem;
max-height: 10rem; max-height: 10rem;
width: calc(100% - 7rem); width: calc(100% - 7rem);
height: 1.25rem; height: 1.25rem;
@ -94,9 +103,10 @@ export default {
vertical-align: middle; vertical-align: middle;
font-family: Avenir, Helvetica, Arial, sans-serif; font-family: Avenir, Helvetica, Arial, sans-serif;
} }
#sendMessageBtn{ .sendMessageBtn{
position: absolute; position: absolute;
right: 1rem; right: 1rem;
bottom: 0.5rem; bottom: 0.25rem;
background-color: unset;
} }
</style> </style>

@ -0,0 +1,133 @@
<template>
<div class="timeline">
<div class="timeGroup"
v-for="timeGroup in splitArray(timeline,obj => getDate(obj.event.origin_server_ts),obj => obj.event)"
:key="timeGroup[0].origin_server_ts"
>
<div class="time">{{getDate(timeGroup[0].origin_server_ts)}}</div>
<div class="eventGroup" v-for="group in splitArray(timeGroup, obj => obj.sender)" :key="group[0].origin_server_ts">
<div class="thumbnailContainer">
<div class="filler"></div>
<userThumbnail
v-if="group[0].sender !== user && groupTimeline"
:fallback="group[0].sender"
class="userThumbnail"
:mxcURL="getUser(group[0].sender).avatarUrl"
:size="2"
:title="group[0].sender"
/>
</div>
<div :class="groupTimeline?'indent username':'username'"
v-if="group[0].sender !== user && groupTimeline">{{getUser(group[0].sender).displayName || group[0].sender}}
</div>
<div :class="groupTimeline?'indent event':'event'"
v-for="event in group" :key="event.origin_server_ts"
:title="`${group[0].sender} at ${getTime(event.origin_server_ts)}`"
>
<message v-if="event.content.msgtype==='m.text'"
:type="event.sender === user?'send':'receive'"
:msg=event.content.body :time=getTime(event.origin_server_ts)
/>
<div v-else-if="event.type==='m.room.member'" class="info">{{membershipEvents[event.content.membership]}}</div>
<div v-else class="info">unknown event</div>
</div>
</div>
</div>
</div>
</template>
<script>
import message from "@/components/message";
import userThumbnail from "@/components/userThumbnail";
import {matrix} from "@/main";
import splitArray from "@/lib/splitArray";
import {getDate, getTime} from "@/lib/getTimeStrings";
export default {
name: 'eventGroup',
components: {
message,
userThumbnail
},
props: {
timeline: Array,
user: String,
groupTimeline: Boolean
},
methods: {
getUser(userId) {
return matrix.client.getUser(userId);
},
splitArray,
getDate,
getTime
},
data(){
return {
membershipEvents:{
invite: 'was invented',
join: 'joined the room',
leave: 'left the room',
ban: 'was banned'
}
}
}
}
</script>
<style scoped lang="scss">
.timeline{
margin-top: 0.5rem;
margin-bottom: 0.5rem;
.timeGroup {
.time {
top: 0.25rem;
position: sticky;
z-index: 100;
background-color: #2d2d2d;
padding: 0.5rem;
border-radius: 0.5rem;
width: fit-content;
left: 50%;
transform: translate(-50%, 0);
margin-top: 0.5rem;
}
.eventGroup {
position: relative;
width: calc(100% - 1rem);
height: fit-content;
margin-top: 0.75rem;
margin-left: 0.5rem;
margin-right: 0.5rem;
.thumbnailContainer {
position: absolute;
top: 0;
left: 0;
height: 100%;
.filler {
height: calc(100% - 2rem);
}
.userThumbnail {
position: sticky;
bottom: 0.5rem;
width: 2rem;
height: 2rem;
}
}
.username{
margin-left: 1rem;
}
.event{
.info{
font-style: italic;
margin-top: 0.5rem;
margin-bottom: 0.5rem;
}
}
.indent{
margin-left: 2.5rem;
}
}
}
}
</style>

@ -1,34 +1,44 @@
<template> <template>
<div class="topBanner"> <div class="topBanner">
<div> <div>
<icon @click.native="session.currentRoom = undefined" class="smallIcon" id="icon-arrow" ic="./sym/arrow_back-24px.svg" /> <icon @click.native="closeChat()" class="smallIcon" id="icon-arrow" ic="./sym/arrow_back-24px.svg" />
<div @click="showChatInfo()" class="smallIcon" id="picTop">{{session.currentRoom.name.substr(0,2)}}</div> <userThumbnail @click.native="openChatInfo()" class="userThumbnail"
:mxcURL="getUrl()" :fallback="room.roomId" :size="3"/>
<div id="container"> <div id="container">
<div id="chatName">{{session.currentRoom.name}}</div> <div id="chatName">{{room.name}}</div>
<div id="users">{{session.currentRoom.members.length}} members</div> <div id="users">{{Object.keys(room.currentState.members).length}} members</div>
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<script> <script>
import icon from '@/components/icon.vue'; import icon from '@/components/icon.vue';
import main from '@/main.js'; import {matrix} from "@/main";
import matrix from '@/matrix.js'; import userThumbnail from "@/components/userThumbnail";
import sdk from 'matrix-js-sdk'
export default { export default {
name: "topBanner", name: "topBanner",
components:{ components:{
icon, icon,
userThumbnail
}, },
methods:{ props:{
showChatInfo(){ room: [Object, undefined],
document.getElementById("chatInformation").style.display = 'block'; closeChat: Function,
} openChatInfo: Function
}, },
data(){ data(){
return { return {
chatroom: main.data().chatroom, }
session: matrix.data().session },
methods: {
getRoom(roomId) {
return matrix.client.getRoom(roomId);
},
getUrl(){
let avatarState = this.room.getLiveTimeline().getState(sdk.EventTimeline.FORWARDS).getStateEvents("m.room.avatar");
return avatarState.length>0?avatarState[avatarState.length-1].getContent().url:undefined;
} }
} }
} }
@ -39,7 +49,7 @@ export default {
top: 0; top: 0;
left: 0; left: 0;
width: 100%; width: 100%;
height: 3rem; height: 3.5rem;
background-color: #1d1d1d; background-color: #1d1d1d;
} }
.smallIcon{ .smallIcon{
@ -61,10 +71,12 @@ export default {
background-color: unset; background-color: unset;
box-shadow: none; box-shadow: none;
} }
#picTop{ .userThumbnail{
position: absolute; position: absolute;
top: 0.25rem;
left: 3.5rem; left: 3.5rem;
background-color: #42a7b9; width: 3rem;
height: 3rem;
} }
#container{ #container{
position: absolute; position: absolute;

@ -1,46 +1,47 @@
<template> <template>
<img v-if="mxcURL" :src="thumbnailUrl()" class="userThumbnail" /> <img v-if="mxcURL" :src="thumbnailUrl()" class="userThumbnail image"/>
<div v-else class="userThumbnail"> <Identicon v-else :value="fallback" :theme="'jdenticon'" :size="this.getFontSize()*this.size" class="userThumbnail identicon"/>
<p>{{username?username.substr(0,2):userId.substr(1,2)}}</p>
</div>
</template> </template>
<script> <script>
import parseMXC from '@modular-matrix/parse-mxc'; import parseMXC from '@modular-matrix/parse-mxc';
import matrix from '@/matrix.js'; import {matrix} from "@/main";
import Identicon from '@vue-polkadot/vue-identicon';
export default { export default {
name: "userThumbnail.vue", name: "userThumbnail.vue",
components: {
Identicon
},
props: { props: {
mxcURL: String, mxcURL: String,
username: String, username: String,
userId: String, fallback: String,
width: Number, homeserver: String,
height: Number, size: Number
resizeMethod: String
}, },
methods: { methods: {
thumbnailUrl(){ thumbnailUrl(){
let mxc = parseMXC.parse(this.mxcURL); let mxc = parseMXC.parse(this.mxcURL);
return `${this.homeserver}/_matrix/media/v1/thumbnail/${mxc.homeserver}/${mxc.id}?width=${this.width}&height=${this.height}&method=${this.resizeMethod}`; return `${this.homeserver||matrix.baseUrl}/_matrix/media/v1/thumbnail/${
mxc.homeserver}/${mxc.id}?width=${this.imageSize}&height=${this.imageSize}&method=${this.resizeMethod}`;
},
getFontSize(){
return window.getComputedStyle(document.body,null).fontSize.split("px", 1)||16;
} }
}, },
data(){ data(){
return { return {
homeserver: matrix.data().session.baseUrl resizeMethod: 'scale',
imageSize: 128
} }
} }
} }
</script> </script>
<style scoped> <style scoped lang="scss">
.userThumbnail{ .userThumbnail{
background-color: #42a7b9; border-radius: 50%;
width: 3rem;
height: 3rem;
border-radius: 1.5rem;
}
img.userThumbnail{
background-color: unset; background-color: unset;
} }
</style> </style>

@ -0,0 +1,46 @@
export class cookieHandler {
constructor() {
this.cookies = {};
this.reload();
this.expires = undefined;
this.SameSite = 'Strict';
}
getCookies(){
return this.cookies;
}
setCookie(cookies){
Object.keys(cookies).forEach(key => {
this.cookies[key] = cookies[key];
})
}
parseCookie(string){
let cookies = {};
string.replace(/ /g, '').split(';').forEach(cookie => {
let arr = cookie.split('=');
cookies[arr[0]] = arr[1];
})
return cookies;
}
reload(){
if (document.cookie) this.cookies = this.parseCookie(document.cookie);
console.log('cookie loaded')
console.log(this.cookies);
}
store(){
Object.keys(this.cookies).forEach(key => {
document.cookie = `${key}=${this.cookies[key]}; expires=${this.expires}; SameSite=${this.SameSite}; Secure;`;
});
console.log('cookie stored');
console.log(this.cookies);
}
toString(cookies = this.cookies){
let string = '';
Object.keys(cookies).forEach(key => {
string += `${key}=${cookies[key]}; `;
})
return string;
}
setExpire(days){
this.expires = new Date(Date.now() + 86400 * 10000 * days);
}
}

@ -0,0 +1,10 @@
export function getTime(time) {
let date = new Date(time);
return `${date.getHours()}:${(date.getMinutes() < 10) ? '0' : ''}${date.getMinutes()}`;
}
export function getDate(time) {
let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
let date = new Date(time);
return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
}

@ -0,0 +1,75 @@
import matrix from 'matrix-js-sdk';
export class MatrixHandler {
constructor(clientDisplayName = 'matrix-chat') {
this.clientDisplayName = clientDisplayName;
this.accessToken;
this.client = undefined;
this.rooms = [];
this.loading = undefined;
this.user = undefined;
this.baseUrl = undefined;
}
login(user, password, baseUrl, onError, callback = ()=>{}){
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) => {
if (response.error) {
this.logout();
console.log(`login error => ${response.error}`);
onError(response.error);
}
if (response.access_token){
console.log(`access token => ${response.access_token}`);
callback(response.access_token);
this.user = user;
this.baseUrl = baseUrl;
this.startSync()
}
}).catch(error => {
this.logout();
console.log(error);
onError(error.toString());
})
}
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.user = userId;
this.baseUrl = baseUrl;
this.startSync();
}
logout(){
this.client.stopClient();
this.client = undefined;
}
startSync(callback = ()=>{}){
this.loading = true;
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.client.on('event', (event) => {
if (event.getType() === 'm.room.create') {
console.log(event)
}
})
}
async sendEvent(msg, roomId){
await this.client.sendEvent(roomId, msg.type, msg.content, '').then(() => {
console.log('message sent successfully');
}).catch((err) => {
console.log(`error while sending message => ${err}`);
});
}
}

@ -0,0 +1,10 @@
export default function splitArray(arr, key, get=obj=>obj){
let payload = [[]];
arr.forEach((obj, i) => {
let nextObj = arr[i+1];
payload[payload.length-1].push(get(obj));
if (!nextObj) return payload;
if (key(obj) !== key(nextObj)) payload.push([]);
})
return payload;
}

@ -1,81 +1,26 @@
import Vue from "vue" import Vue from 'vue'
import VueRouter from "vue-router" import VueRouter from 'vue-router'
import App from "./App.vue" import App from './App.vue'
import login from "./views/login.vue" import {router} from './router.js'
import chat from "./views/chat.vue" import {MatrixHandler} from './lib/matrixHandler.js'
import rooms from "./views/rooms.vue" import {cookieHandler} from './lib/cookieHandler.js';
Vue.config.productionTip = false Vue.config.productionTip = false;
Vue.use(VueRouter) Vue.use(VueRouter);
const router = new VueRouter({ export let matrix = new MatrixHandler();
routes: [
{
path: "/",
name: "home",
component: login
},
{
path: "/login",
name: "login",
component: login
},
{
path: "/chat/*",
name: "chat",
component: chat
},
{
path: "/rooms/*",
name: "room",
component: rooms
},
{
path: "/rooms",
name: "rooms",
component: rooms
}
]
})
let chatroom = { let cookie = new cookieHandler().getCookies();
name: "open chat", if (cookie && cookie.baseUrl && cookie.accessToken && cookie.userId) {
user: [], matrix.tokenLogin(cookie.baseUrl, cookie.accessToken, cookie.userId);
username: "you",
messages: []
}
export default {
data(){
return {
chatroom: chatroom
}
},
methods: {
error(msg){
show_error(msg)
},
router(route){router.push(route)}
}
} }
new Vue({ new Vue({
el: "#app", el: '#app',
router, router,
template: "<App/>", template: '<App/>',
components: {App}, components: {App},
data() { data() {
return { return {}
chatroom: chatroom
}
}
}).$mount("#app")
function element(id){ return document.getElementById(id)}
function show_error(msg) {
let error_style = element("errorBox").style
element("errorMessage").innerText = msg
error_style.display = "block"
error_style.animation = "slide-from-left alternate 0.2s"
setTimeout(() => {error_style.animation = ""}, 200)
} }
}).$mount('#app');

@ -1,8 +1,8 @@
import matrix from 'matrix-js-sdk'; /*import matrix from 'matrix-js-sdk';
import main from '@/main.js'; import main from '@/main.js';
// import Vue from 'vue'; // import Vue from 'vue';
let client = matrix.createClient({}); let client = undefined;
let session = { let session = {
user: '', user: '',
baseUrl: '', baseUrl: '',
@ -44,23 +44,12 @@ export default {
data() { data() {
return { return {
session, session,
client
}; };
}, },
methods: { methods: {
login() { login() {
if (session.accessToken !== '') {
main.methods.error('you are already logged in');
return;
} if (session.login.user === '') {
main.methods.error('username is empty');
return;
} if (session.login.password === '') {
main.methods.error('password is empty');
return;
} if (!(session.login.user.includes('@') && session.login.user.includes(':'))) {
main.methods.error('username is in wrong style');
return;
}
client = matrix.createClient({ client = matrix.createClient({
baseUrl: session.login.baseUrl baseUrl: session.login.baseUrl
}); });
@ -72,6 +61,7 @@ export default {
document.cookie = `accessToken=${response.access_token}`; document.cookie = `accessToken=${response.access_token}`;
document.cookie = `userId=${session.login.user}`; document.cookie = `userId=${session.login.user}`;
document.cookie = `baseUrl=${session.login.baseUrl}`; document.cookie = `baseUrl=${session.login.baseUrl}`;
document.cookie = `SameSite=Strict`;
document.cookie = `expires=${new Date(Date.now() + 86400 * 10 * 1000)}`; document.cookie = `expires=${new Date(Date.now() + 86400 * 10 * 1000)}`;
session = { session = {
user: session.login.user, user: session.login.user,
@ -86,12 +76,12 @@ export default {
console.log(`login error => ${response.error}`); console.log(`login error => ${response.error}`);
} }
window.location.href = '/#/rooms/'; window.location.href = '/#/rooms/';
window.location.reload(); window.location.reload();*/
/*client.startClient(); /*client.startClient();
client.once('sync', (state) => { client.once('sync', (state) => {
console.log(state); console.log(state);
});*/ });*/
}); /* });
}, },
logout(){ logout(){
document.cookie = `accessToken=`; document.cookie = `accessToken=`;
@ -124,7 +114,7 @@ function getCookie(key) {
return cookie ? cookie.split('=')[1] : false; return cookie ? cookie.split('=')[1] : false;
} }
client.on('event', (event) => { /*client.on('event', (event) => {
//console.log(event.getType()); //console.log(event.getType());
//console.log(event); //console.log(event);
if (event.getType() === 'm.room.name') { if (event.getType() === 'm.room.name') {
@ -175,4 +165,4 @@ client.on('Room.timeline', (event, room) => {
} else document.getElementById('scrollDown').style.display = 'block'; } else document.getElementById('scrollDown').style.display = 'block';
} }
} }
}); });*/

@ -0,0 +1,34 @@
import VueRouter from 'vue-router';
import login from '@/views/login';
import chat from '@/views/chat';
import rooms from '@/views/rooms';
export const router = new VueRouter({
routes: [
{
path: '/',
name: 'home',
component: login
},
{
path: '/login',
name: 'login',
component: login
},
{
path: '/chat/*',
name: 'chat',
component: chat
},
{
path: '/rooms/*',
name: 'room',
component: rooms
},
{
path: '/rooms',
name: 'rooms',
component: rooms
}
]
})

@ -1,103 +1,112 @@
<template> <template>
<div> <div>
<div ref="chatContainer" class="chatContainer">
<div @scroll="scrollHandler()" ref="msgContainer" id="messagesContainer" class="messagesContainer"> <div @scroll="scrollHandler()" ref="msgContainer" id="messagesContainer" class="messagesContainer">
<div id="messages" class="messages"> <div v-if="loadingStatus" @click="loadEvents()" class="loadMore">{{loadingStatus}}</div>
<p v-if="session.currentRoom.messages.length === 0" class="info">this room is empty</p> <p v-if="room.timeline.length === 0" class="chatInfo">this room is empty</p>
<div v-for="(message, i) in session.currentRoom.messages" :key="message.origin_server_ts"> <timeline :timeline="room.timeline" :group-timeline="isGroup()" :user="user"/>
<div v-if="i===0 || getDate(session.currentRoom.messages[i-1].origin_server_ts)!==getDate(message.origin_server_ts)"
style="margin-left: 2rem; margin-top: 1rem" class="info">{{getDate(message.origin_server_ts)}}
</div> </div>
<div v-if="(message.sender !== session.user) && (i===0 || session.currentRoom.messages[i-1].sender!==message.sender)" <icon v-if="showScrollBtn" @click.native="scrollToBottom()" id="scrollDown" ic="./sym/expand_more-black-24dp.svg" />
style="margin-left: 2rem; margin-top: 1rem">{{message.sender}}
</div> </div>
<message :msgClass="message.sender === session.user?'messageSend':'messageReceive'" <newMessage :onResize="height=>resize(height)" :roomId="room.roomId"/>
:msg=message.content.body :time=getTime(message.origin_server_ts) /> <topBanner :room="room" :close-chat="()=>closeChat()" :open-chat-info="()=>openChatInfo()"/>
</div>
</div>
</div>
<newMessage />
<icon v-if="showScrollBtn" v-on:click.native="scrollToBottom()" id="scrollDown" ic="./sym/expand_more-black-24dp.svg" />
<topBanner />
</div> </div>
</template> </template>
<script> <script>
import message from '@/components/message.vue';
import newMessage from '@/components/newMessage.vue'; import newMessage from '@/components/newMessage.vue';
import topBanner from '@/components/topBanner.vue'; import topBanner from '@/components/topBanner.vue';
import main from '@/main.js'; import Icon from '@/components/icon';
import Icon from "@/components/icon"; import {matrix} from '@/main';
import matrix from '@/matrix.js'; import splitArray from '@/lib/splitArray.js'
import timeline from '@/components/timeline';
export default { export default {
name: 'chat', name: 'chat',
components: { components: {
timeline,
Icon, Icon,
message,
newMessage, newMessage,
topBanner topBanner
}, },
props: {
room: [Object, undefined],
user: String,
closeChat: Function,
openChatInfo: Function
},
methods:{ methods:{
scrollToBottom(){ scrollToBottom(){
let msgContainer = document.getElementById("messagesContainer") this.$refs.msgContainer.scrollTop = this.$refs.msgContainer.scrollHeight;
msgContainer.scrollTo(0, msgContainer.scrollHeight)
}, },
getTime(time){ scrollHandler(){
let date = new Date(time); if (this.$refs.msgContainer.scrollTop === 0) this.loadEvents();
return `${date.getHours()}:${(date.getMinutes()<10)?"0":""}${date.getMinutes()}`; let msg = this.$refs.msgContainer;
this.showScrollBtn = msg.scrollHeight - msg.scrollTop > msg.offsetHeight + 200;
}, },
getDate(time){ resize(height){
let months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; this.$refs.chatContainer.style.height = `calc(100% - ${height}px - 3.5rem)`;
let date = new Date(time);
return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
}, },
scrollHandler(){ isGroup(){
if (this.$refs.msgContainer.scrollTop === 0){ return Object.keys(this.room.currentState.members).length > 2;
console.log("load messages") },
} async loadEvents(){
let msgContainer = document.getElementById("messagesContainer") this.loadingStatus = 'loading ...';
this.showScrollBtn = msgContainer.scrollHeight - msgContainer.scrollTop > msgContainer.offsetHeight + 200; await matrix.client.paginateEventTimeline(this.room.getLiveTimeline(), {backwards: true})
} .then(state => this.loadingStatus = state?'load more':false);
},
getUser(userId){
return matrix.client.getUser(userId);
},
splitArray
}, },
data(){ data(){
return { return {
chatroom: main.data().chatroom,
session: matrix.data().session,
showScrollBtn: false, showScrollBtn: false,
scrollOnUpdate: true scrollOnUpdate: true,
loadingStatus: 'load more'
} }
}, },
updated(){ updated(){
//this.scrollToBottom(); //this.scrollToBottom();
},
mounted(){
//this.scrollToBottom();
} }
} }
</script> </script>
<style scoped> <style scoped lang="scss">
.messagesContainer{ .chatContainer{
position: absolute; position: absolute;
margin: 0; margin: 0;
left: 0; left: 0;
top: 3rem; top: 3.5rem;
height: calc(100% - 7rem);
width: 100%; width: 100%;
height: calc(100% - 7rem);
.messagesContainer{
height: 100%;
overflow-y: auto; overflow-y: auto;
} }
.messages{
position: relative;
margin-top: 1rem;
margin-bottom: 1rem;
}
#scrollDown{ #scrollDown{
position: absolute; position: absolute;
background-color: #fff; background-color: #fff;
bottom: 5rem; bottom: 1rem;
right: 1rem; right: 1rem;
display: block; display: block;
height: 2rem;
width: 2rem;
} }
.info{ }
text-align: center; .loadMore{
font-style: italic; position: relative;
margin: 1rem; background-color: #2d2d2d;
padding: 0.5rem;
border-radius: 0.5rem;
width: fit-content;
left: 50%;
transform: translate(-50%,0);
margin-top: 0.5rem;
cursor: pointer;
} }
</style> </style>

@ -1,15 +1,16 @@
<template> <template>
<div id="login"> <div id="login">
<h1 class="title">[chat]</h1> <h1 class="title">[chat]</h1>
<form v-if="session.login" @submit.prevent="login()"> <form v-if="showLogin" @submit.prevent="login()">
<input v-model="session.login.user" class="input" name="user" type="text" maxlength="30" placeholder="@user:adb.sh"><br> <input v-model="user" class="input" name="user" type="text" maxlength="30" placeholder="@user:adb.sh"><br>
<input v-model="session.login.password" class="input" name="password" type="password" maxlength="30" placeholder="password"><br> <input v-model="password" class="input" name="password" type="password" maxlength="30" placeholder="password"><br>
<input v-model="session.login.baseUrl" class="input" name="homeserver" maxlength="50" placeholder="https://matrix.org"><br> <input v-model="homeServer" class="input" name="homeserver" maxlength="50" placeholder="https://matrix.org"><br>
<div v-if="loginError" class="info">{{loginError}}</div>
<textbtn type="submit" text="login" /> <textbtn type="submit" text="login" />
</form> </form>
<div v-else> <div v-else>
<p>you are already logged in</p> <p>you are already logged in</p>
<textbtn @click.native="$router.push('room')" text="chat" /> <textbtn @click.native="$router.push('rooms')" text="chat" />
<textbtn @click.native="logout()" text="logout" /> <textbtn @click.native="logout()" text="logout" />
</div> </div>
</div> </div>
@ -17,7 +18,8 @@
<script> <script>
import textbtn from '@/components/textbtn'; import textbtn from '@/components/textbtn';
import matrix from '@/matrix.js'; import {matrix} from '@/main.js';
import {cookieHandler} from "@/lib/cookieHandler";
export default { export default {
name: "login.vue", name: "login.vue",
@ -26,15 +28,44 @@ export default {
}, },
methods: { methods: {
login(){ login(){
matrix.methods.login(); if (matrix.client !== undefined) {
this.loginError = 'you are already logged in';
return;
} if (this.user === '') {
this.loginError = 'username is empty';
return;
} if (this.password === '') {
this.loginError = 'password is empty';
return;
} if (!(this.user.match(/^@[a-zA-Z0-9]+:[a-z0-9]+\.[a-z]/))) {
this.loginError = 'username is in wrong style';
return;
}
matrix.login(this.user, this.password, this.homeServer, (error) => {
this.loginError = `login failed: ${error}`;
}, token => {
let cookie = new cookieHandler();
cookie.setCookie({
baseUrl: this.homeServer,
userId: this.user,
accessToken: token
});
cookie.setExpire(15);
cookie.store();
this.$router.push('/rooms/');
});
}, },
logout(){ logout(){
matrix.methods.logout(); matrix.logout();
} }
}, },
data(){ data(){
return { return {
session: matrix.data().session user: "",
password: "",
homeServer: "https://adb.sh",
loginError: "",
showLogin: (matrix.client === undefined)
} }
} }
} }
@ -59,7 +90,7 @@ input{
border: 1px solid #fff; border: 1px solid #fff;
text-align: center; text-align: center;
font-size: 1.1rem; font-size: 1.1rem;
margin-top: 1rem; margin: 0.5rem;
appearance: none; appearance: none;
outline: none; outline: none;
} }

@ -1,51 +1,80 @@
<template> <template>
<div> <div v-if="matrix.loading">
loading...
</div>
<div v-else>
<div id="roomList" class="roomList"> <div id="roomList" class="roomList">
<h1>[chat]</h1> <h1>[chat]</h1>
<h2>{{session.rooms.length}} rooms:</h2> <div v-for="room in matrix.rooms" :key="room.roomId" @click="openChat(room)" class="roomListElement">
<div v-for="room in session.rooms" :key="room.roomId" @click="openChat(room)" class="roomListElement"> <userThumbnail
<div class="roomImgPlaceholder">{{room.name.substr(0,2)}}</div> class="roomImg"
:mxcURL="getUrl(room)"
:fallback="room.roomId"
:size="3"
/>
<div class="roomListName">{{room.name}}</div> <div class="roomListName">{{room.name}}</div>
</div> </div>
</div> </div>
<chat class="chat" v-if="session.currentRoom" /> <chat
class="chat"
v-if="currentRoom"
:room="currentRoom"
:user="matrix.user"
:close-chat="()=>currentRoom=undefined"
:open-chat-info="()=>showChatInfo=true"
/>
<div class="noRoomSelected" v-else>Please select a room to be displayed.</div> <div class="noRoomSelected" v-else>Please select a room to be displayed.</div>
<div class="roomListSmall"> <div class="roomListSmall">
<h1>[c]</h1> <h1>[c]</h1>
<h2></h2> <div v-for="(room, index) in matrix.rooms" :key="index" @click="openChat(room)" class="roomListElement" :title="room.name">
<div v-for="(room, index) in session.rooms" :key="index" @click="openChat(room)" class="roomListElement" :title="room.name"> <userThumbnail
<div class="roomImgPlaceholder">{{room.name.substr(0,2)}}</div> class="roomImg"
:mxcURL="getUrl(room)"
:fallback="room.roomId"
:size="3"
/>
<div class="roomListName">{{room.name}}</div> <div class="roomListName">{{room.name}}</div>
</div> </div>
</div> </div>
<chatInformation v-if="session.currentRoom" :room="session.currentRoom"/> <chatInformation v-if="currentRoom && showChatInfo" :room="currentRoom" :close-chat-info="()=>showChatInfo=false"/>
</div> </div>
</template> </template>
<script> <script>
import matrix from '@/matrix.js';
import chat from '@/views/chat.vue'; import chat from '@/views/chat.vue';
import chatInformation from "@/components/chatInformation"; import chatInformation from "@/components/chatInformation";
import userThumbnail from "@/components/userThumbnail";
import {matrix} from "@/main";
import sdk from "matrix-js-sdk";
export default { export default {
name: "rooms", name: "rooms",
components:{ components:{
chat, chat,
chatInformation chatInformation,
userThumbnail
}, },
methods:{ methods:{
openChat(room){ openChat(room){
this.session.currentRoom = room; this.currentRoom = room;
this.$router.push(`/rooms/${room.roomId}`) this.$router.push(`/rooms/${room.roomId}`);
this.$forceUpdate() this.$forceUpdate();
let msgContainer = document.getElementById("messagesContainer") //chat.methods.scrollToBottom();
setTimeout(() => {msgContainer.scrollTo(0, msgContainer.scrollHeight)}, 50) },
getUrl(room){
let avatarState = room.getLiveTimeline().getState(sdk.EventTimeline.FORWARDS).getStateEvents("m.room.avatar");
return avatarState.length>0?avatarState[avatarState.length-1].getContent().url:undefined;
} }
}, },
data(){ data(){
return { return {
session: matrix.data().session matrix,
currentRoom: undefined,
showChatInfo: false
} }
},
mounted() {
if (matrix.client === undefined) this.$router.push('/login');
} }
} }
</script> </script>
@ -116,17 +145,13 @@ export default {
left: 20rem; left: 20rem;
text-align: center; text-align: center;
} }
.roomImgPlaceholder{ .roomImg{
position: absolute; position: absolute;
left: 1rem; left: 0.5rem;
height: 2rem; height: 3rem;
width: 3rem; width: 3rem;
padding-top: 1rem;
background-color: #42a7b9;
border-radius: 1.5rem;
text-align: center;
} }
.roomImgPlaceholder.small{ .roomImg.small{
margin-left: calc(50% - 2rem); margin-left: calc(50% - 2rem);
} }

Loading…
Cancel
Save