Skip to content

Commit 60e72db

Browse files
committed
feat: broadcast to a specific room instead of broadcasting
1 parent 6e16308 commit 60e72db

File tree

5 files changed

+54
-16
lines changed

5 files changed

+54
-16
lines changed

api/src/chat/services/block.service.ts

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@
66
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
77
*/
88

9-
import { Injectable } from '@nestjs/common';
9+
import {
10+
Injectable,
11+
InternalServerErrorException,
12+
Optional,
13+
} from '@nestjs/common';
1014
import { OnEvent } from '@nestjs/event-emitter';
1115

1216
import EventWrapper from '@/channel/lib/EventWrapper';
@@ -21,6 +25,15 @@ import { PluginType } from '@/plugins/types';
2125
import { SettingService } from '@/setting/services/setting.service';
2226
import { BaseService } from '@/utils/generics/base-service';
2327
import { getRandomElement } from '@/utils/helpers/safeRandom';
28+
import {
29+
SocketGet,
30+
SocketPost,
31+
} from '@/websocket/decorators/socket-method.decorator';
32+
import { SocketReq } from '@/websocket/decorators/socket-req.decorator';
33+
import { SocketRes } from '@/websocket/decorators/socket-res.decorator';
34+
import { SocketRequest } from '@/websocket/utils/socket-request';
35+
import { SocketResponse } from '@/websocket/utils/socket-response';
36+
import { WebsocketGateway } from '@/websocket/websocket.gateway';
2437

2538
import { BlockDto } from '../dto/block.dto';
2639
import { EnvelopeFactory } from '../helpers/envelope-factory';
@@ -46,15 +59,40 @@ export class BlockService extends BaseService<
4659
BlockFull,
4760
BlockDto
4861
> {
62+
private readonly gateway: WebsocketGateway;
63+
4964
constructor(
5065
readonly repository: BlockRepository,
5166
private readonly contentService: ContentService,
5267
private readonly settingService: SettingService,
5368
private readonly pluginService: PluginService,
5469
protected readonly i18n: I18nService,
5570
protected readonly languageService: LanguageService,
71+
@Optional() gateway?: WebsocketGateway,
5672
) {
5773
super(repository);
74+
if (gateway) {
75+
this.gateway = gateway;
76+
}
77+
}
78+
79+
@SocketGet('/block/subscribe/')
80+
@SocketPost('/block/subscribe/')
81+
subscribe(@SocketReq() req: SocketRequest, @SocketRes() res: SocketResponse) {
82+
debugger;
83+
try {
84+
if (req.session.web?.profile?.id) {
85+
this.gateway.io.socketsJoin(`blocks:${req.session.web.profile.id}`);
86+
return res.status(200).json({
87+
success: true,
88+
});
89+
} else {
90+
throw new Error('Unable to join highlight blocks room');
91+
}
92+
} catch (e) {
93+
this.logger.error('Websocket subscription', e);
94+
throw new InternalServerErrorException(e);
95+
}
5896
}
5997

6098
/**
@@ -577,7 +615,7 @@ export class BlockService extends BaseService<
577615
this.logger.log('triggered: hook:highlight:error');
578616
this.eventEmitter.emit('hook:highlight:error', {
579617
flowId,
580-
userId: recipient.foreign_id,
618+
userId: recipient.id,
581619
blockId: block.id,
582620
});
583621
} else {
@@ -641,7 +679,7 @@ export class BlockService extends BaseService<
641679
this.logger.log('triggered: hook:highlight:error');
642680
this.eventEmitter.emit('hook:highlight:error', {
643681
flowId,
644-
userId: recipient.foreign_id,
682+
userId: recipient.id,
645683
blockId: block.id,
646684
});
647685
} else {
@@ -678,7 +716,7 @@ export class BlockService extends BaseService<
678716
this.logger.log('triggered: hook:highlight:error');
679717
this.eventEmitter.emit('hook:highlight:error', {
680718
flowId,
681-
userId: recipient.foreign_id,
719+
userId: recipient.id,
682720
blockId: block.id,
683721
});
684722
} else {

api/src/chat/services/bot.service.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ export class BotService {
154154
this.eventEmitter.emit('hook:highlight:block', {
155155
flowId: block.category!.id,
156156
blockId: block.id,
157-
userId: recipient.foreign_id,
157+
userId: recipient.id,
158158
});
159159
if (envelope.format !== OutgoingMessageFormat.system) {
160160
await this.sendMessageToSubscriber(
@@ -330,7 +330,7 @@ export class BotService {
330330
if (next && next.id !== fallbackBlock?.id) {
331331
this.eventEmitter.emit('hook:highlight:error', {
332332
flowId: matchedBlock!.category!.id,
333-
userId: convo.sender.foreign_id,
333+
userId: convo.sender.id,
334334
blockId: next.id!,
335335
});
336336
}

api/src/websocket/websocket.gateway.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -413,20 +413,14 @@ export class WebsocketGateway
413413
async handleHighlightBlock(
414414
payload: IHookOperationMap['highlight']['operations']['block'],
415415
) {
416-
this.logger.log(
417-
'broadcasting event highlight:flow through socketio ',
418-
payload,
419-
);
420-
// todo: fix emit event to subscriber
421-
this.io.emit('highlight:flow', payload);
416+
this.io.to(`blocks:${payload.userId}`).emit('highlight:block', payload);
422417
}
423418

424419
@OnEvent('hook:highlight:error')
425420
async highlightBlockErrored(
426421
payload: IHookOperationMap['highlight']['operations']['error'],
427422
) {
428423
this.logger.warn('hook:highlight:error ', payload);
429-
// todo: fix emit event to subscriber
430-
this.io.emit('highlight:error', payload);
424+
this.io.to(`blocks:${payload.userId}`).emit('highlight:error', payload);
431425
}
432426
}

frontend/src/components/visual-editor/v2/Diagrams.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import { useTranslate } from "@/hooks/useTranslate";
5252
import { EntityType, Format, QueryType, RouterType } from "@/services/types";
5353
import { IBlock } from "@/types/block.types";
5454
import { BlockPorts } from "@/types/visual-editor.types";
55+
import { useSocketGetQuery } from "@/websocket/socket-hooks";
5556

5657
import { BlockEditFormDialog } from "../BlockEditFormDialog";
5758
import { ZOOM_LEVEL } from "../constants";
@@ -161,6 +162,9 @@ const Diagrams = () => {
161162
const getBlockFromCache = useGetFromCache(EntityType.BLOCK);
162163
const updateCachedBlock = useUpdateCache(EntityType.BLOCK);
163164
const deleteCachedBlock = useDeleteFromCache(EntityType.BLOCK);
165+
166+
useSocketGetQuery("/block/subscribe/");
167+
164168
const onCategoryChange = (targetCategory: number) => {
165169
if (categories) {
166170
const { id } = categories[targetCategory];

frontend/src/websocket/socket-hooks.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,10 @@ export const SocketProvider = (props: PropsWithChildren) => {
4141
const [connected, setConnected] = useState(false);
4242
const { toast } = useToast();
4343
const { user } = useAuth();
44-
// todo: fix we aren't sending auth token
45-
const socket = useMemo(() => new SocketIoClient(apiUrl), [apiUrl]);
44+
const socket = useMemo(
45+
() => new SocketIoClient(apiUrl, { auth: user }),
46+
[apiUrl],
47+
);
4648

4749
useEffect(() => {
4850
if (user && apiUrl)

0 commit comments

Comments
 (0)