mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-05 06:28:51 +00:00
feat/messages additions (in memory of Leonard Nimoy) (#118)
* feat(resouces/messages): broadcast messagse to participants * feat(phone/messages): notifications for messages * remove weird empty onNet * reformat? * last reformat! This pr will be squashed * tweak(phone/messages): send groupName to notification alert * fix identifer * fixing notification groupName * resbasee...i think * feat(messages): check for unread messages * send nui event is count > 0 * remove usless test * import.sql update * Refactor NotificationsProvider and fix messages notifications * Send groupId on message broadcast * Update phone/src/apps/messages/components/modal/Conversation.tsx * Update phone/src/apps/messages/hooks/useMessageNotifications.ts * Update phone/src/os/notifications/providers/NotificationsProvider.tsx * Update phone/src/common/typings/messages.ts * Update phone/src/apps/messages/hooks/useMessageNotifications.ts * clean sql file * Update resources/server/sv_messages.ts * Fetch message groups when other person created for you * fix sql * Select unreadCount from messageGroups * whatever husky again * Add members menu and add contact in messages * Add from group bubbles * Fix messages scroll with new msg * Message image menu flicker + justify bottom messages * Improve debugging * Add container to Slider * Improve logger * Fix create message * add creator identifier to group hash * Fix dafuq i broke * group_id bigger varchar in column * group_id bigger varchar in column * Phone visibility default browser * Add debugging Co-authored-by: J Francisco Rader <[email protected]> Co-authored-by: J Francisco Rader <[email protected]>
This commit is contained in:
38 files changed
+601
-295
No files matched your search
@@ -0,0 +1,30 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
if [ -z "$husky_skip_init" ]; then
|
||||||
|
debug () {
|
||||||
|
[ "$HUSKY_DEBUG" = "1" ] && echo "husky (debug) - $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
readonly hook_name="$(basename "$0")"
|
||||||
|
debug "starting $hook_name..."
|
||||||
|
|
||||||
|
if [ "$HUSKY" = "0" ]; then
|
||||||
|
debug "HUSKY env variable is set to 0, skipping hook"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -f ~/.huskyrc ]; then
|
||||||
|
debug "sourcing ~/.huskyrc"
|
||||||
|
. ~/.huskyrc
|
||||||
|
fi
|
||||||
|
|
||||||
|
export readonly husky_skip_init=1
|
||||||
|
sh -e "$0" "$@"
|
||||||
|
exitCode="$?"
|
||||||
|
|
||||||
|
if [ $exitCode != 0 ]; then
|
||||||
|
echo "husky - $hook_name hook exited with code $exitCode (error)"
|
||||||
|
exit $exitCode
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
Regular → Executable
File mode changed.
@@ -6,7 +6,6 @@
|
|||||||
|
|
||||||
.Phone {
|
.Phone {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 0;
|
|
||||||
right: 0;
|
right: 0;
|
||||||
width: 500px;
|
width: 500px;
|
||||||
height: 1000px;
|
height: 1000px;
|
||||||
|
|||||||
+2
-2
@@ -52,9 +52,9 @@ function Phone() {
|
|||||||
const { bottom, visibility } = usePhoneVisibility();
|
const { bottom, visibility } = usePhoneVisibility();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<div>
|
||||||
<Slide direction="up" in={visibility}>
|
<Slide direction="up" in={visibility}>
|
||||||
<div className="PhoneWrapper">
|
<div className="PhoneWrapper">
|
||||||
<div>
|
|
||||||
<div
|
<div
|
||||||
className="Phone"
|
className="Phone"
|
||||||
style={{
|
style={{
|
||||||
@@ -94,8 +94,8 @@ function Phone() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</Slide>
|
</Slide>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,7 +45,12 @@ InjectDebugData([
|
|||||||
{
|
{
|
||||||
id: 3,
|
id: 3,
|
||||||
display: 'Chip',
|
display: 'Chip',
|
||||||
number: '777-7777',
|
number: '111-1111',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
display: 'Kidz',
|
||||||
|
number: '444-4444',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Avatar as MuiAvatar, Box, Button, Paper, TextField } from '@material-ui/core';
|
import { Avatar as MuiAvatar, Box, Button, Paper, TextField } from '@material-ui/core';
|
||||||
import { makeStyles, Theme } from '@material-ui/core/styles';
|
import { makeStyles } from '@material-ui/core/styles';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useHistory, useParams } from 'react-router-dom';
|
import { useHistory, useParams } from 'react-router-dom';
|
||||||
import { useContacts } from '../../hooks/useContacts';
|
import { useContacts } from '../../hooks/useContacts';
|
||||||
@@ -19,7 +19,7 @@ interface ContactInfoRouteQuery {
|
|||||||
referal?: string;
|
referal?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const useStyles = makeStyles((theme: Theme) => ({
|
const useStyles = makeStyles({
|
||||||
root: {
|
root: {
|
||||||
height: '100%',
|
height: '100%',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
@@ -44,7 +44,7 @@ const useStyles = makeStyles((theme: Theme) => ({
|
|||||||
inputProps: {
|
inputProps: {
|
||||||
fontSize: 22,
|
fontSize: 22,
|
||||||
},
|
},
|
||||||
}));
|
});
|
||||||
|
|
||||||
const ContactsInfoPage = () => {
|
const ContactsInfoPage = () => {
|
||||||
const classes = useStyles();
|
const classes = useStyles();
|
||||||
|
|||||||
@@ -7,11 +7,13 @@ import { useCallback } from 'react';
|
|||||||
interface IUseContacts {
|
interface IUseContacts {
|
||||||
contacts: Contact[];
|
contacts: Contact[];
|
||||||
getDisplayByNumber: (number: string) => string;
|
getDisplayByNumber: (number: string) => string;
|
||||||
getContact: (id: number) => Contact;
|
getContactByNumber: (number: string) => Contact | null;
|
||||||
|
getContact: (id: number) => Contact | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useContacts = (): IUseContacts => {
|
export const useContacts = (): IUseContacts => {
|
||||||
const contacts = useRecoilValue(contactsState.contacts);
|
const contacts = useRecoilValue(contactsState.contacts);
|
||||||
|
|
||||||
const getDisplayByNumber = useCallback(
|
const getDisplayByNumber = useCallback(
|
||||||
(number: string) => {
|
(number: string) => {
|
||||||
const found = contacts.find((contact) => contact.number === number);
|
const found = contacts.find((contact) => contact.number === number);
|
||||||
@@ -19,13 +21,26 @@ export const useContacts = (): IUseContacts => {
|
|||||||
},
|
},
|
||||||
[contacts],
|
[contacts],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const getContactByNumber = useCallback(
|
||||||
|
(number: string): Contact | null => {
|
||||||
|
for (const contact of contacts) {
|
||||||
|
if (contact.number === number) return contact;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
[contacts],
|
||||||
|
);
|
||||||
|
|
||||||
const getContact = useCallback(
|
const getContact = useCallback(
|
||||||
(id: number): Contact | null => {
|
(id: number): Contact | null => {
|
||||||
for (const contact of contacts) {
|
for (const contact of contacts) {
|
||||||
if (contact.id === id) return contact;
|
if (contact.id === id) return contact;
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
},
|
},
|
||||||
[contacts],
|
[contacts],
|
||||||
);
|
);
|
||||||
return { contacts, getDisplayByNumber, getContact };
|
|
||||||
|
return { contacts, getDisplayByNumber, getContact, getContactByNumber };
|
||||||
};
|
};
|
||||||
@@ -33,6 +33,7 @@ export const MessagesApp = () => {
|
|||||||
render={() => (
|
render={() => (
|
||||||
<>
|
<>
|
||||||
<MessagesList />
|
<MessagesList />
|
||||||
|
<NewMessageGroupButton onClick={() => history.push('/messages/new')} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
@@ -45,7 +46,6 @@ export const MessagesApp = () => {
|
|||||||
/>
|
/>
|
||||||
</Switch>
|
</Switch>
|
||||||
</AppContent>
|
</AppContent>
|
||||||
<NewMessageGroupButton onClick={() => history.push('/messages/new')} />
|
|
||||||
</AppWrapper>
|
</AppWrapper>
|
||||||
</MessagesThemeProvider>
|
</MessagesThemeProvider>
|
||||||
);
|
);
|
||||||
@@ -63,6 +63,7 @@ InjectDebugData([
|
|||||||
phone_number: '444-4444',
|
phone_number: '444-4444',
|
||||||
display: 'kidz',
|
display: 'kidz',
|
||||||
avatar: null,
|
avatar: null,
|
||||||
|
groupId: '2',
|
||||||
isRead: true,
|
isRead: true,
|
||||||
isMine: false,
|
isMine: false,
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
@@ -74,6 +75,7 @@ InjectDebugData([
|
|||||||
phone_number: '444-4444',
|
phone_number: '444-4444',
|
||||||
display: 'kidz',
|
display: 'kidz',
|
||||||
avatar: null,
|
avatar: null,
|
||||||
|
groupId: '2',
|
||||||
isRead: true,
|
isRead: true,
|
||||||
isMine: false,
|
isMine: false,
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
@@ -81,80 +83,27 @@ InjectDebugData([
|
|||||||
{
|
{
|
||||||
id: 3,
|
id: 3,
|
||||||
message: 'sup!',
|
message: 'sup!',
|
||||||
user_identifier: '1234',
|
user_identifier: '123',
|
||||||
phone_number: '444-4444',
|
phone_number: '444-4444',
|
||||||
display: 'kidz',
|
display: 'kidz',
|
||||||
avatar: null,
|
avatar: null,
|
||||||
|
groupId: '2',
|
||||||
isRead: true,
|
isRead: true,
|
||||||
isMine: false,
|
isMine: false,
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 4,
|
id: 3,
|
||||||
message: 'sup!',
|
message: 'what are you doing!?',
|
||||||
user_identifier: '1234',
|
user_identifier: '12345',
|
||||||
phone_number: '444-4444',
|
phone_number: '444-5555',
|
||||||
display: 'kidz',
|
display: '444-5555',
|
||||||
avatar: null,
|
avatar: null,
|
||||||
|
groupId: '2',
|
||||||
isRead: true,
|
isRead: true,
|
||||||
isMine: false,
|
isMine: false,
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: 5,
|
|
||||||
message: 'sup!',
|
|
||||||
user_identifier: '1234',
|
|
||||||
phone_number: '444-4444',
|
|
||||||
display: 'kidz',
|
|
||||||
avatar: null,
|
|
||||||
isRead: true,
|
|
||||||
isMine: false,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 6,
|
|
||||||
message: 'sup!',
|
|
||||||
user_identifier: '1234',
|
|
||||||
phone_number: '444-4444',
|
|
||||||
display: 'kidz',
|
|
||||||
avatar: null,
|
|
||||||
isRead: true,
|
|
||||||
isMine: false,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 7,
|
|
||||||
message: 'sup!',
|
|
||||||
user_identifier: '1234',
|
|
||||||
phone_number: '444-4444',
|
|
||||||
display: 'kidz',
|
|
||||||
avatar: null,
|
|
||||||
isRead: true,
|
|
||||||
isMine: true,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 8,
|
|
||||||
message: 'sup!',
|
|
||||||
user_identifier: '1234',
|
|
||||||
phone_number: '444-4444',
|
|
||||||
display: 'kidz',
|
|
||||||
avatar: null,
|
|
||||||
isRead: true,
|
|
||||||
isMine: false,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 9,
|
|
||||||
message: 'sup!',
|
|
||||||
user_identifier: '1234',
|
|
||||||
phone_number: '444-4444',
|
|
||||||
display: 'kidz',
|
|
||||||
avatar: null,
|
|
||||||
isRead: true,
|
|
||||||
isMine: true,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -165,10 +114,55 @@ InjectDebugData([
|
|||||||
groupId: '2',
|
groupId: '2',
|
||||||
groupDisplay: 'dev-chat',
|
groupDisplay: 'dev-chat',
|
||||||
isGroupChat: true,
|
isGroupChat: true,
|
||||||
|
phoneNumbers: ['444-4444', '111-1134', '111-1111'],
|
||||||
avatar: null,
|
avatar: null,
|
||||||
label: null,
|
label: null,
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
|
unreadCount: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
groupId: '3',
|
||||||
|
groupDisplay: 'Chip',
|
||||||
|
isGroupChat: false,
|
||||||
|
phoneNumbers: ['111-1134', '111-1111'],
|
||||||
|
avatar: null,
|
||||||
|
label: null,
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
unreadCount: 0,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
InjectDebugData(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
app: 'MESSAGES',
|
||||||
|
method: 'createMessagesBroadcast',
|
||||||
|
data: {
|
||||||
|
groupId: '2',
|
||||||
|
number: '777-7777',
|
||||||
|
message: 'Hi! Just checking in on you!',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
app: 'MESSAGES',
|
||||||
|
method: 'createMessagesBroadcast',
|
||||||
|
data: {
|
||||||
|
groupId: '2',
|
||||||
|
number: 'Kidz',
|
||||||
|
message: 'Hi! You are awesome!',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
app: 'MESSAGES',
|
||||||
|
method: 'createMessagesBroadcast',
|
||||||
|
data: {
|
||||||
|
groupId: '3',
|
||||||
|
number: 'Kidz',
|
||||||
|
message: 'I am testing this like crazy',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
3000,
|
||||||
|
);
|
||||||
@@ -8,6 +8,7 @@ import Nui from '../../../../os/nui-events/utils/Nui';
|
|||||||
interface IProps {
|
interface IProps {
|
||||||
onAddImageClick(): void;
|
onAddImageClick(): void;
|
||||||
messageGroupId: string | undefined;
|
messageGroupId: string | undefined;
|
||||||
|
messageGroupName: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const useStyles = makeStyles({
|
const useStyles = makeStyles({
|
||||||
@@ -23,6 +24,7 @@ const MessageInput = ({ messageGroupId, onAddImageClick }: IProps) => {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (message.trim()) {
|
if (message.trim()) {
|
||||||
// don't allow the user to submit white space
|
// don't allow the user to submit white space
|
||||||
|
|
||||||
Nui.send('phone:sendMessage', {
|
Nui.send('phone:sendMessage', {
|
||||||
groupId: messageGroupId,
|
groupId: messageGroupId,
|
||||||
message,
|
message,
|
||||||
|
|||||||
@@ -1,18 +1,30 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { ListItem, ListItemText, ListItemAvatar, Avatar as MuiAvatar } from '@material-ui/core';
|
import {
|
||||||
|
ListItem,
|
||||||
|
ListItemText,
|
||||||
|
ListItemAvatar,
|
||||||
|
Avatar as MuiAvatar,
|
||||||
|
Badge,
|
||||||
|
} from '@material-ui/core';
|
||||||
|
|
||||||
import { MessageGroup } from '../../../../common/typings/messages';
|
import { MessageGroup } from '../../../../common/typings/messages';
|
||||||
|
|
||||||
interface IProps {
|
interface IProps {
|
||||||
messageGroup: MessageGroup;
|
messageGroup: MessageGroup;
|
||||||
handleClick: (group: MessageGroup) => () => void;
|
handleClick: (group: MessageGroup) => () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => {
|
const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => {
|
||||||
|
// get unread messages, check the length. If we have any, get the groupId,
|
||||||
|
// and show the badge
|
||||||
|
|
||||||
|
const hasUnread = messageGroup.unreadCount > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ListItem key={messageGroup.groupId} onClick={handleClick(messageGroup)} divider button>
|
<ListItem key={messageGroup.groupId} onClick={handleClick(messageGroup)} divider button>
|
||||||
<ListItemAvatar>
|
<ListItemAvatar>
|
||||||
|
<Badge color='error' variant='dot' invisible={!hasUnread}>
|
||||||
<MuiAvatar src={messageGroup?.avatar} />
|
<MuiAvatar src={messageGroup?.avatar} />
|
||||||
|
</Badge>
|
||||||
</ListItemAvatar>
|
</ListItemAvatar>
|
||||||
<ListItemText>{messageGroup.label || messageGroup.groupDisplay}</ListItemText>
|
<ListItemText>{messageGroup.label || messageGroup.groupDisplay}</ListItemText>
|
||||||
</ListItem>
|
</ListItem>
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import React, { useCallback, useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { List } from '@material-ui/core';
|
import { List } from '@material-ui/core';
|
||||||
import qs from 'qs';
|
|
||||||
import { MessageGroup } from '../../../../common/typings/messages';
|
import { MessageGroup } from '../../../../common/typings/messages';
|
||||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
import Nui from '../../../../os/nui-events/utils/Nui';
|
||||||
import useMessages from '../../hooks/useMessages';
|
import useMessages from '../../hooks/useMessages';
|
||||||
@@ -8,6 +7,7 @@ import MessageSearch from './MessageSearch';
|
|||||||
import MessageGroupItem from './MessageGroupItem';
|
import MessageGroupItem from './MessageGroupItem';
|
||||||
import useStyles from './list.styles';
|
import useStyles from './list.styles';
|
||||||
import { useHistory } from 'react-router-dom';
|
import { useHistory } from 'react-router-dom';
|
||||||
|
import { goToConversation } from '../../utils/goToConversation';
|
||||||
|
|
||||||
const MessagesList = (): any => {
|
const MessagesList = (): any => {
|
||||||
const classes = useStyles();
|
const classes = useStyles();
|
||||||
@@ -17,31 +17,6 @@ const MessagesList = (): any => {
|
|||||||
|
|
||||||
const [searchValue, setSearchValue] = useState('');
|
const [searchValue, setSearchValue] = useState('');
|
||||||
|
|
||||||
const goToConversation = useCallback(
|
|
||||||
(messageGroup) =>
|
|
||||||
history.push(
|
|
||||||
`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(messageGroup)}`,
|
|
||||||
),
|
|
||||||
[history],
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (createMessageGroupResult?.groupId) {
|
|
||||||
const findGroup = messageGroups.find((g) => g.groupId === createMessageGroupResult.groupId);
|
|
||||||
clearMessageGroupResult();
|
|
||||||
if (findGroup) {
|
|
||||||
goToConversation(findGroup);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [messageGroups, createMessageGroupResult, goToConversation, clearMessageGroupResult]);
|
|
||||||
|
|
||||||
if (!messageGroups) return null;
|
|
||||||
|
|
||||||
const handleClick = (messageGroup: MessageGroup) => () => {
|
|
||||||
Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId });
|
|
||||||
history.push(`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(messageGroup)}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const formattedSearch = searchValue.toLowerCase().trim();
|
const formattedSearch = searchValue.toLowerCase().trim();
|
||||||
const filteredGroups = formattedSearch
|
const filteredGroups = formattedSearch
|
||||||
? messageGroups.filter((group) => {
|
? messageGroups.filter((group) => {
|
||||||
@@ -53,6 +28,23 @@ const MessagesList = (): any => {
|
|||||||
})
|
})
|
||||||
: messageGroups;
|
: messageGroups;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (createMessageGroupResult?.groupId) {
|
||||||
|
const findGroup = messageGroups.find((g) => g.groupId === createMessageGroupResult.groupId);
|
||||||
|
clearMessageGroupResult();
|
||||||
|
if (findGroup) {
|
||||||
|
goToConversation(findGroup, history);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [messageGroups, createMessageGroupResult, clearMessageGroupResult, history]);
|
||||||
|
|
||||||
|
if (!messageGroups) return null;
|
||||||
|
|
||||||
|
const handleClick = (messageGroup: MessageGroup) => () => {
|
||||||
|
Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId });
|
||||||
|
goToConversation(messageGroup, history);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<MessageSearch value={searchValue} handleChange={(e) => setSearchValue(e.target.value)} />
|
<MessageSearch value={searchValue} handleChange={(e) => setSearchValue(e.target.value)} />
|
||||||
|
|||||||
@@ -11,11 +11,12 @@ import { MessageBubble } from './MessageBubble';
|
|||||||
interface IProps {
|
interface IProps {
|
||||||
activeMessageGroup: MessageGroup;
|
activeMessageGroup: MessageGroup;
|
||||||
messages: Message[];
|
messages: Message[];
|
||||||
|
onClickDisplay(phoneNumber: string): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CONVERSATION_ELEMENT_ID = 'message-modal-conversation';
|
export const CONVERSATION_ELEMENT_ID = 'message-modal-conversation';
|
||||||
|
|
||||||
const Conversation = ({ activeMessageGroup, messages }: IProps) => {
|
const Conversation = ({ activeMessageGroup, messages, onClickDisplay }: IProps) => {
|
||||||
const classes = useStyles();
|
const classes = useStyles();
|
||||||
const [imageModalOpen, setImageModalOpen] = useState(false);
|
const [imageModalOpen, setImageModalOpen] = useState(false);
|
||||||
const query = useQueryParams();
|
const query = useQueryParams();
|
||||||
@@ -34,11 +35,13 @@ const Conversation = ({ activeMessageGroup, messages }: IProps) => {
|
|||||||
height="85%"
|
height="85%"
|
||||||
display="flex"
|
display="flex"
|
||||||
flexDirection="column"
|
flexDirection="column"
|
||||||
|
justifyContent="flex-end"
|
||||||
pb={4}
|
pb={4}
|
||||||
className={classes.overflowAutoY}
|
className={classes.overflowAutoY}
|
||||||
>
|
>
|
||||||
{messages.map((message) => (
|
{messages.map((message) => (
|
||||||
<MessageBubble
|
<MessageBubble
|
||||||
|
onClickDisplay={onClickDisplay}
|
||||||
key={message.id}
|
key={message.id}
|
||||||
message={message}
|
message={message}
|
||||||
isGroupChat={activeMessageGroup?.isGroupChat}
|
isGroupChat={activeMessageGroup?.isGroupChat}
|
||||||
@@ -46,6 +49,8 @@ const Conversation = ({ activeMessageGroup, messages }: IProps) => {
|
|||||||
))}
|
))}
|
||||||
</Box>
|
</Box>
|
||||||
<MessageInput
|
<MessageInput
|
||||||
|
/* I should do some groupDiplay here */
|
||||||
|
messageGroupName={activeMessageGroup.label || activeMessageGroup.groupDisplay}
|
||||||
messageGroupId={activeMessageGroup.groupId}
|
messageGroupId={activeMessageGroup.groupId}
|
||||||
onAddImageClick={() => setImageModalOpen(true)}
|
onAddImageClick={() => setImageModalOpen(true)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Box, makeStyles, Paper, Typography } from '@material-ui/core';
|
import { Box, Link, makeStyles, Paper, Typography } from '@material-ui/core';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Message } from '../../../../common/typings/messages';
|
import { Message } from '../../../../common/typings/messages';
|
||||||
|
|
||||||
@@ -44,9 +44,11 @@ const isImage = (url) => {
|
|||||||
export const MessageBubble = ({
|
export const MessageBubble = ({
|
||||||
message,
|
message,
|
||||||
isGroupChat,
|
isGroupChat,
|
||||||
|
onClickDisplay,
|
||||||
}: {
|
}: {
|
||||||
message: Message;
|
message: Message;
|
||||||
isGroupChat: boolean;
|
isGroupChat: boolean;
|
||||||
|
onClickDisplay(phoneNumber: string): void;
|
||||||
}) => {
|
}) => {
|
||||||
const classes = useStyles();
|
const classes = useStyles();
|
||||||
return (
|
return (
|
||||||
@@ -60,9 +62,13 @@ export const MessageBubble = ({
|
|||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
<Box>
|
<Box>
|
||||||
|
{isGroupChat && !message.isMine ? (
|
||||||
|
<Link onClick={() => onClickDisplay(message.phone_number)}>
|
||||||
<Typography variant="subtitle1" color="secondary">
|
<Typography variant="subtitle1" color="secondary">
|
||||||
{isGroupChat && !message.isMine ? message.display || message.phone_number : null}
|
{message.display || message.phone_number}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,76 +1,92 @@
|
|||||||
import React, { useEffect, useRef, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Slide, Paper, Typography, Button } from '@material-ui/core';
|
import {
|
||||||
|
Slide,
|
||||||
|
Paper,
|
||||||
|
Typography,
|
||||||
|
Button,
|
||||||
|
Box,
|
||||||
|
List,
|
||||||
|
ListItem,
|
||||||
|
ListItemText,
|
||||||
|
ListItemSecondaryAction,
|
||||||
|
} from '@material-ui/core';
|
||||||
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
|
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
|
||||||
|
import MoreVertIcon from '@material-ui/icons/MoreVert';
|
||||||
|
import PersonAddIcon from '@material-ui/icons/PersonAdd';
|
||||||
import useStyles from './modal.styles';
|
import useStyles from './modal.styles';
|
||||||
import useMessages from '../../hooks/useMessages';
|
import useMessages from '../../hooks/useMessages';
|
||||||
import Conversation, { CONVERSATION_ELEMENT_ID } from './Conversation';
|
import Conversation, { CONVERSATION_ELEMENT_ID } from './Conversation';
|
||||||
import MessageSkeletonList from './MessageSkeletonList';
|
import MessageSkeletonList from './MessageSkeletonList';
|
||||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
import Nui from '../../../../os/nui-events/utils/Nui';
|
||||||
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
|
import { useHistory, useLocation, useParams } from 'react-router-dom';
|
||||||
import { MessageGroup } from '../../../../common/typings/messages';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useHistory, useParams } from 'react-router-dom';
|
import Modal from '../../../../ui/components/Modal';
|
||||||
|
import { useContacts } from '../../../contacts/hooks/useContacts';
|
||||||
|
import { useSimcard } from '../../../../os/simcard/hooks/useSimcard';
|
||||||
|
|
||||||
const LARGE_HEADER_CHARS = 30;
|
const LARGE_HEADER_CHARS = 30;
|
||||||
const MAX_HEADER_CHARS = 80;
|
const MAX_HEADER_CHARS = 80;
|
||||||
const MINIMUM_LOAD_TIME = 750;
|
|
||||||
const MESSAGES_REFRESH_RATE = 5000;
|
const memberDisplay = (display, number, myNumber, t) => {
|
||||||
|
if (myNumber === number) {
|
||||||
|
return (
|
||||||
|
<span>
|
||||||
|
{t('APPS_MESSAGES_ME')} ({number})
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (display !== number) {
|
||||||
|
return (
|
||||||
|
<span>
|
||||||
|
{display} ({number})
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return <span>{number}</span>;
|
||||||
|
};
|
||||||
|
|
||||||
export const MessageModal = () => {
|
export const MessageModal = () => {
|
||||||
const classes = useStyles();
|
const classes = useStyles();
|
||||||
const history = useHistory();
|
const history = useHistory();
|
||||||
const activeMessageGroup = useQueryParams<MessageGroup>();
|
const { number: myNumber } = useSimcard();
|
||||||
|
const { pathname } = useLocation();
|
||||||
|
const { t } = useTranslation();
|
||||||
const { groupId } = useParams<{ groupId: string }>();
|
const { groupId } = useParams<{ groupId: string }>();
|
||||||
const { messages, setMessages } = useMessages();
|
const { messages, setMessages, activeMessageGroup, setActiveMessageGroup } = useMessages();
|
||||||
|
const { getContactByNumber, getDisplayByNumber } = useContacts();
|
||||||
|
|
||||||
const [minimumLoadPassed, setMimimumLoadPassed] = useState(false);
|
const [groupActionsOpen, setGroupActionsOpen] = useState(false);
|
||||||
|
|
||||||
const minLoadTimeoutRef = useRef(null);
|
|
||||||
const fetchInterval = useRef(null);
|
|
||||||
|
|
||||||
const closeModal = () => {
|
const closeModal = () => {
|
||||||
history.push('/messages');
|
history.push('/messages');
|
||||||
setMessages(null);
|
setMessages(null);
|
||||||
setMimimumLoadPassed(false);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!groupId) return;
|
if (!groupId) return;
|
||||||
|
|
||||||
minLoadTimeoutRef.current = setTimeout(() => {
|
setActiveMessageGroup(groupId);
|
||||||
setMimimumLoadPassed(true);
|
}, [groupId, setActiveMessageGroup]);
|
||||||
}, MINIMUM_LOAD_TIME);
|
|
||||||
|
|
||||||
fetchInterval.current = setInterval(() => {
|
|
||||||
if (!groupId) return;
|
|
||||||
Nui.send('phone:fetchMessages', {
|
|
||||||
groupId,
|
|
||||||
});
|
|
||||||
}, MESSAGES_REFRESH_RATE);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
clearInterval(fetchInterval.current);
|
|
||||||
fetchInterval.current = null;
|
|
||||||
clearTimeout(minLoadTimeoutRef.current);
|
|
||||||
minLoadTimeoutRef.current = null;
|
|
||||||
};
|
|
||||||
}, [groupId]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// when we get a new message group we should scroll to the
|
if (messages) {
|
||||||
// bottom to show the latest messages
|
|
||||||
if (activeMessageGroup) {
|
|
||||||
const element = document.getElementById(CONVERSATION_ELEMENT_ID);
|
const element = document.getElementById(CONVERSATION_ELEMENT_ID);
|
||||||
if (element) {
|
if (element) {
|
||||||
element.scrollTop = element.scrollHeight;
|
element.scrollTop = element.scrollHeight;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [activeMessageGroup, minimumLoadPassed]);
|
}, [messages]);
|
||||||
|
|
||||||
// we add a minimum (but short) load time here so that
|
// sends all unread messages
|
||||||
// there isn't a quick flash of loading and immediately
|
useEffect(() => {
|
||||||
// another flash to the tweets screen.
|
if (activeMessageGroup?.groupId && activeMessageGroup.unreadCount > 0) {
|
||||||
const hasLoaded = messages && minimumLoadPassed;
|
Nui.send('phone:setReadMessages', {
|
||||||
|
groupId: activeMessageGroup.groupId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [activeMessageGroup]);
|
||||||
|
|
||||||
|
const hasLoaded = !!(messages && activeMessageGroup);
|
||||||
|
|
||||||
// don't allow too many characters, it takes too much room
|
// don't allow too many characters, it takes too much room
|
||||||
let header = activeMessageGroup ? activeMessageGroup.groupDisplay : '';
|
let header = activeMessageGroup ? activeMessageGroup.groupDisplay : '';
|
||||||
@@ -80,23 +96,73 @@ export const MessageModal = () => {
|
|||||||
const headerClass =
|
const headerClass =
|
||||||
header.length > LARGE_HEADER_CHARS ? classes.largeGroupDisplay : classes.groupdisplay;
|
header.length > LARGE_HEADER_CHARS ? classes.largeGroupDisplay : classes.groupdisplay;
|
||||||
|
|
||||||
|
const handleAddContact = (number) => {
|
||||||
|
const exists = getContactByNumber(number);
|
||||||
|
if (exists) {
|
||||||
|
return history.push(`/contacts/${exists.id}/?referal=${pathname}`);
|
||||||
|
}
|
||||||
|
return history.push(`/contacts/-1/?addNumber=${number}&referal=${pathname}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const phoneNumbers = activeMessageGroup?.phoneNumbers || [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<div>
|
||||||
|
<Modal visible={groupActionsOpen} handleClose={() => setGroupActionsOpen(false)}>
|
||||||
|
<Typography variant="h6">{t('APPS_MESSAGES_MEMBERS_TITLE')}</Typography>
|
||||||
|
<List>
|
||||||
|
{phoneNumbers.map((number) => {
|
||||||
|
const display = getDisplayByNumber(number);
|
||||||
|
return (
|
||||||
|
<ListItem divider>
|
||||||
|
<ListItemText>{memberDisplay(display, number, myNumber, t)}</ListItemText>
|
||||||
|
{!getContactByNumber(number) && myNumber !== number && (
|
||||||
|
<ListItemSecondaryAction>
|
||||||
|
<Button onClick={() => handleAddContact(number)}>
|
||||||
|
<PersonAddIcon />
|
||||||
|
</Button>
|
||||||
|
</ListItemSecondaryAction>
|
||||||
|
)}
|
||||||
|
</ListItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</List>
|
||||||
|
</Modal>
|
||||||
<Slide direction="left" in={!!activeMessageGroup}>
|
<Slide direction="left" in={!!activeMessageGroup}>
|
||||||
<Paper className={classes.modalRoot}>
|
<Paper className={classes.modalRoot}>
|
||||||
<Paper className={classes.topContainer}>
|
<Paper>
|
||||||
|
<Box display="flex" justifyContent="space-between">
|
||||||
<Button onClick={closeModal}>
|
<Button onClick={closeModal}>
|
||||||
<ArrowBackIcon fontSize="large" />
|
<ArrowBackIcon fontSize="large" />
|
||||||
</Button>
|
</Button>
|
||||||
<Typography variant="h5" className={headerClass}>
|
<Typography variant="h5" className={headerClass}>
|
||||||
{header}
|
{header}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
{activeMessageGroup?.isGroupChat ? (
|
||||||
|
<Button>
|
||||||
|
<MoreVertIcon onClick={() => setGroupActionsOpen(true)} fontSize="large" />
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button>
|
||||||
|
<PersonAddIcon
|
||||||
|
onClick={() => handleAddContact(phoneNumbers.find((n) => myNumber !== n))}
|
||||||
|
fontSize="large"
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
{hasLoaded ? (
|
{hasLoaded ? (
|
||||||
<Conversation messages={messages} activeMessageGroup={activeMessageGroup} />
|
<Conversation
|
||||||
|
onClickDisplay={handleAddContact}
|
||||||
|
messages={messages}
|
||||||
|
activeMessageGroup={activeMessageGroup}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<MessageSkeletonList />
|
<MessageSkeletonList />
|
||||||
)}
|
)}
|
||||||
</Paper>
|
</Paper>
|
||||||
</Slide>
|
</Slide>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -6,15 +6,11 @@ const useStyles = makeStyles({
|
|||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
|
overflowY: 'hidden',
|
||||||
},
|
},
|
||||||
modalHide: {
|
modalHide: {
|
||||||
display: 'none',
|
display: 'none',
|
||||||
},
|
},
|
||||||
topContainer: {
|
|
||||||
display: 'flex',
|
|
||||||
flexFlow: 'row nowrap',
|
|
||||||
padding: '3px 0px',
|
|
||||||
},
|
|
||||||
overflowAutoY: {
|
overflowAutoY: {
|
||||||
overflowY: 'auto',
|
overflowY: 'auto',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -25,4 +25,8 @@ export const messageState = {
|
|||||||
key: 'useImageModal',
|
key: 'useImageModal',
|
||||||
default: false,
|
default: false,
|
||||||
}),
|
}),
|
||||||
|
unreadMessagesCount: atom({
|
||||||
|
key: 'unreadMessagesCount',
|
||||||
|
default: 0,
|
||||||
|
})
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useHistory } from 'react-router-dom';
|
||||||
|
import { useApp } from '../../../os/apps/hooks/useApps';
|
||||||
|
import { useNotifications } from '../../../os/notifications/hooks/useNotifications';
|
||||||
|
import { goToConversation } from '../utils/goToConversation';
|
||||||
|
import useMessages from './useMessages';
|
||||||
|
|
||||||
|
const NOTIFICATION_ID = 'messages:broadcast';
|
||||||
|
|
||||||
|
export const useMessageNotifications = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const history = useHistory();
|
||||||
|
const {
|
||||||
|
removeId,
|
||||||
|
addNotification,
|
||||||
|
addNotificationAlert,
|
||||||
|
} = useNotifications();
|
||||||
|
const { icon, notificationIcon } = useApp('MESSAGES');
|
||||||
|
const { getMessageGroupById } = useMessages();
|
||||||
|
|
||||||
|
const setNotification = ({ groupId, message }) => {
|
||||||
|
const group = getMessageGroupById(groupId);
|
||||||
|
if (!group) return;
|
||||||
|
|
||||||
|
const id = `${NOTIFICATION_ID}:${groupId}`;
|
||||||
|
|
||||||
|
const notification = {
|
||||||
|
app: 'MESSAGES',
|
||||||
|
id,
|
||||||
|
sound: true,
|
||||||
|
title: group.label || group.groupDisplay,
|
||||||
|
onClick: () => goToConversation(group, history),
|
||||||
|
content: message,
|
||||||
|
icon,
|
||||||
|
notificationIcon,
|
||||||
|
};
|
||||||
|
|
||||||
|
addNotificationAlert(notification, (n) => {
|
||||||
|
removeId(id);
|
||||||
|
if (group.unreadCount > 1) {
|
||||||
|
addNotification({
|
||||||
|
...n,
|
||||||
|
title: group.label || group.groupDisplay,
|
||||||
|
content: t('APPS_MESSAGES_UNREAD_MESSAGES', {
|
||||||
|
count: group.unreadCount,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
addNotification(n);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return { setNotification };
|
||||||
|
};
|
||||||
@@ -2,16 +2,19 @@ import { useSetRecoilState } from 'recoil';
|
|||||||
import { messageState } from './state';
|
import { messageState } from './state';
|
||||||
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
|
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
|
||||||
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
|
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
|
||||||
|
import { useMessageNotifications } from './useMessageNotifications';
|
||||||
|
|
||||||
export const useMessagesService = () => {
|
export const useMessagesService = () => {
|
||||||
const setMessageGroups = useSetRecoilState(messageState.messageGroups);
|
const setMessageGroups = useSetRecoilState(messageState.messageGroups);
|
||||||
const setMessages = useSetRecoilState(messageState.messages);
|
const setMessages = useSetRecoilState(messageState.messages);
|
||||||
const setCreateMessageGroupResult = useSetRecoilState(messageState.createMessageGroupResult);
|
const setCreateMessageGroupResult = useSetRecoilState(messageState.createMessageGroupResult);
|
||||||
const { addAlert } = useSnackbar();
|
const { addAlert } = useSnackbar();
|
||||||
|
const { setNotification } = useMessageNotifications();
|
||||||
|
|
||||||
useNuiEvent('MESSAGES', 'phone:fetchMessageGroupsSuccess', setMessageGroups);
|
useNuiEvent('MESSAGES', 'phone:fetchMessageGroupsSuccess', setMessageGroups);
|
||||||
useNuiEvent('MESSAGES', 'phone:fetchMessagesSuccess', setMessages);
|
useNuiEvent('MESSAGES', 'phone:fetchMessagesSuccess', setMessages);
|
||||||
useNuiEvent('MESSAGES', 'phone:createMessageGroupSuccess', setCreateMessageGroupResult);
|
useNuiEvent('MESSAGES', 'phone:createMessageGroupSuccess', setCreateMessageGroupResult);
|
||||||
useNuiEvent('MESSAGES', 'phone:createMessageGroupFailed', setCreateMessageGroupResult);
|
useNuiEvent('MESSAGES', 'phone:createMessageGroupFailed', setCreateMessageGroupResult);
|
||||||
useNuiEvent('MESSAGES', 'phone:setMessagesAlert', addAlert);
|
useNuiEvent('MESSAGES', 'phone:setMessagesAlert', addAlert);
|
||||||
|
useNuiEvent('MESSAGES', 'createMessagesBroadcast', setNotification);
|
||||||
};
|
};
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useCallback } from 'react';
|
||||||
import { useRecoilState, useRecoilValue } from 'recoil';
|
import { useRecoilState, useRecoilValue } from 'recoil';
|
||||||
import { CreateMessageGroupResult, Message, MessageGroup } from '../../../common/typings/messages';
|
import { CreateMessageGroupResult, Message, MessageGroup } from '../../../common/typings/messages';
|
||||||
import { messageState } from './state';
|
import { messageState } from './state';
|
||||||
@@ -8,11 +9,24 @@ interface IUseMessages {
|
|||||||
messageGroups?: MessageGroup[] | null;
|
messageGroups?: MessageGroup[] | null;
|
||||||
createMessageGroupResult?: CreateMessageGroupResult | null;
|
createMessageGroupResult?: CreateMessageGroupResult | null;
|
||||||
clearMessageGroupResult(): void;
|
clearMessageGroupResult(): void;
|
||||||
|
getMessageGroupById: (id: string) => MessageGroup | null;
|
||||||
|
setActiveMessageGroup: (groupId: string) => MessageGroup | null;
|
||||||
|
activeMessageGroup: MessageGroup | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default (): IUseMessages => {
|
export default (): IUseMessages => {
|
||||||
const [messages, setMessages] = useRecoilState<Message[] | null>(messageState.messages);
|
const [messages, setMessages] = useRecoilState<Message[] | null>(messageState.messages);
|
||||||
const messageGroups = useRecoilValue<MessageGroup[] | null>(messageState.messageGroups);
|
const messageGroups = useRecoilValue<MessageGroup[] | null>(messageState.messageGroups);
|
||||||
|
const [activeMessageGroup, _setActiveMessageGroup] = useRecoilState<MessageGroup | null>(
|
||||||
|
messageState.activeMessageGroup,
|
||||||
|
);
|
||||||
|
|
||||||
|
const getMessageGroupById = useCallback(
|
||||||
|
(id: string): MessageGroup | null => {
|
||||||
|
return messageGroups ? messageGroups.find((c) => c.groupId === id) : null;
|
||||||
|
},
|
||||||
|
[messageGroups],
|
||||||
|
);
|
||||||
|
|
||||||
const [
|
const [
|
||||||
createMessageGroupResult,
|
createMessageGroupResult,
|
||||||
@@ -21,11 +35,23 @@ export default (): IUseMessages => {
|
|||||||
|
|
||||||
const clearMessageGroupResult = () => setCreateMessageGroupResult(null);
|
const clearMessageGroupResult = () => setCreateMessageGroupResult(null);
|
||||||
|
|
||||||
|
const setActiveMessageGroup = useCallback(
|
||||||
|
(groupId: string) => {
|
||||||
|
const group = getMessageGroupById(groupId);
|
||||||
|
_setActiveMessageGroup(group);
|
||||||
|
return group;
|
||||||
|
},
|
||||||
|
[_setActiveMessageGroup, getMessageGroupById],
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages,
|
messages,
|
||||||
setMessages,
|
setMessages,
|
||||||
messageGroups,
|
messageGroups,
|
||||||
createMessageGroupResult,
|
createMessageGroupResult,
|
||||||
clearMessageGroupResult,
|
clearMessageGroupResult,
|
||||||
|
getMessageGroupById,
|
||||||
|
activeMessageGroup,
|
||||||
|
setActiveMessageGroup,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export const goToConversation = (messageGroup, history) =>
|
||||||
|
history.push(`/messages/conversations/${messageGroup.groupId}`);
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { useCallback } from 'react';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useHistory } from 'react-router-dom';
|
import { useHistory } from 'react-router-dom';
|
||||||
import { useRecoilState } from 'recoil';
|
import { useRecoilState } from 'recoil';
|
||||||
@@ -6,43 +5,50 @@ import { useApp } from '../../../os/apps/hooks/useApps';
|
|||||||
import { useNotifications } from '../../../os/notifications/hooks/useNotifications';
|
import { useNotifications } from '../../../os/notifications/hooks/useNotifications';
|
||||||
import { twitterState } from './state';
|
import { twitterState } from './state';
|
||||||
|
|
||||||
|
const NOTIFICATION_ID = 'twitter:broadcast';
|
||||||
|
|
||||||
export const useTwitterNotifications = () => {
|
export const useTwitterNotifications = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const history = useHistory();
|
const history = useHistory();
|
||||||
|
|
||||||
const { addNotificationAlert } = useNotifications();
|
const {
|
||||||
|
addNotificationAlert,
|
||||||
|
addNotification,
|
||||||
|
hasNotification,
|
||||||
|
removeId,
|
||||||
|
} = useNotifications();
|
||||||
|
|
||||||
const { icon, notificationIcon } = useApp('TWITTER');
|
const { icon, notificationIcon } = useApp('TWITTER');
|
||||||
|
|
||||||
const [unreadCount, setUnreadCount] = useRecoilState(twitterState.unreadTweetsCount);
|
const [unreadCount, setUnreadCount] = useRecoilState(twitterState.unreadTweetsCount);
|
||||||
|
|
||||||
const setNotification = useCallback(
|
const setNotification = ({ profile_name, message }) => {
|
||||||
({ profile_name, message }) => {
|
const notification = {
|
||||||
setUnreadCount((curr) => {
|
|
||||||
const unread = curr + 1;
|
|
||||||
addNotificationAlert(
|
|
||||||
{
|
|
||||||
app: 'TWITTER',
|
app: 'TWITTER',
|
||||||
|
id: NOTIFICATION_ID,
|
||||||
sound: true,
|
sound: true,
|
||||||
title: t('APPS_TWITTER_NEW_BROADCAST', { profile_name }),
|
title: t('APPS_TWITTER_NEW_BROADCAST', { profile_name }),
|
||||||
onClick: () => history.push('/twitter'),
|
onClick: () => history.push('/twitter'),
|
||||||
content: message,
|
content: message,
|
||||||
icon,
|
icon,
|
||||||
notificationIcon,
|
notificationIcon,
|
||||||
},
|
};
|
||||||
true,
|
const newCount = unreadCount + 1;
|
||||||
{
|
setUnreadCount(newCount);
|
||||||
|
addNotificationAlert(notification);
|
||||||
|
if (hasNotification(NOTIFICATION_ID)) {
|
||||||
|
removeId(NOTIFICATION_ID);
|
||||||
|
addNotification({
|
||||||
|
...notification,
|
||||||
title: t('APPS_TWITTER_UNREAD_MESSAGES', {
|
title: t('APPS_TWITTER_UNREAD_MESSAGES', {
|
||||||
count: unread,
|
count: newCount,
|
||||||
}),
|
}),
|
||||||
content: null,
|
content: null,
|
||||||
},
|
|
||||||
);
|
|
||||||
return unread;
|
|
||||||
});
|
});
|
||||||
},
|
return;
|
||||||
[setUnreadCount, addNotificationAlert, t, icon, notificationIcon, history],
|
}
|
||||||
);
|
addNotification(notification);
|
||||||
|
};
|
||||||
|
|
||||||
return { setNotification, setUnreadCount, unreadCount };
|
return { setNotification, setUnreadCount, unreadCount };
|
||||||
};
|
};
|
||||||
@@ -3,6 +3,7 @@ export interface Message {
|
|||||||
message: string;
|
message: string;
|
||||||
user_identifier: string;
|
user_identifier: string;
|
||||||
phone_number: string;
|
phone_number: string;
|
||||||
|
groupId?: string;
|
||||||
display?: string;
|
display?: string;
|
||||||
avatar?: string;
|
avatar?: string;
|
||||||
isRead: boolean;
|
isRead: boolean;
|
||||||
@@ -17,6 +18,9 @@ export interface MessageGroup {
|
|||||||
avatar?: string;
|
avatar?: string;
|
||||||
label?: string;
|
label?: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
unreadCount: number;
|
||||||
|
phoneNumbers: string[];
|
||||||
|
participants: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateMessageGroupResult {
|
export interface CreateMessageGroupResult {
|
||||||
@@ -25,4 +29,15 @@ export interface CreateMessageGroupResult {
|
|||||||
duplicate?: boolean;
|
duplicate?: boolean;
|
||||||
groupId?: string;
|
groupId?: string;
|
||||||
mine?: boolean;
|
mine?: boolean;
|
||||||
|
identifiers?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateMessageBroadcast {
|
||||||
|
message: string;
|
||||||
|
groupName: string;
|
||||||
|
groupId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetMessageRead {
|
||||||
|
groupId: string;
|
||||||
}
|
}
|
||||||
@@ -77,6 +77,9 @@
|
|||||||
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED": "Failed to create message group",
|
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED": "Failed to create message group",
|
||||||
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_MINE": "You cannot add yourself!",
|
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_MINE": "You cannot add yourself!",
|
||||||
"APPS_MESSAGES_INPUT_NAME_OR_NUMBER": "Search contacts or type number and press enter",
|
"APPS_MESSAGES_INPUT_NAME_OR_NUMBER": "Search contacts or type number and press enter",
|
||||||
|
"APPS_MESSAGES_UNREAD_MESSAGES": "You have {{ count }} unread messages",
|
||||||
|
"APPS_MESSAGES_MEMBERS_TITLE": "Members",
|
||||||
|
"APPS_MESSAGES_ME": "Me",
|
||||||
|
|
||||||
"APPS_CONTACT_FORM_NAME": "Name",
|
"APPS_CONTACT_FORM_NAME": "Name",
|
||||||
"APPS_CONTACT_FORM_NUMBER": "Number",
|
"APPS_CONTACT_FORM_NUMBER": "Number",
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export const useCallNotifications = () => {
|
|||||||
</CallNotification>
|
</CallNotification>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
true,
|
(n) => addNotification(n)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ InjectDebugData<CallProps | boolean>([
|
|||||||
app: 'CALL',
|
app: 'CALL',
|
||||||
method: 'setCaller',
|
method: 'setCaller',
|
||||||
data: {
|
data: {
|
||||||
accepted: false,
|
accepted: true,
|
||||||
isTransmitter: false,
|
isTransmitter: false,
|
||||||
transmitter: 'Chip',
|
transmitter: 'Chip',
|
||||||
receiver: 'Taso',
|
receiver: 'Taso',
|
||||||
|
|||||||
@@ -40,13 +40,13 @@ export const NotificationsContext = createContext<{
|
|||||||
icons: INotificationIcon[];
|
icons: INotificationIcon[];
|
||||||
count: number;
|
count: number;
|
||||||
removeAlerts(): void;
|
removeAlerts(): void;
|
||||||
addOrUpdateNotification(add: INotification, update?: INotification): void;
|
|
||||||
addNotification(value: INotification): void;
|
addNotification(value: INotification): void;
|
||||||
removeNotification(idx: number): void;
|
removeNotification(idx: number): void;
|
||||||
updateId(id: string, value: Partial<INotification>): void;
|
updateId(id: string, value: Partial<INotification>): void;
|
||||||
removeId(id: string): void;
|
removeId(id: string): void;
|
||||||
hasNotification(app: string): number;
|
hasNotification(id: string): INotification | null;
|
||||||
addNotificationAlert(n: INotification, persist: boolean, update?: Partial<INotification>);
|
hasAppNotification(app: string): number;
|
||||||
|
addNotificationAlert(n: INotification, cb?: (n: INotification) => void);
|
||||||
}>(null);
|
}>(null);
|
||||||
|
|
||||||
export function NotificationsProvider({ children }) {
|
export function NotificationsProvider({ children }) {
|
||||||
@@ -62,7 +62,7 @@ export function NotificationsProvider({ children }) {
|
|||||||
|
|
||||||
const alertTimeout = useRef<NodeJS.Timeout>();
|
const alertTimeout = useRef<NodeJS.Timeout>();
|
||||||
const [alerts, setAlerts] = useState<
|
const [alerts, setAlerts] = useState<
|
||||||
Array<[INotification, boolean, Partial<INotification>, string | undefined]>
|
Array<[INotification, (n: INotification) => void, string | undefined]>
|
||||||
>([]);
|
>([]);
|
||||||
const [currentAlert, setCurrentAlert] = useState<INotificationAlert>();
|
const [currentAlert, setCurrentAlert] = useState<INotificationAlert>();
|
||||||
|
|
||||||
@@ -96,32 +96,28 @@ export function NotificationsProvider({ children }) {
|
|||||||
* Checks if a notification exists for current app
|
* Checks if a notification exists for current app
|
||||||
* and returns its index or -1 if not found.
|
* and returns its index or -1 if not found.
|
||||||
*/
|
*/
|
||||||
const hasNotification = useCallback(
|
const hasAppNotification = useCallback(
|
||||||
(appId: string): number => {
|
(appId: string): number => {
|
||||||
return notifications.findIndex((n) => n.app === appId);
|
return notifications.findIndex((n) => n.app === appId);
|
||||||
},
|
},
|
||||||
[notifications],
|
[notifications],
|
||||||
);
|
);
|
||||||
|
|
||||||
const addOrUpdateNotification = useCallback(
|
/**
|
||||||
(add: INotification, update?: INotification) => {
|
* Checks if a notification exists by its `id`
|
||||||
const exists = hasNotification(add.app);
|
*/
|
||||||
if (update && exists !== -1) {
|
const hasNotification = useCallback(
|
||||||
updateNotification(exists, update);
|
(id: string): INotification | null => {
|
||||||
return;
|
return notifications.find((n) => n.id === id) || null;
|
||||||
}
|
|
||||||
addNotification(add);
|
|
||||||
},
|
},
|
||||||
[addNotification, hasNotification, updateNotification],
|
[notifications]
|
||||||
);
|
);
|
||||||
|
|
||||||
const _showAlert = useCallback(
|
const _showAlert = useCallback(
|
||||||
(n: INotification, persist: boolean, update: Partial<INotification>, soundUrl: string) => {
|
(n: INotification, cb: (n: INotification) => void, soundUrl: string) => {
|
||||||
return new Promise<void>((res) => {
|
return new Promise<void>((res) => {
|
||||||
const resolve = () => {
|
const resolve = () => {
|
||||||
if (persist) {
|
cb?.(n);
|
||||||
addOrUpdateNotification(n, update ? { ...n, ...update } : null);
|
|
||||||
}
|
|
||||||
res();
|
res();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -153,29 +149,25 @@ export function NotificationsProvider({ children }) {
|
|||||||
}, DEFAULT_ALERT_HIDE_TIME + 300);
|
}, DEFAULT_ALERT_HIDE_TIME + 300);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[addOrUpdateNotification, play],
|
[play]
|
||||||
);
|
);
|
||||||
|
|
||||||
const addNotificationAlert = (
|
const addNotificationAlert = (
|
||||||
n: INotification,
|
n: INotification,
|
||||||
persist?: boolean,
|
cb: (n: INotification) => void
|
||||||
update?: Partial<INotification>,
|
|
||||||
) => {
|
) => {
|
||||||
if (n.sound) {
|
if (n.sound) {
|
||||||
const { sound, volume } = getSoundSettings('notiSound', settings, n.app);
|
const { sound, volume } = getSoundSettings('notiSound', settings, n.app);
|
||||||
mount(sound, volume, false).then(({ url }) =>
|
mount(sound, volume, false).then(({ url }) =>
|
||||||
setAlerts((curr) => [...curr, [n, persist, update, url]]),
|
setAlerts((curr) => [...curr, [n, cb, url]])
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAlerts((curr) => [...curr, [n, persist, update, undefined]]);
|
setAlerts((curr) => [...curr, [n, cb, undefined]]);
|
||||||
};
|
};
|
||||||
|
|
||||||
const removeId = (id: string) => {
|
const removeId = (id: string) => {
|
||||||
const idx = notifications.findIndex((n) => n.id === id);
|
setNotifications((curr) => curr.filter((n) => n.id !== id));
|
||||||
if (idx !== -1) {
|
|
||||||
removeNotification(idx);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateId = (id: string, value: Partial<INotification>) => {
|
const updateId = (id: string, value: Partial<INotification>) => {
|
||||||
@@ -231,8 +223,8 @@ export function NotificationsProvider({ children }) {
|
|||||||
updateId,
|
updateId,
|
||||||
removeId,
|
removeId,
|
||||||
hasNotification,
|
hasNotification,
|
||||||
|
hasAppNotification,
|
||||||
addNotificationAlert,
|
addNotificationAlert,
|
||||||
addOrUpdateNotification,
|
|
||||||
icons,
|
icons,
|
||||||
count: notifications.length,
|
count: notifications.length,
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
export const setClipboard = (value: string) => {
|
export const setClipboard = (value: string) => {
|
||||||
|
// 420 Blaze it
|
||||||
|
// YOLO
|
||||||
|
// Only live once for tonight
|
||||||
const clipElem = document.createElement('input');
|
const clipElem = document.createElement('input');
|
||||||
clipElem.value = value;
|
clipElem.value = value;
|
||||||
document.body.appendChild(clipElem);
|
document.body.appendChild(clipElem);
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export const usePhoneVisibility = () => {
|
|||||||
|
|
||||||
const bottom = useMemo(() => {
|
const bottom = useMemo(() => {
|
||||||
if (!visibility) {
|
if (!visibility) {
|
||||||
return `calc(-728px * ${zoom})`;
|
return `${-728 * zoom.value}px`;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}, [visibility, zoom]);
|
}, [visibility, zoom]);
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ const useStyles = makeStyles((theme) => ({
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
interface IContextMenuOption {
|
export interface IContextMenuOption {
|
||||||
onClick(e, option): void;
|
onClick(e, option): void;
|
||||||
label: string;
|
label: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ export const Modal = ({ children, visible, handleClose }) => {
|
|||||||
|
|
||||||
// when the user presses escape we should close the modal
|
// when the user presses escape we should close the modal
|
||||||
const _handleEscape = (e) => {
|
const _handleEscape = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
const isEscapeKey = e.key === 'Escape' || e.key === 'Esc';
|
const isEscapeKey = e.key === 'Escape' || e.key === 'Esc';
|
||||||
if (isEscapeKey) {
|
if (isEscapeKey) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { ContextMenu } from '../components/ContextMenu';
|
import { ContextMenu, IContextMenuOption } from '../components/ContextMenu';
|
||||||
|
|
||||||
type UseContextMenu = [any, any, () => JSX.Element, boolean];
|
type UseContextMenu = [any, any, () => JSX.Element, boolean];
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ export const MapSettingItem = (current: SettingOption, onClick: Function) => (
|
|||||||
label: item.label,
|
label: item.label,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const useContextMenu = (_options?): UseContextMenu => {
|
export const useContextMenu = (_options?: IContextMenuOption[]): UseContextMenu => {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [options, setOptions] = useState(_options || []);
|
const [options, setOptions] = useState(_options || []);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import events from '../utils/events';
|
import events from '../utils/events';
|
||||||
import { Message, MessageGroup } from '../../phone/src/common/typings/messages';
|
import {
|
||||||
|
CreateMessageBroadcast,
|
||||||
|
Message,
|
||||||
|
MessageGroup,
|
||||||
|
SetMessageRead,
|
||||||
|
} from '../../phone/src/common/typings/messages';
|
||||||
import { sendMessageEvent } from '../utils/messages';
|
import { sendMessageEvent } from '../utils/messages';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,6 +24,10 @@ onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED, () => {
|
|||||||
sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED);
|
sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, () => {
|
||||||
|
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS);
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Messages create message group
|
* Messages create message group
|
||||||
*/
|
*/
|
||||||
@@ -49,6 +58,12 @@ on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGES}`, ({ groupId }: any, cb: Functio
|
|||||||
cb();
|
cb();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
RegisterNuiCallbackType(events.MESSAGES_SET_MESSAGE_READ);
|
||||||
|
on(`__cfx_nui:${events.MESSAGES_SET_MESSAGE_READ}`, (data: SetMessageRead, cb: Function) => {
|
||||||
|
emitNet(events.MESSAGES_SET_MESSAGE_READ, data.groupId);
|
||||||
|
cb();
|
||||||
|
});
|
||||||
|
|
||||||
onNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, (messages: Message[]): void => {
|
onNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, (messages: Message[]): void => {
|
||||||
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_SUCCESS, messages);
|
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_SUCCESS, messages);
|
||||||
});
|
});
|
||||||
@@ -62,7 +77,7 @@ onNet(events.MESSAGES_FETCH_MESSAGES_FAILED, (): void => {
|
|||||||
*/
|
*/
|
||||||
RegisterNuiCallbackType(events.MESSAGES_SEND_MESSAGE);
|
RegisterNuiCallbackType(events.MESSAGES_SEND_MESSAGE);
|
||||||
on(`__cfx_nui:${events.MESSAGES_SEND_MESSAGE}`, (data: any, cb: Function) => {
|
on(`__cfx_nui:${events.MESSAGES_SEND_MESSAGE}`, (data: any, cb: Function) => {
|
||||||
emitNet(events.MESSAGES_SEND_MESSAGE, data.groupId, data.message);
|
emitNet(events.MESSAGES_SEND_MESSAGE, data.groupId, data.message, data.groupName);
|
||||||
cb();
|
cb();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -78,3 +93,7 @@ onNet(events.MESSAGES_SEND_MESSAGE_FAILED, () => {
|
|||||||
onNet(events.MESSAGES_ACTION_RESULT, (result: any) => {
|
onNet(events.MESSAGES_ACTION_RESULT, (result: any) => {
|
||||||
sendMessageEvent(events.MESSAGES_ACTION_RESULT, result);
|
sendMessageEvent(events.MESSAGES_ACTION_RESULT, result);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onNet(events.MESSAGES_CREATE_MESSAGE_BROADCAST, (result: CreateMessageBroadcast) => {
|
||||||
|
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_BROADCAST, result);
|
||||||
|
});
|
||||||
+17
-51
@@ -11,10 +11,7 @@ CREATE TABLE IF NOT EXISTS npwd_phone_contacts (
|
|||||||
number varchar(10) DEFAULT NULL,
|
number varchar(10) DEFAULT NULL,
|
||||||
display varchar(60) NOT NULL DEFAULT '',
|
display varchar(60) NOT NULL DEFAULT '',
|
||||||
PRIMARY KEY (id)
|
PRIMARY KEY (id)
|
||||||
)
|
);
|
||||||
ENGINE = INNODB,
|
|
||||||
AUTO_INCREMENT = 6,
|
|
||||||
AVG_ROW_LENGTH = 4096;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
|
CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
`id` int NOT NULL AUTO_INCREMENT,
|
||||||
@@ -26,7 +23,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
|
|||||||
`visible` tinyint NOT NULL DEFAULT '1',
|
`visible` tinyint NOT NULL DEFAULT '1',
|
||||||
`images` varchar(1000) DEFAULT '',
|
`images` varchar(1000) DEFAULT '',
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=19;
|
);
|
||||||
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `npwd_twitter_profiles` (
|
CREATE TABLE IF NOT EXISTS `npwd_twitter_profiles` (
|
||||||
@@ -41,7 +38,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_profiles` (
|
|||||||
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `profile_name_UNIQUE` (`profile_name`)
|
UNIQUE KEY `profile_name_UNIQUE` (`profile_name`)
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=15;
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
|
CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
`id` int NOT NULL AUTO_INCREMENT,
|
||||||
@@ -53,7 +50,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
|
|||||||
KEY `tweet_idx` (`tweet_id`),
|
KEY `tweet_idx` (`tweet_id`),
|
||||||
CONSTRAINT `profile` FOREIGN KEY (`profile_id`) REFERENCES `npwd_twitter_profiles` (`id`),
|
CONSTRAINT `profile` FOREIGN KEY (`profile_id`) REFERENCES `npwd_twitter_profiles` (`id`),
|
||||||
CONSTRAINT `tweet` FOREIGN KEY (`tweet_id`) REFERENCES `npwd_twitter_tweets` (`id`) ON DELETE CASCADE
|
CONSTRAINT `tweet` FOREIGN KEY (`tweet_id`) REFERENCES `npwd_twitter_tweets` (`id`) ON DELETE CASCADE
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=41;
|
);
|
||||||
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS npwd_notes (
|
CREATE TABLE IF NOT EXISTS npwd_notes (
|
||||||
@@ -62,10 +59,7 @@ CREATE TABLE IF NOT EXISTS npwd_notes (
|
|||||||
title varchar(255) NOT NULL,
|
title varchar(255) NOT NULL,
|
||||||
content varchar(255) NOT NULL,
|
content varchar(255) NOT NULL,
|
||||||
PRIMARY KEY (id)
|
PRIMARY KEY (id)
|
||||||
)
|
);
|
||||||
ENGINE = INNODB,
|
|
||||||
AUTO_INCREMENT = 5,
|
|
||||||
AVG_ROW_LENGTH = 4096;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS npwd_sellout_listings (
|
CREATE TABLE IF NOT EXISTS npwd_sellout_listings (
|
||||||
id int(11) NOT NULL AUTO_INCREMENT,
|
id int(11) NOT NULL AUTO_INCREMENT,
|
||||||
@@ -76,12 +70,7 @@ CREATE TABLE IF NOT EXISTS npwd_sellout_listings (
|
|||||||
url varchar(255) DEFAULT NULL,
|
url varchar(255) DEFAULT NULL,
|
||||||
description varchar(255) NOT NULL,
|
description varchar(255) NOT NULL,
|
||||||
PRIMARY KEY (id)
|
PRIMARY KEY (id)
|
||||||
)
|
);
|
||||||
ENGINE = INNODB,
|
|
||||||
AUTO_INCREMENT = 26,
|
|
||||||
AVG_ROW_LENGTH = 2048,
|
|
||||||
CHARACTER SET utf8mb4,
|
|
||||||
COLLATE utf8mb4_general_ci;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `npwd_twitter_reports` (
|
CREATE TABLE IF NOT EXISTS `npwd_twitter_reports` (
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
`id` int NOT NULL AUTO_INCREMENT,
|
||||||
@@ -93,26 +82,19 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_reports` (
|
|||||||
KEY `tweet_idx` (`tweet_id`),
|
KEY `tweet_idx` (`tweet_id`),
|
||||||
CONSTRAINT `report_profile` FOREIGN KEY (`profile_id`) REFERENCES `npwd_twitter_profiles` (`id`),
|
CONSTRAINT `report_profile` FOREIGN KEY (`profile_id`) REFERENCES `npwd_twitter_profiles` (`id`),
|
||||||
CONSTRAINT `report_tweet` FOREIGN KEY (`tweet_id`) REFERENCES `npwd_twitter_tweets` (`id`) ON DELETE CASCADE
|
CONSTRAINT `report_tweet` FOREIGN KEY (`tweet_id`) REFERENCES `npwd_twitter_tweets` (`id`) ON DELETE CASCADE
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=45;
|
);
|
||||||
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `npwd_messages_groups` (
|
CREATE TABLE IF NOT EXISTS `npwd_messages_groups` (
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
`id` int NOT NULL AUTO_INCREMENT,
|
||||||
`user_identifier` varchar(40) NOT NULL,
|
`user_identifier` varchar(40) NOT NULL,
|
||||||
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
`group_id` varchar(60) NOT NULL,
|
`group_id` varchar(512) NOT NULL,
|
||||||
`participant_identifier` varchar(40) NOT NULL,
|
`participant_identifier` varchar(40) NOT NULL,
|
||||||
`label` varchar(60) DEFAULT '',
|
`label` varchar(60) DEFAULT '',
|
||||||
PRIMARY KEY (`id`),
|
`unreadCount` int(11) NOT NULL DEFAULT 0,
|
||||||
KEY `npwd_messages_groups_group_id` (`group_id`),
|
PRIMARY KEY (`id`)
|
||||||
KEY `npwd_messages_groups_user_identifier_idx` (`user_identifier`),
|
);
|
||||||
KEY `npwd_messages_groups_participant_identifier_idx` (`participant_identifier`),
|
|
||||||
# This table is erroring out because of default collation and charset values on the `user` table
|
|
||||||
# We should discuss an adequate solution
|
|
||||||
CONSTRAINT `npwd_messages_groups_participant_identifier` FOREIGN KEY (`participant_identifier`) REFERENCES `users` (`identifier`),
|
|
||||||
CONSTRAINT `npwd_messages_groups_user_identifier` FOREIGN KEY (`user_identifier`) REFERENCES `users` (`identifier`)
|
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=66;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `npwd_messages_labels` (
|
CREATE TABLE IF NOT EXISTS `npwd_messages_labels` (
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
`id` int NOT NULL AUTO_INCREMENT,
|
||||||
@@ -120,27 +102,20 @@ CREATE TABLE IF NOT EXISTS `npwd_messages_labels` (
|
|||||||
`label` varchar(60) NOT NULL,
|
`label` varchar(60) NOT NULL,
|
||||||
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
`group_id` varchar(45) NOT NULL,
|
`group_id` varchar(512) NOT NULL,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`)
|
||||||
KEY `npwd_messages_labels_group_id_idx` (`group_id`),
|
|
||||||
KEY `npwd_messages_labels_group_id_idx1` (`user_identifier`),
|
|
||||||
CONSTRAINT `npwd_messages_labels_group_id` FOREIGN KEY (`group_id`) REFERENCES `npwd_messages_groups` (`group_id`)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `npwd_messages` (
|
CREATE TABLE IF NOT EXISTS `npwd_messages` (
|
||||||
`id` int NOT NULL AUTO_INCREMENT,
|
`id` int NOT NULL AUTO_INCREMENT,
|
||||||
`message` varchar(512) NOT NULL,
|
`message` varchar(512) NOT NULL,
|
||||||
`user_identifier` varchar(40) NOT NULL,
|
`user_identifier` varchar(40) NOT NULL,
|
||||||
`group_id` varchar(60) NOT NULL,
|
`group_id` varchar(512) NOT NULL,
|
||||||
`isRead` tinyint NOT NULL DEFAULT '0',
|
`isRead` tinyint NOT NULL DEFAULT '0',
|
||||||
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
`visible` tinyint NOT NULL DEFAULT '1',
|
`visible` tinyint NOT NULL DEFAULT '1',
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`)
|
||||||
KEY `messages_identifier_idx` (`user_identifier`),
|
|
||||||
KEY `npwd_messages_group_id_idx` (`group_id`),
|
|
||||||
CONSTRAINT `npwd_messages_group_id` FOREIGN KEY (`group_id`) REFERENCES `npwd_messages_groups` (`group_id`),
|
|
||||||
CONSTRAINT `npwd_messages_user_identifier` FOREIGN KEY (`user_identifier`) REFERENCES `users` (`identifier`)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS npwd_calls (
|
CREATE TABLE IF NOT EXISTS npwd_calls (
|
||||||
@@ -152,20 +127,11 @@ CREATE TABLE IF NOT EXISTS npwd_calls (
|
|||||||
start varchar(255) DEFAULT NULL,
|
start varchar(255) DEFAULT NULL,
|
||||||
end varchar(255) DEFAULT NULL,
|
end varchar(255) DEFAULT NULL,
|
||||||
PRIMARY KEY (id)
|
PRIMARY KEY (id)
|
||||||
)
|
);
|
||||||
ENGINE = INNODB,
|
|
||||||
AUTO_INCREMENT = 8,
|
|
||||||
CHARACTER SET utf8mb4,
|
|
||||||
COLLATE utf8mb4_general_ci;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS npwd_phone_gallery (
|
CREATE TABLE IF NOT EXISTS npwd_phone_gallery (
|
||||||
id int(11) NOT NULL AUTO_INCREMENT,
|
id int(11) NOT NULL AUTO_INCREMENT,
|
||||||
identifier varchar(255) DEFAULT NULL,
|
identifier varchar(255) DEFAULT NULL,
|
||||||
image varchar(255) DEFAULT NULL,
|
image varchar(255) DEFAULT NULL,
|
||||||
PRIMARY KEY (id)
|
PRIMARY KEY (id)
|
||||||
)
|
);
|
||||||
ENGINE = INNODB,
|
|
||||||
AUTO_INCREMENT = 53,
|
|
||||||
AVG_ROW_LENGTH = 4096,
|
|
||||||
CHARACTER SET utf8mb4,
|
|
||||||
COLLATE utf8mb4_general_ci;
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
import { ESX } from './server';
|
import { ESX } from './server';
|
||||||
|
import { XPlayer } from 'esx.js/@types/server';
|
||||||
|
|
||||||
interface IPhoneNumber {
|
interface IPhoneNumber {
|
||||||
phone_number: string;
|
phone_number: string;
|
||||||
@@ -18,6 +19,8 @@ export async function usePhoneNumber(identifier: string): Promise<string> {
|
|||||||
|
|
||||||
export const getSource = () => (global as any).source;
|
export const getSource = () => (global as any).source;
|
||||||
|
|
||||||
|
// we might need to run a db query on this.
|
||||||
|
// to make it more standalone
|
||||||
export function getIdentifier(source: number): string {
|
export function getIdentifier(source: number): string {
|
||||||
return ESX.GetPlayerFromId(source).getIdentifier();
|
return ESX.GetPlayerFromId(source).getIdentifier();
|
||||||
}
|
}
|
||||||
@@ -28,3 +31,27 @@ export async function getIdentifierByPhoneNumber(phoneNumber: string): Promise<s
|
|||||||
const identifier = <Identifier[]>results;
|
const identifier = <Identifier[]>results;
|
||||||
return identifier[0].identifier;
|
return identifier[0].identifier;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the player phoneNumber for a passed identifier
|
||||||
|
* @param identifier The players phone number
|
||||||
|
*/
|
||||||
|
export async function getPlayerFromIdentifier(
|
||||||
|
identifier: string
|
||||||
|
): Promise<XPlayer> {
|
||||||
|
return new Promise((res, rej) => {
|
||||||
|
const xPlayers = ESX.GetPlayers();
|
||||||
|
|
||||||
|
for (const player of xPlayers) {
|
||||||
|
const xPlayer = ESX.GetPlayerFromId(player);
|
||||||
|
if (
|
||||||
|
xPlayer.getIdentifier() != null &&
|
||||||
|
xPlayer.getIdentifier() == identifier
|
||||||
|
) {
|
||||||
|
res(xPlayer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rej(new Error('Call Target Identifier was not found in xPlayers array'));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
import { ESX } from './server';
|
import { ESX } from './server';
|
||||||
import events from '../utils/events';
|
import events from '../utils/events';
|
||||||
import { getIdentifierByPhoneNumber, usePhoneNumber, getIdentifier, getSource } from './functions';
|
import {
|
||||||
import { XPlayer } from 'esx.js/@types/server';
|
getIdentifierByPhoneNumber,
|
||||||
|
usePhoneNumber,
|
||||||
|
getIdentifier,
|
||||||
|
getSource,
|
||||||
|
} from './functions';
|
||||||
|
|
||||||
|
import { getPlayerFromIdentifier } from './functions'
|
||||||
import { ICall } from '../../phone/src/common/typings/call';
|
import { ICall } from '../../phone/src/common/typings/call';
|
||||||
|
|
||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
@@ -10,25 +16,6 @@ import { mainLogger } from './sv_logger';
|
|||||||
|
|
||||||
const callLogger = mainLogger.child({ module: 'calls' });
|
const callLogger = mainLogger.child({ module: 'calls' });
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the player phoneNumber for a passed identifier
|
|
||||||
* @param identifier The players phone number
|
|
||||||
*/
|
|
||||||
async function getPlayerFromIdentifier(identifier: string): Promise<XPlayer> {
|
|
||||||
return new Promise((res, rej) => {
|
|
||||||
const xPlayers = ESX.GetPlayers();
|
|
||||||
|
|
||||||
for (const player of xPlayers) {
|
|
||||||
const xPlayer = ESX.GetPlayerFromId(player);
|
|
||||||
if (xPlayer.getIdentifier() != null && xPlayer.getIdentifier() == identifier) {
|
|
||||||
res(xPlayer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rej(new Error('Call Target Identifier was not found in xPlayers array'));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function saveCall(call: ICall) {
|
async function saveCall(call: ICall) {
|
||||||
const query =
|
const query =
|
||||||
'INSERT INTO npwd_calls (identifier, transmitter, receiver, start) VALUES (?, ?, ?, ?)';
|
'INSERT INTO npwd_calls (identifier, transmitter, receiver, start) VALUES (?, ?, ?, ?)';
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ const formatLogs = (log: winston.Logform.TransformableInfo): string => {
|
|||||||
return `${log.label} [${log.level}]: ${log.message}`;
|
return `${log.label} [${log.level}]: ${log.message}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
const findLogPath = () => `${path.join(GetResourcePath(GetCurrentResourceName()), 'sv_npwd.log')}`;
|
const findLogPath = () =>
|
||||||
|
`${path.join(GetResourcePath(GetCurrentResourceName()), 'sv_npwd.log')}`;
|
||||||
// Initiate the main logger for NPWD
|
// Initiate the main logger for NPWD
|
||||||
|
|
||||||
export const mainLogger = winston.createLogger({
|
export const mainLogger = winston.createLogger({
|
||||||
|
|||||||
@@ -2,13 +2,14 @@ import md5 from 'md5';
|
|||||||
|
|
||||||
import events from '../utils/events';
|
import events from '../utils/events';
|
||||||
import {
|
import {
|
||||||
|
CreateMessageGroupResult,
|
||||||
Message,
|
Message,
|
||||||
MessageGroup,
|
MessageGroup,
|
||||||
CreateMessageGroupResult,
|
|
||||||
} from '../../phone/src/common/typings/messages';
|
} from '../../phone/src/common/typings/messages';
|
||||||
import { pool, withTransaction } from './db';
|
import { pool, withTransaction } from './db';
|
||||||
import { getSource, getIdentifier } from './functions';
|
import { getIdentifier, getSource, getPlayerFromIdentifier } from './functions';
|
||||||
import { mainLogger } from './sv_logger';
|
import { mainLogger } from './sv_logger';
|
||||||
|
import { group } from 'console';
|
||||||
|
|
||||||
const messageLogger = mainLogger.child({ module: 'messages' });
|
const messageLogger = mainLogger.child({ module: 'messages' });
|
||||||
|
|
||||||
@@ -24,6 +25,7 @@ interface UnformattedMessageGroup {
|
|||||||
avatar?: string;
|
avatar?: string;
|
||||||
display?: string;
|
display?: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
unreadCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,9 +36,11 @@ interface MessageGroupMapping {
|
|||||||
[groupId: string]: {
|
[groupId: string]: {
|
||||||
user_identifier: string;
|
user_identifier: string;
|
||||||
participants: string[];
|
participants: string[];
|
||||||
|
phoneNumbers: string[];
|
||||||
label?: string;
|
label?: string;
|
||||||
avatar?: string;
|
avatar?: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
unreadCount: number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,13 +54,27 @@ async function createMessage(
|
|||||||
userIdentifier: string,
|
userIdentifier: string,
|
||||||
groupId: string,
|
groupId: string,
|
||||||
message: string,
|
message: string,
|
||||||
|
participants: string[],
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
const query = `
|
const query = `
|
||||||
INSERT INTO npwd_messages
|
INSERT INTO npwd_messages
|
||||||
(user_identifier, message, group_id)
|
(user_identifier, message, group_id)
|
||||||
VALUES (?, ?, ?)
|
VALUES (?, ?, ?)
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
const groupQuery = `
|
||||||
|
UPDATE npwd_messages_groups SET unreadCount = unreadCount + 1 WHERE participant_identifier = ? AND group_id = ?
|
||||||
|
`;
|
||||||
|
|
||||||
const [results] = await pool.query(query, [userIdentifier, message, groupId]);
|
const [results] = await pool.query(query, [userIdentifier, message, groupId]);
|
||||||
|
|
||||||
|
// updates unreadCount for all participants
|
||||||
|
await Promise.all(
|
||||||
|
participants
|
||||||
|
.filter((s) => userIdentifier !== s)
|
||||||
|
.map((s) => pool.query(groupQuery, [s, groupId])),
|
||||||
|
);
|
||||||
|
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,6 +86,7 @@ async function createMessage(
|
|||||||
async function getMessageGroups(userIdentifier: string): Promise<UnformattedMessageGroup[]> {
|
async function getMessageGroups(userIdentifier: string): Promise<UnformattedMessageGroup[]> {
|
||||||
const query = `
|
const query = `
|
||||||
SELECT
|
SELECT
|
||||||
|
npwd_messages_groups.unreadCount,
|
||||||
npwd_messages_groups.group_id,
|
npwd_messages_groups.group_id,
|
||||||
npwd_messages_groups.participant_identifier,
|
npwd_messages_groups.participant_identifier,
|
||||||
npwd_messages_groups.user_identifier,
|
npwd_messages_groups.user_identifier,
|
||||||
@@ -103,6 +122,7 @@ async function getMessages(userIdentifier: string, groupId: string): Promise<Mes
|
|||||||
SELECT
|
SELECT
|
||||||
npwd_messages.id,
|
npwd_messages.id,
|
||||||
npwd_messages.message,
|
npwd_messages.message,
|
||||||
|
npwd_messages.group_id,
|
||||||
npwd_messages.user_identifier,
|
npwd_messages.user_identifier,
|
||||||
npwd_messages.isRead,
|
npwd_messages.isRead,
|
||||||
npwd_messages.updatedAt,
|
npwd_messages.updatedAt,
|
||||||
@@ -220,12 +240,17 @@ async function getConsolidatedMessageGroups(userIdentifier: string): Promise<Mes
|
|||||||
|
|
||||||
if (groupId in mapping) {
|
if (groupId in mapping) {
|
||||||
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm);
|
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm);
|
||||||
|
mapping[groupId].phoneNumbers = mapping[groupId].phoneNumbers.concat(
|
||||||
|
messageGroup.phone_number,
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
mapping[groupId] = {
|
mapping[groupId] = {
|
||||||
user_identifier: messageGroup.user_identifier,
|
user_identifier: messageGroup.user_identifier,
|
||||||
|
unreadCount: messageGroup.unreadCount,
|
||||||
avatar: messageGroup.avatar,
|
avatar: messageGroup.avatar,
|
||||||
label: messageGroup.label,
|
label: messageGroup.label,
|
||||||
participants: [displayTerm],
|
participants: [displayTerm],
|
||||||
|
phoneNumbers: [messageGroup.phone_number],
|
||||||
updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null,
|
updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -280,12 +305,12 @@ function createGroupHashID(identifiers: string[]) {
|
|||||||
// that this not change! Changing this order can result in the ability
|
// that this not change! Changing this order can result in the ability
|
||||||
// of duplicate message groups being created.
|
// of duplicate message groups being created.
|
||||||
identifiers.sort();
|
identifiers.sort();
|
||||||
const mergedIdentifiers = identifiers.join('-');
|
const mergedIdentifiers = identifiers.join('+');
|
||||||
// we don't need this to be secure. Its purpose is to create a unique
|
// we don't need this to be secure. Its purpose is to create a unique
|
||||||
// string derived from the identifiers. In this way we can check
|
// string derived from the identifiers. In this way we can check
|
||||||
// that this groupId isn't used before. If it has then it means
|
// that this groupId isn't used before. If it has then it means
|
||||||
// we are trying to create a duplicate message group!
|
// we are trying to create a duplicate message group!
|
||||||
return md5(mergedIdentifiers);
|
return mergedIdentifiers;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -312,12 +337,8 @@ async function createMessageGroupsFromPhoneNumbers(
|
|||||||
// we check that each phoneNumber exists before we create the group
|
// we check that each phoneNumber exists before we create the group
|
||||||
const identifiers: string[] = [];
|
const identifiers: string[] = [];
|
||||||
for (const phoneNumber of phoneNumbers) {
|
for (const phoneNumber of phoneNumbers) {
|
||||||
try {
|
|
||||||
const identifier = await getIdentifierFromPhoneNumber(phoneNumber);
|
const identifier = await getIdentifierFromPhoneNumber(phoneNumber);
|
||||||
identifiers.push(identifier);
|
identifiers.push(identifier);
|
||||||
} catch (err) {
|
|
||||||
return { error: true, phoneNumber };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// don't allow explicitly adding yourself
|
// don't allow explicitly adding yourself
|
||||||
@@ -325,9 +346,9 @@ async function createMessageGroupsFromPhoneNumbers(
|
|||||||
return { error: true, mine: true };
|
return { error: true, mine: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupId = createGroupHashID(identifiers);
|
const groupId = createGroupHashID([userIdentifier, ...identifiers]);
|
||||||
if (await checkIfMessageGroupExists(groupId)) {
|
if (await checkIfMessageGroupExists(groupId)) {
|
||||||
return { error: false, duplicate: true, groupId };
|
return { error: false, duplicate: true, groupId, identifiers };
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryPromises = [
|
const queryPromises = [
|
||||||
@@ -345,13 +366,25 @@ async function createMessageGroupsFromPhoneNumbers(
|
|||||||
// wrap this in a transaction to make sure ALL of these INSERTs succeed
|
// 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.
|
// group exist while other are left off.
|
||||||
try {
|
|
||||||
await withTransaction(queryPromises);
|
await withTransaction(queryPromises);
|
||||||
} catch (err) {
|
|
||||||
return { error: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { error: false, groupId };
|
return { error: false, groupId, identifiers };
|
||||||
|
}
|
||||||
|
|
||||||
|
// getting the participants from groupId.
|
||||||
|
// this should return the source or and array of identifiers
|
||||||
|
function getIdentifiersFromParticipants(groupId: string) {
|
||||||
|
return groupId.split('+');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the current message isRead to 0 for said player
|
||||||
|
* @param id
|
||||||
|
*/
|
||||||
|
async function setMessageRead(groupId: string, identifier: string) {
|
||||||
|
const query =
|
||||||
|
'UPDATE npwd_messages_groups SET unreadCount = 0 WHERE group_id = ? AND participant_identifier = ?';
|
||||||
|
await pool.query(query, [groupId, identifier]);
|
||||||
}
|
}
|
||||||
|
|
||||||
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
|
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
|
||||||
@@ -402,6 +435,15 @@ onNet(
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result);
|
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result);
|
||||||
|
if (result.identifiers) {
|
||||||
|
for (const participantId of result.identifiers) {
|
||||||
|
// we don't broadcast to the source of the event.
|
||||||
|
if (participantId !== _identifier) {
|
||||||
|
const participantPlayer = await getPlayerFromIdentifier(participantId);
|
||||||
|
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, participantPlayer.source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source);
|
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source);
|
||||||
@@ -412,6 +454,7 @@ onNet(
|
|||||||
});
|
});
|
||||||
messageLogger.error(`Failed to create message group, ${e.message}`, {
|
messageLogger.error(`Failed to create message group, ${e.message}`, {
|
||||||
source: _source,
|
source: _source,
|
||||||
|
e,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -431,12 +474,29 @@ onNet(events.MESSAGES_FETCH_MESSAGES, async (groupId: string) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
onNet(events.MESSAGES_SEND_MESSAGE, async (groupId: string, message: string) => {
|
onNet(events.MESSAGES_SEND_MESSAGE, async (groupId: string, message: string, groupName: string) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const _identifier = getIdentifier(_source);
|
const _identifier = getIdentifier(_source);
|
||||||
await createMessage(_identifier, groupId, message);
|
const userParticipants = getIdentifiersFromParticipants(groupId);
|
||||||
|
|
||||||
|
await createMessage(_identifier, groupId, message, userParticipants);
|
||||||
|
|
||||||
emitNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, _source, groupId);
|
emitNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, _source, groupId);
|
||||||
|
|
||||||
|
// gets the identifiers foe the participants for current groupId.
|
||||||
|
|
||||||
|
for (const participantId of userParticipants) {
|
||||||
|
// we don't broadcast to the source of the event.
|
||||||
|
if (participantId !== _identifier) {
|
||||||
|
const participantPlayer = await getPlayerFromIdentifier(participantId);
|
||||||
|
emitNet(events.MESSAGES_CREATE_MESSAGE_BROADCAST, participantPlayer.source, {
|
||||||
|
groupName,
|
||||||
|
groupId,
|
||||||
|
message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Not really sure what this does? As I cant find any reference
|
// Not really sure what this does? As I cant find any reference
|
||||||
// of this in the ui part.
|
// of this in the ui part.
|
||||||
@@ -453,3 +513,15 @@ onNet(events.MESSAGES_SEND_MESSAGE, async (groupId: string, message: string) =>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onNet(events.MESSAGES_SET_MESSAGE_READ, async (groupId: string) => {
|
||||||
|
const pSource = getSource();
|
||||||
|
try {
|
||||||
|
const identifier = getIdentifier(pSource);
|
||||||
|
await setMessageRead(groupId, identifier);
|
||||||
|
} catch (e) {
|
||||||
|
messageLogger.error(`Failed to set message as read, ${e.message}`, {
|
||||||
|
source: pSource,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -70,6 +70,8 @@ export default {
|
|||||||
MESSAGES_FETCH_MESSAGES_SUCCESS: 'phone:fetchMessagesSuccess',
|
MESSAGES_FETCH_MESSAGES_SUCCESS: 'phone:fetchMessagesSuccess',
|
||||||
MESSAGES_FETCH_MESSAGES_FAILED: 'phone:fetchMessagesFailed',
|
MESSAGES_FETCH_MESSAGES_FAILED: 'phone:fetchMessagesFailed',
|
||||||
MESSAGES_ACTION_RESULT: 'phone:setMessagesAlert',
|
MESSAGES_ACTION_RESULT: 'phone:setMessagesAlert',
|
||||||
|
MESSAGES_CREATE_MESSAGE_BROADCAST: 'createMessagesBroadcast',
|
||||||
|
MESSAGES_SET_MESSAGE_READ: 'phone:setReadMessages',
|
||||||
|
|
||||||
// Notes
|
// Notes
|
||||||
NOTE_ADD_NOTE: 'phone:addNote',
|
NOTE_ADD_NOTE: 'phone:addNote',
|
||||||
|
|||||||
Reference in new issue
Block a user