Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"license": "ISC",
"devDependencies": {
"rollup": "^3.23.0",
"rollup-plugin-dts": "^5.3.0",
"rollup-plugin-dts": "5.3.1",
"rollup-plugin-esbuild": "^5.0.0",
"rollup-plugin-serve": "^2.0.2"
},
Expand Down
19 changes: 16 additions & 3 deletions packages/api/playground/playground.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import EmbeddedChatApi from '../src/EmbeddedChatApi';
let api = new EmbeddedChatApi('http://localhost:3000', 'GENERAL')
let messages = [];
async function saveToken(token) {
localStorage.setItem("ec_token", token);
}

async function getToken() {
return localStorage.getItem("ec_token");
}

async function deleteToken() {
localStorage.removeItem("ec_token");
}

let api;

async function loginWithPassword() {
const user = document.getElementById("email").value;
const password = document.getElementById("password").value;
Expand Down Expand Up @@ -33,7 +46,7 @@ const onConfigChange = async (e) => {
const host = document.getElementById('hostUrl').value;
const roomId = document.getElementById('roomId').value;
await api.close()
api = new EmbeddedChatApi(host, roomId);
api = new EmbeddedChatApi(host, roomId, { deleteToken, getToken, saveToken });
api.auth.onAuthChange((user) => {
showAuth(user)
if (user) {
Expand Down Expand Up @@ -70,7 +83,7 @@ window.addEventListener('DOMContentLoaded', () => {
const roomInput = document.getElementById("roomId")
const host = hostInput.value;
const room = roomInput.value;
api = new EmbeddedChatApi(host, room);
api = new EmbeddedChatApi(host, room, { deleteToken, getToken, saveToken });
hostInput.addEventListener("change", onConfigChange)
hostInput.addEventListener("change", onConfigChange)
onConfigChange();
Expand Down
171 changes: 165 additions & 6 deletions packages/api/src/EmbeddedChatApi.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import { Rocketchat } from '@rocket.chat/sdk';
import cloneArray from './cloneArray';
import { RocketChatAuth } from '@embeddedchat/auth';
import { IRocketChatAuthOptions, RocketChatAuth } from '@embeddedchat/auth';

// mutliple typing status can come at the same time they should be processed in order.
let typingHandlerLock = 0;

export default class EmbeddedChatApi {
host: string;
rid: string;
rcClient: Rocketchat;
onMessageCallbacks: ((message: any) => void)[]
onMessageDeleteCallbacks: ((messageId: string) => void)[]
onTypingStatusCallbacks: ((users: string[]) => void)[];
onActionTriggeredCallbacks: ((data: any) => void)[];
onUiInteractionCallbacks: ((data: any) => void)[];
typingUsers: string[];
auth: RocketChatAuth;

constructor(host: string, rid: string) {
constructor(host: string, rid: string, { getToken, saveToken, deleteToken, autoLogin }: IRocketChatAuthOptions ) {
this.host = host;
this.rid = rid;
this.rcClient = new Rocketchat({
Expand All @@ -28,7 +29,15 @@ export default class EmbeddedChatApi {
this.onMessageDeleteCallbacks = [];
this.onTypingStatusCallbacks = [];
this.typingUsers = [];
this.auth = new RocketChatAuth(this.host);
this.onActionTriggeredCallbacks = [];
this.onUiInteractionCallbacks = [];
this.auth = new RocketChatAuth({
host: this.host,
deleteToken,
getToken,
saveToken,
autoLogin,
});
}

setAuth(auth: RocketChatAuth) {
Expand Down Expand Up @@ -147,8 +156,19 @@ export default class EmbeddedChatApi {
const token = (await this.auth.getCurrentUser())?.authToken;
await this.rcClient.resume({ token });
await this.rcClient.subscribe('stream-room-messages', this.rid);
await this.rcClient.onMessage((data) => {
this.onMessageCallbacks.map((callback) => callback(data));
await this.rcClient.onMessage((data: any) => {
if (!data) {
return;
}
const message = JSON.parse(JSON.stringify(data));
if( message.ts?.$date) {
console.log(message.ts?.$date);
message.ts = message.ts.$date;
}
if (!message.ts) {
message.ts = new Date().toISOString();
}
this.onMessageCallbacks.map((callback) => callback(message));
});
await this.rcClient.subscribe(
'stream-notify-room',
Expand Down Expand Up @@ -178,6 +198,32 @@ export default class EmbeddedChatApi {
this.onMessageDeleteCallbacks.map((callback) => callback(messageId));
}
});
await this.rcClient.subscribeNotifyUser();
await this.rcClient.onStreamData('stream-notify-user', (ddpMessage: any) => {
const [, event] = ddpMessage.fields.eventName.split('/');
const args: any[] = ddpMessage.fields.args
? Array.isArray(ddpMessage.fields.args)
? ddpMessage.fields.args
: [ddpMessage.fields.args]
: [];
if (event === 'message') {
const data = args[0];
if (!data || data?.rid !== this.rid) {
return;
}
const message = JSON.parse(JSON.stringify(data));
if( message.ts?.$date) {
message.ts = message.ts.$date;
}
if (!message.ts) {
message.ts = new Date().toISOString();
}
message.renderType = 'blocks';
this.onMessageCallbacks.map((callback) => callback(message));
} else if (event === 'uiInteraction') {
this.onUiInteractionCallbacks.forEach((callback) => callback(args[0]));
}
});
} catch (err) {
await this.close();
}
Expand Down Expand Up @@ -228,6 +274,40 @@ export default class EmbeddedChatApi {
);
}

async addActionTriggeredListener(callback: (data: any) => void) {
const idx = this.onActionTriggeredCallbacks.findIndex(
(c) => c === callback
);
if (idx !== -1) {
this.onActionTriggeredCallbacks[idx] = callback;
} else {
this.onActionTriggeredCallbacks.push(callback);
}
}

async removeActionTriggeredListener(callback: (data: any) => void) {
this.onActionTriggeredCallbacks = this.onActionTriggeredCallbacks.filter(
(c) => c !== callback
);
}

async addUiInteractionListener(callback: (data: any) => void) {
const idx = this.onUiInteractionCallbacks.findIndex(
(c) => c === callback
);
if (idx !== -1) {
this.onUiInteractionCallbacks[idx] = callback;
} else {
this.onUiInteractionCallbacks.push(callback);
}
}

async removeUiInteractionListener(callback: (data: any) => void) {
this.onUiInteractionCallbacks = this.onUiInteractionCallbacks.filter(
(c) => c !== callback
);
}

handleTypingEvent({ typingUser, isTyping }: {
typingUser: string;
isTyping: boolean;
Expand Down Expand Up @@ -756,4 +836,83 @@ export default class EmbeddedChatApi {
console.error(err);
}
}
async triggerBlockAction({
type,
actionId,
appId,
rid,
mid,
viewId,
container,
...rest
}: any) {
try {
const { userId, authToken } = await this.auth.getCurrentUser() || {};

const triggerId = Math.random().toString(32).slice(2, 16);

const payload = rest.payload || rest;

const response = await fetch(
`${this.host}/api/apps/ui.interaction/${appId}`,
{
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': authToken,
'X-User-Id': userId,
},
method: 'POST',
body: JSON.stringify({
type: 'blockAction',
actionId,
payload,
container,
mid,
rid,
triggerId,
viewId,
}),
}
);
const data = await response.json();
this.onActionTriggeredCallbacks.map((cb) => cb(data));
return data;
} catch (e) {
console.error(e);
}
}

async getCommandsList() {
const { userId, authToken } = await this.auth.getCurrentUser() || {};
const response = await fetch(`${this.host}/api/v1/commands.list`, {
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': authToken,
'X-User-Id': userId,
},
method: 'GET',
});
const data = await response.json();
return data;
}

async execCommand({ command, params }: { command: string, params: string; }) {
const { userId, authToken } = await this.auth.getCurrentUser() || {};
const response = await fetch(`${this.host}/api/v1/commands.run`, {
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': authToken,
'X-User-Id': userId,
},
method: 'POST',
body: JSON.stringify({
command,
params,
roomId: this.rid,
triggerId: Math.random().toString(32).slice(2, 20),
}),
});
const data = await response.json();
return data;
}
}
3 changes: 3 additions & 0 deletions packages/htmlembed/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-react"]
}
2 changes: 2 additions & 0 deletions packages/htmlembed/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
Loading