refactor: remove messageSearch method calls (server) (#34979)
Some checks are pending
Deploy GitHub Pages / deploy-preview (push) Waiting to run
CI / ⚙️ Variables Setup (push) Waiting to run
CI / 🚀 Notify external services - draft (push) Blocked by required conditions
CI / 📦 Build Packages (push) Blocked by required conditions
CI / deploy-preview (push) Blocked by required conditions
CI / 📦 Meteor Build - coverage (push) Blocked by required conditions
CI / 📦 Meteor Build - official (push) Blocked by required conditions
CI / Builds matrix rust bindings against alpine (push) Waiting to run
CI / 🚢 Build Docker Images for Testing (alpine) (push) Blocked by required conditions
CI / 🚢 Build Docker Images for Production (alpine) (push) Blocked by required conditions
CI / 🔎 Code Check (push) Blocked by required conditions
CI / 🔨 Test Unit (push) Blocked by required conditions
CI / 🔨 Test API (CE) (push) Blocked by required conditions
CI / 🔨 Test UI (CE) (push) Blocked by required conditions
CI / 🔨 Test API (EE) (push) Blocked by required conditions
CI / 🔨 Test UI (EE) (push) Blocked by required conditions
CI / ✅ Tests Done (push) Blocked by required conditions
CI / 🚀 Publish build assets (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (main) (alpine) (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (services) (account) (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (services) (authorization) (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (services) (ddp-streamer) (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (services) (omnichannel-transcript) (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (services) (presence) (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (services) (queue-worker) (push) Blocked by required conditions
CI / 🚀 Publish Docker Image (services) (stream-hub) (push) Blocked by required conditions
CI / 🚀 Notify external services (push) Blocked by required conditions
CI / Update Version Durability (push) Blocked by required conditions
Code scanning - action / CodeQL-Build (push) Waiting to run

This commit is contained in:
Marcos Spessatto Defendi 2025-01-30 10:06:37 -03:00 committed by GitHub
parent 483b4a3917
commit 1bf0c451dc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 95 additions and 67 deletions

View File

@ -13,6 +13,7 @@ import { escapeRegExp } from '@rocket.chat/string-helpers';
import { Meteor } from 'meteor/meteor';
import { reportMessage } from '../../../../server/lib/moderation/reportMessage';
import { messageSearch } from '../../../../server/methods/messageSearch';
import { roomAccessAttributes } from '../../../authorization/server';
import { canAccessRoomAsync, canAccessRoomIdAsync } from '../../../authorization/server/functions/canAccessRoom';
import { canSendMessageAsync } from '../../../authorization/server/functions/canSendMessage';
@ -222,7 +223,14 @@ API.v1.addRoute(
throw new Meteor.Error('error-searchText-param-not-provided', 'The required "searchText" query param is missing.');
}
const result = (await Meteor.callAsync('messageSearch', searchText, roomId, count, offset)).message.docs;
const searchResult = await messageSearch(this.userId, searchText, roomId, count, offset);
if (searchResult === false) {
return API.v1.failure();
}
if (!searchResult.message) {
return API.v1.failure();
}
const result = searchResult.message.docs;
return API.v1.success({
messages: await normalizeMessagesForUser(result, this.userId),

View File

@ -55,8 +55,13 @@ Meteor.methods<ServerMethods>({
SearchLogger.debug({ msg: 'search', text, context, payload });
const userId = Meteor.userId();
if (!userId) {
throw new Error('User not logged in');
}
return new Promise<IRawSearchResult>((resolve, reject) => {
searchProviderService.activeProvider?.search(text, context, payload, (error, data) => {
void searchProviderService.activeProvider?.search(userId, text, context, payload, (error, data) => {
if (error) {
return reject(error);
}

View File

@ -64,11 +64,12 @@ export abstract class SearchProvider<TPayload = any> {
* @param callback is used to return result an can be called with (error,result)
*/
public abstract search(
userId: string,
text: string,
context: { uid?: IUser['_id']; rid: IRoom['_id'] },
payload?: TPayload,
callback?: (error: Error | null, result: IRawSearchResult) => void,
): void;
): Promise<void>;
/**
* Returns an ordered list of suggestions. The result should have at least the form [{text:string}]

View File

@ -1,6 +1,6 @@
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import { Meteor } from 'meteor/meteor';
import { messageSearch } from '../../../../server/methods/messageSearch';
import type { IRawSearchResult } from '../model/ISearchResult';
import { SearchProvider } from '../model/SearchProvider';
@ -33,16 +33,20 @@ export class DefaultProvider extends SearchProvider<{ searchAll?: boolean; limit
/**
* Uses Meteor function 'messageSearch'
*/
search(
async search(
userId: string,
text: string,
context: { uid?: IUser['_id']; rid: IRoom['_id'] },
payload: { searchAll?: boolean; limit?: number } = {},
callback?: (error: Error | null, result: IRawSearchResult) => void,
): void {
): Promise<void> {
const _rid = payload.searchAll ? undefined : context.rid;
const _limit = payload.limit || this._settings.get<number>('PageSize');
Meteor.call('messageSearch', text, _rid, _limit, callback);
const result = await messageSearch(userId, text, _rid, _limit);
if (callback && result !== false) {
return callback(null, result);
}
}
}

View File

@ -13,17 +13,80 @@ import { parseMessageSearchQuery } from '../lib/parseMessageSearchQuery';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
messageSearch(text: string, rid?: string, limit?: number, offset?: number): IRawSearchResult | boolean;
messageSearch(text: string, rid?: string, limit?: number, offset?: number): IRawSearchResult | false;
}
}
export const messageSearch = async function (
userId: string,
text: string,
rid?: string,
limit?: number,
offset?: number,
): Promise<IRawSearchResult | false> {
check(text, String);
check(rid, Match.Maybe(String));
check(limit, Match.Optional(Number));
check(offset, Match.Optional(Number));
// Don't process anything else if the user can't access the room
if (rid) {
if (!(await canAccessRoomIdAsync(rid, userId))) {
return false;
}
} else if (settings.get('Search.defaultProvider.GlobalSearchEnabled') !== true) {
return {
message: {
docs: [],
},
};
}
const user = (await Meteor.userAsync()) as IUser | undefined;
const { query, options } = parseMessageSearchQuery(text, {
user,
offset,
limit,
forceRegex: settings.get('Message_AlwaysSearchRegExp'),
});
if (Object.keys(query).length === 0) {
return {
message: {
docs: [],
},
};
}
query.t = {
$ne: 'rm', // hide removed messages (useful when searching for user messages)
};
query._hidden = {
$ne: true, // don't return _hidden messages
};
if (rid) {
query.rid = rid;
} else {
query.rid = {
$in: user?._id ? (await Subscriptions.findByUserId(user._id).toArray()).map((subscription: ISubscription) => subscription.rid) : [],
};
}
return {
message: {
docs: await Messages.find(query, {
// @ts-expect-error col.s.db is not typed
readPreference: readSecondaryPreferred(Messages.col.s.db),
...options,
}).toArray(),
},
};
};
Meteor.methods<ServerMethods>({
async messageSearch(text, rid, limit, offset) {
check(text, String);
check(rid, Match.Maybe(String));
check(limit, Match.Optional(Number));
check(offset, Match.Optional(Number));
const currentUserId = Meteor.userId();
if (!currentUserId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
@ -31,59 +94,6 @@ Meteor.methods<ServerMethods>({
});
}
// Don't process anything else if the user can't access the room
if (rid) {
if (!(await canAccessRoomIdAsync(rid, currentUserId))) {
return false;
}
} else if (settings.get('Search.defaultProvider.GlobalSearchEnabled') !== true) {
return {
message: {
docs: [],
},
};
}
const user = (await Meteor.userAsync()) as IUser | undefined;
const { query, options } = parseMessageSearchQuery(text, {
user,
offset,
limit,
forceRegex: settings.get('Message_AlwaysSearchRegExp'),
});
if (Object.keys(query).length === 0) {
return {
message: {
docs: [],
},
};
}
query.t = {
$ne: 'rm', // hide removed messages (useful when searching for user messages)
};
query._hidden = {
$ne: true, // don't return _hidden messages
};
if (rid) {
query.rid = rid;
} else {
query.rid = {
$in: user?._id ? (await Subscriptions.findByUserId(user._id).toArray()).map((subscription: ISubscription) => subscription.rid) : [],
};
}
return {
message: {
docs: await Messages.find(query, {
// @ts-expect-error col.s.db is not typed
readPreference: readSecondaryPreferred(Messages.col.s.db),
...options,
}).toArray(),
},
};
return messageSearch(currentUserId, text, rid, limit, offset);
},
});