Skip to content

Commit 0d5b923

Browse files
committed
feat: web worker for search services
1 parent daea14f commit 0d5b923

File tree

6 files changed

+133
-1
lines changed

6 files changed

+133
-1
lines changed

src/api/search/index.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import type { ApiMessage } from '../types';
2+
3+
let worker: Worker;
4+
5+
export function initSearchWorker() {
6+
// eslint-disable-next-line no-console
7+
console.log('>>> INIT SEARCH WORKER');
8+
9+
worker = new Worker(new URL('./worker.ts', import.meta.url));
10+
11+
worker.addEventListener('message', (event) => {
12+
// eslint-disable-next-line no-console
13+
console.log('message from search worker', event.data);
14+
});
15+
16+
worker.addEventListener('error', (event) => {
17+
// eslint-disable-next-line no-console
18+
console.log('error from search worker', event);
19+
});
20+
}
21+
22+
export function processMessages(messages: ApiMessage[]) {
23+
worker.postMessage({
24+
type: 'message:process',
25+
payload: { messages },
26+
});
27+
}
28+
29+
export function searchMessages(params: { chatId: string; content: string }) {
30+
return new Promise((resolve) => {
31+
worker.addEventListener('message', (event) => {
32+
const { type, data } = event.data as { type: string; data: any };
33+
34+
if (type === 'storage:search:messages:data') {
35+
resolve(data.messages);
36+
}
37+
});
38+
39+
worker.postMessage({
40+
type: 'storage:search:messages',
41+
payload: {
42+
...params,
43+
useVector: true,
44+
},
45+
});
46+
});
47+
}

src/api/search/worker.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// eslint-disable-next-line no-console
2+
console.log('>>> SEARCH WORKER');
3+
4+
const ws = new WebSocket('ws://localhost:3000/ws?sessionId=ecc944e0-edc4-4417-afa8-683bd66446c9');
5+
6+
ws.onopen = () => {
7+
// eslint-disable-next-line no-console
8+
console.log('>>> connected to search worker');
9+
10+
// Register events
11+
ws.send(JSON.stringify({ type: 'server:event:register', data: { event: 'storage:search:messages:data' } }));
12+
};
13+
14+
ws.onmessage = (event) => {
15+
// eslint-disable-next-line no-console
16+
console.log('>>> message to search worker', JSON.parse(event.data));
17+
18+
self.postMessage(JSON.parse(event.data));
19+
};
20+
21+
ws.onclose = () => {
22+
// eslint-disable-next-line no-console
23+
console.log('>>> disconnected from search worker');
24+
};
25+
26+
ws.onerror = (event) => {
27+
// eslint-disable-next-line no-console
28+
console.log('>>> error from search worker', event);
29+
};
30+
31+
self.onmessage = (msg) => {
32+
const { type, payload } = msg.data as { type: string; payload: any };
33+
34+
// eslint-disable-next-line no-console
35+
console.log('>>> message from search worker', type, payload);
36+
37+
ws.send(JSON.stringify({ type, data: payload }));
38+
};

src/global/actions/api/messages.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import { formatStarsAsText } from '../../../util/localization/format';
5454
import { oldTranslate } from '../../../util/oldLangProvider';
5555
import { debounce, onTickEnd, rafPromise } from '../../../util/schedulers';
5656
import { callApi, cancelApiProgress } from '../../../api/gramjs';
57+
import { processMessages } from '../../../api/search';
5758
import {
5859
getIsSavedDialog,
5960
getUserFullName,
@@ -300,6 +301,10 @@ addActionHandler('loadMessage', async (global, actions, payload): Promise<void>
300301
);
301302
setGlobal(global);
302303
}
304+
305+
if (message) {
306+
processMessages([message]);
307+
}
303308
});
304309

305310
addActionHandler('sendMessage', async (global, actions, payload): Promise<void> => {

src/global/actions/api/middleSearch.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { ApiMessage } from '../../../api/types';
12
import type {
23
ChatMediaSearchParams, ChatMediaSearchSegment, LoadingState, SharedMediaType, ThreadId,
34
} from '../../../types';
@@ -12,6 +13,7 @@ import { getCurrentTabId } from '../../../util/establishMultitabRole';
1213
import { buildCollectionByKey, isInsideSortedArrayRange } from '../../../util/iteratees';
1314
import { getSearchResultKey } from '../../../util/keys/searchResultKey';
1415
import { callApi } from '../../../api/gramjs';
16+
import { searchMessages } from '../../../api/search';
1517
import { getChatMediaMessageIds, getIsSavedDialog, isSameReaction } from '../../helpers';
1618
import {
1719
addActionHandler, getGlobal, setGlobal,
@@ -126,10 +128,47 @@ addActionHandler('performMiddleSearch', async (global, actions, payload): Promis
126128
return;
127129
}
128130

131+
const msgs = await searchMessages({
132+
chatId: realChatId.startsWith('-100') ? realChatId.split('-100')[1] : realChatId,
133+
content: query!,
134+
}) as {
135+
content: string;
136+
chatId: string;
137+
platformMessageId: string;
138+
fromId: string;
139+
fromName: string;
140+
platformTimestamp: number;
141+
}[];
142+
143+
console.log('>>> ', msgs);
144+
145+
const insertMsgs = []
146+
for (const msg of msgs) {
147+
const messageToInsert: ApiMessage = {
148+
chatId: '-100' + msg.chatId,
149+
id: Number(msg.platformMessageId),
150+
senderId: msg.fromId,
151+
content: {
152+
text: { text: msg.content },
153+
},
154+
date: msg.platformTimestamp,
155+
isOutgoing: msg.fromId === currentUserId,
156+
};
157+
158+
console.log('>>>> ', messageToInsert);
159+
160+
insertMsgs.push(messageToInsert);
161+
}
162+
163+
result.messages = [...insertMsgs, ...result.messages];
164+
result.totalCount += insertMsgs.length;
165+
129166
const {
130167
userStatusesById, messages, totalCount, nextOffsetId, nextOffsetRate, nextOffsetPeerId,
131168
} = result;
132169

170+
console.log('>>>> ', result);
171+
133172
const newFoundIds = messages.map(getSearchResultKey);
134173

135174
global = getGlobal();

src/global/init.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { isLocalMessageId } from '../util/keys/messageKey';
1111
import { Bundles, loadBundle } from '../util/moduleLoader';
1212
import { parseLocationHash } from '../util/routing';
1313
import { updatePeerColors } from '../util/theme';
14+
import { initSearchWorker } from '../api/search';
1415
import { initializeChatMediaSearchResults } from './reducers/middleSearch';
1516
import { updateTabState } from './reducers/tabs';
1617
import { initSharedState } from './shared/sharedStateConnector';
@@ -24,6 +25,8 @@ import { selectTabState, selectThreadParam } from './selectors';
2425

2526
initCache();
2627

28+
initSearchWorker();
29+
2730
addActionHandler('initShared', async (prevGlobal, actions, payload): Promise<void> => {
2831
const { force } = payload || {};
2932
await initGlobal(force, prevGlobal);

webpack.config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ const {
4040

4141
const CSP = `
4242
default-src 'self';
43-
connect-src 'self' wss://*.web.telegram.org blob: http: https: ${APP_ENV === 'development' ? 'wss:' : ''};
43+
connect-src 'self' wss://*.web.telegram.org ws://localhost:3000 blob: http: https: ${APP_ENV === 'development' ? 'wss:' : ''};
4444
script-src 'self' 'wasm-unsafe-eval' https://t.me/_websync_ https://telegram.me/_websync_;
4545
style-src 'self' 'unsafe-inline';
4646
img-src 'self' data: blob: https://ss3.4sqi.net/img/categories_v2/

0 commit comments

Comments
 (0)