added tab notification and fixed websocket q-chat

This commit is contained in:
Phillip 2023-06-13 13:30:23 +03:00
parent 02a78173a3
commit 22ca790f51
10 changed files with 1361 additions and 1122 deletions

View File

@ -15,7 +15,7 @@ import './login-section.js'
import '../qort-theme-toggle.js' import '../qort-theme-toggle.js'
import settings from '../../functional-components/settings-page.js' import settings from '../../functional-components/settings-page.js'
import { addAutoLoadImageChat, removeAutoLoadImageChat, addChatLastSeen, allowQAPPAutoAuth, removeQAPPAutoAuth, removeQAPPAutoLists, allowQAPPAutoLists } from '../../redux/app/app-actions.js' import { addAutoLoadImageChat, removeAutoLoadImageChat, addChatLastSeen, allowQAPPAutoAuth, removeQAPPAutoAuth, removeQAPPAutoLists, allowQAPPAutoLists, addTabInfo, setTabNotifications, setNewTab } from '../../redux/app/app-actions.js'
window.reduxStore = store window.reduxStore = store
window.reduxAction = { window.reduxAction = {
@ -25,7 +25,10 @@ window.reduxAction = {
allowQAPPAutoAuth: allowQAPPAutoAuth, allowQAPPAutoAuth: allowQAPPAutoAuth,
removeQAPPAutoAuth: removeQAPPAutoAuth, removeQAPPAutoAuth: removeQAPPAutoAuth,
allowQAPPAutoLists: allowQAPPAutoLists, allowQAPPAutoLists: allowQAPPAutoLists,
removeQAPPAutoLists: removeQAPPAutoLists removeQAPPAutoLists: removeQAPPAutoLists,
addTabInfo: addTabInfo,
setTabNotifications: setTabNotifications,
setNewTab: setNewTab
} }
const animationDuration = 0.7 // Seconds const animationDuration = 0.7 // Seconds

View File

@ -6,9 +6,13 @@ import { addPluginRoutes } from '../plugins/addPluginRoutes.js'
import { repeat } from 'lit/directives/repeat.js'; import { repeat } from 'lit/directives/repeat.js';
import ShortUniqueId from 'short-unique-id'; import ShortUniqueId from 'short-unique-id';
import { setNewTab } from '../redux/app/app-actions.js' import { setNewTab } from '../redux/app/app-actions.js'
import localForage from "localforage";
import '@material/mwc-icon' import '@material/mwc-icon'
const chatLastSeen = localForage.createInstance({
name: "chat-last-seen",
});
class ShowPlugin extends connect(store)(LitElement) { class ShowPlugin extends connect(store)(LitElement) {
static get properties() { static get properties() {
return { return {
@ -20,6 +24,9 @@ class ShowPlugin extends connect(store)(LitElement) {
currentTab: { type: Number }, currentTab: { type: Number },
tabs: { type: Array }, tabs: { type: Array },
theme: { type: String, reflect: true }, theme: { type: String, reflect: true },
tabInfo: { type: Object },
chatLastSeen: { type: Array },
chatHeads: { type: Array }
} }
} }
@ -50,7 +57,7 @@ class ShowPlugin extends connect(store)(LitElement) {
} }
.hideIframe { .hideIframe {
visibility: hidden; display: none;
position: absolute; position: absolute;
zIndex: -10; zIndex: -10;
} }
@ -58,7 +65,7 @@ class ShowPlugin extends connect(store)(LitElement) {
.showIframe { .showIframe {
zIndex: 1; zIndex: 1;
position: relative; position: relative;
visibility: visible; display: block;
} }
.tabs { .tabs {
@ -155,6 +162,20 @@ class ShowPlugin extends connect(store)(LitElement) {
color: #999; color: #999;
--mdc-icon-size: 20px; --mdc-icon-size: 20px;
} }
.count {
position: absolute;
background: red;
color: white;
padding: 5px;
font-size: 12px;
border-radius: 50%;
height: 10px;
width: 10px;
display: flex;
justify-content: center;
align-items: center;
}
` `
} }
@ -165,6 +186,9 @@ class ShowPlugin extends connect(store)(LitElement) {
this.tabs = [] this.tabs = []
this.uid = new ShortUniqueId() this.uid = new ShortUniqueId()
this.theme = localStorage.getItem('qortalTheme') ? localStorage.getItem('qortalTheme') : 'light' this.theme = localStorage.getItem('qortalTheme') ? localStorage.getItem('qortalTheme') : 'light'
this.tabInfo = {}
this.chatLastSeen = []
this.chatHeads = []
} }
async getUpdateComplete() { async getUpdateComplete() {
@ -189,9 +213,44 @@ class ShowPlugin extends connect(store)(LitElement) {
return myPlug === undefined ? 'about:blank' : `${window.location.origin}/plugin/${myPlug.domain}/${myPlug.page}${this.linkParam}` return myPlug === undefined ? 'about:blank' : `${window.location.origin}/plugin/${myPlug.domain}/${myPlug.page}${this.linkParam}`
} }
return html` return html`
<div class="tabs"> <div class="tabs">
${this.tabs.map((tab, index) => html` ${this.tabs.map((tab, index) => {
let title = ''
let count = 0
if (tab.myPlugObj && tab.myPlugObj.title) {
title = tab.myPlugObj.title
}
if (tab.myPlugObj && (tab.myPlugObj.url === 'websites' || tab.myPlugObj.url === 'qapps') && this.tabInfo[tab.id]) {
title = this.tabInfo[tab.id].name
}
if (tab.myPlugObj && (tab.myPlugObj.url === 'websites' || tab.myPlugObj.url === 'qapps') && this.tabInfo[tab.id]) {
count = this.tabInfo[tab.id].count
}
if (tab.myPlugObj && tab.myPlugObj.url === 'q-chat') {
for (const chat of this.chatHeads) {
const lastReadMessage = this.chatLastSeen.find((ch) => {
let id
if (chat.groupId === 0) {
id = chat.groupId
} else if (chat.groupId) {
id = chat.groupId
} else {
id = chat.address
}
return ch.key.includes(id)
})
if (lastReadMessage && lastReadMessage.timestamp < chat.timestamp) {
count = count + 1
}
}
}
return html`
<div <div
class="tab ${this.currentTab === index ? 'active' : ''}" class="tab ${this.currentTab === index ? 'active' : ''}"
@click=${() => this.currentTab = index} @click=${() => this.currentTab = index}
@ -200,15 +259,20 @@ class ShowPlugin extends connect(store)(LitElement) {
<div class="${this.currentTab === index ? "iconActive" : "iconInactive"}"> <div class="${this.currentTab === index ? "iconActive" : "iconInactive"}">
<mwc-icon>${tab.myPlugObj && tab.myPlugObj.mwcicon}</mwc-icon> <mwc-icon>${tab.myPlugObj && tab.myPlugObj.mwcicon}</mwc-icon>
</div> </div>
${count ? html`
<div class="count">${count}</div>
` : ''}
<div> <div>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
${tab.myPlugObj && tab.myPlugObj.title} ${title}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</div> </div>
<div class="close" @click=${() => { this.removeTab(index) }}>x</div> <div class="close" @click=${() => { this.removeTab(index) }}>x</div>
</div> </div>
</div> </div>
`)}&nbsp;&nbsp;&nbsp; `
})}&nbsp;&nbsp;&nbsp;
<button <button
class="add-tab-button" class="add-tab-button"
title="Add Tab" title="Add Tab"
@ -227,7 +291,7 @@ class ShowPlugin extends connect(store)(LitElement) {
${repeat(this.tabs, (tab) => tab.id, (tab, index) => html` ${repeat(this.tabs, (tab) => tab.id, (tab, index) => html`
<div class=${this.currentTab === index ? "showIframe" : "hideIframe"}> <div class=${this.currentTab === index ? "showIframe" : "hideIframe"}>
<iframe src="${plugSrc(tab.myPlugObj)}" id="showPluginFrame${index}" style="width:100%; <iframe src="${plugSrc(tab.myPlugObj)}" data-id=${tab.id} id="showPluginFrame${index}" style="width:100%;
height:calc(var(--window-height) - 102px); height:calc(var(--window-height) - 102px);
border:0; border:0;
padding:0; padding:0;
@ -321,7 +385,7 @@ class ShowPlugin extends connect(store)(LitElement) {
this.tabs = copiedTabs this.tabs = copiedTabs
} }
stateChanged(state) { async stateChanged(state) {
const split = state.app.url.split('/') const split = state.app.url.split('/')
const newRegisteredUrls = state.app.registeredUrls const newRegisteredUrls = state.app.registeredUrls
@ -352,6 +416,23 @@ class ShowPlugin extends connect(store)(LitElement) {
if (newLinkParam !== this.linkParam) { if (newLinkParam !== this.linkParam) {
this.linkParam = newLinkParam this.linkParam = newLinkParam
} }
if (this.tabInfo !== state.app.tabInfo) {
this.tabInfo = state.app.tabInfo
}
if (this.chatLastSeen !== state.app.chatLastSeen) {
this.chatLastSeen = state.app.chatLastSeen
}
if (state.app.chatHeads !== this.unModifiedChatHeads) {
let chatHeads = []
if (state.app.chatHeads && state.app.chatHeads.groups) {
chatHeads = [...chatHeads, ...state.app.chatHeads.groups]
}
if (state.app.chatHeads && state.app.chatHeads.direct) {
chatHeads = [...chatHeads, ...state.app.chatHeads.direct]
}
this.chatHeads = chatHeads
this.unModifiedChatHeads = state.app.chatHeads
}
if (state.app.newTab) { if (state.app.newTab) {
const newTab = state.app.newTab const newTab = state.app.newTab

View File

@ -1,5 +1,5 @@
// Core App Actions here... // Core App Actions here...
import { UPDATE_BLOCK_INFO, UPDATE_NODE_STATUS, UPDATE_NODE_INFO, CHAT_HEADS, ACCOUNT_INFO, ADD_AUTO_LOAD_IMAGES_CHAT, REMOVE_AUTO_LOAD_IMAGES_CHAT, ALLOW_QAPP_AUTO_AUTH, REMOVE_QAPP_AUTO_AUTH, SET_CHAT_LAST_SEEN, ADD_CHAT_LAST_SEEN, ALLOW_QAPP_AUTO_LISTS, REMOVE_QAPP_AUTO_LISTS, SET_NEW_TAB } from '../app-action-types.js' import { UPDATE_BLOCK_INFO, UPDATE_NODE_STATUS, UPDATE_NODE_INFO, CHAT_HEADS, ACCOUNT_INFO, ADD_AUTO_LOAD_IMAGES_CHAT, REMOVE_AUTO_LOAD_IMAGES_CHAT, ALLOW_QAPP_AUTO_AUTH, REMOVE_QAPP_AUTO_AUTH, SET_CHAT_LAST_SEEN, ADD_CHAT_LAST_SEEN, ALLOW_QAPP_AUTO_LISTS, REMOVE_QAPP_AUTO_LISTS, SET_NEW_TAB, ADD_TAB_INFO, SET_TAB_NOTIFICATIONS } from '../app-action-types.js'
export const doUpdateBlockInfo = (blockObj) => { export const doUpdateBlockInfo = (blockObj) => {
return (dispatch, getState) => { return (dispatch, getState) => {
@ -127,3 +127,16 @@ export const setNewTab = (payload) => {
} }
} }
export const addTabInfo = (payload) => {
return {
type: ADD_TAB_INFO,
payload
}
}
export const setTabNotifications = (payload) => {
return {
type: SET_TAB_NOTIFICATIONS,
payload
}
}

View File

@ -26,3 +26,5 @@ export const REMOVE_QAPP_AUTO_LISTS = 'REMOVE_QAPP_AUTO_LISTS'
export const SET_CHAT_LAST_SEEN = 'SET_CHAT_LAST_SEEN' export const SET_CHAT_LAST_SEEN = 'SET_CHAT_LAST_SEEN'
export const ADD_CHAT_LAST_SEEN = 'ADD_CHAT_LAST_SEEN' export const ADD_CHAT_LAST_SEEN = 'ADD_CHAT_LAST_SEEN'
export const SET_NEW_TAB = 'SET_NEW_TAB' export const SET_NEW_TAB = 'SET_NEW_TAB'
export const ADD_TAB_INFO = 'ADD_TAB_INFO'
export const SET_TAB_NOTIFICATIONS = 'SET_TAB_NOTIFICATIONS'

View File

@ -1,6 +1,6 @@
// Loading state, login state, isNavDrawOpen state etc. None of this needs to be saved to localstorage. // Loading state, login state, isNavDrawOpen state etc. None of this needs to be saved to localstorage.
import { loadStateFromLocalStorage, saveStateToLocalStorage } from '../../localStorageHelpers.js' import { loadStateFromLocalStorage, saveStateToLocalStorage } from '../../localStorageHelpers.js'
import { LOG_IN, LOG_OUT, NETWORK_CONNECTION_STATUS, INIT_WORKERS, ADD_PLUGIN_URL, ADD_PLUGIN, ADD_NEW_PLUGIN_URL, NAVIGATE, SELECT_ADDRESS, ACCOUNT_INFO, CHAT_HEADS, UPDATE_BLOCK_INFO, UPDATE_NODE_STATUS, UPDATE_NODE_INFO, LOAD_NODE_CONFIG, SET_NODE, ADD_NODE, PAGE_URL, ADD_AUTO_LOAD_IMAGES_CHAT, REMOVE_AUTO_LOAD_IMAGES_CHAT, ALLOW_QAPP_AUTO_AUTH, REMOVE_QAPP_AUTO_AUTH, SET_CHAT_LAST_SEEN, ADD_CHAT_LAST_SEEN, ALLOW_QAPP_AUTO_LISTS, REMOVE_QAPP_AUTO_LISTS, SET_NEW_TAB } from './app-action-types.js' import { LOG_IN, LOG_OUT, NETWORK_CONNECTION_STATUS, INIT_WORKERS, ADD_PLUGIN_URL, ADD_PLUGIN, ADD_NEW_PLUGIN_URL, NAVIGATE, SELECT_ADDRESS, ACCOUNT_INFO, CHAT_HEADS, UPDATE_BLOCK_INFO, UPDATE_NODE_STATUS, UPDATE_NODE_INFO, LOAD_NODE_CONFIG, SET_NODE, ADD_NODE, PAGE_URL, ADD_AUTO_LOAD_IMAGES_CHAT, REMOVE_AUTO_LOAD_IMAGES_CHAT, ALLOW_QAPP_AUTO_AUTH, REMOVE_QAPP_AUTO_AUTH, SET_CHAT_LAST_SEEN, ADD_CHAT_LAST_SEEN, ALLOW_QAPP_AUTO_LISTS, REMOVE_QAPP_AUTO_LISTS, SET_NEW_TAB, ADD_TAB_INFO, SET_TAB_NOTIFICATIONS } from './app-action-types.js'
import { initWorkersReducer } from './reducers/init-workers.js' import { initWorkersReducer } from './reducers/init-workers.js'
import { loginReducer } from './reducers/login-reducer.js' import { loginReducer } from './reducers/login-reducer.js'
import { setNode, addNode } from './reducers/manage-node.js' import { setNode, addNode } from './reducers/manage-node.js'
@ -47,7 +47,8 @@ const INITIAL_STATE = {
qAPPAutoAuth: loadStateFromLocalStorage('qAPPAutoAuth') || false, qAPPAutoAuth: loadStateFromLocalStorage('qAPPAutoAuth') || false,
qAPPAutoLists: loadStateFromLocalStorage('qAPPAutoLists') || false, qAPPAutoLists: loadStateFromLocalStorage('qAPPAutoLists') || false,
chatLastSeen: [], chatLastSeen: [],
newTab: null newTab: null,
tabInfo: {}
} }
export default (state = INITIAL_STATE, action) => { export default (state = INITIAL_STATE, action) => {
@ -228,6 +229,40 @@ export default (state = INITIAL_STATE, action) => {
newTab: action.payload newTab: action.payload
} }
} }
case ADD_TAB_INFO: {
const newTabInfo = action.payload
if (state.tabInfo[newTabInfo.id] && state.tabInfo[newTabInfo.id].name && newTabInfo.name === state.tabInfo[newTabInfo.id].name) break
return {
...state,
tabInfo: {
...state.tabInfo,
[newTabInfo.id]: {
...newTabInfo,
count: 0
}
}
}
}
case SET_TAB_NOTIFICATIONS: {
const count = action.payload.count
const name = action.payload.name
const newTabInfo = {}
Object.keys(state.tabInfo).forEach((key) => {
const tab = state.tabInfo[key]
if (tab.name == name) {
newTabInfo[key] = {
...tab,
count
}
} else {
newTabInfo[key] = tab
}
})
return {
...state,
tabInfo: newTabInfo
}
}
default: default:
return state return state

View File

@ -1,5 +1,5 @@
import { LitElement, html, css } from 'lit'; import { LitElement, html, css } from 'lit';
import {animate} from '@lit-labs/motion'; import { animate } from '@lit-labs/motion';
import { Epml } from '../../../epml.js'; import { Epml } from '../../../epml.js';
import { use, get, translate, registerTranslateConfig } from 'lit-translate'; import { use, get, translate, registerTranslateConfig } from 'lit-translate';
import { generateHTML } from '@tiptap/core' import { generateHTML } from '@tiptap/core'
@ -7,7 +7,7 @@ import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'; import Underline from '@tiptap/extension-underline';
import Placeholder from '@tiptap/extension-placeholder' import Placeholder from '@tiptap/extension-placeholder'
import Highlight from '@tiptap/extension-highlight' import Highlight from '@tiptap/extension-highlight'
import {unsafeHTML} from 'lit/directives/unsafe-html.js'; import { unsafeHTML } from 'lit/directives/unsafe-html.js';
import { Editor, Extension } from '@tiptap/core' import { Editor, Extension } from '@tiptap/core'
import * as zip from "@zip.js/zip.js"; import * as zip from "@zip.js/zip.js";
import './ChatGifs/ChatGifs.js'; import './ChatGifs/ChatGifs.js';
@ -91,28 +91,28 @@ class ChatPage extends LitElement {
webSocket: { attribute: false }, webSocket: { attribute: false },
chatHeads: { type: Array }, chatHeads: { type: Array },
forwardActiveChatHeadUrl: { type: Object }, forwardActiveChatHeadUrl: { type: Object },
openForwardOpen: {type: Boolean }, openForwardOpen: { type: Boolean },
groupAdmin: {type: Array}, groupAdmin: { type: Array },
groupMembers: {type: Array}, groupMembers: { type: Array },
shifted: {type: Boolean}, shifted: { type: Boolean },
groupInfo: {type: Object}, groupInfo: { type: Object },
setActiveChatHeadUrl: {attribute: false}, setActiveChatHeadUrl: { attribute: false },
userFound: { type: Array }, userFound: { type: Array },
userFoundModalOpen: { type: Boolean }, userFoundModalOpen: { type: Boolean },
webWorker: { type: Object }, webWorker: { type: Object },
webWorkerFile: { type: Object }, webWorkerFile: { type: Object },
myTrimmedMeassage: { type: String }, myTrimmedMeassage: { type: String },
editor: {type: Object}, editor: { type: Object },
currentEditor: {type: String}, currentEditor: { type: String },
isEnabledChatEnter: {type: Boolean}, isEnabledChatEnter: { type: Boolean },
openTipUser: { type: Boolean }, openTipUser: { type: Boolean },
openUserInfo: { type: Boolean }, openUserInfo: { type: Boolean },
selectedHead: { type: Object }, selectedHead: { type: Object },
userName: { type: String }, userName: { type: String },
openGifModal: { type: Boolean }, openGifModal: { type: Boolean },
gifsLoading: { type: Boolean }, gifsLoading: { type: Boolean },
goToRepliedMessage: {attribute: false}, goToRepliedMessage: { attribute: false },
isLoadingGoToRepliedMessage: {type: Object} isLoadingGoToRepliedMessage: { type: Object }
} }
} }
@ -1268,7 +1268,7 @@ class ChatPage extends LitElement {
padding: 5px 0px; padding: 5px 0px;
} }
` `
} }
constructor() { constructor() {
super() super()
@ -1349,7 +1349,7 @@ class ChatPage extends LitElement {
} }
setOpenGifModal(value){ setOpenGifModal(value) {
this.openGifModal = value this.openGifModal = value
} }
@ -1379,12 +1379,12 @@ class ChatPage extends LitElement {
}; };
} }
toggleEnableChatEnter(){ toggleEnableChatEnter() {
localStorage.setItem('isEnabledChatEnter', !this.isEnabledChatEnter ) localStorage.setItem('isEnabledChatEnter', !this.isEnabledChatEnter)
this.isEnabledChatEnter = !this.isEnabledChatEnter this.isEnabledChatEnter = !this.isEnabledChatEnter
} }
addGifs(gifs){ addGifs(gifs) {
this.gifsToBeAdded = [...this.gifsToBeAdded, ...gifs] this.gifsToBeAdded = [...this.gifsToBeAdded, ...gifs]
} }
@ -1450,7 +1450,7 @@ class ChatPage extends LitElement {
.webWorkerImage=${this.webWorkerFile} .webWorkerImage=${this.webWorkerFile}
.setGifsLoading=${(val) => this.setGifsLoading(val)} .setGifsLoading=${(val) => this.setGifsLoading(val)}
.sendMessage=${(val) => this._sendMessage(val)} .sendMessage=${(val) => this._sendMessage(val)}
.setOpenGifModal=${(val)=> this.setOpenGifModal(val)}> .setOpenGifModal=${(val) => this.setOpenGifModal(val)}>
</chat-gifs> </chat-gifs>
<div <div
class='last-message-ref' class='last-message-ref'
@ -1459,7 +1459,7 @@ class ChatPage extends LitElement {
this.shadowRoot.querySelector("chat-scroller").shadowRoot.getElementById("downObserver") this.shadowRoot.querySelector("chat-scroller").shadowRoot.getElementById("downObserver")
.scrollIntoView({ .scrollIntoView({
behavior: 'smooth', behavior: 'smooth',
block: 'nearest',
}); });
}}> }}>
</vaadin-icon> </vaadin-icon>
@ -1531,13 +1531,13 @@ class ChatPage extends LitElement {
?isLoadingMessages=${this.isLoadingMessages} ?isLoadingMessages=${this.isLoadingMessages}
?isEditMessageOpen=${this.isEditMessageOpen} ?isEditMessageOpen=${this.isEditMessageOpen}
.editor=${this.editor} .editor=${this.editor}
.updatePlaceholder=${(editor, value)=> this.updatePlaceholder(editor, value)} .updatePlaceholder=${(editor, value) => this.updatePlaceholder(editor, value)}
id="_chatEditorDOM" id="_chatEditorDOM"
.repliedToMessageObj=${this.repliedToMessageObj} .repliedToMessageObj=${this.repliedToMessageObj}
.toggleEnableChatEnter=${this.toggleEnableChatEnter} .toggleEnableChatEnter=${this.toggleEnableChatEnter}
?isEnabledChatEnter=${this.isEnabledChatEnter} ?isEnabledChatEnter=${this.isEnabledChatEnter}
?openGifModal=${this.openGifModal} ?openGifModal=${this.openGifModal}
.setOpenGifModal=${(val)=> this.setOpenGifModal(val)} .setOpenGifModal=${(val) => this.setOpenGifModal(val)}
chatId=${this.chatId} chatId=${this.chatId}
> >
</chat-text-editor> </chat-text-editor>
@ -1596,7 +1596,7 @@ class ChatPage extends LitElement {
?isLoadingMessages=${this.isLoadingMessages} ?isLoadingMessages=${this.isLoadingMessages}
id="chatTextCaption" id="chatTextCaption"
.editor=${this.editorImage} .editor=${this.editorImage}
.updatePlaceholder=${(editor, value)=> this.updatePlaceholder(editor, value)} .updatePlaceholder=${(editor, value) => this.updatePlaceholder(editor, value)}
> >
</chat-text-editor> </chat-text-editor>
</div> </div>
@ -1609,7 +1609,7 @@ class ChatPage extends LitElement {
</button> </button>
<button <button
class="modal-button" class="modal-button"
@click=${()=> { @click=${() => {
const chatTextEditor = this.shadowRoot.getElementById('chatTextCaption') const chatTextEditor = this.shadowRoot.getElementById('chatTextCaption')
chatTextEditor.sendMessageFunc({ chatTextEditor.sendMessageFunc({
type: 'image', type: 'image',
@ -1649,7 +1649,7 @@ class ChatPage extends LitElement {
?isLoadingMessages=${this.isLoadingMessages} ?isLoadingMessages=${this.isLoadingMessages}
id="chatAttachmentId" id="chatAttachmentId"
.editor=${this.editorAttachment} .editor=${this.editorAttachment}
.updatePlaceholder=${(editor, value)=> this.updatePlaceholder(editor, value)} .updatePlaceholder=${(editor, value) => this.updatePlaceholder(editor, value)}
> >
</chat-text-editor> </chat-text-editor>
</div> </div>
@ -1688,7 +1688,7 @@ class ChatPage extends LitElement {
this.openForwardOpen = false; this.openForwardOpen = false;
this.forwardActiveChatHeadUrl = {}; this.forwardActiveChatHeadUrl = {};
this.requestUpdate(); this.requestUpdate();
} } }}
style=${this.openForwardOpen ? "display: block" : "display: none"}> style=${this.openForwardOpen ? "display: block" : "display: none"}>
<div> <div>
<div class="dialog-container"> <div class="dialog-container">
@ -1759,7 +1759,7 @@ class ChatPage extends LitElement {
return html` return html`
<chat-select <chat-select
activeChatHeadUrl=${this.forwardActiveChatHeadUrl.url} activeChatHeadUrl=${this.forwardActiveChatHeadUrl.url}
.setActiveChatHeadUrl=${(val)=> { .setActiveChatHeadUrl=${(val) => {
this.forwardActiveChatHeadUrl = { this.forwardActiveChatHeadUrl = {
...this.forwardActiveChatHeadUrl, ...this.forwardActiveChatHeadUrl,
url: val url: val
@ -1783,7 +1783,7 @@ class ChatPage extends LitElement {
</button> </button>
<button <button
class="modal-button" class="modal-button"
@click=${()=> { @click=${() => {
this.sendForwardMessage() this.sendForwardMessage()
}} }}
> >
@ -1832,8 +1832,7 @@ class ChatPage extends LitElement {
this.setUserName(""); this.setUserName("");
this.setSelectedHead({}); this.setSelectedHead({});
}} }}
style=${ style=${this.openUserInfo ? "display: block" : "display: none"
this.openUserInfo ? "display: block" : "display: none"
}> }>
<user-info <user-info
.setOpenUserInfo=${(val) => this.setOpenUserInfo(val)} .setOpenUserInfo=${(val) => this.setOpenUserInfo(val)}
@ -1846,8 +1845,8 @@ class ChatPage extends LitElement {
</div> </div>
<div class="chat-right-panel ${this.shifted ? "movedin" : "movedout"}" ${animate()}> <div class="chat-right-panel ${this.shifted ? "movedin" : "movedout"}" ${animate()}>
<chat-right-panel <chat-right-panel
.getMoreMembers=${(val)=> this.getMoreMembers(val)} .getMoreMembers=${(val) => this.getMoreMembers(val)}
.toggle=${(val)=> this._toggle(val)} .toggle=${(val) => this._toggle(val)}
.selectedAddress=${this.selectedAddress} .selectedAddress=${this.selectedAddress}
.groupMembers=${this.groupMembers} .groupMembers=${this.groupMembers}
.groupAdmin=${this.groupAdmin} .groupAdmin=${this.groupAdmin}
@ -1863,7 +1862,7 @@ class ChatPage extends LitElement {
` `
} }
async getMoreMembers(groupId){ async getMoreMembers(groupId) {
try { try {
const getMembers = await parentEpml.request("apiCall", { const getMembers = await parentEpml.request("apiCall", {
type: "api", type: "api",
@ -1903,7 +1902,7 @@ class ChatPage extends LitElement {
const elementChatImageId = this.shadowRoot.getElementById('chatTextCaption').shadowRoot.getElementById('newChat'); const elementChatImageId = this.shadowRoot.getElementById('chatTextCaption').shadowRoot.getElementById('newChat');
const elementChatAttachmentId = this.shadowRoot.getElementById('chatAttachmentId').shadowRoot.getElementById('newAttachmentChat'); const elementChatAttachmentId = this.shadowRoot.getElementById('chatAttachmentId').shadowRoot.getElementById('newAttachmentChat');
this.editor = new Editor({ this.editor = new Editor({
onUpdate: ()=> { onUpdate: () => {
this.shadowRoot.getElementById('_chatEditorDOM').getMessageSize(this.editor.getJSON()) this.shadowRoot.getElementById('_chatEditorDOM').getMessageSize(this.editor.getJSON())
}, },
@ -1917,10 +1916,10 @@ class ChatPage extends LitElement {
}), }),
Extension.create({ Extension.create({
name: 'shortcuts', name: 'shortcuts',
addKeyboardShortcuts:()=> { addKeyboardShortcuts: () => {
return { return {
'Enter': ()=> { 'Enter': () => {
if(this.isEnabledChatEnter){ if (this.isEnabledChatEnter) {
const chatTextEditor = this.shadowRoot.getElementById('_chatEditorDOM') const chatTextEditor = this.shadowRoot.getElementById('_chatEditorDOM')
chatTextEditor.sendMessageFunc({ chatTextEditor.sendMessageFunc({
}) })
@ -1929,7 +1928,7 @@ class ChatPage extends LitElement {
}, },
"Shift-Enter": () => { "Shift-Enter": () => {
if(this.isEnabledChatEnter){ if (this.isEnabledChatEnter) {
this.editor.commands.first(() => [ this.editor.commands.first(() => [
this.editor.commands.newlineInCode() this.editor.commands.newlineInCode()
]) ])
@ -1939,12 +1938,13 @@ class ChatPage extends LitElement {
} }
}}) }
})
] ]
}) })
this.editorImage = new Editor({ this.editorImage = new Editor({
onUpdate: ()=> { onUpdate: () => {
this.shadowRoot.getElementById('chatTextCaption').getMessageSize(this.editorImage.getJSON()) this.shadowRoot.getElementById('chatTextCaption').getMessageSize(this.editorImage.getJSON())
}, },
element: elementChatImageId, element: elementChatImageId,
@ -1956,9 +1956,9 @@ class ChatPage extends LitElement {
placeholder: 'Write something …', placeholder: 'Write something …',
}), }),
Extension.create({ Extension.create({
addKeyboardShortcuts:()=> { addKeyboardShortcuts: () => {
return { return {
'Enter':() => { 'Enter': () => {
const chatTextEditor = this.shadowRoot.getElementById('chatTextCaption') const chatTextEditor = this.shadowRoot.getElementById('chatTextCaption')
chatTextEditor.sendMessageFunc({ chatTextEditor.sendMessageFunc({
type: 'image' type: 'image'
@ -1966,7 +1966,8 @@ class ChatPage extends LitElement {
return true return true
} }
} }
}}) }
})
] ]
}) })
@ -1983,9 +1984,9 @@ class ChatPage extends LitElement {
placeholder: 'Write something …', placeholder: 'Write something …',
}), }),
Extension.create({ Extension.create({
addKeyboardShortcuts:()=> { addKeyboardShortcuts: () => {
return { return {
'Enter':()=> { 'Enter': () => {
const chatTextEditor = this.shadowRoot.getElementById('chatAttachmentId') const chatTextEditor = this.shadowRoot.getElementById('chatAttachmentId')
chatTextEditor.sendMessageFunc({ chatTextEditor.sendMessageFunc({
type: 'attachment' type: 'attachment'
@ -1993,42 +1994,76 @@ class ChatPage extends LitElement {
return true return true
} }
} }
}}) }
})
] ]
}) })
document.addEventListener('keydown', this.initialChat); document.addEventListener('keydown', this.initialChat);
document.addEventListener('paste', this.pasteImage); document.addEventListener('paste', this.pasteImage);
if(this.chatId){ if (this.chatId) {
window.parent.reduxStore.dispatch( window.parent.reduxAction.addChatLastSeen({ window.parent.reduxStore.dispatch(window.parent.reduxAction.addChatLastSeen({
key: this.chatId, key: this.chatId,
timestamp: Date.now() timestamp: Date.now()
})) }))
} }
let callback = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.isPageVisible = true
if (this.chatId) {
window.parent.reduxStore.dispatch(window.parent.reduxAction.addChatLastSeen({
key: this.chatId,
timestamp: Date.now()
}))
}
} else {
this.isPageVisible = false
}
});
};
let options = {
root: null,
rootMargin: '0px',
threshold: 0.5
};
// Create the observer with the callback function and options
this.observer = new IntersectionObserver(callback, options);
const mainContainer = this.shadowRoot.querySelector('.main-container')
this.observer.observe(mainContainer);
} }
disconnectedCallback() { disconnectedCallback() {
super.disconnectedCallback(); super.disconnectedCallback();
if(this.webSocket){ if (this.webSocket) {
this.webSocket.close(1000, 'switch chat') this.webSocket.close(1000, 'switch chat')
this.webSocket= '' this.webSocket = ''
} }
if(this.webWorker){ if (this.webWorker) {
this.webWorker.terminate(); this.webWorker.terminate();
} }
if(this.webWorkerFile){ if (this.webWorkerFile) {
this.webWorkerFile.terminate(); this.webWorkerFile.terminate();
} }
if(this.editor){ if (this.editor) {
this.editor.destroy() this.editor.destroy()
} }
if(this.editorImage){ if (this.editorImage) {
this.editorImage.destroy() this.editorImage.destroy()
} }
if (this.observer) {
this.observer.disconnect();
}
document.removeEventListener('keydown', this.initialChat); document.removeEventListener('keydown', this.initialChat);
document.removeEventListener('paste', this.pasteImage); document.removeEventListener('paste', this.pasteImage);
if(this.chatId){ if (this.chatId) {
window.parent.reduxStore.dispatch( window.parent.reduxAction.addChatLastSeen({ window.parent.reduxStore.dispatch(window.parent.reduxAction.addChatLastSeen({
key: this.chatId, key: this.chatId,
timestamp: Date.now() timestamp: Date.now()
})) }))
@ -2051,7 +2086,7 @@ class ChatPage extends LitElement {
} }
async pasteImage (e) { async pasteImage(e) {
const event = e; const event = e;
const handleTransferIntoURL = (dataTransfer) => { const handleTransferIntoURL = (dataTransfer) => {
try { try {
@ -2071,8 +2106,8 @@ class ChatPage extends LitElement {
const item_list = await navigator.clipboard.read(); const item_list = await navigator.clipboard.read();
let image_type; let image_type;
const item = item_list.find(item => const item = item_list.find(item =>
item.types.some( type => { item.types.some(type => {
if (type.startsWith( 'image/')) { if (type.startsWith('image/')) {
image_type = type; image_type = type;
return true; return true;
} }
@ -2098,22 +2133,22 @@ class ChatPage extends LitElement {
} }
async goToRepliedMessage(message, clickedOnMessage){ async goToRepliedMessage(message, clickedOnMessage) {
const findMessage = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById(message.signature) const findMessage = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById(message.signature)
if(findMessage){ if (findMessage) {
findMessage.scrollIntoView({ behavior: 'smooth', block: 'center' }) findMessage.scrollIntoView({ behavior: 'smooth', block: 'center' })
const findElement = findMessage.shadowRoot.querySelector('.message-parent') const findElement = findMessage.shadowRoot.querySelector('.message-parent')
if(findElement){ if (findElement) {
findElement.classList.add('blink-bg') findElement.classList.add('blink-bg')
setTimeout(()=> { setTimeout(() => {
findElement.classList.remove('blink-bg') findElement.classList.remove('blink-bg')
}, 2000) }, 2000)
} }
return return
} }
if((message.timestamp - this.messagesRendered[0].timestamp) > 86400000){ if ((message.timestamp - this.messagesRendered[0].timestamp) > 86400000) {
let errorMsg = get("chatpage.cchange66") let errorMsg = get("chatpage.cchange66")
parentEpml.request('showSnackBar', `${errorMsg}`) parentEpml.request('showSnackBar', `${errorMsg}`)
return return
@ -2122,9 +2157,9 @@ class ChatPage extends LitElement {
if((message.timestamp - this.messagesRendered[0].timestamp) < 86400000){ if ((message.timestamp - this.messagesRendered[0].timestamp) < 86400000) {
const findOriginalMessage = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById(clickedOnMessage.signature) const findOriginalMessage = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById(clickedOnMessage.signature)
if(findOriginalMessage){ if (findOriginalMessage) {
const messageClientRect = findOriginalMessage.getBoundingClientRect() const messageClientRect = findOriginalMessage.getBoundingClientRect()
this.isLoadingGoToRepliedMessage = { this.isLoadingGoToRepliedMessage = {
...this.isLoadingGoToRepliedMessage, ...this.isLoadingGoToRepliedMessage,
@ -2136,16 +2171,16 @@ class ChatPage extends LitElement {
} }
await this.getOldMessageDynamic(0, this.messagesRendered[0].timestamp, message.timestamp - 7200000) await this.getOldMessageDynamic(0, this.messagesRendered[0].timestamp, message.timestamp - 7200000)
const findMessage = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById(message.signature) const findMessage = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById(message.signature)
if(findMessage){ if (findMessage) {
this.isLoadingGoToRepliedMessage = { this.isLoadingGoToRepliedMessage = {
...this.isLoadingGoToRepliedMessage, ...this.isLoadingGoToRepliedMessage,
loading: false loading: false
} }
findMessage.scrollIntoView({block: 'center' }) findMessage.scrollIntoView({ block: 'center' })
const findElement = findMessage.shadowRoot.querySelector('.message-parent') const findElement = findMessage.shadowRoot.querySelector('.message-parent')
if(findElement){ if (findElement) {
findElement.classList.add('blink-bg') findElement.classList.add('blink-bg')
setTimeout(()=> { setTimeout(() => {
findElement.classList.remove('blink-bg') findElement.classList.remove('blink-bg')
}, 2000) }, 2000)
} }
@ -2194,7 +2229,7 @@ class ChatPage extends LitElement {
} }
} }
setForwardProperties(forwardedMessage){ setForwardProperties(forwardedMessage) {
this.openForwardOpen = true this.openForwardOpen = true
this.forwardedMessage = forwardedMessage this.forwardedMessage = forwardedMessage
} }
@ -2255,7 +2290,7 @@ class ChatPage extends LitElement {
this.initChatEditor(); this.initChatEditor();
} }
async initUpdate(){ async initUpdate() {
this.pageNumber = 1 this.pageNumber = 1
const getAddressPublicKey = () => { const getAddressPublicKey = () => {
@ -2301,7 +2336,7 @@ class ChatPage extends LitElement {
const isRecipient = this.chatId.includes('direct') === true ? true : false; const isRecipient = this.chatId.includes('direct') === true ? true : false;
const groupId = this.chatId.split('/')[1]; const groupId = this.chatId.split('/')[1];
if(!isRecipient && groupId.toString() !== '0'){ if (!isRecipient && groupId.toString() !== '0') {
try { try {
const getMembers = await parentEpml.request("apiCall", { const getMembers = await parentEpml.request("apiCall", {
@ -2379,7 +2414,7 @@ class ChatPage extends LitElement {
const isEnabledChatEnter = localStorage.getItem('isEnabledChatEnter') const isEnabledChatEnter = localStorage.getItem('isEnabledChatEnter')
if(isEnabledChatEnter){ if (isEnabledChatEnter) {
this.isEnabledChatEnter = isEnabledChatEnter === 'false' ? false : true this.isEnabledChatEnter = isEnabledChatEnter === 'false' ? false : true
} }
@ -2406,14 +2441,14 @@ class ChatPage extends LitElement {
} }
} }
async getName (recipient) { async getName(recipient) {
try { try {
const getNames = await parentEpml.request("apiCall", { const getNames = await parentEpml.request("apiCall", {
type: "api", type: "api",
url: `/names/address/${recipient}`, url: `/names/address/${recipient}`,
}); });
if (Array.isArray(getNames) && getNames.length > 0 ) { if (Array.isArray(getNames) && getNames.length > 0) {
return getNames[0].name return getNames[0].name
} else { } else {
return '' return ''
@ -2425,14 +2460,14 @@ class ChatPage extends LitElement {
} }
async renderPlaceholder() { async renderPlaceholder() {
const getName = async (recipient)=> { const getName = async (recipient) => {
try { try {
const getNames = await parentEpml.request("apiCall", { const getNames = await parentEpml.request("apiCall", {
type: "api", type: "api",
url: `/names/address/${recipient}`, url: `/names/address/${recipient}`,
}); });
if (Array.isArray(getNames) && getNames.length > 0 ) { if (Array.isArray(getNames) && getNames.length > 0) {
return getNames[0].name return getNames[0].name
} else { } else {
return '' return ''
@ -2443,7 +2478,7 @@ class ChatPage extends LitElement {
} }
} }
let userName = "" let userName = ""
if(this.isReceipient){ if (this.isReceipient) {
userName = await getName(this._chatId); userName = await getName(this._chatId);
} }
const mstring = get("chatpage.cchange8"); const mstring = get("chatpage.cchange8");
@ -2461,12 +2496,12 @@ class ChatPage extends LitElement {
.setRepliedToMessageObj=${(val) => this.setRepliedToMessageObj(val)} .setRepliedToMessageObj=${(val) => this.setRepliedToMessageObj(val)}
.setEditedMessageObj=${(val) => this.setEditedMessageObj(val)} .setEditedMessageObj=${(val) => this.setEditedMessageObj(val)}
.sendMessage=${(val) => this._sendMessage(val)} .sendMessage=${(val) => this._sendMessage(val)}
.sendMessageForward=${(messageText, typeMessage, chatReference, isForward, forwardParams)=> this.sendMessage(messageText, typeMessage, chatReference, isForward, forwardParams)} .sendMessageForward=${(messageText, typeMessage, chatReference, isForward, forwardParams) => this.sendMessage(messageText, typeMessage, chatReference, isForward, forwardParams)}
.showLastMessageRefScroller=${(val) => this.showLastMessageRefScroller(val)} .showLastMessageRefScroller=${(val) => this.showLastMessageRefScroller(val)}
.emojiPicker=${this.emojiPicker} .emojiPicker=${this.emojiPicker}
?isLoadingMessages=${this.isLoadingOldMessages} ?isLoadingMessages=${this.isLoadingOldMessages}
.setIsLoadingMessages=${(val) => this.setIsLoadingMessages(val)} .setIsLoadingMessages=${(val) => this.setIsLoadingMessages(val)}
.setForwardProperties=${(forwardedMessage)=> this.setForwardProperties(forwardedMessage)} .setForwardProperties=${(forwardedMessage) => this.setForwardProperties(forwardedMessage)}
.setOpenPrivateMessage=${(val) => this.setOpenPrivateMessage(val)} .setOpenPrivateMessage=${(val) => this.setOpenPrivateMessage(val)}
.setOpenTipUser=${(val) => this.setOpenTipUser(val)} .setOpenTipUser=${(val) => this.setOpenTipUser(val)}
.setOpenUserInfo=${(val) => this.setOpenUserInfo(val)} .setOpenUserInfo=${(val) => this.setOpenUserInfo(val)}
@ -2474,13 +2509,13 @@ class ChatPage extends LitElement {
.setSelectedHead=${(val) => this.setSelectedHead(val)} .setSelectedHead=${(val) => this.setSelectedHead(val)}
?openTipUser=${this.openTipUser} ?openTipUser=${this.openTipUser}
.selectedHead=${this.selectedHead} .selectedHead=${this.selectedHead}
.goToRepliedMessage=${(val, val2)=> this.goToRepliedMessage(val, val2)} .goToRepliedMessage=${(val, val2) => this.goToRepliedMessage(val, val2)}
.getOldMessageAfter=${(val)=> this.getOldMessageAfter(val)} .getOldMessageAfter=${(val) => this.getOldMessageAfter(val)}
> >
</chat-scroller> </chat-scroller>
` `
} }
setIsLoadingMessages(val){ setIsLoadingMessages(val) {
this.isLoadingOldMessages = val this.isLoadingOldMessages = val
} }
async getUpdateComplete() { async getUpdateComplete() {
@ -2499,7 +2534,7 @@ class ChatPage extends LitElement {
return true; return true;
} }
updatePlaceholder(editor, text){ updatePlaceholder(editor, text) {
editor.extensionManager.extensions.forEach((extension) => { editor.extensionManager.extensions.forEach((extension) => {
if (extension.name === "placeholder") { if (extension.name === "placeholder") {
@ -2537,7 +2572,7 @@ class ChatPage extends LitElement {
await this.getUpdateComplete(); await this.getUpdateComplete();
const viewElement = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById('viewElement'); const viewElement = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById('viewElement');
if(viewElement){ if (viewElement) {
viewElement.scrollTop = 200 viewElement.scrollTop = 200
} }
@ -2572,7 +2607,7 @@ class ChatPage extends LitElement {
await this.getUpdateComplete(); await this.getUpdateComplete();
const viewElement = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById('viewElement'); const viewElement = this.shadowRoot.querySelector('chat-scroller').shadowRoot.getElementById('viewElement');
if(viewElement){ if (viewElement) {
viewElement.scrollTop = 200 viewElement.scrollTop = 200
} }
@ -2612,9 +2647,9 @@ class ChatPage extends LitElement {
await this.getUpdateComplete(); await this.getUpdateComplete();
const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template')); const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template'));
const findElement = marginElements.find((item)=> item.messageObj.signature === scrollElement.messageObj.signature) const findElement = marginElements.find((item) => item.messageObj.signature === scrollElement.messageObj.signature)
if(findElement){ if (findElement) {
findElement.scrollIntoView({ behavior: 'auto', block: 'center' }); findElement.scrollIntoView({ behavior: 'auto', block: 'center' });
} }
@ -2645,9 +2680,9 @@ class ChatPage extends LitElement {
this.isLoadingOldMessages = false this.isLoadingOldMessages = false
await this.getUpdateComplete(); await this.getUpdateComplete();
const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template')); const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template'));
const findElement = marginElements.find((item)=> item.messageObj.signature === scrollElement.messageObj.signature) const findElement = marginElements.find((item) => item.messageObj.signature === scrollElement.messageObj.signature)
if(findElement){ if (findElement) {
findElement.scrollIntoView({ behavior: 'auto', block: 'center' }); findElement.scrollIntoView({ behavior: 'auto', block: 'center' });
} }
@ -2683,9 +2718,9 @@ class ChatPage extends LitElement {
await this.getUpdateComplete(); await this.getUpdateComplete();
const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template')); const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template'));
const findElement = marginElements.find((item)=> item.messageObj.signature === scrollElement.messageObj.signature) const findElement = marginElements.find((item) => item.messageObj.signature === scrollElement.messageObj.signature)
if(findElement){ if (findElement) {
findElement.scrollIntoView({ behavior: 'auto', block: 'center' }); findElement.scrollIntoView({ behavior: 'auto', block: 'center' });
} }
@ -2709,16 +2744,16 @@ class ChatPage extends LitElement {
_publicKey: this._publicKey _publicKey: this._publicKey
}) })
this.messagesRendered = [ ...this.messagesRendered, ...replacedMessages].sort(function (a, b) { this.messagesRendered = [...this.messagesRendered, ...replacedMessages].sort(function (a, b) {
return a.timestamp return a.timestamp
- b.timestamp - b.timestamp
}) })
this.isLoadingOldMessages = false this.isLoadingOldMessages = false
await this.getUpdateComplete(); await this.getUpdateComplete();
const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template')); const marginElements = Array.from(this.shadowRoot.querySelector('chat-scroller').shadowRoot.querySelectorAll('message-template'));
const findElement = marginElements.find((item)=> item.messageObj.signature === scrollElement.messageObj.signature) const findElement = marginElements.find((item) => item.messageObj.signature === scrollElement.messageObj.signature)
if(findElement){ if (findElement) {
findElement.scrollIntoView({ behavior: 'auto', block: 'center' }); findElement.scrollIntoView({ behavior: 'auto', block: 'center' });
} }
@ -2770,12 +2805,12 @@ class ChatPage extends LitElement {
isNotInitial: true isNotInitial: true
}) })
const renderEachMessage = replacedMessages.map(async(msg)=> { const renderEachMessage = replacedMessages.map(async (msg) => {
await this.renderNewMessage(msg) await this.renderNewMessage(msg)
}) })
await Promise.all(renderEachMessage) await Promise.all(renderEachMessage)
if(this.chatId){ if (this.chatId && this.isPageVisible) {
window.parent.reduxStore.dispatch( window.parent.reduxAction.addChatLastSeen({ window.parent.reduxStore.dispatch(window.parent.reduxAction.addChatLastSeen({
key: this.chatId, key: this.chatId,
timestamp: Date.now() timestamp: Date.now()
})) }))
@ -2793,7 +2828,7 @@ class ChatPage extends LitElement {
setRepliedToMessageObj(messageObj) { setRepliedToMessageObj(messageObj) {
this.editor.commands.focus('end') this.editor.commands.focus('end')
this.repliedToMessageObj = {...messageObj}; this.repliedToMessageObj = { ...messageObj };
this.editedMessageObj = null; this.editedMessageObj = null;
this.requestUpdate(); this.requestUpdate();
} }
@ -2802,7 +2837,7 @@ class ChatPage extends LitElement {
setEditedMessageObj(messageObj) { setEditedMessageObj(messageObj) {
this.editor.commands.focus('end') this.editor.commands.focus('end')
this.editedMessageObj = {...messageObj}; this.editedMessageObj = { ...messageObj };
this.repliedToMessageObj = null; this.repliedToMessageObj = null;
this.requestUpdate(); this.requestUpdate();
} }
@ -2828,12 +2863,14 @@ class ChatPage extends LitElement {
*/ */
async renderNewMessage(newMessage) { async renderNewMessage(newMessage) {
if(newMessage.chatReference){ if (newMessage.chatReference) {
const findOriginalMessageIndex = this.messagesRendered.findIndex(msg=> msg.signature === newMessage.chatReference || (msg.chatReference && msg.chatReference === newMessage.chatReference) ) const findOriginalMessageIndex = this.messagesRendered.findIndex(msg => msg.signature === newMessage.chatReference || (msg.chatReference && msg.chatReference === newMessage.chatReference))
if(findOriginalMessageIndex !== -1 && this.messagesRendered[findOriginalMessageIndex].sender === newMessage.sender){ if (findOriginalMessageIndex !== -1 && this.messagesRendered[findOriginalMessageIndex].sender === newMessage.sender) {
const newMessagesRendered = [...this.messagesRendered] const newMessagesRendered = [...this.messagesRendered]
newMessagesRendered[findOriginalMessageIndex] = {...newMessage, timestamp: newMessagesRendered[findOriginalMessageIndex].timestamp, senderName: newMessagesRendered[findOriginalMessageIndex].senderName, newMessagesRendered[findOriginalMessageIndex] = {
sender: newMessagesRendered[findOriginalMessageIndex].sender, editedTimestamp: newMessage.timestamp } ...newMessage, timestamp: newMessagesRendered[findOriginalMessageIndex].timestamp, senderName: newMessagesRendered[findOriginalMessageIndex].senderName,
sender: newMessagesRendered[findOriginalMessageIndex].sender, editedTimestamp: newMessage.timestamp
}
this.messagesRendered = newMessagesRendered this.messagesRendered = newMessagesRendered
await this.getUpdateComplete(); await this.getUpdateComplete();
} }
@ -2869,7 +2906,7 @@ class ChatPage extends LitElement {
* @param {Object} encodedMessageObj * @param {Object} encodedMessageObj
* *
*/ */
decodeMessage(encodedMessageObj, isReceipient, _publicKey ) { decodeMessage(encodedMessageObj, isReceipient, _publicKey) {
let isReceipientVar; let isReceipientVar;
let _publicKeyVar; let _publicKeyVar;
try { try {
@ -2906,6 +2943,7 @@ class ChatPage extends LitElement {
async fetchChatMessages(chatId) { async fetchChatMessages(chatId) {
const initDirect = async (cid, noInitial) => { const initDirect = async (cid, noInitial) => {
let timeoutId
let initial = 0 let initial = 0
let directSocketTimeout let directSocketTimeout
@ -2932,8 +2970,13 @@ class ChatPage extends LitElement {
// Message Event // Message Event
this.webSocket.onmessage = async (e) => { this.webSocket.onmessage = async (e) => {
if (e.data === 'pong') {
clearTimeout(timeoutId);
directSocketTimeout = setTimeout(pingDirectSocket, 45000)
return
}
if (initial === 0) { if (initial === 0) {
if(noInitial) return if (noInitial) return
const cachedData = null const cachedData = null
let getInitialMessages = [] let getInitialMessages = []
if (cachedData && cachedData.length !== 0) { if (cachedData && cachedData.length !== 0) {
@ -2958,7 +3001,7 @@ class ChatPage extends LitElement {
} else { } else {
try { try {
if(e.data){ if (e.data) {
this.processMessages(JSON.parse(e.data), false) this.processMessages(JSON.parse(e.data), false)
} }
} catch (error) { } catch (error) {
@ -2972,7 +3015,7 @@ class ChatPage extends LitElement {
// Closed Event // Closed Event
this.webSocket.onclose = (e) => { this.webSocket.onclose = (e) => {
clearTimeout(directSocketTimeout) clearTimeout(directSocketTimeout)
if(e.reason === 'switch chat') return if (e.reason === 'switch chat') return
restartDirectWebSocket() restartDirectWebSocket()
} }
@ -2983,10 +3026,13 @@ class ChatPage extends LitElement {
const pingDirectSocket = () => { const pingDirectSocket = () => {
this.webSocket.send('ping') this.webSocket.send('ping')
timeoutId = setTimeout(() => {
directSocketTimeout = setTimeout(pingDirectSocket, 295000) this.webSocket.close();
clearTimeout(directSocketTimeout)
}, 5000);
} }
}; };
const restartDirectWebSocket = () => { const restartDirectWebSocket = () => {
const noInitial = true const noInitial = true
@ -2999,6 +3045,7 @@ class ChatPage extends LitElement {
} }
const initGroup = (gId, noInitial) => { const initGroup = (gId, noInitial) => {
let timeoutId
let groupId = Number(gId) let groupId = Number(gId)
let initial = 0 let initial = 0
@ -3029,9 +3076,13 @@ class ChatPage extends LitElement {
// Message Event // Message Event
this.webSocket.onmessage = async (e) => { this.webSocket.onmessage = async (e) => {
if (e.data === 'pong') {
clearTimeout(timeoutId);
groupSocketTimeout = setTimeout(pingGroupSocket, 45000)
return
}
if (initial === 0) { if (initial === 0) {
if(noInitial) return if (noInitial) return
const cachedData = null; const cachedData = null;
let getInitialMessages = [] let getInitialMessages = []
if (cachedData && cachedData.length !== 0) { if (cachedData && cachedData.length !== 0) {
@ -3071,19 +3122,22 @@ class ChatPage extends LitElement {
// Closed Event // Closed Event
this.webSocket.onclose = (e) => { this.webSocket.onclose = (e) => {
clearTimeout(groupSocketTimeout) clearTimeout(groupSocketTimeout)
if(e.reason === 'switch chat') return if (e.reason === 'switch chat') return
restartGroupWebSocket() restartGroupWebSocket()
} }
// Error Event // Error Event
this.webSocket.onerror = () => { this.webSocket.onerror = () => {
clearTimeout(groupSocketTimeout) clearTimeout(groupSocketTimeout)
this.webSocket.close();
} }
const pingGroupSocket = () => { const pingGroupSocket = () => {
this.webSocket.send('ping') this.webSocket.send('ping')
timeoutId = setTimeout(() => {
groupSocketTimeout = setTimeout(pingGroupSocket, 295000) this.webSocket.close();
clearTimeout(groupSocketTimeout)
}, 5000); // Close the WebSocket connection if no pong message is received within 5 seconds.
} }
}; };
@ -3105,22 +3159,22 @@ class ChatPage extends LitElement {
// Add to the messages... TODO: Save messages to localstorage and fetch from it to make it persistent... // Add to the messages... TODO: Save messages to localstorage and fetch from it to make it persistent...
} }
resetChatEditor(){ resetChatEditor() {
if(this.currentEditor === '_chatEditorDOM'){ if (this.currentEditor === '_chatEditorDOM') {
this.editor.commands.setContent('') this.editor.commands.setContent('')
} }
if(this.currentEditor === 'newChat'){ if (this.currentEditor === 'newChat') {
this.editorImage.commands.setContent('') this.editorImage.commands.setContent('')
} }
if(this.currentEditor === 'newAttachmentChat'){ if (this.currentEditor === 'newAttachmentChat') {
this.editorAttachment.commands.setContent('') this.editorAttachment.commands.setContent('')
} }
} }
async _sendMessage(outSideMsg, msg) { async _sendMessage(outSideMsg, msg) {
if(this.isReceipient){ if (this.isReceipient) {
let hasPublicKey = true let hasPublicKey = true
if(!this._publicKey.hasPubKey){ if (!this._publicKey.hasPubKey) {
hasPublicKey = false hasPublicKey = false
try { try {
const res = await parentEpml.request('apiCall', { const res = await parentEpml.request('apiCall', {
@ -3141,7 +3195,7 @@ class ChatPage extends LitElement {
} catch (error) { } catch (error) {
} }
if(!hasPublicKey || !this._publicKey.hasPubKey){ if (!hasPublicKey || !this._publicKey.hasPubKey) {
let err4string = get("chatpage.cchange39"); let err4string = get("chatpage.cchange39");
parentEpml.request('showSnackBar', `${err4string}`) parentEpml.request('showSnackBar', `${err4string}`)
return return
@ -3159,14 +3213,14 @@ class ChatPage extends LitElement {
this.isLoading = true; this.isLoading = true;
const trimmedMessage = msg const trimmedMessage = msg
const getName = async (recipient)=> { const getName = async (recipient) => {
try { try {
const getNames = await parentEpml.request("apiCall", { const getNames = await parentEpml.request("apiCall", {
type: "api", type: "api",
url: `/names/address/${recipient}`, url: `/names/address/${recipient}`,
}); });
if (Array.isArray(getNames) && getNames.length > 0 ) { if (Array.isArray(getNames) && getNames.length > 0) {
return getNames[0].name return getNames[0].name
} else { } else {
return '' return ''
@ -3191,7 +3245,7 @@ class ChatPage extends LitElement {
this.webWorkerFile = new WebWorkerFile(); this.webWorkerFile = new WebWorkerFile();
const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data); const byteCharacters = atob(b64Data);
const byteArrays = []; const byteArrays = [];
@ -3207,7 +3261,7 @@ class ChatPage extends LitElement {
byteArrays.push(byteArray); byteArrays.push(byteArray);
} }
const blob = new Blob(byteArrays, {type: contentType}); const blob = new Blob(byteArrays, { type: contentType });
return blob; return blob;
} }
const blob = b64toBlob(str, 'image/png'); const blob = b64toBlob(str, 'image/png');
@ -3231,7 +3285,7 @@ class ChatPage extends LitElement {
try { try {
await publishData({ await publishData({
registeredName: userName, registeredName: userName,
file : compressedFile, file: compressedFile,
service: 'QCHAT_IMAGE', service: 'QCHAT_IMAGE',
identifier: identifier, identifier: identifier,
parentEpml, parentEpml,
@ -3248,7 +3302,7 @@ class ChatPage extends LitElement {
typeMessage = 'edit'; typeMessage = 'edit';
let chatReference = outSideMsg.editedMessageObj.signature; let chatReference = outSideMsg.editedMessageObj.signature;
if(outSideMsg.editedMessageObj.chatReference){ if (outSideMsg.editedMessageObj.chatReference) {
chatReference = outSideMsg.editedMessageObj.chatReference; chatReference = outSideMsg.editedMessageObj.chatReference;
} }
@ -3280,7 +3334,7 @@ class ChatPage extends LitElement {
this.webWorkerFile = new WebWorkerFile(); this.webWorkerFile = new WebWorkerFile();
const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data); const byteCharacters = atob(b64Data);
const byteArrays = []; const byteArrays = [];
@ -3296,7 +3350,7 @@ class ChatPage extends LitElement {
byteArrays.push(byteArray); byteArrays.push(byteArray);
} }
const blob = new Blob(byteArrays, {type: contentType}); const blob = new Blob(byteArrays, { type: contentType });
return blob; return blob;
} }
@ -3339,7 +3393,7 @@ class ChatPage extends LitElement {
typeMessage = 'edit'; typeMessage = 'edit';
let chatReference = outSideMsg.editedMessageObj.signature; let chatReference = outSideMsg.editedMessageObj.signature;
if(outSideMsg.editedMessageObj.chatReference){ if (outSideMsg.editedMessageObj.chatReference) {
chatReference = outSideMsg.editedMessageObj.chatReference; chatReference = outSideMsg.editedMessageObj.chatReference;
} }
@ -3380,10 +3434,10 @@ class ChatPage extends LitElement {
const identifier = `qchat_${id}`; const identifier = `qchat_${id}`;
let compressedFile = ''; let compressedFile = '';
await new Promise(resolve => { await new Promise(resolve => {
new Compressor( image, { new Compressor(image, {
quality: .6, quality: .6,
maxWidth: 1200, maxWidth: 1200,
success(result){ success(result) {
const file = new File([result], "name", { const file = new File([result], "name", {
type: image.type type: image.type
}); });
@ -3405,9 +3459,9 @@ class ChatPage extends LitElement {
try { try {
await publishData({ await publishData({
registeredName: userName, registeredName: userName,
file : compressedFile, file: compressedFile,
service: 'QCHAT_IMAGE', service: 'QCHAT_IMAGE',
identifier : identifier, identifier: identifier,
parentEpml, parentEpml,
metaData: undefined, metaData: undefined,
uploadType: 'file', uploadType: 'file',
@ -3487,9 +3541,9 @@ class ChatPage extends LitElement {
try { try {
await publishData({ await publishData({
registeredName: userName, registeredName: userName,
file : attachment, file: attachment,
service: 'QCHAT_ATTACHMENT', service: 'QCHAT_ATTACHMENT',
identifier : identifier, identifier: identifier,
parentEpml, parentEpml,
metaData: undefined, metaData: undefined,
uploadType: 'file', uploadType: 'file',
@ -3539,11 +3593,11 @@ class ChatPage extends LitElement {
} }
let reactions = message.reactions || [] let reactions = message.reactions || []
const findEmojiIndex = reactions.findIndex((reaction)=> reaction.type === outSideMsg.reaction) const findEmojiIndex = reactions.findIndex((reaction) => reaction.type === outSideMsg.reaction)
if(findEmojiIndex !== -1){ if (findEmojiIndex !== -1) {
let users = reactions[findEmojiIndex].users || [] let users = reactions[findEmojiIndex].users || []
const findUserIndex = users.findIndex((user)=> user.address === this.selectedAddress.address ) const findUserIndex = users.findIndex((user) => user.address === this.selectedAddress.address)
if(findUserIndex !== -1){ if (findUserIndex !== -1) {
users.splice(findUserIndex, 1) users.splice(findUserIndex, 1)
} else { } else {
users.push({ users.push({
@ -3556,7 +3610,7 @@ class ChatPage extends LitElement {
qty: users.length, qty: users.length,
users users
} }
if(users.length === 0){ if (users.length === 0) {
reactions.splice(findEmojiIndex, 1) reactions.splice(findEmojiIndex, 1)
} }
} else { } else {
@ -3581,7 +3635,7 @@ class ChatPage extends LitElement {
} }
else if (this.repliedToMessageObj) { else if (this.repliedToMessageObj) {
let chatReference = this.repliedToMessageObj.signature; let chatReference = this.repliedToMessageObj.signature;
if(this.repliedToMessageObj.chatReference){ if (this.repliedToMessageObj.chatReference) {
chatReference = this.repliedToMessageObj.chatReference; chatReference = this.repliedToMessageObj.chatReference;
} }
typeMessage = 'reply'; typeMessage = 'reply';
@ -3597,7 +3651,7 @@ class ChatPage extends LitElement {
typeMessage = 'edit' typeMessage = 'edit'
let chatReference = this.editedMessageObj.signature let chatReference = this.editedMessageObj.signature
if(this.editedMessageObj.chatReference){ if (this.editedMessageObj.chatReference) {
chatReference = this.editedMessageObj.chatReference chatReference = this.editedMessageObj.chatReference
} }
@ -3686,9 +3740,9 @@ class ChatPage extends LitElement {
const sendForwardRequest = async () => { const sendForwardRequest = async () => {
const userInput = this.shadowRoot.getElementById("sendTo").value.trim(); const userInput = this.shadowRoot.getElementById("sendTo").value.trim();
if(!userInput && !this.forwardActiveChatHeadUrl.url) { if (!userInput && !this.forwardActiveChatHeadUrl.url) {
let err4string = get("chatpage.cchange65"); let err4string = get("chatpage.cchange65");
getSendChatResponse(false, true, err4string ); getSendChatResponse(false, true, err4string);
return return
} }
let publicKey = { let publicKey = {
@ -3794,7 +3848,7 @@ class ChatPage extends LitElement {
const recipientAddress = this.forwardActiveChatHeadUrl.url.split('/')[1]; const recipientAddress = this.forwardActiveChatHeadUrl.url.split('/')[1];
this.openForwardOpen = false; this.openForwardOpen = false;
if (isRecipient === true) { if (isRecipient === true) {
if(!publicKey.hasPubKey){ if (!publicKey.hasPubKey) {
let err4string = get("chatpage.cchange39"); let err4string = get("chatpage.cchange39");
parentEpml.request('showSnackBar', `${err4string}`); parentEpml.request('showSnackBar', `${err4string}`);
getSendChatResponse(false); getSendChatResponse(false);
@ -3857,7 +3911,7 @@ class ChatPage extends LitElement {
let chatBytesArray = null; let chatBytesArray = null;
await new Promise((res) => { await new Promise((res) => {
worker.postMessage({chatBytes, path, difficulty}); worker.postMessage({ chatBytes, path, difficulty });
worker.onmessage = e => { worker.onmessage = e => {
chatBytesArray = e.data.chatBytesArray; chatBytesArray = e.data.chatBytesArray;
nonce = e.data.nonce; nonce = e.data.nonce;
@ -3877,7 +3931,7 @@ class ChatPage extends LitElement {
const getSendChatResponse = (response, isForward, customErrorMessage) => { const getSendChatResponse = (response, isForward, customErrorMessage) => {
if (response === true) { if (response === true) {
this.resetChatEditor() this.resetChatEditor()
if(isForward){ if (isForward) {
let successString = get("blockpage.bcchange15"); let successString = get("blockpage.bcchange15");
parentEpml.request('showSnackBar', `${successString}`); parentEpml.request('showSnackBar', `${successString}`);
} }
@ -3896,7 +3950,7 @@ class ChatPage extends LitElement {
let err2string = get("chatpage.cchange21"); let err2string = get("chatpage.cchange21");
parentEpml.request('showSnackBar', `${customErrorMessage || err2string}`); parentEpml.request('showSnackBar', `${customErrorMessage || err2string}`);
} }
if(isForward && response !== true){ if (isForward && response !== true) {
this.isLoading = false; this.isLoading = false;
return return
} }

View File

@ -2,7 +2,7 @@ import { LitElement, html, css } from 'lit';
import { render } from 'lit/html.js'; import { render } from 'lit/html.js';
import { repeat } from 'lit/directives/repeat.js'; import { repeat } from 'lit/directives/repeat.js';
import { translate, get } from 'lit-translate'; import { translate, get } from 'lit-translate';
import {unsafeHTML} from 'lit/directives/unsafe-html.js'; import { unsafeHTML } from 'lit/directives/unsafe-html.js';
import { chatStyles } from './ChatScroller-css.js' import { chatStyles } from './ChatScroller-css.js'
import { Epml } from "../../../epml"; import { Epml } from "../../../epml";
import { cropAddress } from "../../utils/cropAddress"; import { cropAddress } from "../../utils/cropAddress";
@ -24,10 +24,12 @@ import axios from "axios";
import StarterKit from '@tiptap/starter-kit' import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'; import Underline from '@tiptap/extension-underline';
import Highlight from '@tiptap/extension-highlight' import Highlight from '@tiptap/extension-highlight'
import ShortUniqueId from 'short-unique-id';
const parentEpml = new Epml({ type: 'WINDOW', source: window.parent }) const parentEpml = new Epml({ type: 'WINDOW', source: window.parent })
let toggledMessage = {} let toggledMessage = {}
const uid = new ShortUniqueId()
const getApiKey = () => { const getApiKey = () => {
const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node]; const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node];
let apiKey = myNode.apiKey; let apiKey = myNode.apiKey;
@ -113,7 +115,20 @@ function processText(input) {
if (path) { if (path) {
query = query + `&path=${path}` query = query + `&path=${path}`
} }
window.location = `../../qdn/browser/index.html${query}` window.parent.reduxStore.dispatch(window.parent.reduxAction.setNewTab({
url: `qdn/browser/index.html${query}`,
id: uid(),
myPlugObj: {
"url": service === 'WEBSITE' ? "websites" : "qapps",
"domain": "core",
"page": `qdn/browser/index.html${query}`,
"title": name,
"mwcicon": service === 'WEBSITE' ? 'vaadin:desktop' : 'open_in_browser',
"menus": [],
"parent": false
}
}))
} catch (error) { } catch (error) {
console.log({ error }) console.log({ error })
} }
@ -157,7 +172,7 @@ class ChatScroller extends LitElement {
sendMessageForward: { attribute: false }, sendMessageForward: { attribute: false },
showLastMessageRefScroller: { attribute: false }, showLastMessageRefScroller: { attribute: false },
emojiPicker: { attribute: false }, emojiPicker: { attribute: false },
isLoadingMessages: { type: Boolean}, isLoadingMessages: { type: Boolean },
setIsLoadingMessages: { attribute: false }, setIsLoadingMessages: { attribute: false },
chatId: { type: String }, chatId: { type: String },
setForwardProperties: { attribute: false }, setForwardProperties: { attribute: false },
@ -171,8 +186,8 @@ class ChatScroller extends LitElement {
userName: { type: String }, userName: { type: String },
selectedHead: { type: Object }, selectedHead: { type: Object },
goToRepliedMessage: { attribute: false }, goToRepliedMessage: { attribute: false },
getOldMessageAfter: {attribute: false}, getOldMessageAfter: { attribute: false },
listSeenMessages: {type: Array} listSeenMessages: { type: Array }
} }
} }
@ -189,10 +204,10 @@ class ChatScroller extends LitElement {
this.hideMessages = JSON.parse(localStorage.getItem("MessageBlockedAddresses") || "[]") this.hideMessages = JSON.parse(localStorage.getItem("MessageBlockedAddresses") || "[]")
this.openTipUser = false; this.openTipUser = false;
this.openUserInfo = false; this.openUserInfo = false;
this.listSeenMessages= [] this.listSeenMessages = []
} }
addSeenMessage(val){ addSeenMessage(val) {
this.listSeenMessages.push(val) this.listSeenMessages.push(val)
} }
@ -210,7 +225,7 @@ class ChatScroller extends LitElement {
firstMessageInChat = false; firstMessageInChat = false;
} }
message = {...message, firstMessageInChat} message = { ...message, firstMessageInChat }
if (lastGroupedMessage) { if (lastGroupedMessage) {
timestamp = lastGroupedMessage.timestamp; timestamp = lastGroupedMessage.timestamp;
@ -267,7 +282,7 @@ class ChatScroller extends LitElement {
.setUserName=${(val) => this.setUserName(val)} .setUserName=${(val) => this.setUserName(val)}
id=${message.signature} id=${message.signature}
.goToRepliedMessage=${this.goToRepliedMessage} .goToRepliedMessage=${this.goToRepliedMessage}
.addSeenMessage=${(val)=> this.addSeenMessage(val)} .addSeenMessage=${(val) => this.addSeenMessage(val)}
.listSeenMessages=${this.listSeenMessages} .listSeenMessages=${this.listSeenMessages}
chatId=${this.chatId} chatId=${this.chatId}
> >
@ -280,19 +295,19 @@ class ChatScroller extends LitElement {
} }
shouldUpdate(changedProperties) { shouldUpdate(changedProperties) {
if(changedProperties.has('isLoadingMessages')){ if (changedProperties.has('isLoadingMessages')) {
return true return true
} }
if(changedProperties.has('chatId') && changedProperties.get('chatId')){ if (changedProperties.has('chatId') && changedProperties.get('chatId')) {
return true return true
} }
if(changedProperties.has('openTipUser')){ if (changedProperties.has('openTipUser')) {
return true return true
} }
if(changedProperties.has('openUserInfo')){ if (changedProperties.has('openUserInfo')) {
return true return true
} }
if(changedProperties.has('userName')){ if (changedProperties.has('userName')) {
return true return true
} }
// Only update element if prop1 changed. // Only update element if prop1 changed.
@ -339,7 +354,7 @@ class ChatScroller extends LitElement {
_upObserverhandler(entries) { _upObserverhandler(entries) {
if (entries[0].isIntersecting) { if (entries[0].isIntersecting) {
if(this.messages.length < 20){ if (this.messages.length < 20) {
return return
} }
this.setIsLoadingMessages(true); this.setIsLoadingMessages(true);
@ -413,11 +428,11 @@ class MessageTemplate extends LitElement {
setToggledMessage: { attribute: false }, setToggledMessage: { attribute: false },
setForwardProperties: { attribute: false }, setForwardProperties: { attribute: false },
viewImage: { type: Boolean }, viewImage: { type: Boolean },
setOpenPrivateMessage : { attribute: false }, setOpenPrivateMessage: { attribute: false },
setOpenTipUser: { attribute: false }, setOpenTipUser: { attribute: false },
setOpenUserInfo: { attribute: false }, setOpenUserInfo: { attribute: false },
setUserName: { attribute: false }, setUserName: { attribute: false },
openTipUser:{ type: Boolean }, openTipUser: { type: Boolean },
goToRepliedMessage: { attribute: false }, goToRepliedMessage: { attribute: false },
listSeenMessages: { type: Array }, listSeenMessages: { type: Array },
addSeenMessage: { attribute: false }, addSeenMessage: { attribute: false },
@ -480,12 +495,12 @@ class MessageTemplate extends LitElement {
const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node]; const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node];
const nodeUrl = myNode.protocol + '://' + myNode.domain + ':' + myNode.port; const nodeUrl = myNode.protocol + '://' + myNode.domain + ':' + myNode.port;
try{ try {
axios.get(`${nodeUrl}/arbitrary/QCHAT_ATTACHMENT/${attachment.name}/${attachment.identifier}?apiKey=${myNode.apiKey}`, { responseType: 'blob'}) axios.get(`${nodeUrl}/arbitrary/QCHAT_ATTACHMENT/${attachment.name}/${attachment.identifier}?apiKey=${myNode.apiKey}`, { responseType: 'blob' })
.then(response =>{ .then(response => {
let filename = attachment.attachmentName; let filename = attachment.attachmentName;
let blob = new Blob([response.data], { type:"application/octet-stream" }); let blob = new Blob([response.data], { type: "application/octet-stream" });
this.saveFileToDisk(blob , filename); this.saveFileToDisk(blob, filename);
}) })
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@ -511,9 +526,9 @@ class MessageTemplate extends LitElement {
} }
} }
firstUpdated(){ firstUpdated() {
const autoSeeChatList = window.parent.reduxStore.getState().app.autoLoadImageChats const autoSeeChatList = window.parent.reduxStore.getState().app.autoLoadImageChats
if(autoSeeChatList.includes(this.chatId) || this.listSeenMessages.includes(this.messageObj.signature)){ if (autoSeeChatList.includes(this.chatId) || this.listSeenMessages.includes(this.messageObj.signature)) {
this.viewImage = true this.viewImage = true
} }
@ -542,7 +557,7 @@ class MessageTemplate extends LitElement {
let attachment = null; let attachment = null;
try { try {
const parsedMessageObj = JSON.parse(this.messageObj.decodedMessage); const parsedMessageObj = JSON.parse(this.messageObj.decodedMessage);
if(+parsedMessageObj.version > 1 && parsedMessageObj.messageText){ if (+parsedMessageObj.version > 1 && parsedMessageObj.messageText) {
messageVersion2 = generateHTML(parsedMessageObj.messageText, [ messageVersion2 = generateHTML(parsedMessageObj.messageText, [
StarterKit, StarterKit,
Underline, Underline,
@ -598,8 +613,8 @@ class MessageTemplate extends LitElement {
const createImage = (imageUrl) => { const createImage = (imageUrl) => {
const imageHTMLRes = new Image(); const imageHTMLRes = new Image();
imageHTMLRes.src = imageUrl; imageHTMLRes.src = imageUrl;
imageHTMLRes.style= "max-width:45vh; max-height:40vh; border-radius: 5px; cursor: pointer"; imageHTMLRes.style = "max-width:45vh; max-height:40vh; border-radius: 5px; cursor: pointer";
imageHTMLRes.onclick= () => { imageHTMLRes.onclick = () => {
this.openDialogImage = true; this.openDialogImage = true;
} }
imageHTMLRes.onload = () => { imageHTMLRes.onload = () => {
@ -624,8 +639,8 @@ class MessageTemplate extends LitElement {
const createGif = (gif) => { const createGif = (gif) => {
const gifHTMLRes = new Image(); const gifHTMLRes = new Image();
gifHTMLRes.src = gif; gifHTMLRes.src = gif;
gifHTMLRes.style= "max-width:45vh; max-height:40vh; border-radius: 5px; cursor: pointer"; gifHTMLRes.style = "max-width:45vh; max-height:40vh; border-radius: 5px; cursor: pointer";
gifHTMLRes.onclick= () => { gifHTMLRes.onclick = () => {
this.openDialogGif = true; this.openDialogGif = true;
} }
gifHTMLRes.onload = () => { gifHTMLRes.onload = () => {
@ -639,8 +654,8 @@ class MessageTemplate extends LitElement {
}, 500); }, 500);
} else { } else {
gifHTMLRes.src = '/img/chain.png'; gifHTMLRes.src = '/img/chain.png';
gifHTMLRes.style= "max-width:45vh; max-height:20vh; border-radius: 5px; filter: opacity(0.5)"; gifHTMLRes.style = "max-width:45vh; max-height:20vh; border-radius: 5px; filter: opacity(0.5)";
gifHTMLRes.onclick= () => {} gifHTMLRes.onclick = () => { }
this.isGifLoaded = true this.isGifLoaded = true
} }
}; };
@ -655,7 +670,7 @@ class MessageTemplate extends LitElement {
if (this.viewImage || this.myAddress === this.messageObj.sender) { if (this.viewImage || this.myAddress === this.messageObj.sender) {
imageHTML = createImage(imageUrl); imageHTML = createImage(imageUrl);
imageHTMLDialog = createImage(imageUrl) imageHTMLDialog = createImage(imageUrl)
imageHTMLDialog.style= "height: auto; max-height: 80vh; width: auto; max-width: 80vw; object-fit: contain; border-radius: 5px"; imageHTMLDialog.style = "height: auto; max-height: 80vh; width: auto; max-width: 80vw; object-fit: contain; border-radius: 5px";
} }
} }
@ -663,10 +678,10 @@ class MessageTemplate extends LitElement {
const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node]; const myNode = window.parent.reduxStore.getState().app.nodeConfig.knownNodes[window.parent.reduxStore.getState().app.nodeConfig.node];
const nodeUrl = myNode.protocol + '://' + myNode.domain + ':' + myNode.port; const nodeUrl = myNode.protocol + '://' + myNode.domain + ':' + myNode.port;
gifUrl = `${nodeUrl}/arbitrary/${gif.service}/${gif.name}/${gif.identifier}?filepath=${gif.filePath}&apiKey=${myNode.apiKey}`; gifUrl = `${nodeUrl}/arbitrary/${gif.service}/${gif.name}/${gif.identifier}?filepath=${gif.filePath}&apiKey=${myNode.apiKey}`;
if (this.viewImage || this.myAddress === this.messageObj.sender){ if (this.viewImage || this.myAddress === this.messageObj.sender) {
gifHTML = createGif(gifUrl); gifHTML = createGif(gifUrl);
gifHTMLDialog = createGif(gifUrl) gifHTMLDialog = createGif(gifUrl)
gifHTMLDialog.style= "height: auto; max-height: 80vh; width: auto; max-width: 80vw; object-fit: contain; border-radius: 5px"; gifHTMLDialog.style = "height: auto; max-height: 80vh; width: auto; max-width: 80vw; object-fit: contain; border-radius: 5px";
} }
} }
@ -750,7 +765,7 @@ class MessageTemplate extends LitElement {
`} `}
<div <div
class="${`message-subcontainer2 class="${`message-subcontainer2
${this.myAddress === this.messageObj.sender && "message-myBg" } ${this.myAddress === this.messageObj.sender && "message-myBg"}
${(((this.isFirstMessage === true && this.isSingleMessageInGroup === false) || ${(((this.isFirstMessage === true && this.isSingleMessageInGroup === false) ||
(this.isSingleMessageInGroup === true && this.isLastMessageInGroup === true)) && this.myAddress !== this.messageObj.sender) (this.isSingleMessageInGroup === true && this.isLastMessageInGroup === true)) && this.myAddress !== this.messageObj.sender)
? 'message-triangle' ? 'message-triangle'
@ -799,7 +814,7 @@ class MessageTemplate extends LitElement {
</div> </div>
${repliedToData && html` ${repliedToData && html`
<div class="original-message" <div class="original-message"
@click=${()=> { @click=${() => {
this.goToRepliedMessage(repliedToData, this.messageObj) this.goToRepliedMessage(repliedToData, this.messageObj)
}}> }}>
<p <p
@ -807,7 +822,7 @@ class MessageTemplate extends LitElement {
class=${this.myAddress !== repliedToData.sender class=${this.myAddress !== repliedToData.sender
? "original-message-sender" ? "original-message-sender"
: "message-data-my-name"}> : "message-data-my-name"}>
${repliedToData.senderName ? repliedToData.senderName : cropAddress(repliedToData.sender) } ${repliedToData.senderName ? repliedToData.senderName : cropAddress(repliedToData.sender)}
</p> </p>
<p class="replied-message"> <p class="replied-message">
${version && version.toString() === '1' ? html` ${version && version.toString() === '1' ? html`
@ -822,7 +837,7 @@ class MessageTemplate extends LitElement {
`} `}
${image && !isImageDeleted && !this.viewImage && this.myAddress !== this.messageObj.sender ? html` ${image && !isImageDeleted && !this.viewImage && this.myAddress !== this.messageObj.sender ? html`
<div <div
@click=${()=> { @click=${() => {
this.viewImage = true this.viewImage = true
this.addSeenMessage(this.messageObj.signature) this.addSeenMessage(this.messageObj.signature)
}} }}
@ -841,7 +856,7 @@ class MessageTemplate extends LitElement {
`: ''} `: ''}
${image && !isImageDeleted && (this.viewImage || this.myAddress === this.messageObj.sender) ? html` ${image && !isImageDeleted && (this.viewImage || this.myAddress === this.messageObj.sender) ? html`
<div <div
class=${[`image-container`, !this.isImageLoaded ? 'defaultSize' : '', !this.isImageLoaded ? 'hideImg': ''].join(' ')} class=${[`image-container`, !this.isImageLoaded ? 'defaultSize' : '', !this.isImageLoaded ? 'hideImg' : ''].join(' ')}
style=${this.isFirstMessage && "margin-top: 10px;"}> style=${this.isFirstMessage && "margin-top: 10px;"}>
${imageHTML} ${imageHTML}
${this.myAddress === this.messageObj.sender ? html` ${this.myAddress === this.messageObj.sender ? html`
@ -858,7 +873,7 @@ class MessageTemplate extends LitElement {
` : html``} ` : html``}
${gif && !this.viewImage && this.myAddress !== this.messageObj.sender ? html` ${gif && !this.viewImage && this.myAddress !== this.messageObj.sender ? html`
<div <div
@click=${()=> { @click=${() => {
this.viewImage = true this.viewImage = true
}} }}
class=${[`image-container`, !this.isImageLoaded ? 'defaultSize' : ''].join(' ')} class=${[`image-container`, !this.isImageLoaded ? 'defaultSize' : ''].join(' ')}
@ -923,7 +938,7 @@ class MessageTemplate extends LitElement {
<div <div
id="messageContent" id="messageContent"
class="message" class="message"
style=${(image && replacedMessage !== "") &&"margin-top: 15px;"}> style=${(image && replacedMessage !== "") && "margin-top: 15px;"}>
${+version > 1 ? messageVersion2WithLink ? html`${messageVersion2WithLink}` : html` ${+version > 1 ? messageVersion2WithLink ? html`${messageVersion2WithLink}` : html`
${unsafeHTML(messageVersion2)} ${unsafeHTML(messageVersion2)}
` : ''} ` : ''}
@ -968,7 +983,7 @@ class MessageTemplate extends LitElement {
.showBlockUserModal=${() => this.showBlockUserModal()} .showBlockUserModal=${() => this.showBlockUserModal()}
.showBlockIconFunc=${(props) => this.showBlockIconFunc(props)} .showBlockIconFunc=${(props) => this.showBlockIconFunc(props)}
.showBlockAddressIcon=${this.showBlockAddressIcon} .showBlockAddressIcon=${this.showBlockAddressIcon}
.originalMessage=${{...this.messageObj, message}} .originalMessage=${{ ...this.messageObj, message }}
.setRepliedToMessageObj=${this.setRepliedToMessageObj} .setRepliedToMessageObj=${this.setRepliedToMessageObj}
.setEditedMessageObj=${this.setEditedMessageObj} .setEditedMessageObj=${this.setEditedMessageObj}
.myAddress=${this.myAddress} .myAddress=${this.myAddress}
@ -989,7 +1004,7 @@ class MessageTemplate extends LitElement {
</div> </div>
<div class="message-reactions" style="${reactions.length > 0 && <div class="message-reactions" style="${reactions.length > 0 &&
'margin-top: 10px; margin-bottom: 5px;'}"> 'margin-top: 10px; margin-bottom: 5px;'}">
${reactions.map((reaction, index)=> { ${reactions.map((reaction, index) => {
return html` return html`
<span <span
@click=${() => this.sendMessage({ @click=${() => this.sendMessage({
@ -1045,7 +1060,7 @@ class MessageTemplate extends LitElement {
? reaction.users[0].name ? reaction.users[0].name
: cropAddress(reaction.users[0].address)} ${get("chatpage.cchange74")} ${reaction.type}` : cropAddress(reaction.users[0].address)} ${get("chatpage.cchange74")} ${reaction.type}`
) )
: "" }> : ""}>
</vaadin-tooltip> </vaadin-tooltip>
</span> </span>
` `
@ -1067,7 +1082,7 @@ class MessageTemplate extends LitElement {
<mwc-dialog <mwc-dialog
id="showDialogPublicKey" id="showDialogPublicKey"
?open=${this.openDialogImage} ?open=${this.openDialogImage}
@closed=${()=> { @closed=${() => {
this.openDialogImage = false this.openDialogImage = false
}}> }}>
<div class="dialog-header"></div> <div class="dialog-header"></div>
@ -1078,7 +1093,7 @@ class MessageTemplate extends LitElement {
slot="primaryAction" slot="primaryAction"
dialogAction="cancel" dialogAction="cancel"
class="red" class="red"
@click=${()=>{ @click=${() => {
this.openDialogImage = false this.openDialogImage = false
}} }}
@ -1089,7 +1104,7 @@ class MessageTemplate extends LitElement {
<mwc-dialog <mwc-dialog
id="showDialogPublicKey" id="showDialogPublicKey"
?open=${this.openDialogGif} ?open=${this.openDialogGif}
@closed=${()=> { @closed=${() => {
this.openDialogGif = false this.openDialogGif = false
}}> }}>
<div class="dialog-header"></div> <div class="dialog-header"></div>
@ -1100,7 +1115,7 @@ class MessageTemplate extends LitElement {
slot="primaryAction" slot="primaryAction"
dialogAction="cancel" dialogAction="cancel"
class="red" class="red"
@click=${()=>{ @click=${() => {
this.openDialogGif = false this.openDialogGif = false
}} }}
@ -1111,7 +1126,7 @@ class MessageTemplate extends LitElement {
<mwc-dialog <mwc-dialog
hideActions hideActions
?open=${this.openDeleteImage} ?open=${this.openDeleteImage}
@closed=${()=> { @closed=${() => {
this.openDeleteImage = false; this.openDeleteImage = false;
}}> }}>
<div class="delete-image-msg"> <div class="delete-image-msg">
@ -1136,7 +1151,7 @@ class MessageTemplate extends LitElement {
<mwc-dialog <mwc-dialog
hideActions hideActions
?open=${this.openDeleteAttachment} ?open=${this.openDeleteAttachment}
@closed=${()=> { @closed=${() => {
this.openDeleteAttachment = false; this.openDeleteAttachment = false;
}}> }}>
<div class="delete-image-msg"> <div class="delete-image-msg">
@ -1155,7 +1170,8 @@ class MessageTemplate extends LitElement {
name: attachment.name, name: attachment.name,
identifier: attachment.identifier, identifier: attachment.identifier,
editedMessageObj: this.messageObj, editedMessageObj: this.messageObj,
})} })
}
}> }>
Yes Yes
</button> </button>
@ -1171,14 +1187,14 @@ class ChatMenu extends LitElement {
static get properties() { static get properties() {
return { return {
menuItems: { type: Array }, menuItems: { type: Array },
showPrivateMessageModal: {attribute: false}, showPrivateMessageModal: { attribute: false },
showBlockUserModal: {attribute: false}, showBlockUserModal: { attribute: false },
toblockaddress: { type: String, attribute: true }, toblockaddress: { type: String, attribute: true },
showBlockIconFunc: {attribute: false}, showBlockIconFunc: { attribute: false },
showBlockAddressIcon: { type: Boolean }, showBlockAddressIcon: { type: Boolean },
originalMessage: { type: Object }, originalMessage: { type: Object },
setRepliedToMessageObj: {attribute: false}, setRepliedToMessageObj: { attribute: false },
setEditedMessageObj: {attribute: false}, setEditedMessageObj: { attribute: false },
myAddress: { type: Object }, myAddress: { type: Object },
emojiPicker: { attribute: false }, emojiPicker: { attribute: false },
sendMessage: { attribute: false }, sendMessage: { attribute: false },
@ -1196,8 +1212,8 @@ class ChatMenu extends LitElement {
constructor() { constructor() {
super(); super();
this.showPrivateMessageModal = () => {}; this.showPrivateMessageModal = () => { };
this.showBlockUserModal = () => {}; this.showBlockUserModal = () => { };
} }
static get styles() { static get styles() {
@ -1217,12 +1233,12 @@ class ChatMenu extends LitElement {
} }
} }
versionErrorSnack(){ versionErrorSnack() {
let errorMsg = get("chatpage.cchange34") let errorMsg = get("chatpage.cchange34")
parentEpml.request('showSnackBar', `${errorMsg}`) parentEpml.request('showSnackBar', `${errorMsg}`)
} }
async messageForwardFunc(){ async messageForwardFunc() {
let parsedMessageObj = {} let parsedMessageObj = {}
let publicKey = { let publicKey = {
hasPubKey: false, hasPubKey: false,
@ -1272,7 +1288,7 @@ class ChatMenu extends LitElement {
class=${`menu-icon reaction ${!this.firstMessageInChat ? "tooltip" : ""}`} class=${`menu-icon reaction ${!this.firstMessageInChat ? "tooltip" : ""}`}
data-text="${translate("blockpage.bcchange13")}" data-text="${translate("blockpage.bcchange13")}"
@click=${(e) => { @click=${(e) => {
if(this.version === '0'){ if (this.version === '0') {
this.versionErrorSnack() this.versionErrorSnack()
return return
} }
@ -1318,7 +1334,7 @@ class ChatMenu extends LitElement {
this.versionErrorSnack() this.versionErrorSnack()
return return
} }
this.setRepliedToMessageObj({...this.originalMessage, version: this.version}); this.setRepliedToMessageObj({ ...this.originalMessage, version: this.version });
}}"> }}">
<vaadin-icon icon="vaadin:reply" slot="icon"></vaadin-icon> <vaadin-icon icon="vaadin:reply" slot="icon"></vaadin-icon>
</div> </div>
@ -1330,7 +1346,7 @@ class ChatMenu extends LitElement {
class=${`menu-icon ${!this.firstMessageInChat ? "tooltip" : ""}`} class=${`menu-icon ${!this.firstMessageInChat ? "tooltip" : ""}`}
data-text="${translate("blockpage.bcchange12")}" data-text="${translate("blockpage.bcchange12")}"
@click=${() => { @click=${() => {
if (this.version === '0'){ if (this.version === '0') {
this.versionErrorSnack() this.versionErrorSnack()
return return
} }

View File

@ -45,3 +45,6 @@ export const DECRYPT_DATA = 'DECRYPT_DATA'
// SAVE_FILE // SAVE_FILE
export const SAVE_FILE = 'SAVE_FILE' export const SAVE_FILE = 'SAVE_FILE'
//SET_TAB_NOTIFICATIONS
export const SET_TAB_NOTIFICATIONS = 'SET_TAB_NOTIFICATIONS'

View File

@ -892,10 +892,42 @@ class WebBrowser extends LitElement {
this.service = data.service; this.service = data.service;
this.identifier = data.identifier; this.identifier = data.identifier;
this.displayUrl = url; this.displayUrl = url;
const frame = window.frameElement
let tabId = ""
if (frame && frame.dataset.id) {
tabId = frame.dataset.id
}
if (data.name === 'Q-Mail') { if (data.name === 'Q-Mail') {
localStorage.setItem("Q-Mail-last-visited", Date.now()) localStorage.setItem("Q-Mail-last-visited", Date.now())
} }
window.parent.reduxStore.dispatch(window.parent.reduxAction.addTabInfo({
name: data.name,
service: data.service,
id: tabId ? tabId : ""
}))
return; return;
case actions.SET_TAB_NOTIFICATIONS: {
const { count } = data
if (isNaN(count)) {
response['error'] = 'count is not a number'
break
}
if (count === undefined) {
response['error'] = 'missing count'
break
}
window.parent.reduxStore.dispatch(window.parent.reduxAction.setTabNotifications({
name: this.name,
count: count
}))
response = true
break
}
case actions.PUBLISH_QDN_RESOURCE: { case actions.PUBLISH_QDN_RESOURCE: {
// optional fields: encrypt:boolean recipientPublicKey:string // optional fields: encrypt:boolean recipientPublicKey:string

View File

@ -115,6 +115,7 @@ let closeGracefully = false
let onceLoggedIn = false let onceLoggedIn = false
let retryOnClose = false let retryOnClose = false
let canPing = false let canPing = false
let timeoutId
parentEpml.subscribe('logged_in', async isLoggedIn => { parentEpml.subscribe('logged_in', async isLoggedIn => {
@ -127,18 +128,16 @@ parentEpml.subscribe('logged_in', async isLoggedIn => {
if (window.parent.location.protocol === "https:") { if (window.parent.location.protocol === "https:") {
activeChatSocketLink = `wss://${nodeUrl}/websockets/chat/active/${window.parent.reduxStore.getState().app.selectedAddress.address}`; activeChatSocketLink = `wss://${nodeUrl}/websockets/chat/active/${window.parent.reduxStore.getState().app.selectedAddress.address}?encoding=BASE64`;
} else { } else {
activeChatSocketLink = `ws://${nodeUrl}/websockets/chat/active/${window.parent.reduxStore.getState().app.selectedAddress.address}`; activeChatSocketLink = `ws://${nodeUrl}/websockets/chat/active/${window.parent.reduxStore.getState().app.selectedAddress.address}?encoding=BASE64`;
} }
const activeChatSocket = new WebSocket(activeChatSocketLink); const activeChatSocket = new WebSocket(activeChatSocketLink);
// Open Connection // Open Connection
activeChatSocket.onopen = () => { activeChatSocket.onopen = () => {
console.log(`[SOCKET]: Connected.`);
socketObject = activeChatSocket socketObject = activeChatSocket
initial = initial + 1 initial = initial + 1
@ -147,28 +146,26 @@ parentEpml.subscribe('logged_in', async isLoggedIn => {
// Message Event // Message Event
activeChatSocket.onmessage = (e) => { activeChatSocket.onmessage = (e) => {
if (e.data === 'pong') {
clearTimeout(timeoutId);
activeChatSocketTimeout = setTimeout(pingActiveChatSocket, 45000)
return
}
try {
chatHeadWatcher(JSON.parse(e.data)) chatHeadWatcher(JSON.parse(e.data))
} catch (error) {
}
} }
// Closed Event // Closed Event
activeChatSocket.onclose = () => { activeChatSocket.onclose = () => {
console.log(`[SOCKET]: CLOSED`);
clearInterval(activeChatSocketTimeout) clearInterval(activeChatSocketTimeout)
if (closeGracefully === false && initial <= 52) { if (closeGracefully === false) {
if (initial <= 52) {
parentEpml.request('showSnackBar', "Connection to the Qortal Core was lost, is your Core running ?")
retryOnClose = true retryOnClose = true
setTimeout(pingActiveChatSocket, 10000) setTimeout(pingActiveChatSocket, 10000)
initial = initial + 1
} else {
parentEpml.request('showSnackBar', "Cannot connect to the Qortal Core, restart UI and Core!")
}
} }
} }
@ -188,18 +185,21 @@ parentEpml.subscribe('logged_in', async isLoggedIn => {
initChatHeadSocket() initChatHeadSocket()
onceLoggedIn = true onceLoggedIn = true
activeChatSocketTimeout = setTimeout(pingActiveChatSocket, 295000) activeChatSocketTimeout = setTimeout(pingActiveChatSocket, 45000)
} else if (retryOnClose) { } else if (retryOnClose) {
retryOnClose = false retryOnClose = false
clearTimeout(activeChatSocketTimeout) clearTimeout(activeChatSocketTimeout)
initChatHeadSocket() initChatHeadSocket()
onceLoggedIn = true onceLoggedIn = true
activeChatSocketTimeout = setTimeout(pingActiveChatSocket, 295000) activeChatSocketTimeout = setTimeout(pingActiveChatSocket, 45000)
} else if (canPing) { } else if (canPing) {
socketObject.send('ping') socketObject.send('ping')
activeChatSocketTimeout = setTimeout(pingActiveChatSocket, 295000) timeoutId = setTimeout(() => {
socketObject.close();
clearTimeout(activeChatSocketTimeout)
}, 5000);
} }
} else { } else {