Skip to content

Commit

Permalink
getting default chats
Browse files Browse the repository at this point in the history
  • Loading branch information
dendidibe committed Aug 6, 2023
1 parent 768e751 commit a46c8b7
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 58 deletions.
16 changes: 9 additions & 7 deletions client-web/src/components/AppTopNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import { TActiveRoomFilter, useStoreState } from "../store";
import { Badge, Divider } from "@mui/material";
import {
coinsMainName,
defaultChats,
defaultMetaRoom,
ROOMS_FILTERS,
} from "../config/config";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}
});
Expand Down
9 changes: 9 additions & 0 deletions client-web/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<IDefaultChatRoom[]>("/apps/get-default-rooms");
}
export function createApp(fd: FormData) {
const owner = useStoreState.getState().user;
return http.post("/apps", fd, {
Expand Down
37 changes: 17 additions & 20 deletions client-web/src/pages/AppEdit/UserDefaults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -28,10 +27,12 @@ export const UserDefaults: React.FC<IUserDefaults> = ({}) => {
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,
Expand All @@ -58,14 +59,18 @@ export const UserDefaults: React.FC<IUserDefaults> = ({}) => {
) => {
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(
"defaultAccessProfileOpen",
defaultAccessProfileOpen.toString()
);
fd.append("usersCanFree", usersCanFree.toString());
fd.append("defaultRooms", JSON.stringify(defaultRooms));
try {
const res = await http.updateAppSettings(appId, fd);
setUser({ ...user, homeScreen: "" });
Expand Down Expand Up @@ -124,41 +129,33 @@ export const UserDefaults: React.FC<IUserDefaults> = ({}) => {
<Box
sx={{
display: "grid",
gridTemplateColumns: "0.25fr 3.5fr 0.25fr",
gridTemplateColumns: "0.9fr 0.1fr",
gap: 1,
alignItems: "center",
fontWeight: "bold",
fontSize: 14,
}}
>
<Typography sx={{ fontWeight: "bold", width: 150 }}>
Title
</Typography>
<Typography sx={{ fontWeight: "bold" }}>JID</Typography>
<Typography sx={{ fontWeight: "bold" }}>Pinned</Typography>
<Typography
sx={{ fontWeight: "bold", textAlign: "center" }}
>
Pinned
</Typography>
</Box>
{defaultChatRooms.map((item, i) => {
return (
<Box
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,
}}
>
<TextField
sx={{ width: 150 }}
margin="dense"
name="name"
fullWidth
variant="outlined"
value={item.name}
onChange={(e) => changeRoomInfo(e, i)}
/>
<TextField
margin="dense"
name="jid"
Expand Down
7 changes: 7 additions & 0 deletions client-web/src/pages/Routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export const Routes = () => {
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) => {
Expand Down Expand Up @@ -117,6 +118,12 @@ export const Routes = () => {
useEffect(() => {
getAppConfig();
}, []);
useEffect(() => {
if(appConfig.appToken) {

getDefaultChats();
}
}, [appConfig.appToken]);

useEffect(() => {
if (user.walletAddress) {
Expand Down
45 changes: 32 additions & 13 deletions client-web/src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 = {
Expand All @@ -166,7 +166,7 @@ export type TApp = {
appGoogleId?: string;
appLogo?: string;
firebaseWebConfigString?: string;
stats: AppStats;
stats: AppStats;
bundleId: string;
coinName: string;
coinSymbol: string;
Expand Down Expand Up @@ -258,6 +258,9 @@ interface IStore {
};
showHeaderError: boolean;
setShowHeaderError: (value: boolean) => void;
defaultChatRooms: IDefaultChatRoom[];
setDefaultChatRooms: (value: IDefaultChatRoom[]) => void;
getDefaultChats: () => Promise<void>;
ACL: http.IUserAcl;
messages: TMessage[];
currentThreadViewMessage: TMessageHistory;
Expand Down Expand Up @@ -345,6 +348,7 @@ const _useStore = create<IStore>()(
isAgreeWithTerms: false,
homeScreen: "",
},
defaultChatRooms: [],
config: {
firebaseWebConfigString: "",
primaryColor: "",
Expand Down Expand Up @@ -492,6 +496,21 @@ const _useStore = create<IStore>()(
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 = {
Expand Down
14 changes: 6 additions & 8 deletions client-web/src/xmpp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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) =>
Expand Down Expand Up @@ -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) {
Expand Down
23 changes: 13 additions & 10 deletions client-web/src/xmppHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand Down Expand Up @@ -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, () => {
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit a46c8b7

Please sign in to comment.