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
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:
19
apps/meteor/server/lib/search/events/EventService.ts
Normal file
19
apps/meteor/server/lib/search/events/EventService.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { SearchLogger } from '../logger/logger';
|
||||
import { searchProviderService } from '../service';
|
||||
|
||||
export class EventService {
|
||||
_pushError(name: string, value: string, _payload?: unknown) {
|
||||
// TODO implement a (performant) cache
|
||||
SearchLogger.debug({
|
||||
msg: 'Error on event',
|
||||
eventName: name,
|
||||
eventId: value,
|
||||
});
|
||||
}
|
||||
|
||||
promoteEvent(name: string, value: string, payload?: unknown) {
|
||||
if (!searchProviderService.activeProvider?.on(name, value)) {
|
||||
this._pushError(name, value, payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
32
apps/meteor/server/lib/search/events/index.ts
Normal file
32
apps/meteor/server/lib/search/events/index.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { IMessage } from '@rocket.chat/core-typings';
|
||||
|
||||
import { EventService } from './EventService';
|
||||
import { settings } from '../../../settings';
|
||||
import { callbacks } from '../../callbacks';
|
||||
import { searchProviderService } from '../service';
|
||||
|
||||
export const searchEventService = new EventService();
|
||||
|
||||
/**
|
||||
* Listen to message changes via Hooks
|
||||
*/
|
||||
function afterSaveMessage(m: IMessage) {
|
||||
searchEventService.promoteEvent('message.save', m._id, m);
|
||||
return m;
|
||||
}
|
||||
|
||||
function afterDeleteMessage(m: IMessage) {
|
||||
searchEventService.promoteEvent('message.delete', m._id);
|
||||
return m;
|
||||
}
|
||||
|
||||
settings.watch('Search.Provider', () => {
|
||||
if (searchProviderService.activeProvider?.on) {
|
||||
callbacks.add('afterSaveMessage', afterSaveMessage, callbacks.priority.MEDIUM, 'search-events');
|
||||
callbacks.add('afterDeleteMessage', afterDeleteMessage, callbacks.priority.MEDIUM, 'search-events-delete');
|
||||
return;
|
||||
}
|
||||
|
||||
callbacks.remove('afterSaveMessage', 'search-events');
|
||||
callbacks.remove('afterDeleteMessage', 'search-events-delete');
|
||||
});
|
||||
3
apps/meteor/server/lib/search/logger/logger.ts
Normal file
3
apps/meteor/server/lib/search/logger/logger.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { Logger } from '@rocket.chat/logger';
|
||||
|
||||
export const SearchLogger = new Logger('Search Logger');
|
||||
29
apps/meteor/server/lib/search/model/ISearchResult.ts
Normal file
29
apps/meteor/server/lib/search/model/ISearchResult.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { IMessage, IRoom, IUser, RoomType } from '@rocket.chat/core-typings';
|
||||
|
||||
export type IRawSearchResult = {
|
||||
message?: { docs: IMessage[] };
|
||||
room?: { docs: IRoom[] };
|
||||
};
|
||||
|
||||
export type ISearchResult = {
|
||||
message?: {
|
||||
docs: (IMessage & {
|
||||
user: IUser['_id'];
|
||||
rid: IRoom['_id'];
|
||||
r?: {
|
||||
name: string | undefined;
|
||||
t: RoomType;
|
||||
};
|
||||
username?: string;
|
||||
valid?: boolean;
|
||||
})[];
|
||||
};
|
||||
room?: {
|
||||
docs: {
|
||||
_id: IRoom['_id'];
|
||||
valid?: boolean;
|
||||
t?: RoomType;
|
||||
name?: string;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
117
apps/meteor/server/lib/search/model/SearchProvider.ts
Normal file
117
apps/meteor/server/lib/search/model/SearchProvider.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import type { IMessageSearchSuggestion, IRoom, IUser } from '@rocket.chat/core-typings';
|
||||
import type { TranslationKey } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import type { IRawSearchResult } from './ISearchResult';
|
||||
import { Settings } from './Settings';
|
||||
import { SearchLogger } from '../logger/logger';
|
||||
|
||||
export abstract class SearchProvider<TPayload = any> {
|
||||
private _key: string;
|
||||
|
||||
protected _settings: Settings;
|
||||
|
||||
/**
|
||||
* Create search provider, key must match /^[A-Za-z0-9]+$/
|
||||
*/
|
||||
constructor(key: string) {
|
||||
if (!key.match(/^[A-Za-z0-9]+$/)) {
|
||||
throw new Error(`cannot instantiate provider: ${key} does not match key-pattern`);
|
||||
}
|
||||
|
||||
SearchLogger.info({
|
||||
msg: 'create search provider',
|
||||
providerKey: key,
|
||||
});
|
||||
|
||||
this._key = key;
|
||||
this._settings = new Settings(key);
|
||||
}
|
||||
|
||||
/* --- basic params ---*/
|
||||
get key() {
|
||||
return this._key;
|
||||
}
|
||||
|
||||
abstract get i18nLabel(): TranslationKey;
|
||||
|
||||
abstract get i18nDescription(): TranslationKey;
|
||||
|
||||
get iconName() {
|
||||
return 'magnifier';
|
||||
}
|
||||
|
||||
get settings() {
|
||||
return this._settings.list();
|
||||
}
|
||||
|
||||
get settingsAsMap() {
|
||||
return this._settings.map();
|
||||
}
|
||||
|
||||
/* --- templates ---*/
|
||||
get resultTemplate() {
|
||||
return 'DefaultSearchResultTemplate';
|
||||
}
|
||||
|
||||
get suggestionItemTemplate() {
|
||||
return 'DefaultSuggestionItemTemplate';
|
||||
}
|
||||
|
||||
/* --- search functions ---*/
|
||||
/**
|
||||
* Search using the current search provider and check if results are valid for the user. The search result has
|
||||
* the format {messages:{start:0,numFound:1,docs:[{...}]},users:{...},rooms:{...}}
|
||||
* @param text the search text
|
||||
* @param context the context (uid, rid)
|
||||
* @param payload custom payload (e.g. for paging)
|
||||
* @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,
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Returns an ordered list of suggestions. The result should have at least the form [{text:string}]
|
||||
* @param _text the search text
|
||||
* @param _context the context (uid, rid)
|
||||
* @param _payload custom payload (e.g. for paging)
|
||||
* @param callback is used to return result an can be called with (error,result)
|
||||
*/
|
||||
suggest(
|
||||
_text: string,
|
||||
_context: { uid?: IUser['_id']; rid: IRoom['_id'] },
|
||||
_payload: TPayload,
|
||||
callback?: (error: Error | null, result: IMessageSearchSuggestion[]) => void,
|
||||
) {
|
||||
callback?.(null, []);
|
||||
}
|
||||
|
||||
get supportsSuggestions() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* --- triggers ---*/
|
||||
on(_name: string, _value: unknown) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* --- livecycle ---*/
|
||||
run(reason: any) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this._settings.load();
|
||||
this.start(reason, resolve, reject);
|
||||
});
|
||||
}
|
||||
|
||||
start(_reason: any, resolve: (value: unknown) => void, _reject: (reason?: any) => void) {
|
||||
resolve(undefined);
|
||||
}
|
||||
|
||||
stop(resolve: () => void) {
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
48
apps/meteor/server/lib/search/model/Setting.ts
Normal file
48
apps/meteor/server/lib/search/model/Setting.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { SettingValue } from '@rocket.chat/core-typings';
|
||||
|
||||
import { settings } from '../../../settings';
|
||||
|
||||
/**
|
||||
* Setting Object in order to manage settings loading for providers and admin ui display
|
||||
*/
|
||||
export class Setting {
|
||||
private readonly _basekey: string;
|
||||
|
||||
public readonly key: string;
|
||||
|
||||
public readonly type: string;
|
||||
|
||||
public readonly defaultValue: SettingValue;
|
||||
|
||||
public readonly options: Record<string, unknown>;
|
||||
|
||||
private _value: SettingValue;
|
||||
|
||||
constructor(basekey: string, key: string, type: string, defaultValue: SettingValue, options = {}) {
|
||||
this._basekey = basekey;
|
||||
this.key = key;
|
||||
this.type = type;
|
||||
this.defaultValue = defaultValue;
|
||||
this.options = options;
|
||||
this._value = undefined;
|
||||
}
|
||||
|
||||
get value() {
|
||||
return this._value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Id is generated based on baseKey and key
|
||||
*/
|
||||
get id() {
|
||||
return `Search.${this._basekey}.${this.key}`;
|
||||
}
|
||||
|
||||
load() {
|
||||
this._value = settings.get(this.id);
|
||||
|
||||
if (this._value === undefined) {
|
||||
this._value = this.defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
45
apps/meteor/server/lib/search/model/Settings.ts
Normal file
45
apps/meteor/server/lib/search/model/Settings.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import type { SettingValue } from '@rocket.chat/core-typings';
|
||||
|
||||
import { Setting } from './Setting';
|
||||
|
||||
/**
|
||||
* Settings Object allows to manage Setting Objects
|
||||
*/
|
||||
export class Settings {
|
||||
private settings: Record<string, Setting>;
|
||||
|
||||
constructor(public basekey: string) {
|
||||
this.settings = {};
|
||||
}
|
||||
|
||||
add(key: string, type: string, defaultValue: SettingValue, options: Record<string, unknown>) {
|
||||
this.settings[key] = new Setting(this.basekey, key, type, defaultValue, options);
|
||||
}
|
||||
|
||||
list() {
|
||||
return Object.keys(this.settings).map((key) => this.settings[key]);
|
||||
}
|
||||
|
||||
map() {
|
||||
return this.settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* return the value for key
|
||||
*/
|
||||
get<TValue>(key: string) {
|
||||
if (!this.settings[key]) {
|
||||
throw new Error('Setting is not set');
|
||||
}
|
||||
return this.settings[key].value as TValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* load currently stored values of all settings
|
||||
*/
|
||||
load() {
|
||||
Object.keys(this.settings).forEach((key) => {
|
||||
this.settings[key].load();
|
||||
});
|
||||
}
|
||||
}
|
||||
52
apps/meteor/server/lib/search/provider/DefaultProvider.ts
Normal file
52
apps/meteor/server/lib/search/provider/DefaultProvider.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { IRoom, IUser } from '@rocket.chat/core-typings';
|
||||
|
||||
import { messageSearch } from '../../../meteor-methods/messages/messageSearch';
|
||||
import type { IRawSearchResult } from '../model/ISearchResult';
|
||||
import { SearchProvider } from '../model/SearchProvider';
|
||||
|
||||
/**
|
||||
* Implements the default provider (based on mongo db search)
|
||||
*/
|
||||
export class DefaultProvider extends SearchProvider<{ searchAll?: boolean; limit?: number }> {
|
||||
/**
|
||||
* Enable settings: GlobalSearchEnabled, PageSize
|
||||
*/
|
||||
constructor() {
|
||||
super('defaultProvider');
|
||||
this._settings.add('GlobalSearchEnabled', 'boolean', false, {
|
||||
i18nLabel: 'Global_Search',
|
||||
alert: 'This feature is currently in beta and could decrease the application performance',
|
||||
});
|
||||
this._settings.add('PageSize', 'int', 10, {
|
||||
i18nLabel: 'Search_Page_Size',
|
||||
});
|
||||
}
|
||||
|
||||
get i18nLabel() {
|
||||
return 'Default_provider' as const;
|
||||
}
|
||||
|
||||
get i18nDescription() {
|
||||
return 'You_can_search_using_RegExp_eg' as const;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses Meteor function 'messageSearch'
|
||||
*/
|
||||
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,
|
||||
): Promise<void> {
|
||||
const _rid = payload.searchAll ? undefined : context.rid;
|
||||
|
||||
const _limit = payload.limit || this._settings.get<number>('PageSize');
|
||||
|
||||
const result = await messageSearch(userId, text, _rid, _limit);
|
||||
if (callback && result !== false) {
|
||||
return callback(null, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
5
apps/meteor/server/lib/search/register.ts
Normal file
5
apps/meteor/server/lib/search/register.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { DefaultProvider } from './provider/DefaultProvider';
|
||||
import { searchProviderService } from './service';
|
||||
|
||||
// register provider
|
||||
searchProviderService.register(new DefaultProvider());
|
||||
45
apps/meteor/server/lib/search/search.internalService.ts
Normal file
45
apps/meteor/server/lib/search/search.internalService.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { api, ServiceClassInternal } from '@rocket.chat/core-services';
|
||||
import { Users } from '@rocket.chat/models';
|
||||
|
||||
import { searchEventService } from './events';
|
||||
import { searchProviderService } from './service';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
class Search extends ServiceClassInternal {
|
||||
protected name = 'search';
|
||||
|
||||
protected override internal = true;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.onEvent('watch.users', async ({ clientAction, id, ...rest }) => {
|
||||
if (clientAction === 'removed') {
|
||||
searchEventService.promoteEvent('user.delete', id, undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const user = ('data' in rest && rest.data) || (await Users.findOneById(id));
|
||||
searchEventService.promoteEvent('user.save', id, user);
|
||||
});
|
||||
|
||||
this.onEvent('watch.rooms', async ({ clientAction, room }) => {
|
||||
if (clientAction === 'removed') {
|
||||
searchEventService.promoteEvent('room.delete', room._id, undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
searchEventService.promoteEvent('room.save', room._id, room);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const service = new Search();
|
||||
|
||||
settings.watch('Search.Provider', async () => {
|
||||
if (searchProviderService.activeProvider?.on) {
|
||||
api.registerService(service);
|
||||
} else {
|
||||
await api.destroyService(service);
|
||||
}
|
||||
});
|
||||
122
apps/meteor/server/lib/search/service/SearchProviderService.ts
Normal file
122
apps/meteor/server/lib/search/service/SearchProviderService.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { withDebouncing } from '../../../../lib/utils/highOrderFunctions';
|
||||
import { settings, settingsRegistry } from '../../../settings';
|
||||
import { SearchLogger } from '../logger/logger';
|
||||
import type { SearchProvider } from '../model/SearchProvider';
|
||||
|
||||
export class SearchProviderService {
|
||||
public providers: Record<string, SearchProvider> = {};
|
||||
|
||||
public activeProvider?: SearchProvider;
|
||||
|
||||
/**
|
||||
* Stop current provider (if there is one) and start the new
|
||||
* @param id the id of the provider which should be started
|
||||
*/
|
||||
async use(id: SearchProvider['key']) {
|
||||
if (!this.providers[id]) {
|
||||
throw new Error(`provider ${id} cannot be found`);
|
||||
}
|
||||
|
||||
let reason: 'startup' | 'update' | 'switch';
|
||||
|
||||
if (!this.activeProvider) {
|
||||
reason = 'startup';
|
||||
} else if (this.activeProvider.key === this.providers[id].key) {
|
||||
reason = 'update';
|
||||
} else {
|
||||
reason = 'switch';
|
||||
}
|
||||
|
||||
if (this.activeProvider) {
|
||||
const provider = this.activeProvider;
|
||||
SearchLogger.debug({
|
||||
msg: 'Stopping provider',
|
||||
providerKey: provider.key,
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => provider.stop(resolve));
|
||||
}
|
||||
|
||||
this.activeProvider = undefined;
|
||||
|
||||
SearchLogger.debug({
|
||||
msg: 'Start provider',
|
||||
providerKey: id,
|
||||
});
|
||||
|
||||
await this.providers[id].run(reason);
|
||||
this.activeProvider = this.providers[id];
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a search provider on system startup
|
||||
*/
|
||||
register(provider: SearchProvider) {
|
||||
this.providers[provider.key] = provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the service (loads provider settings for admin ui, add lister not setting changes, enable current provider
|
||||
*/
|
||||
async start() {
|
||||
SearchLogger.debug('Load data for all providers');
|
||||
|
||||
const { providers } = this;
|
||||
|
||||
// add settings for admininistration
|
||||
await settingsRegistry.addGroup('Search', async function () {
|
||||
await this.add('Search.Provider', 'defaultProvider', {
|
||||
type: 'select',
|
||||
values: Object.values(providers).map((provider) => ({
|
||||
key: provider.key,
|
||||
i18nLabel: provider.i18nLabel,
|
||||
})),
|
||||
public: true,
|
||||
i18nLabel: 'Search_Provider',
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
Object.keys(providers)
|
||||
.filter((key) => providers[key].settings && providers[key].settings.length > 0)
|
||||
.map(async (key) => {
|
||||
await this.section(providers[key].i18nLabel, async function () {
|
||||
await Promise.all(
|
||||
providers[key].settings.map(async (setting) => {
|
||||
const _options: Record<string, unknown> = {
|
||||
type: setting.type,
|
||||
...setting.options,
|
||||
};
|
||||
|
||||
_options.enableQuery = _options.enableQuery || [];
|
||||
|
||||
if (!_options.enableQuery) {
|
||||
_options.enableQuery = [];
|
||||
}
|
||||
|
||||
if (Array.isArray(_options.enableQuery)) {
|
||||
_options.enableQuery.push({
|
||||
_id: 'Search.Provider',
|
||||
value: key,
|
||||
});
|
||||
}
|
||||
|
||||
await this.add(setting.id, setting.defaultValue, _options);
|
||||
}),
|
||||
);
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// add listener to react on setting changes
|
||||
const configProvider = withDebouncing({ wait: 1000 })(() => {
|
||||
const providerId = settings.get<string>('Search.Provider');
|
||||
|
||||
if (providerId) {
|
||||
void this.use(providerId); // TODO do something with success and errors
|
||||
}
|
||||
});
|
||||
|
||||
settings.watchByRegex(/^Search\./, configProvider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { IRoom, IUser } from '@rocket.chat/core-typings';
|
||||
import { Users, Rooms } from '@rocket.chat/models';
|
||||
import { isTruthy } from '@rocket.chat/tools';
|
||||
import mem from 'mem';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { canAccessRoomAsync } from '../../authorization';
|
||||
import { SearchLogger } from '../logger/logger';
|
||||
import type { IRawSearchResult, ISearchResult } from '../model/ISearchResult';
|
||||
|
||||
export class SearchResultValidationService {
|
||||
private getSubscription = mem(async (rid: IRoom['_id'], uid?: IUser['_id']) => {
|
||||
if (!rid) {
|
||||
return;
|
||||
}
|
||||
|
||||
const room = await Rooms.findOneById(rid);
|
||||
if (!room) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!uid || !(await canAccessRoomAsync(room, { _id: uid }))) {
|
||||
return;
|
||||
}
|
||||
|
||||
return room;
|
||||
});
|
||||
|
||||
private getUser = mem(async (uid: IUser['_id']) => {
|
||||
if (!uid) {
|
||||
return;
|
||||
}
|
||||
|
||||
return Users.findOneById(uid, { projection: { username: 1 } });
|
||||
});
|
||||
|
||||
async validateSearchResult(result: IRawSearchResult): Promise<ISearchResult> {
|
||||
const uid = Meteor.userId() ?? undefined;
|
||||
|
||||
const validatedResult: ISearchResult = {};
|
||||
|
||||
// get subscription for message
|
||||
if (result.message) {
|
||||
validatedResult.message = {
|
||||
docs: (
|
||||
await Promise.all(
|
||||
result.message.docs.map(async (msg) => {
|
||||
const user = await this.getUser(msg.u._id);
|
||||
const subscription = await this.getSubscription(msg.rid, uid);
|
||||
|
||||
if (subscription) {
|
||||
SearchLogger.debug({
|
||||
msg: 'User can access message',
|
||||
userId: uid,
|
||||
roomId: msg.rid,
|
||||
});
|
||||
return {
|
||||
...msg,
|
||||
user: msg.u._id,
|
||||
r: { name: subscription.name, t: subscription.t },
|
||||
username: user?.username,
|
||||
valid: true,
|
||||
};
|
||||
}
|
||||
|
||||
SearchLogger.debug({
|
||||
msg: 'User cannot access message',
|
||||
userId: uid,
|
||||
roomId: msg.rid,
|
||||
});
|
||||
return undefined;
|
||||
}),
|
||||
)
|
||||
).filter(isTruthy),
|
||||
};
|
||||
}
|
||||
|
||||
if (result.room) {
|
||||
result.room.docs = (
|
||||
await Promise.all(
|
||||
result.room.docs.map(async (room) => {
|
||||
const subscription = await this.getSubscription(room._id, uid);
|
||||
|
||||
if (!subscription) {
|
||||
SearchLogger.debug({
|
||||
msg: 'User cannot access room',
|
||||
userId: uid,
|
||||
roomId: room._id,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
SearchLogger.debug({
|
||||
msg: 'User can access room',
|
||||
userId: uid,
|
||||
roomId: room._id,
|
||||
});
|
||||
|
||||
return {
|
||||
...room,
|
||||
valid: true,
|
||||
t: subscription.t,
|
||||
name: subscription.name,
|
||||
};
|
||||
}),
|
||||
)
|
||||
).filter(isTruthy);
|
||||
}
|
||||
|
||||
return validatedResult;
|
||||
}
|
||||
}
|
||||
5
apps/meteor/server/lib/search/service/index.ts
Normal file
5
apps/meteor/server/lib/search/service/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { SearchProviderService } from './SearchProviderService';
|
||||
import { SearchResultValidationService } from './SearchResultValidationService';
|
||||
|
||||
export const searchProviderService = new SearchProviderService();
|
||||
export const validationService = new SearchResultValidationService();
|
||||
7
apps/meteor/server/lib/search/startup.ts
Normal file
7
apps/meteor/server/lib/search/startup.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { searchProviderService } from './service';
|
||||
|
||||
Meteor.startup(async () => {
|
||||
await searchProviderService.start();
|
||||
});
|
||||
Reference in New Issue
Block a user