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:
authored and GitHub committed 2021-03-04 18:35:33 -05:00
1 parent 42d3d573cb
commit 9abac70427
38 files changed
+634 -328

No files matched your search

+21 -2
View File
@@ -1,5 +1,10 @@
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';
/**
@@ -19,6 +24,10 @@ onNet(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
*/
@@ -49,6 +58,12 @@ on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGES}`, ({ groupId }: any, cb: Functio
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 => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_SUCCESS, messages);
});
@@ -62,7 +77,7 @@ onNet(events.MESSAGES_FETCH_MESSAGES_FAILED, (): void => {
*/
RegisterNuiCallbackType(events.MESSAGES_SEND_MESSAGE);
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();
});
@@ -78,3 +93,7 @@ onNet(events.MESSAGES_SEND_MESSAGE_FAILED, () => {
onNet(events.MESSAGES_ACTION_RESULT, (result: any) => {
sendMessageEvent(events.MESSAGES_ACTION_RESULT, result);
});
onNet(events.MESSAGES_CREATE_MESSAGE_BROADCAST, (result: CreateMessageBroadcast) => {
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_BROADCAST, result);
});
+17 -51
View File
@@ -11,10 +11,7 @@ CREATE TABLE IF NOT EXISTS npwd_phone_contacts (
number varchar(10) DEFAULT NULL,
display varchar(60) NOT NULL DEFAULT '',
PRIMARY KEY (id)
)
ENGINE = INNODB,
AUTO_INCREMENT = 6,
AVG_ROW_LENGTH = 4096;
);
CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
`id` int NOT NULL AUTO_INCREMENT,
@@ -26,7 +23,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
`visible` tinyint NOT NULL DEFAULT '1',
`images` varchar(1000) DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19;
);
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,
PRIMARY KEY (`id`),
UNIQUE KEY `profile_name_UNIQUE` (`profile_name`)
) ENGINE=InnoDB AUTO_INCREMENT=15;
);
CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
`id` int NOT NULL AUTO_INCREMENT,
@@ -53,7 +50,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
KEY `tweet_idx` (`tweet_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
) ENGINE=InnoDB AUTO_INCREMENT=41;
);
CREATE TABLE IF NOT EXISTS npwd_notes (
@@ -62,10 +59,7 @@ CREATE TABLE IF NOT EXISTS npwd_notes (
title varchar(255) NOT NULL,
content varchar(255) NOT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB,
AUTO_INCREMENT = 5,
AVG_ROW_LENGTH = 4096;
);
CREATE TABLE IF NOT EXISTS npwd_sellout_listings (
id int(11) NOT NULL AUTO_INCREMENT,
@@ -76,12 +70,7 @@ CREATE TABLE IF NOT EXISTS npwd_sellout_listings (
url varchar(255) DEFAULT NULL,
description varchar(255) NOT NULL,
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` (
`id` int NOT NULL AUTO_INCREMENT,
@@ -93,26 +82,19 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_reports` (
KEY `tweet_idx` (`tweet_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
) ENGINE=InnoDB AUTO_INCREMENT=45;
);
CREATE TABLE IF NOT EXISTS `npwd_messages_groups` (
`id` int NOT NULL AUTO_INCREMENT,
`user_identifier` varchar(40) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT 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,
`label` varchar(60) DEFAULT '',
PRIMARY KEY (`id`),
KEY `npwd_messages_groups_group_id` (`group_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;
`unreadCount` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `npwd_messages_labels` (
`id` int NOT NULL AUTO_INCREMENT,
@@ -120,27 +102,20 @@ CREATE TABLE IF NOT EXISTS `npwd_messages_labels` (
`label` varchar(60) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`group_id` varchar(45) NOT NULL,
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`)
`group_id` varchar(512) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `npwd_messages` (
`id` int NOT NULL AUTO_INCREMENT,
`message` varchar(512) 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',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`visible` tinyint NOT NULL DEFAULT '1',
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`)
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS npwd_calls (
@@ -152,20 +127,11 @@ CREATE TABLE IF NOT EXISTS npwd_calls (
start varchar(255) DEFAULT NULL,
end varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB,
AUTO_INCREMENT = 8,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_general_ci;
);
CREATE TABLE IF NOT EXISTS npwd_phone_gallery (
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(255) DEFAULT NULL,
image varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB,
AUTO_INCREMENT = 53,
AVG_ROW_LENGTH = 4096,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_general_ci;
);
+27
View File
@@ -1,5 +1,6 @@
import { pool } from './db';
import { ESX } from './server';
import { XPlayer } from 'esx.js/@types/server';
interface IPhoneNumber {
phone_number: string;
@@ -18,6 +19,8 @@ export async function usePhoneNumber(identifier: string): Promise<string> {
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 {
return ESX.GetPlayerFromId(source).getIdentifier();
}
@@ -28,3 +31,27 @@ export async function getIdentifierByPhoneNumber(phoneNumber: string): Promise<s
const identifier = <Identifier[]>results;
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'));
});
}
+8 -21
View File
@@ -1,7 +1,13 @@
import { ESX } from './server';
import events from '../utils/events';
import { getIdentifierByPhoneNumber, usePhoneNumber, getIdentifier, getSource } from './functions';
import { XPlayer } from 'esx.js/@types/server';
import {
getIdentifierByPhoneNumber,
usePhoneNumber,
getIdentifier,
getSource,
} from './functions';
import { getPlayerFromIdentifier } from './functions'
import { ICall } from '../../phone/src/common/typings/call';
import { pool } from './db';
@@ -10,25 +16,6 @@ import { mainLogger } from './sv_logger';
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) {
const query =
'INSERT INTO npwd_calls (identifier, transmitter, receiver, start) VALUES (?, ?, ?, ?)';
+2 -1
View File
@@ -13,7 +13,8 @@ const formatLogs = (log: winston.Logform.TransformableInfo): string => {
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
export const mainLogger = winston.createLogger({
+92 -20
View File
@@ -2,13 +2,14 @@ import md5 from 'md5';
import events from '../utils/events';
import {
CreateMessageGroupResult,
Message,
MessageGroup,
CreateMessageGroupResult,
} from '../../phone/src/common/typings/messages';
import { pool, withTransaction } from './db';
import { getSource, getIdentifier } from './functions';
import { getIdentifier, getSource, getPlayerFromIdentifier } from './functions';
import { mainLogger } from './sv_logger';
import { group } from 'console';
const messageLogger = mainLogger.child({ module: 'messages' });
@@ -24,6 +25,7 @@ interface UnformattedMessageGroup {
avatar?: string;
display?: string;
updatedAt: string;
unreadCount: number;
}
/**
@@ -34,9 +36,11 @@ interface MessageGroupMapping {
[groupId: string]: {
user_identifier: string;
participants: string[];
phoneNumbers: string[];
label?: string;
avatar?: string;
updatedAt: string;
unreadCount: number;
};
}
@@ -50,13 +54,27 @@ async function createMessage(
userIdentifier: string,
groupId: string,
message: string,
participants: string[],
): Promise<any> {
const query = `
INSERT INTO npwd_messages
(user_identifier, message, group_id)
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]);
// updates unreadCount for all participants
await Promise.all(
participants
.filter((s) => userIdentifier !== s)
.map((s) => pool.query(groupQuery, [s, groupId])),
);
return results;
}
@@ -68,6 +86,7 @@ async function createMessage(
async function getMessageGroups(userIdentifier: string): Promise<UnformattedMessageGroup[]> {
const query = `
SELECT
npwd_messages_groups.unreadCount,
npwd_messages_groups.group_id,
npwd_messages_groups.participant_identifier,
npwd_messages_groups.user_identifier,
@@ -103,6 +122,7 @@ async function getMessages(userIdentifier: string, groupId: string): Promise<Mes
SELECT
npwd_messages.id,
npwd_messages.message,
npwd_messages.group_id,
npwd_messages.user_identifier,
npwd_messages.isRead,
npwd_messages.updatedAt,
@@ -220,12 +240,17 @@ async function getConsolidatedMessageGroups(userIdentifier: string): Promise<Mes
if (groupId in mapping) {
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm);
mapping[groupId].phoneNumbers = mapping[groupId].phoneNumbers.concat(
messageGroup.phone_number,
);
} else {
mapping[groupId] = {
user_identifier: messageGroup.user_identifier,
unreadCount: messageGroup.unreadCount,
avatar: messageGroup.avatar,
label: messageGroup.label,
participants: [displayTerm],
phoneNumbers: [messageGroup.phone_number],
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
// of duplicate message groups being created.
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
// string derived from the identifiers. In this way we can check
// that this groupId isn't used before. If it has then it means
// 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
const identifiers: string[] = [];
for (const phoneNumber of phoneNumbers) {
try {
const identifier = await getIdentifierFromPhoneNumber(phoneNumber);
identifiers.push(identifier);
} catch (err) {
return { error: true, phoneNumber };
}
const identifier = await getIdentifierFromPhoneNumber(phoneNumber);
identifiers.push(identifier);
}
// don't allow explicitly adding yourself
@@ -325,9 +346,9 @@ async function createMessageGroupsFromPhoneNumbers(
return { error: true, mine: true };
}
const groupId = createGroupHashID(identifiers);
const groupId = createGroupHashID([userIdentifier, ...identifiers]);
if (await checkIfMessageGroupExists(groupId)) {
return { error: false, duplicate: true, groupId };
return { error: false, duplicate: true, groupId, identifiers };
}
const queryPromises = [
@@ -345,13 +366,25 @@ 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
// group exist while other are left off.
try {
await withTransaction(queryPromises);
} catch (err) {
return { error: true };
}
await withTransaction(queryPromises);
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 () => {
@@ -402,6 +435,15 @@ onNet(
});
} else {
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) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source);
@@ -412,6 +454,7 @@ onNet(
});
messageLogger.error(`Failed to create message group, ${e.message}`, {
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();
try {
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);
// 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) {
// Not really sure what this does? As I cant find any reference
// 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,
});
}
});
+2
View File
@@ -70,6 +70,8 @@ export default {
MESSAGES_FETCH_MESSAGES_SUCCESS: 'phone:fetchMessagesSuccess',
MESSAGES_FETCH_MESSAGES_FAILED: 'phone:fetchMessagesFailed',
MESSAGES_ACTION_RESULT: 'phone:setMessagesAlert',
MESSAGES_CREATE_MESSAGE_BROADCAST: 'createMessagesBroadcast',
MESSAGES_SET_MESSAGE_READ: 'phone:setReadMessages',
// Notes
NOTE_ADD_NOTE: 'phone:addNote',