mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-03 14:38:45 +00:00
working error handling
This commit is contained in:
1 parent
aeebec4a90
commit
9403edcb92
15 files changed
+267
-78
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Snackbar } from "@material-ui/core";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import useAlerts from "../hooks/useAlerts";
|
||||
import Alert from "../../../ui/components/Alert";
|
||||
|
||||
const useStyles = makeStyles(() => ({
|
||||
root: {
|
||||
width: "100%",
|
||||
bottom: "60px",
|
||||
position: 'absolute',
|
||||
},
|
||||
}));
|
||||
|
||||
const ALERT_TIMEOUT = 6000;
|
||||
|
||||
export default function AlertBar() {
|
||||
const classes = useStyles();
|
||||
const { t } = useTranslation();
|
||||
const { createMessageGroupResult, setCreateMessageGroupResult } = useAlerts();
|
||||
const [severity, setSeverity] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
setCreateMessageGroupResult(null);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!createMessageGroupResult) return;
|
||||
|
||||
const { error, phoneNumber } = createMessageGroupResult
|
||||
if (error && phoneNumber) {
|
||||
const error = `${t("APPS_MESSAGES_INVALID_PHONE_NUMBER")}${phoneNumber}`;
|
||||
setOpen(true);
|
||||
setSeverity("error");
|
||||
setMessage(error);
|
||||
} else if (error) {
|
||||
setOpen(true);
|
||||
setSeverity("error");
|
||||
setMessage(t("APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED"));
|
||||
}
|
||||
}, [createMessageGroupResult, t]);
|
||||
|
||||
return (
|
||||
<Snackbar
|
||||
autoHideDuration={ALERT_TIMEOUT}
|
||||
className={classes.root}
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
>
|
||||
<Alert onClose={handleClose} severity={severity}>
|
||||
{message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
);
|
||||
}
|
||||
@@ -3,10 +3,11 @@ import { AppWrapper } from "../../../ui/components";
|
||||
import { AppTitle } from "../../../ui/components/AppTitle";
|
||||
import { AppContent } from "../../../ui/components/AppContent";
|
||||
import { useApp } from "../../../os/apps/hooks/useApps";
|
||||
import MessagesList from "./list/MessagesList";
|
||||
import AlertBar from './AlertBar';
|
||||
import { MessageModal } from "./modal/MessageModal";
|
||||
import MessageGroupModal from "./modal/MessageGroupModal";
|
||||
import NewMessageGroupButton from "./buttons/NewMessageGroupButton";
|
||||
import MessagesList from "./list/MessagesList";
|
||||
import './messages.css'
|
||||
|
||||
export const MessagesApp = () => {
|
||||
@@ -20,6 +21,7 @@ export const MessagesApp = () => {
|
||||
<MessagesList />
|
||||
<NewMessageGroupButton />
|
||||
</AppContent>
|
||||
<AlertBar />
|
||||
</AppWrapper>
|
||||
);
|
||||
};
|
||||
@@ -41,7 +41,7 @@ const NewMessageGroupForm = () => {
|
||||
onChange={e => setParticipants(e.target.value)}
|
||||
placeholder={t("APPS_MESSAGES_NEW_MESSAGE_GROUP")}
|
||||
className={classes.newGroupinput}
|
||||
inputRef={(input) => input && input.focus()}
|
||||
autoFocus
|
||||
inputProps={{
|
||||
className: classes.messagesInput
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import React from 'react'
|
||||
import { ListItem, ListItemText, ListItemAvatar, Avatar as MuiAvatar } from '@material-ui/core';
|
||||
|
||||
import { MessageGroup } from '../../../../common/interfaces/messages';
|
||||
|
||||
interface IProps {
|
||||
messageGroup: MessageGroup;
|
||||
handleClick: (group: MessageGroup) => () => void;
|
||||
}
|
||||
|
||||
const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => {
|
||||
return (
|
||||
<ListItem
|
||||
key={messageGroup.groupId}
|
||||
onClick={handleClick(messageGroup)}
|
||||
divider
|
||||
button
|
||||
>
|
||||
<ListItemAvatar>
|
||||
<MuiAvatar src={messageGroup?.avatar} />
|
||||
</ListItemAvatar>
|
||||
<ListItemText>
|
||||
{messageGroup.label || messageGroup.groupDisplay}
|
||||
</ListItemText>
|
||||
</ListItem>
|
||||
)
|
||||
}
|
||||
|
||||
export default MessageGroupItem;
|
||||
@@ -1,13 +1,13 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { List, ListItem, ListItemText, ListItemAvatar, Avatar as MuiAvatar } from '@material-ui/core';
|
||||
import { List } from '@material-ui/core';
|
||||
|
||||
import { MessageGroup } from '../../../../common/interfaces/messages';
|
||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
||||
import useMessages from '../../hooks/useMessages';
|
||||
import useModals from '../../hooks/useModals';
|
||||
import MessageSearch from './MessageSearch';
|
||||
import MessageGroupItem from './MessageGroupItem';
|
||||
import useStyles from './list.styles';
|
||||
import { format } from 'path';
|
||||
|
||||
const MessagesList = (): any => {
|
||||
const classes = useStyles();
|
||||
@@ -40,19 +40,11 @@ const MessagesList = (): any => {
|
||||
<MessageSearch value={searchValue} handleChange={e => setSearchValue(e.target.value)} />
|
||||
<List className={classes.root}>
|
||||
{filteredGroups.map((messageGroup) => (
|
||||
<ListItem
|
||||
<MessageGroupItem
|
||||
key={messageGroup.groupId}
|
||||
onClick={handleClick(messageGroup)}
|
||||
divider
|
||||
button
|
||||
>
|
||||
<ListItemAvatar>
|
||||
<MuiAvatar src={messageGroup?.avatar} />
|
||||
</ListItemAvatar>
|
||||
<ListItemText>
|
||||
{messageGroup.label || messageGroup.groupDisplay}
|
||||
</ListItemText>
|
||||
</ListItem>
|
||||
messageGroup={messageGroup}
|
||||
handleClick={handleClick}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
</>
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
#messages-app {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* override the FAB (action buttons) background when selected */
|
||||
#messages-app .MuiFab-primary {
|
||||
background: #ffa000 !important;
|
||||
|
||||
@@ -17,4 +17,8 @@ export const messageState = {
|
||||
key: 'showNewMessageGroup',
|
||||
default: false
|
||||
}),
|
||||
createMessageGroupResult: atom({
|
||||
key: 'createMessageGroupResult',
|
||||
default: null
|
||||
}),
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useRecoilState } from 'recoil';
|
||||
|
||||
import { messageState } from './state';
|
||||
|
||||
interface IUseAlerts {
|
||||
createMessageGroupResult: any;
|
||||
setCreateMessageGroupResult: any;
|
||||
}
|
||||
|
||||
export default (): IUseAlerts => {
|
||||
const [createMessageGroupResult, setCreateMessageGroupResult] = useRecoilState<any>(messageState.createMessageGroupResult)
|
||||
return { createMessageGroupResult, setCreateMessageGroupResult };
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { useRecoilState } from 'recoil';
|
||||
import { messageState } from './state';
|
||||
|
||||
export const useFilter = () => {
|
||||
const [ messageFilter, setMessageFilter ] = useRecoilState(messageState.filter)
|
||||
return { messageFilter, setMessageFilter}
|
||||
}
|
||||
@@ -3,10 +3,23 @@ import { messageState } from './state';
|
||||
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
|
||||
|
||||
|
||||
const NOTIFICATION_TIMEOUT = 6000;
|
||||
|
||||
export const useMessagesService = () => {
|
||||
const setMessageGroups = useSetRecoilState(messageState.messageGroups);
|
||||
const setMessages = useSetRecoilState(messageState.messages);
|
||||
const setCreateMessageGroupResult = useSetRecoilState(messageState.createMessageGroupResult);
|
||||
|
||||
const _handleCreateMessageGroupResult = (result) => {
|
||||
console.log(result);
|
||||
setCreateMessageGroupResult(result);
|
||||
window.setTimeout(() => {
|
||||
setCreateMessageGroupResult(null);
|
||||
}, NOTIFICATION_TIMEOUT);
|
||||
};
|
||||
|
||||
useNuiEvent('MESSAGES', 'phone:fetchMessageGroupsSuccess', setMessageGroups);
|
||||
useNuiEvent('MESSAGES', 'phone:fetchMessagesSuccess', setMessages);
|
||||
useNuiEvent('MESSAGES', 'phone:createMessageGroupSuccess', _handleCreateMessageGroupResult);
|
||||
useNuiEvent('MESSAGES', 'phone:createMessageGroupFailed', _handleCreateMessageGroupResult);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import { useTweetStatus } from "../../hooks/useTweetStatus";
|
||||
import Alert from "./Alert";
|
||||
import Alert from "../../../../ui/components/Alert";
|
||||
|
||||
const useStyles = makeStyles((theme) => ({
|
||||
root: {
|
||||
|
||||
@@ -56,6 +56,8 @@
|
||||
"APPS_MESSAGES_NEW_MESSAGE": "Message...",
|
||||
"APPS_MESSAGES_NEW_MESSAGE_GROUP": "Phone numbers...",
|
||||
"APPS_MESSAGES_GROUP_CHAT_LABEL": "Group chat label...",
|
||||
"APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT": "Submit"
|
||||
"APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT": "Submit",
|
||||
"APPS_MESSAGES_INVALID_PHONE_NUMBER": "Invalid phone number: ",
|
||||
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED": "Failed to create message group"
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -33,13 +33,13 @@ on(`__cfx_nui:${events.MESSAGES_CREATE_MESSAGE_GROUP}`, ({ phoneNumbers, label }
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP, phoneNumbers, label);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, (): void => {
|
||||
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS);
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, (result: any): void => {
|
||||
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, result);
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, (): void => {
|
||||
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED);
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, (result: any): void => {
|
||||
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, result);
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
+126
-49
@@ -5,6 +5,9 @@ import { Message, MessageGroup } from '../../phone/src/common/interfaces/message
|
||||
import { pool, withTransaction } from "./db";
|
||||
import { getSource, useIdentifier } from './functions';
|
||||
|
||||
/**
|
||||
* Used for the raw npwd_messages_groups row responses
|
||||
*/
|
||||
interface UnformattedMessageGroup {
|
||||
group_id: string;
|
||||
participant_identifier: string;
|
||||
@@ -15,6 +18,10 @@ interface UnformattedMessageGroup {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to help consolidate raw npwd_messages_groups rows into
|
||||
* a mapping of a single message group
|
||||
*/
|
||||
interface MessageGroupMapping {
|
||||
[groupId: string]: {
|
||||
participants: string[];
|
||||
@@ -24,6 +31,12 @@ interface MessageGroupMapping {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a message in the database
|
||||
* @param userIdentifier - identifier of the user creating this message
|
||||
* @param groupId - the message group ID to attach this message to
|
||||
* @param message - content of the message
|
||||
*/
|
||||
async function createMessage(userIdentifier: string, groupId: string, message: string): Promise<any> {
|
||||
const query = `
|
||||
INSERT INTO npwd_messages
|
||||
@@ -38,6 +51,11 @@ async function createMessage(userIdentifier: string, groupId: string, message: s
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all message groups associated with a user. This will
|
||||
* populate the list of message groups on the UI
|
||||
* @param userIdentifier - identifier of the user to get message groups for
|
||||
*/
|
||||
async function getMessageGroups(userIdentifier: string): Promise<UnformattedMessageGroup[]> {
|
||||
const query = `
|
||||
SELECT
|
||||
@@ -58,6 +76,13 @@ async function getMessageGroups(userIdentifier: string): Promise<UnformattedMess
|
||||
return <UnformattedMessageGroup[]>results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all messages associated with a group and add a field
|
||||
* "isMine" which determines if the message belongs to the user
|
||||
* making the request
|
||||
* @param userIdentifier - user to get messages for
|
||||
* @param groupId - the group to get messages from
|
||||
*/
|
||||
async function getMessages(userIdentifier: string, groupId: string): Promise<Message[]> {
|
||||
const query = `
|
||||
SELECT
|
||||
@@ -84,6 +109,63 @@ async function getMessages(userIdentifier: string, groupId: string): Promise<Mes
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a message group label
|
||||
* @param userIdentifier - user who is creating the message group
|
||||
* @param groupId - groupId this label is attached to
|
||||
* @param label - the label itself
|
||||
*/
|
||||
async function createLabel(userIdentifier: string, groupId: string, label: string): Promise<any> {
|
||||
const query = `
|
||||
INSERT INTO npwd_messages_labels
|
||||
(user_identifier, group_id, label)
|
||||
VALUES (?, ?, ?)
|
||||
`;
|
||||
await pool.query(query, [ userIdentifier, groupId, label ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a message group
|
||||
* @param userIdentifier - the user creating the message group
|
||||
* @param groupId - the unique group ID this corresponds to
|
||||
* @param participantIdentifier - the participant user identifier. This identifier is what attaches
|
||||
* other players to the message group
|
||||
*/
|
||||
async function createMessageGroup(userIdentifier: string, groupId: string, participantIdentifier: string): Promise<any> {
|
||||
const query = `
|
||||
INSERT INTO npwd_messages_groups
|
||||
(user_identifier, group_id, participant_identifier)
|
||||
VALUES (?, ?, ?)
|
||||
`;
|
||||
const [results] = await pool.query(query, [
|
||||
userIdentifier,
|
||||
groupId,
|
||||
participantIdentifier
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a players identifier from their phone number
|
||||
* @param phoneNumber - the phone number to search for
|
||||
*/
|
||||
async function getIdentifierFromPhoneNumber(phoneNumber: string): Promise<string> {
|
||||
const query = `
|
||||
SELECT identifier
|
||||
FROM users
|
||||
WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ?
|
||||
LIMIT 1
|
||||
`;
|
||||
const [results] = await pool.query(query, [ phoneNumber]);
|
||||
const identifiers = <any>results;
|
||||
return identifiers[0]['identifier']
|
||||
}
|
||||
|
||||
/**
|
||||
* Consolidate raw message groups into a mapping that groups participants
|
||||
* by the message group. The goal of this is to reduce the rows of message
|
||||
* groups into a single MessageGroup object.
|
||||
* @param useIdentifier - the user identifier to get message groups for
|
||||
*/
|
||||
async function getConsolidatedMessageGroups(useIdentifier: string): Promise<MessageGroupMapping> {
|
||||
const messageGroups = await getMessageGroups(useIdentifier);
|
||||
return messageGroups.reduce((mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => {
|
||||
@@ -104,7 +186,11 @@ async function getConsolidatedMessageGroups(useIdentifier: string): Promise<Mess
|
||||
}, {});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Given the mapping of groupId: fields contents reduce it into a list
|
||||
* of MessageGroup objects ready for the UI to consume
|
||||
* @param userIdentifier - user to generate the MessageGroups for
|
||||
*/
|
||||
async function getFormattedMessageGroups(userIdentifier: string): Promise<MessageGroup[]> {
|
||||
const groupMapping = await getConsolidatedMessageGroups(userIdentifier);
|
||||
const groupIds = Object.keys(groupMapping);
|
||||
@@ -118,58 +204,42 @@ async function getFormattedMessageGroups(userIdentifier: string): Promise<Messag
|
||||
});
|
||||
}
|
||||
|
||||
async function createLabel(userIdentifier: string, groupId: string, label: string): Promise<any> {
|
||||
const query = `
|
||||
INSERT INTO npwd_messages_labels
|
||||
(user_identifier, group_id, label)
|
||||
VALUES (?, ?, ?)
|
||||
`;
|
||||
await pool.query(query, [ userIdentifier, groupId, label ]);
|
||||
}
|
||||
|
||||
async function createMessageGroup(userIdentifier: string, groupId: string, participantIdentifier: string): Promise<any> {
|
||||
const query = `
|
||||
INSERT INTO npwd_messages_groups
|
||||
(user_identifier, group_id, participant_identifier)
|
||||
VALUES (?, ?, ?)
|
||||
`;
|
||||
const [results] = await pool.query(query, [
|
||||
userIdentifier,
|
||||
groupId,
|
||||
participantIdentifier
|
||||
]);
|
||||
}
|
||||
|
||||
async function getIdentifierFromPhoneNumber(phoneNumber: string): Promise<string> {
|
||||
const query = `
|
||||
SELECT identifier
|
||||
FROM users
|
||||
WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ?
|
||||
LIMIT 1
|
||||
`;
|
||||
const [results] = await pool.query(query, [ phoneNumber]);
|
||||
const identifiers = <any>results;
|
||||
return identifiers[0]['identifier']
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method to handle creation of new message groups. First
|
||||
* we retrieve identifiers for each submitted phone number and
|
||||
* then rows in npwd_messages_groups are created for each of them
|
||||
* bound to a unique groupId. The groupId is any unique string - we
|
||||
* use UUIDs here.
|
||||
*
|
||||
* These queries are batched with a transaction so that if any of
|
||||
* them fail the queries are not committed to the database. This helps
|
||||
* avoid situations where some participants get added to the group but
|
||||
* one fails resulting in a partial group which would be very confusing
|
||||
* to the player.
|
||||
* @param userIdentifier - user who is creating the group
|
||||
* @param phoneNumbers - list of phone numbers to add to the grup
|
||||
* @param groupLabel - optional group label to give the group
|
||||
*/
|
||||
async function createMessageGroupsFromPhoneNumbers(
|
||||
userIdentifier: string,
|
||||
phoneNumbers: string[],
|
||||
groupLabel: string): Promise<string> {
|
||||
groupLabel: string): Promise<any> {
|
||||
const groupId = uuidv4();
|
||||
|
||||
// we check that each phoneNumber exists before we create the group
|
||||
const identifiers: string[] = [];
|
||||
for (const phoneNumber of phoneNumbers) {
|
||||
const identifier = await getIdentifierFromPhoneNumber(phoneNumber)
|
||||
identifiers.push(identifier);
|
||||
try {
|
||||
const identifier = await getIdentifierFromPhoneNumber(phoneNumber)
|
||||
identifiers.push(identifier);
|
||||
} catch (err) {
|
||||
return { error: true, phoneNumber };
|
||||
}
|
||||
}
|
||||
|
||||
const connection = await pool.getConnection()
|
||||
connection.beginTransaction();
|
||||
|
||||
const queryPromises = [
|
||||
// create a row that contains ourselves so others can reference it
|
||||
// create a row that contains ourselves so reverse accessing from
|
||||
// other players works as expected
|
||||
createMessageGroup(userIdentifier, groupId, userIdentifier),
|
||||
...identifiers.map(identifier => createMessageGroup(userIdentifier, groupId, identifier))
|
||||
]
|
||||
@@ -180,12 +250,15 @@ async function createMessageGroupsFromPhoneNumbers(
|
||||
}
|
||||
|
||||
// wrap this in a transaction to make sure ALL of these INSERTs succeed
|
||||
//so we are not left in a situation where only some of the member of the
|
||||
// so we are not left in a situation where only some of the member of the
|
||||
// group exist while other are left off.
|
||||
const results = withTransaction(queryPromises);
|
||||
console.log(results);
|
||||
try {
|
||||
await withTransaction(queryPromises);
|
||||
} catch (err) {
|
||||
return { error: true };
|
||||
}
|
||||
|
||||
return groupId;
|
||||
return { error: false, groupId };
|
||||
}
|
||||
|
||||
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
|
||||
@@ -200,10 +273,14 @@ onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
|
||||
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP, async (phoneNumbers: string[], label: string = null) => {
|
||||
try {
|
||||
console.log(phoneNumbers);
|
||||
const _identifier = await useIdentifier();
|
||||
await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers, label)
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, getSource());
|
||||
const result = await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers, label)
|
||||
|
||||
if (result.error) {
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource(), result);
|
||||
} else {
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, getSource(), result);
|
||||
}
|
||||
} catch (e) {
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user