snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
import type { IDirectMessageRoom, IRoom } from '@rocket.chat/core-typings';
import { Analytics } from '@rocket.chat/models';
import moment from 'moment';
import { convertDateToInt, diffBetweenDaysInclusive } from './date';
import { roomCoordinator } from '../../../../server/lib/rooms/roomCoordinator';
export const findChannelsWithNumberOfMessages = async ({
start,
end,
options = {},
}: {
start: Date;
end: Date;
options: {
offset?: number;
count?: number;
};
}): Promise<{
channels: {
room: {
_id: IRoom['_id'];
name: IRoom['name'] | IRoom['fname'];
ts: IRoom['ts'];
t: IRoom['t'];
_updatedAt: IRoom['_updatedAt'];
usernames?: IDirectMessageRoom['usernames'];
};
messages: number;
lastWeekMessages: number;
diffFromLastWeek: number;
}[];
total: number;
}> => {
const daysBetweenDates = diffBetweenDaysInclusive(end, start);
const endOfLastWeek = moment(start).subtract(1, 'days').toDate();
const startOfLastWeek = moment(endOfLastWeek).subtract(daysBetweenDates, 'days').toDate();
const roomTypes = roomCoordinator.getTypesToShowOnDashboard() as Array<IRoom['t']>;
const aggregationResult = await Analytics.findRoomsByTypesWithNumberOfMessagesBetweenDate({
types: roomTypes,
start: convertDateToInt(start),
end: convertDateToInt(end),
startOfLastWeek: convertDateToInt(startOfLastWeek),
endOfLastWeek: convertDateToInt(endOfLastWeek),
options,
}).toArray();
// The aggregation result may be undefined if there are no matching analytics or corresponding rooms in the period
if (!aggregationResult.length) {
return { channels: [], total: 0 };
}
const [{ channels, total }] = aggregationResult;
return {
channels,
total,
};
};

View File

@@ -0,0 +1,40 @@
import mem from 'mem';
import moment from 'moment';
export const isDateISOString = mem(
(input: string): input is string => {
const timestamp = Date.parse(input);
return !Number.isNaN(timestamp) && new Date(timestamp).toISOString() === input;
},
{ maxAge: 10000 },
);
export const mapDateForAPI = (input: string): Date => {
if (!isDateISOString(input)) {
throw new Error('invalid ISO 8601 date');
}
return new Date(Date.parse(input));
};
export const convertDateToInt = (date: Date): number => parseInt(moment(date).clone().format('YYYYMMDD'), 10);
export const convertIntToDate = (intValue: number): Date => moment(intValue, 'YYYYMMDD').clone().toDate();
const diffBetweenDays = (start: string | number | Date, end: string | number | Date): number =>
moment(new Date(start)).clone().diff(new Date(end), 'days');
export const diffBetweenDaysInclusive = (start: string | number | Date, end: string | number | Date): number =>
diffBetweenDays(start, end) + 1;
export const getTotalOfWeekItems = <T extends Record<string, number>>(weekItems: T[], property: keyof T): number =>
weekItems.reduce((acc, item) => {
acc += item[property];
return acc;
}, 0);
export function transformDatesForAPI(start: string): { start: Date; end: undefined };
export function transformDatesForAPI(start: string, end: string): { start: Date; end: Date };
export function transformDatesForAPI(start: string, end?: string): { start: Date; end: Date | undefined } {
return {
start: mapDateForAPI(start),
end: end ? mapDateForAPI(end) : undefined,
};
}

View File

@@ -0,0 +1,156 @@
import type { IDirectMessageRoom, IRoom, IMessage } from '@rocket.chat/core-typings';
import { Messages, Analytics } from '@rocket.chat/models';
import moment from 'moment';
import { convertDateToInt, diffBetweenDaysInclusive, convertIntToDate, getTotalOfWeekItems } from './date';
import { roomCoordinator } from '../../../../server/lib/rooms/roomCoordinator';
export const handleMessagesSent = async (message: IMessage, { room }: { room?: IRoom }): Promise<IMessage> => {
const roomTypesToShow = roomCoordinator.getTypesToShowOnDashboard();
if (!room || !roomTypesToShow.includes(room.t)) {
return message;
}
await Analytics.saveMessageSent({
date: convertDateToInt(message.ts),
room,
});
return message;
};
export const handleMessagesDeleted = async (message: IMessage, { room }: { room: IRoom }): Promise<IMessage> => {
const roomTypesToShow = roomCoordinator.getTypesToShowOnDashboard();
if (!room || !roomTypesToShow.includes(room.t)) {
return message;
}
await Analytics.saveMessageDeleted({
date: convertDateToInt(message.ts),
room,
});
return message;
};
export const fillFirstDaysOfMessagesIfNeeded = async (date: Date): Promise<void> => {
const messagesFromAnalytics = await Analytics.findOneByTypeBeforeDate({
type: 'messages',
date: convertDateToInt(date),
});
if (!messagesFromAnalytics) {
const startOfPeriod = moment(date).subtract(90, 'days').toDate();
const messages = await Messages.getTotalOfMessagesSentByDate({
start: startOfPeriod,
end: date,
});
await Promise.all(
messages.map((message) =>
Analytics.insertOne({
...message,
date: parseInt(message.date),
}),
),
);
}
};
export const findWeeklyMessagesSentData = async ({
start,
end,
}: {
start: Date;
end: Date;
}): Promise<{
days: { day: Date; messages: number }[];
period: {
count: number;
variation: number;
};
yesterday: {
count: number;
variation: number;
};
}> => {
const daysBetweenDates = diffBetweenDaysInclusive(end, start);
const endOfLastWeek = moment(start).clone().subtract(1, 'days').toDate();
const startOfLastWeek = moment(endOfLastWeek).clone().subtract(daysBetweenDates, 'days').toDate();
const today = convertDateToInt(end);
const yesterday = convertDateToInt(moment(end).clone().subtract(1, 'days').toDate());
const currentPeriodMessages = await Analytics.getMessagesSentTotalByDate({
start: convertDateToInt(start),
end: convertDateToInt(end),
options: { count: daysBetweenDates, sort: { _id: -1 } },
}).toArray();
const lastPeriodMessages = await Analytics.getMessagesSentTotalByDate({
start: convertDateToInt(startOfLastWeek),
end: convertDateToInt(endOfLastWeek),
options: { count: daysBetweenDates, sort: { _id: -1 } },
}).toArray();
const yesterdayMessages = currentPeriodMessages.find((item) => item._id === yesterday)?.messages || 0;
const todayMessages = currentPeriodMessages.find((item) => item._id === today)?.messages || 0;
const currentPeriodTotalOfMessages = getTotalOfWeekItems(currentPeriodMessages, 'messages');
const lastPeriodTotalOfMessages = getTotalOfWeekItems(lastPeriodMessages, 'messages');
return {
days: currentPeriodMessages.map((day) => ({
day: convertIntToDate(day._id),
messages: day.messages,
})),
period: {
count: currentPeriodTotalOfMessages,
variation: currentPeriodTotalOfMessages - lastPeriodTotalOfMessages,
},
yesterday: {
count: yesterdayMessages,
variation: todayMessages - yesterdayMessages,
},
};
};
export const findMessagesSentOrigin = async ({
start,
end,
}: {
start: Date;
end: Date;
}): Promise<{
origins: {
t: IRoom['t'];
messages: number;
}[];
}> => {
const origins = await Analytics.getMessagesOrigin({
start: convertDateToInt(start),
end: convertDateToInt(end),
}).toArray();
const roomTypesToShow: IRoom['t'][] = roomCoordinator.getTypesToShowOnDashboard() as IRoom['t'][];
const responseTypes = origins.map((origin) => origin.t);
const missingTypes = roomTypesToShow.filter((type): type is IRoom['t'] => !responseTypes.includes(type));
if (missingTypes.length) {
missingTypes.forEach((type) => origins.push({ messages: 0, t: type }));
}
return { origins };
};
export const findTopFivePopularChannelsByMessageSentQuantity = async ({
start,
end,
}: {
start: Date;
end: Date;
}): Promise<{
channels: {
t: IRoom['t'];
messages: number;
name: IRoom['name'] | IRoom['fname'];
usernames?: IDirectMessageRoom['usernames'];
}[];
}> => {
const channels = await Analytics.getMostPopularChannelsByMessagesSentQuantity({
start: convertDateToInt(start),
end: convertDateToInt(end),
options: { count: 5, sort: { messages: -1 } },
}).toArray();
return { channels };
};

View File

@@ -0,0 +1,25 @@
import { fillFirstDaysOfMessagesIfNeeded, handleMessagesDeleted, handleMessagesSent } from './messages';
import { fillFirstDaysOfUsersIfNeeded, handleUserCreated } from './users';
import { callbacks } from '../../../../server/lib/callbacks';
export const attachCallbacks = (): void => {
callbacks.add(
'afterSaveMessage',
(message, { room }) => handleMessagesSent(message, { room }),
callbacks.priority.MEDIUM,
'engagementDashboard.afterSaveMessage',
);
callbacks.add('afterDeleteMessage', handleMessagesDeleted, callbacks.priority.MEDIUM, 'engagementDashboard.afterDeleteMessage');
callbacks.add('afterCreateUser', handleUserCreated, callbacks.priority.MEDIUM, 'engagementDashboard.afterCreateUser');
};
export const detachCallbacks = (): void => {
callbacks.remove('afterSaveMessage', 'engagementDashboard.afterSaveMessage');
callbacks.remove('afterDeleteMessage', 'engagementDashboard.afterDeleteMessage');
callbacks.remove('afterCreateUser', 'engagementDashboard.afterCreateUser');
};
export const prepareAnalytics = async (): Promise<void> => {
const now = new Date();
await Promise.all([fillFirstDaysOfUsersIfNeeded(now), fillFirstDaysOfMessagesIfNeeded(now)]);
};

View File

@@ -0,0 +1,179 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Users, Analytics, Sessions } from '@rocket.chat/models';
import moment from 'moment';
import { convertDateToInt, diffBetweenDaysInclusive, getTotalOfWeekItems, convertIntToDate } from './date';
export const handleUserCreated = async (user: IUser): Promise<IUser> => {
if (user.roles?.includes('anonymous')) {
return user;
}
await Analytics.saveUserData({
date: convertDateToInt(user.createdAt),
});
return user;
};
export const fillFirstDaysOfUsersIfNeeded = async (date: Date): Promise<void> => {
const usersFromAnalytics = await Analytics.findOneByTypeBeforeDate({
type: 'users',
date: convertDateToInt(date),
});
if (!usersFromAnalytics) {
const startOfPeriod = moment(date).subtract(90, 'days').toDate();
const users = await Users.getTotalOfRegisteredUsersByDate({
start: startOfPeriod,
end: date,
});
users.forEach((user) =>
Analytics.insertOne({
...user,
date: parseInt(user.date),
}),
);
}
};
export const findWeeklyUsersRegisteredData = async ({
start,
end,
}: {
start: Date;
end: Date;
}): Promise<{
days: { day: Date; users: number }[];
period: {
count: number;
variation: number;
};
yesterday: {
count: number;
variation: number;
};
}> => {
const daysBetweenDates = diffBetweenDaysInclusive(end, start);
const endOfLastWeek = moment(start).clone().subtract(1, 'days').toDate();
const startOfLastWeek = moment(endOfLastWeek).clone().subtract(daysBetweenDates, 'days').toDate();
const today = convertDateToInt(end);
const yesterday = convertDateToInt(moment(end).clone().subtract(1, 'days').toDate());
const currentPeriodUsers = await Analytics.getTotalOfRegisteredUsersByDate({
start: convertDateToInt(start),
end: convertDateToInt(end),
options: { count: daysBetweenDates, sort: { _id: -1 } },
}).toArray();
const lastPeriodUsers = await Analytics.getTotalOfRegisteredUsersByDate({
start: convertDateToInt(startOfLastWeek),
end: convertDateToInt(endOfLastWeek),
options: { count: daysBetweenDates, sort: { _id: -1 } },
}).toArray();
const yesterdayUsers = currentPeriodUsers.find((item) => item._id === yesterday)?.users || 0;
const todayUsers = currentPeriodUsers.find((item) => item._id === today)?.users || 0;
const currentPeriodTotalUsers = getTotalOfWeekItems(currentPeriodUsers, 'users');
const lastPeriodTotalUsers = getTotalOfWeekItems(lastPeriodUsers, 'users');
return {
days: currentPeriodUsers.map((day) => ({ day: convertIntToDate(day._id), users: day.users })),
period: {
count: currentPeriodTotalUsers,
variation: currentPeriodTotalUsers - lastPeriodTotalUsers,
},
yesterday: {
count: yesterdayUsers,
variation: todayUsers - yesterdayUsers,
},
};
};
const createDestructuredDate = (
input: moment.MomentInput,
): {
year: number;
month: number;
day: number;
} => {
const date = moment(input);
return {
year: date.year(),
month: date.month() + 1,
day: date.date(),
};
};
export const findActiveUsersMonthlyData = async ({
start,
end,
}: {
start: Date;
end: Date;
}): Promise<{
month: {
day: number;
month: number;
year: number;
usersList: IUser['_id'][];
users: number;
}[];
}> => ({
month: await Sessions.getActiveUsersOfPeriodByDayBetweenDates({
start: createDestructuredDate(start),
end: createDestructuredDate(end),
}),
});
export const findBusiestsChatsInADayByHours = async ({
start,
}: {
start: Date;
}): Promise<{
hours: {
hour: number;
users: number;
}[];
}> => ({
hours: await Sessions.getBusiestTimeWithinHoursPeriod({
start: moment(start).subtract(24, 'hours').toDate(),
end: start,
groupSize: 2,
}),
});
export const findBusiestsChatsWithinAWeek = async ({
start,
}: {
start: Date;
}): Promise<{
month: {
day: number;
month: number;
year: number;
users: number;
}[];
}> => ({
month: await Sessions.getTotalOfSessionsByDayBetweenDates({
start: createDestructuredDate(moment(start).subtract(7, 'days')),
end: createDestructuredDate(start),
}),
});
export const findUserSessionsByHourWithinAWeek = async ({
start,
end,
}: {
start: Date;
end: Date;
}): Promise<{
week: {
hour: number;
day: number;
month: number;
year: number;
users: number;
}[];
}> => ({
week: await Sessions.getTotalOfSessionByHourAndDayBetweenDates({
start,
end,
}),
});