Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/meteor/app/authorization/server/constant/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export const permissions = [
{ _id: 'set-owner', roles: ['admin', 'owner'] },
{ _id: 'send-many-messages', roles: ['admin', 'bot', 'app'] },
{ _id: 'set-leader', roles: ['admin', 'owner'] },
{ _id: 'set-important-message-marker', roles: ['admin', 'owner'] },
{ _id: 'start-discussion', roles: ['admin', 'user', 'federated-external', 'guest', 'app'] },
{ _id: 'start-discussion-other-user', roles: ['admin', 'user', 'federated-external', 'owner', 'app'] },
{ _id: 'unarchive-room', roles: ['admin'] },
Expand Down Expand Up @@ -239,4 +240,5 @@ export const permissions = [
{ _id: 'manage-moderation-actions', roles: ['admin'] },
{ _id: 'bypass-time-limit-edit-and-delete', roles: ['bot', 'app'] },
{ _id: 'export-messages-as-pdf', roles: ['admin', 'user'] },
{ _id: 'mark-message-as-important', roles: ['admin', 'owner', 'important-message-marker'] },
];
18 changes: 17 additions & 1 deletion apps/meteor/app/lib/server/methods/sendMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ Meteor.methods<ServerMethods>({
federation: Match.Maybe(Object),
groupable: Match.Maybe(Boolean),
sentByEmail: Match.Maybe(Boolean),
isImportant: Match.Maybe(Boolean),
});

const user = (await Meteor.userAsync()) as IUser;
Expand All @@ -158,13 +159,28 @@ Meteor.methods<ServerMethods>({
});
}

if (message.isImportant) {
console.log('[sendMessage] Received important message:', {
messageId: message._id,
userId: user._id,
roomId: message.rid
});
}

if (MessageTypes.isSystemMessage(message)) {
throw new Error("Cannot send system messages using 'sendMessage'");
}

try {
return await applyAirGappedRestrictionsValidation(() => executeSendMessage(user, message, { previewUrls }));
const result = await applyAirGappedRestrictionsValidation(() => executeSendMessage(user, message, { previewUrls }));
if (message.isImportant) {
console.log('[sendMessage] Important message saved successfully:', { messageId: result._id });
}
return result;
} catch (error: any) {
if (message.isImportant) {
console.error('[sendMessage] Error saving important message:', error);
}
if (['error-not-allowed', 'restricted-workspace'].includes(error.error || error.message)) {
throw new Meteor.Error(error.error || error.message, error.reason, {
method: 'sendMessage',
Expand Down
7 changes: 7 additions & 0 deletions apps/meteor/app/theme/client/imports/general/base_old.css
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@
&.highlight {
animation: highlight 6s;
}

&.rcx-message--important {
background-color: rgba(245, 69, 92, 0.03) !important;
border-left: 3px solid rgba(245, 69, 92, 0.4);
padding-left: 8px;
margin: 2px 0;
}
}

.page-loading {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { Button, Box } from '@rocket.chat/fuselage';
import { useUserId, useMethod, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
import { useQueryClient } from '@tanstack/react-query';
import type { ReactElement } from 'react';
import { memo, useState, useEffect } from 'react';

import ImportantMessageReadInfo from './ImportantMessageReadInfo';

type ImportantMessageReadButtonProps = {
message: IMessage;
};

const ImportantMessageReadButton = ({ message }: ImportantMessageReadButtonProps): ReactElement | null => {
const userId = useUserId();
const toggleImportantMessageRead = useMethod('toggleImportantMessageRead');
const dispatchToastMessage = useToastMessageDispatch();
const queryClient = useQueryClient();

const serverIsRead = message.importantReadBy?.includes(userId || '') ?? false;
const [isRead, setIsRead] = useState(serverIsRead);

useEffect(() => {
setIsRead(serverIsRead);
}, [serverIsRead]);

if (!message.isImportant || !userId) {
return null;
}

const handleToggle = async () => {
const newState = !isRead;
setIsRead(newState);

console.log('[ImportantMessageReadButton] Toggling read status:', { messageId: message._id, newState });

try {
await toggleImportantMessageRead(message._id);

await Promise.all([
queryClient.refetchQueries({
queryKey: ['important-message-readers', message._id],
type: 'active'
}),
queryClient.refetchQueries({
queryKey: ['important-message-non-readers', message._id],
type: 'active'
})
]);

console.log('[ImportantMessageReadButton] Read status toggled successfully');
} catch (error) {
setIsRead(!newState);
console.error('[ImportantMessageReadButton] Error toggling read status:', error);
dispatchToastMessage({
type: 'error',
message: error instanceof Error ? error.message : String(error),
});
}
};

return (
<Box display='flex' alignItems='center'>
<Button
small
onClick={handleToggle}
primary={!isRead}
mis='x8'
mbs='x4'
style={{ width: 'fit-content', minWidth: 'auto' }}
data-important-message-button
data-important-message-controls
>
{isRead ? 'Message read' : 'Mark as read'}
</Button>
<ImportantMessageReadInfo message={message} />
</Box>
);
};

export default memo(ImportantMessageReadButton);
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { Box, Icon } from '@rocket.chat/fuselage';
import { useMethod, useUserId, usePermission, useUserSubscription, useStream, useRoomToolbox } from '@rocket.chat/ui-contexts';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ReactElement } from 'react';
import { memo, useState, useEffect, useRef, useCallback } from 'react';
import { createPortal } from 'react-dom';

type ImportantMessageReadInfoProps = {
message: IMessage;
};

type User = {
_id: string;
username: string;
name?: string;
};

const ImportantMessageReadInfo = ({ message }: ImportantMessageReadInfoProps): ReactElement | null => {
const [showList, setShowList] = useState(false);
const [position, setPosition] = useState<{ top: number; left: number } | null>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const getUsersWhoRead = useMethod('getUsersWhoReadImportantMessage');
const getUserRoomRole = useMethod('getUserRoomRole');
const userId = useUserId();
const subscription = useUserSubscription(message.rid);
const queryClient = useQueryClient();
const subscribeToRoomMessages = useStream('room-messages');
const subscribeToNotifyRoom = useStream('notify-room');
const { openTab } = useRoomToolbox();

useEffect(() => {
const unsubscribeMessages = subscribeToRoomMessages(message.rid, (msg) => {
if (msg._id === message._id && msg.importantReadBy) {
queryClient.setQueryData(['important-message-readers', message._id], (old: User[] | undefined) => {
return old;
});
void queryClient.refetchQueries({
queryKey: ['important-message-readers', message._id],
type: 'active'
});
}
});

const unsubscribeRoom = subscribeToNotifyRoom(`${message.rid}/subscriptions-changed`, () => {
void queryClient.refetchQueries({
queryKey: ['important-message-readers', message._id],
type: 'active'
});
});

return () => {
unsubscribeMessages();
unsubscribeRoom();
};
}, [subscribeToRoomMessages, subscribeToNotifyRoom, message.rid, message._id, queryClient]);

useEffect(() => {
if (!showList) return;

const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement;

if (target.closest('[data-important-message-controls]')) {
return;
}

if (buttonRef.current && buttonRef.current.contains(target)) {
return;
}

if (listRef.current && listRef.current.contains(target)) {
return;
}

setShowList(false);
};

document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [showList]);

const { data: hasRoleFromQuery = false } = useQuery({
queryKey: ['user-room-role-info', userId, message.rid, 'important-message-marker'],
queryFn: async () => {
if (!userId) return false;
try {
const result = await getUserRoomRole(message.rid, userId, 'important-message-marker');
return result ?? false;
} catch (error) {
return false;
}
},
staleTime: 0,
enabled: !!userId,
});

const hasPermission = usePermission('mark-message-as-important', message.rid);
const hasRole = subscription?.roles?.includes('important-message-marker') ?? hasRoleFromQuery;
const canMarkMessagesAsImportant = hasPermission || hasRole;

const { data: readUsers = [], isLoading: isLoadingRead } = useQuery<User[]>({
queryKey: ['important-message-readers', message._id],
queryFn: async () => {
try {
const result = await getUsersWhoRead(message._id);
return result || [];
} catch (error) {
console.error('Error fetching users who read:', error);
return [];
}
},
enabled: showList,
refetchInterval: showList ? 5000 : false,
staleTime: 0,
});

const readCount = readUsers.length;

if (!message.isImportant || !canMarkMessagesAsImportant) {
return null;
}

const handleClick = () => {
if (!showList && buttonRef.current) {
const rect = buttonRef.current.getBoundingClientRect();
setPosition({
top: rect.bottom + 4,
left: rect.left
});
}
setShowList(!showList);
};

const handleUserClick = useCallback((username: string) => () => {
openTab('members-list', username);
setShowList(false);
}, [openTab]);

return (
<>
<Box mis='x4'>
<Box
is='button'
ref={buttonRef}
onClick={handleClick}
title='Read by information'
data-important-message-info-button
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: '2px 4px',
display: 'inline-flex',
alignItems: 'center',
verticalAlign: 'middle'
}}
>
<Icon name='info-circled' size='x16' />
</Box>
</Box>

{showList && position && createPortal(
<Box
ref={listRef}
position='fixed'
zIndex={9999}
style={{
top: `${position.top}px`,
left: `${position.left}px`,
width: '250px',
backgroundColor: 'var(--rcx-color-surface-tint, #f7f8fa)',
borderRadius: '4px',
boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.12), 0 0 1px 0 rgba(0, 0, 0, 0.08)',
border: '1px solid var(--rcx-color-stroke-extra-light, #ebecef)',
padding: '12px',
maxHeight: '300px',
overflowY: 'auto',
color: 'var(--rcx-color-font-default, #2f343d)'
}}
data-important-message-list
>
<Box fontWeight='700' mbe='x8' fontSize='p2'>
Read by ({readCount})
</Box>

{isLoadingRead ? (
<Box>Loading...</Box>
) : readUsers.length > 0 ? (
<Box>
{readUsers.map((user) => (
<Box
key={user._id}
mbe='x4'
fontSize='p2'
onClick={handleUserClick(user.username)}
style={{
cursor: 'pointer',
padding: '4px',
borderRadius: '2px',
transition: 'background-color 0.2s'
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = 'var(--rcx-color-surface-hover, #e8eaed)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
>
@{user.username} {user.name && `(${user.name})`}
</Box>
))}
</Box>
) : (
<Box fontSize='p2'>No one has read this message yet</Box>
)}
</Box>,
document.body
)}
</>
);
};

export default memo(ImportantMessageReadInfo);
Loading