From a46c8b752157e0e74081bac781ebab1360b48c1d Mon Sep 17 00:00:00 2001 From: Mykhailo Mohyliuk Date: Sun, 6 Aug 2023 22:32:25 +0300 Subject: [PATCH] getting default chats --- client-web/src/components/AppTopNav.tsx | 16 ++++--- client-web/src/http.ts | 9 ++++ client-web/src/pages/AppEdit/UserDefaults.tsx | 37 +++++++-------- client-web/src/pages/Routes.tsx | 7 +++ client-web/src/store/index.ts | 45 +++++++++++++------ client-web/src/xmpp.ts | 14 +++--- client-web/src/xmppHandler.ts | 23 +++++----- 7 files changed, 93 insertions(+), 58 deletions(-) diff --git a/client-web/src/components/AppTopNav.tsx b/client-web/src/components/AppTopNav.tsx index 2e0bb8c2..683d0676 100644 --- a/client-web/src/components/AppTopNav.tsx +++ b/client-web/src/components/AppTopNav.tsx @@ -24,7 +24,6 @@ import { TActiveRoomFilter, useStoreState } from "../store"; import { Badge, Divider } from "@mui/material"; import { coinsMainName, - defaultChats, defaultMetaRoom, ROOMS_FILTERS, } from "../config/config"; @@ -106,9 +105,7 @@ const AppTopNav = () => { const mainCoinBalance = useStoreState((state) => state.balance.find((el) => el.tokenName === coinsMainName) ); - const firebaseAppId = useStoreState( - (s) => s.config.firebaseConfig.appId - ); + const firebaseAppId = useStoreState((s) => s.config.firebaseConfig.appId); const setBalance = useStoreState((state) => state.setBalance); const rooms = useStoreState((state) => state.userChatRooms); @@ -189,15 +186,20 @@ const AppTopNav = () => { meta: 0, private: 0, }; + const chats = useStoreState.getState().defaultChatRooms; + const chatsMap = {}; + chats.forEach((c) => { + chatsMap[c.jid] = c; + }); rooms.forEach((item) => { const splitedJid = item.jid.split("@")[0]; - if (defaultChats[splitedJid]) { + if (chatsMap[splitedJid]) { counts.official += item.unreadMessages; } - if (!defaultChats[splitedJid] && +item.users_cnt < 3) { + if (!chatsMap[splitedJid] && +item.users_cnt < 3) { counts.private += item.unreadMessages; } - if (!defaultChats[splitedJid] && +item.users_cnt >= 3) { + if (!chatsMap[splitedJid] && +item.users_cnt >= 3) { counts.meta += item.unreadMessages; } }); diff --git a/client-web/src/http.ts b/client-web/src/http.ts index f37f973f..d6fa7f2d 100644 --- a/client-web/src/http.ts +++ b/client-web/src/http.ts @@ -27,6 +27,11 @@ export interface ICompany { registrationNumber: string; payeReference: string; } +export interface IDefaultChatRoom { + jid: string; + pinned: boolean; + title: string; +} export type TUser = { firstName: string; lastName: string; @@ -564,7 +569,11 @@ export function loginOwner(email: string, password: string) { export function getApps() { return httpWithAuth().get("/apps"); } +export function getDefaultChats() { + const appToken = useStoreState.getState().config.appToken; + return httpWithToken(appToken).get("/apps/get-default-rooms"); +} export function createApp(fd: FormData) { const owner = useStoreState.getState().user; return http.post("/apps", fd, { diff --git a/client-web/src/pages/AppEdit/UserDefaults.tsx b/client-web/src/pages/AppEdit/UserDefaults.tsx index b3f34d8c..007ae1b3 100644 --- a/client-web/src/pages/AppEdit/UserDefaults.tsx +++ b/client-web/src/pages/AppEdit/UserDefaults.tsx @@ -13,7 +13,6 @@ import React, { useState } from "react"; import { useSnackbar } from "../../context/SnackbarContext"; import { useStoreState } from "../../store"; import * as http from "../../http"; -import { defaultChats } from "../../config/config"; import { useParams } from "react-router"; import xmpp from "../../xmpp"; import { CONFERENCEDOMAIN } from "../../constants"; @@ -28,10 +27,12 @@ export const UserDefaults: React.FC = ({}) => { const updateApp = useStoreState((state) => state.updateApp); const setUser = useStoreState((state) => state.setUser); const user = useStoreState((state) => state.user); + const defaultChats = useStoreState((state) => state.defaultChatRooms); + const [defaultChatRooms, setDefaultChatRooms] = useState(() => - Object.entries(defaultChats).map((item, i) => ({ - ...item[1], - jid: item[0], + defaultChats.map((item, i) => ({ + ...item, + jid: item.jid, checked: i === 0, disabled: i === 0, error: false, @@ -58,7 +59,10 @@ export const UserDefaults: React.FC = ({}) => { ) => { setSubmitting(true); const fd = new FormData(); - + const defaultRooms = defaultChatRooms.map((room) => ({ + jid: room.jid, + pinned: room.checked, + })); fd.append("displayName", app.displayName); fd.append("defaultAccessAssetsOpen", defaultAccessAssetsOpen.toString()); fd.append( @@ -66,6 +70,7 @@ export const UserDefaults: React.FC = ({}) => { defaultAccessProfileOpen.toString() ); fd.append("usersCanFree", usersCanFree.toString()); + fd.append("defaultRooms", JSON.stringify(defaultRooms)); try { const res = await http.updateAppSettings(appId, fd); setUser({ ...user, homeScreen: "" }); @@ -124,18 +129,19 @@ export const UserDefaults: React.FC = ({}) => { - - Title - JID - Pinned + + Pinned + {defaultChatRooms.map((item, i) => { return ( @@ -143,22 +149,13 @@ export const UserDefaults: React.FC = ({}) => { key={i} sx={{ display: "grid", - gridTemplateColumns: "0.25fr 3.5fr 0.25fr", + gridTemplateColumns: "0.9fr 0.1fr", gap: 1, alignItems: "center", fontWeight: "bold", fontSize: 14, }} > - changeRoomInfo(e, i)} - /> { const [loading, setLoading] = useState(false); const [isAppConfigError, setIsAppConfigError] = useState(false); const lastAuthUrl = useRef(""); + const getDefaultChats = useStoreState((state) => state.getDefaultChats); const history = useHistory(); const getDocuments = async (walletAddress: string) => { @@ -117,6 +118,12 @@ export const Routes = () => { useEffect(() => { getAppConfig(); }, []); + useEffect(() => { + if(appConfig.appToken) { + + getDefaultChats(); + } + }, [appConfig.appToken]); useEffect(() => { if (user.walletAddress) { diff --git a/client-web/src/store/index.ts b/client-web/src/store/index.ts index 68b6375d..4c87490a 100644 --- a/client-web/src/store/index.ts +++ b/client-web/src/store/index.ts @@ -4,7 +4,7 @@ import { persist, devtools } from "zustand/middleware"; import * as http from "../http"; import { stat } from "fs"; import type { Stripe } from "stripe"; -import { THomeScreen } from "../http"; +import { IDefaultChatRoom, THomeScreen } from "../http"; export type TUser = { firstName: string; @@ -139,18 +139,18 @@ export type TUserChatRooms = { }; export type AppStats = { - recentlyApiCalls: number - recentlyFiles: number - recentlyIssuance: number - recentlyRegistered: number - recentlySessions: number - recentlyTransactions: number - totalApiCalls: number - totalFiles: number - totalIssuance: number + recentlyApiCalls: number; + recentlyFiles: number; + recentlyIssuance: number; + recentlyRegistered: number; + recentlySessions: number; + recentlyTransactions: number; + totalApiCalls: number; + totalFiles: number; + totalIssuance: number; totalRegistered: number; - totalSessions: number - totalTransactions: number + totalSessions: number; + totalTransactions: number; }; export type TApp = { @@ -166,7 +166,7 @@ export type TApp = { appGoogleId?: string; appLogo?: string; firebaseWebConfigString?: string; -stats: AppStats; + stats: AppStats; bundleId: string; coinName: string; coinSymbol: string; @@ -258,6 +258,9 @@ interface IStore { }; showHeaderError: boolean; setShowHeaderError: (value: boolean) => void; + defaultChatRooms: IDefaultChatRoom[]; + setDefaultChatRooms: (value: IDefaultChatRoom[]) => void; + getDefaultChats: () => Promise; ACL: http.IUserAcl; messages: TMessage[]; currentThreadViewMessage: TMessageHistory; @@ -345,6 +348,7 @@ const _useStore = create()( isAgreeWithTerms: false, homeScreen: "", }, + defaultChatRooms: [], config: { firebaseWebConfigString: "", primaryColor: "", @@ -492,6 +496,21 @@ const _useStore = create()( set((state) => { state.apps = []; }), + setDefaultChatRooms: (rooms) => + set((state) => { + state.defaultChatRooms = rooms; + }), + + getDefaultChats: async () => { + try { + const chats = await http.getDefaultChats(); + set((state) => { + state.defaultChatRooms = chats.data; + }); + } catch (error) { + console.log(error); + } + }, clearUser: () => set((state) => { state.user = { diff --git a/client-web/src/xmpp.ts b/client-web/src/xmpp.ts index 438bf142..06f09ebf 100644 --- a/client-web/src/xmpp.ts +++ b/client-web/src/xmpp.ts @@ -4,7 +4,6 @@ import { CONFERENCEDOMAIN, DOMAIN, SERVICE } from "./constants"; import { useStoreState } from "./store"; import { walletToUsername } from "./utils/walletManipulation"; import { XmppHandler } from "./xmppHandler"; -import { defaultChats } from "./config/config"; const xmppMessagesHandler = new XmppHandler(); @@ -25,12 +24,12 @@ export class XmppClass { username: walletToUsername(walletAddress), password, }); - this.client.setMaxListeners(20) + this.client.setMaxListeners(20); this.client.start(); this.client.on("online", (jid) => { - xmppMessagesHandler.getListOfRooms(this) - this.subscribeToDefaultChats() + xmppMessagesHandler.getListOfRooms(this); + this.subscribeToDefaultChats(); }); this.client.on("stanza", xmppMessagesHandler.onMessageHistory); this.client.on("stanza", (stanza) => @@ -129,10 +128,9 @@ export class XmppClass { this.client.send(message); }; subscribeToDefaultChats = () => { - Object.entries(defaultChats).forEach(([key]) => { - const jid = key + CONFERENCEDOMAIN; - - this.subsribe(jid); + const chats = useStoreState.getState().defaultChatRooms; + chats.forEach((chat) => { + this.subsribe(chat.jid); }); }; subsribe(address: string) { diff --git a/client-web/src/xmppHandler.ts b/client-web/src/xmppHandler.ts index cdea9f09..390677cd 100644 --- a/client-web/src/xmppHandler.ts +++ b/client-web/src/xmppHandler.ts @@ -7,8 +7,6 @@ import { useStoreState, } from "./store"; import { Element } from "ltx"; -import { defaultChats } from "./config/config"; -import { CONFERENCEDOMAIN } from "./constants"; import { xml } from "@xmpp/client"; import { sendBrowserNotification } from "./utils"; import { createMessage } from "./utils/createMessage"; @@ -26,8 +24,12 @@ export class XmppHandler { private lastRomJIDLoading: string = ""; getRoomGroup = (jid: string, userCount: number): TActiveRoomFilter => { - const splittedJid = jid.split("@")[0]; - if (defaultChats[splittedJid]) { + const chats = useStoreState.getState().defaultChatRooms; + const chatsMap = {}; + chats.forEach((c) => { + chatsMap[c.jid] = c; + }); + if (chatsMap[jid]) { return "official"; } return "groups"; @@ -78,7 +80,7 @@ export class XmppHandler { const isCurrentUser = msg.data.senderWalletAddress === useStoreState.getState().user.walletAddress; - playCoinSound(+msg.data.tokenAmount) + playCoinSound(+msg.data.tokenAmount); if (!isCurrentUser) { useStoreState.getState().updateCounterChatRoom(data.attrs.roomJid); sendBrowserNotification(msg.body, () => { @@ -213,13 +215,13 @@ export class XmppHandler { stanza.getChild("fin")?.getChild("set")?.getChild("last")?.children[0] ); - if(stanza.attrs.type === "error" || stanza.name === "iq"){ + if (stanza.attrs.type === "error" || stanza.name === "iq") { useStoreState.getState().setLoaderArchive(false); - console.log("ERROR: ",stanza.attrs.type, stanza) + console.log("ERROR: ", stanza.attrs.type, stanza); } if (stanza.getChild("fin")) { - // if (!this.isGettingMessages) { + // if (!this.isGettingMessages) { useStoreState.getState().updateMessageHistory(this.temporaryMessages); this.isGettingMessages = false; @@ -432,8 +434,9 @@ export class XmppHandler { xmpp.client.send(xml("presence")); xmpp.getArchive(xmpp.client?.jid?.toString()); - Object.keys(defaultChats).forEach((roomJID) => { - xmpp.presenceInRoom(roomJID + CONFERENCEDOMAIN); + const chats = useStoreState.getState().defaultChatRooms; + chats.forEach((chat) => { + xmpp.presenceInRoom(chat.jid); }); xmpp.getRooms(); xmpp.getBlackList();