Skip to content

Commit

Permalink
Revert "fix: fixing the message flow"
Browse files Browse the repository at this point in the history
This reverts commit 4dca35b.
  • Loading branch information
AllanPazRibeiro committed Oct 3, 2023
1 parent 4dca35b commit 93a0d23
Show file tree
Hide file tree
Showing 8 changed files with 343 additions and 293 deletions.
3 changes: 1 addition & 2 deletions TeamsBridgeApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ import {
handlePreMessageOperationPreventAsync,
handlePreMessageSentPreventAsync,
handlePreRoomUserLeaveAsync,
handleUninstallApp,
handleUserRegistrationAutoRenewAsync,
} from './lib/EventHandler';
import { getRocketChatAppEndpointUrl } from './lib/UrlHelper';
Expand Down Expand Up @@ -118,7 +117,7 @@ export class TeamsBridgeApp
persistence: IPersistence,
modify: IModify,
): Promise<void> {
return handleUninstallApp(read, http, modify, this)
this.deleteAppUsers(modify);
}

public async executePreMessageSentPrevent(
Expand Down
4 changes: 2 additions & 2 deletions endpoints/AuthenticationEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,14 @@ export class AuthenticationEndpoint extends ApiEndpoint {
http,
userAccessToken
);
if (!subscriptions || subscriptions.length === 0) {
if (!subscriptions || subscriptions.length == 0) {
const subscriberEndpointUrl = await getRocketChatAppEndpointUrl(
this.app.getAccessors(),
SubscriberEndpointPath
);

// Async operation to create subscription
await subscribeToAllMessagesForOneUserAsync(
subscribeToAllMessagesForOneUserAsync(
http,
rocketChatUserId,
teamsUserProfile.id,
Expand Down
2 changes: 1 addition & 1 deletion lib/Const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export const TeamsAppUserNameSurfix = 'msteams.alias';

export const RegistrationAutoRenewSchedulerId = 'registration.auto.renew.scheduler';

export const RegistrationAutoRenewInterval = '1800 seconds';
export const RegistrationAutoRenewInterval = '10 seconds';

export const DefaultThreadName = 'Rocket.Chat interop group';

Expand Down
119 changes: 53 additions & 66 deletions lib/EventHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
DefaultThreadName,
LoggedInBridgeUserRequiredHintMessageText,
LoginRequiredHintMessageText,
SubscriberEndpointPath,
UnsupportedScenarioHintMessageText,
} from "./Const";
import {
Expand All @@ -35,7 +36,6 @@ import {
addMemberToChatThreadAsync,
createChatThreadAsync,
createOneOnOneChatThreadAsync,
deleteAllSubscriptions,
deleteTextMessageInChatThreadAsync,
listMembersInChatThreadAsync,
listSubscriptionsAsync,
Expand All @@ -51,14 +51,16 @@ import {
} from "./MicrosoftGraphApi";
import {
checkDummyUserByRocketChatUserIdAsync,
doesMessageFootPrintExists,
generateMessageFootprint,
getLastBridgedMessageFootprint,
getMessageFootPrintExistenceInfo,
isLastMessageAlreadySent,
persistMessageIdMappingAsync,
persistOneDriveFileAsync,
persistRoomAsync,
persistUserAccessTokenAsync,
retrieveAllUserRegistrationsAsync,
retrieveAllUsersAccessTokenAsync,
retrieveDummyUserByRocketChatUserIdAsync,
retrieveDummyUserByTeamsUserIdAsync,
retrieveLoginMessageSentStatus,
Expand All @@ -67,15 +69,15 @@ import {
retrieveRoomByRocketChatRoomIdAsync,
retrieveUserAccessTokenAsync,
retrieveUserByRocketChatUserIdAsync,
retrieveUserByTeamsUserIdAsync,
retrieveUserRefreshTokenAsync,
saveLastBridgedMessage,
saveLastBridgedMessageFootprint,
saveLoginMessageSentStatus,
UserModel,
} from "./PersistHelper";
import { getLoginUrl, getRocketChatAppEndpointUrl } from "./UrlHelper";

let wasPrevent = false

export const handlePreMessageSentPreventAsync = async (
message: IMessage,
read: IRead,
Expand Down Expand Up @@ -121,21 +123,6 @@ export const handlePreMessageSentPreventAsync = async (
roomType === RoomType.PRIVATE_GROUP ||
roomType === RoomType.DIRECT_MESSAGE
) {
const messageFootprintInfo = await getMessageFootPrintExistenceInfo(message, read)

if (messageFootprintInfo?.itDoesMessageFootprintExists) {
// This message has already been processed, prevent recursion
wasPrevent = true
return true;
} else {
const messageFootprint = generateMessageFootprint(message, message.room, message.sender)

await saveLastBridgedMessageFootprint({
messageFootprint,
persistence,
rocketChatUserId: message.sender.id
})
}
// If room type is PRIVATE_GROUP or DIRECT_MESSAGE, check if there's any dummy user in the room
const members = await read.getRoomReader().getMembers(message.room.id);

Expand All @@ -154,6 +141,16 @@ export const handlePreMessageSentPreventAsync = async (
);

if (roomRecord) {
const messageFootprintInfo = await getMessageFootPrintExistenceInfo(message, read)
console.log("🚀 ~ file: PRE EventHandler.ts:145 ~ messageFootprintInfo:", messageFootprintInfo)

if (messageFootprintInfo.itDoesMessageFootprintExists) {
console.log("🚀 ~ file: PRE EventHandler.ts:148 ~ messageFootprintInfo.itDoesMessageFootprintExists:", messageFootprintInfo.itDoesMessageFootprintExists)
// This message has already been processed, prevent recursion
return true;
}


// If there's an existing room record, check whether it has a bridge user
if (roomRecord.bridgeUserRocketChatUserId) {

Expand Down Expand Up @@ -283,14 +280,35 @@ export const handlePostMessageSentAsync = async (
members
);
if (dummyUsers && dummyUsers.length > 0) {
const messageFootprintInfo = await getMessageFootPrintExistenceInfo(message, read)
console.log("🚀 ~ file: POST EventHandler.ts:284 ~ messageFootprintInfo:", messageFootprintInfo)

// if (messageFootprintInfo.itDoesMessageFootprintExists) {
// // This message has already been processed, prevent recursion
// return;
// }

const messageFootprintInfo = await getMessageFootPrintExistenceInfo(message, read)
await saveLastBridgedMessageFootprint({
messageFootprint: messageFootprintInfo.messageFootprint,
persistence,
rocketChatUserId: message.sender.id
})

if (wasPrevent) {
// This message has already been processed, prevent recursion
return;
}
// If there's any dummy user in the room, this is a Teams interop chat room
// Sanity check has been done in PreMessageSentPrevent for Teams interop scenarios

// There should be a room record in persist with a bridge user assigned


// const isLastMessageSent = await isLastMessageAlreadySent({
// read,
// rocketChatUserId: message.sender.id ,
// message
// });

// if (isLastMessageSent) {
// return;
// }

const roomRecord = await retrieveRoomByRocketChatRoomIdAsync(
read,
Expand Down Expand Up @@ -325,7 +343,6 @@ export const handlePostMessageSentAsync = async (

if (!roomRecord.teamsThreadId) {
// Not yet a thread exist in Teams side, create one & persist in room record

if (
message.room.type === RoomType.DIRECT_MESSAGE &&
members.length === 2
Expand Down Expand Up @@ -449,12 +466,17 @@ export const handlePostMessageSentAsync = async (
rocketChatMessageId = message.id as string;
}

await persistMessageIdMappingAsync(
persistence,
rocketChatMessageId,
teamsMessageId,
roomRecord.teamsThreadId
)
await Promise.all([
persistMessageIdMappingAsync(
persistence,
rocketChatMessageId,
teamsMessageId,
roomRecord.teamsThreadId
),
saveLastBridgedMessage({ persistence, rocketChatUserId: message.sender.id, message })
])


}
};

Expand Down Expand Up @@ -1037,38 +1059,3 @@ const notifyNotLoggedInUserAsync = async (

await notifyRocketChatUserAsync(message, user, read.getNotifier());
};

const deleteAllUsersSubscriptions = async (read: IRead, http: IHttp) => {
const allRegisteredUsersAccessToken = await retrieveAllUsersAccessTokenAsync(read);

if (!allRegisteredUsersAccessToken) {
return;
}

const deletePromises = allRegisteredUsersAccessToken.map(async (registeredUsersAccessToken) => {
try {
await deleteAllSubscriptions(http, registeredUsersAccessToken);
} catch (error) {
console.error(`Error deleting subscriptions for user: ${error.message}`);
}
});

await Promise.all(deletePromises); // Wait for all deletions to complete
};

export const handleUninstallApp = async (
read: IRead,
http: IHttp,
modify: IModify,
app: TeamsBridgeApp
) => {
try {
await Promise.all([
app.deleteAppUsers(modify),
deleteAllUsersSubscriptions(read, http),
]);

} catch (error) {
console.error(`Error during app uninstallation: ${error.message}`);
}
};
35 changes: 34 additions & 1 deletion lib/InboundNotificationHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,32 @@ import {
import { RoomType } from "@rocket.chat/apps-engine/definition/rooms";
import { IUser } from "@rocket.chat/apps-engine/definition/users";
import { syncAllTeamsBotUsersAsync } from "./AppUserHelper";
import { DefaultTeamName } from "./Const";
import { DefaultTeamName, DefaultThreadName } from "./Const";
import {
mapTeamsMessageToRocketChatMessage,
sendRocketChatMessageInRoomAsync,
sendRocketChatOneOnOneMessageAsync,
} from "./MessageHelper";
import {
getChatThreadWithMembersAsync,
getMessageWithResourceStringAsync,
MessageContentType,
MessageType,
ThreadType,
} from "./MicrosoftGraphApi";
import {
UserModel,
getMessageFootPrintExistenceInfo,
isLastMessageAlreadySent,
persistMessageIdMappingAsync,
persistRoomAsync,
retrieveDummyUserByTeamsUserIdAsync,
retrieveMessageIdMappingByTeamsMessageIdAsync,
retrieveRoomByTeamsThreadIdAsync,
retrieveUserAccessTokenAsync,
retrieveUserByTeamsUserIdAsync,
saveLastBridgedMessage,
saveLastBridgedMessageFootprint,
} from "./PersistHelper";
import { IMessage } from "@rocket.chat/apps-engine/definition/messages";

Expand Down Expand Up @@ -57,6 +63,7 @@ export const handleInboundNotificationAsync = async (
persis: IPersistence,
appId: string
): Promise<void> => {
console.log("🚀 ~ file: InboundNotificationHelper.ts:66 ~ inBoundNotification:", inBoundNotification)
const receiverRocketChatUserId =
inBoundNotification.receiverRocketChatUserId;
if (!receiverRocketChatUserId) {
Expand Down Expand Up @@ -126,6 +133,7 @@ const handleInboundMessageCreatedAsync = async (
persis: IPersistence,
appId: string
): Promise<void> => {
console.log("🚀 ~ file: InboundNotificationHelper.ts:135 ~ inBoundNotification:", inBoundNotification)
const receiverRocketChatUserId =
inBoundNotification.receiverRocketChatUserId;
const resourceString = inBoundNotification.resourceString;
Expand Down Expand Up @@ -285,6 +293,7 @@ const handleInboundMessageCreatedAsync = async (
fromUserTeamsId,
http
});
console.log("🚀 ~ file: InboundNotificationHelper.ts:292 ~ senderUser:", senderUser)

if (!senderUser) {
throw new Error('No user found to send the message');
Expand All @@ -298,6 +307,29 @@ const handleInboundMessageCreatedAsync = async (
http,
modify
);
console.log("🚀 ~ file: InboundNotificationHelper.ts:306 ~ messageText:", messageText)

const messageInfo = {
text: messageText,
room,
file: {
name: getMessageResponse?.attachments ? getMessageResponse.attachments[0].name : '',
}
} as IMessage;
console.log("🚀 ~ file: InboundNotificationHelper.ts:315 ~ messageInfo:", messageInfo)

console.log("🚀 ~ file: InboundNotificationHelper.ts:319 ~ fromUserRocketChatUser:", !!fromUserRocketChatUser)
// if (fromUserRocketChatUser) {
// const messageFootprintInfo = await getMessageFootPrintExistenceInfo(messageInfo, read)
// console.log("🚀 ~ file: InboundNotificationHelper.ts:322 ~ messageFootprintInfo:", messageFootprintInfo)

// if (messageFootprintInfo.itDoesMessageFootprintExists) {
// console.log("🚀 ~ file: InboundNotificationHelper.ts:325 ~ messageFootprintInfo.itDoesMessageFootprintExists:", messageFootprintInfo.itDoesMessageFootprintExists)
// // This message has already been processed, prevent recursion
// return;
// }
// }


if (messageText === "") {
// File message, no text content
Expand Down Expand Up @@ -418,6 +450,7 @@ const getSenderUser = async ({
http: IHttp
}) => {
if (fromUserRocketChatUser) {
console.log("🚀 ~ file: InboundNotificationHelper.ts:282 ~ fromUserRocketChatUser:", fromUserRocketChatUser)
const roomMembers = await read.getRoomReader().getMembers(roomRecord.rocketChatRoomId);
if (roomMembers && roomMembers.find((user) => user.id === fromUserRocketChatUser.rocketChatUserId)) {
return read.getUserReader().getById(fromUserRocketChatUser.rocketChatUserId);
Expand Down
Loading

0 comments on commit 93a0d23

Please sign in to comment.