Merge branch 'master' into sh/nodejs-db

# Conflicts:
#	packages/simplex-chat-nodejs/README.md
#	packages/simplex-chat-nodejs/src/download-libs.js
This commit is contained in:
shum committed 2026-10-10 11:52:33 +00:00
commit f9071033c0
801 files changed
+10873 -2673

No files matched your search

+4 -2
View File
@@ -24,13 +24,13 @@ Simple bot that replies with squares of numbers you send to it:
const {bot} = await import("simplex-chat")
// if you are running from this GitHub repo:
// const {bot} = await import("../dist/index.js")
const [chat, _user, _address] = await bot.run({
await bot.run({
profile: {displayName: "Squaring bot example", fullName: ""},
dbOpts: {type: "sqlite", filePrefix: "./squaring_bot"},
options: {
addressSettings: {welcomeMessage: "Send a number, I will square it.",
},
onMessage: async (ci, content) => {
onMessage: async (ci, content, chat) => {
const n = +content.text
const reply = typeof n === "number" && !isNaN(n)
? `${n} * ${n} = ${n * n}`
@@ -62,6 +62,8 @@ There is an example with more options in [./examples/squaring-bot.ts](./examples
You can run it with: `npx ts-node ./examples/squaring-bot.ts`
A larger example, with a business address and commands as keys: [SimpleX Calculator](../../apps/simplex-calculator-bot/).
## Native library
`libsimplex` is downloaded on first use into the user cache (`$XDG_CACHE_HOME/simplex-chat` or `~/.cache/simplex-chat` on Linux, `~/Library/Caches/simplex-chat` on macOS, `%LOCALAPPDATA%\simplex-chat` on Windows), shared with the Python library. To download it ahead of time, for example in a Dockerfile, run as the user that runs the app:
@@ -72,7 +72,7 @@ Chat controller is started
> **apiAcceptContactRequest**(`contactReqId`): `Promise`\<`Contact`\>
Defined in: [src/api.ts:749](../src/api.ts#L749)
Defined in: [src/api.ts:760](../src/api.ts#L760)
Accept contact request.
Network usage: interactive.
@@ -93,7 +93,7 @@ Network usage: interactive.
> **apiAcceptMember**(`groupId`, `groupMemberId`, `memberRole`): `Promise`\<`GroupMember`\>
Defined in: [src/api.ts:569](../src/api.ts#L569)
Defined in: [src/api.ts:580](../src/api.ts#L580)
Accept group member. Requires Admin role.
Network usage: background.
@@ -122,7 +122,7 @@ Network usage: background.
> **apiAddMember**(`groupId`, `contactId`, `memberRole`): `Promise`\<`GroupMember`\>
Defined in: [src/api.ts:549](../src/api.ts#L549)
Defined in: [src/api.ts:560](../src/api.ts#L560)
Add contact to group. Requires bot to have Admin role.
Network usage: interactive.
@@ -151,7 +151,7 @@ Network usage: interactive.
> **apiBlockMembersForAll**(`groupId`, `groupMemberIds`, `blocked`): `Promise`\<`void`\>
Defined in: [src/api.ts:589](../src/api.ts#L589)
Defined in: [src/api.ts:600](../src/api.ts#L600)
Block members. Requires Moderator role.
Network usage: background.
@@ -180,7 +180,7 @@ Network usage: background.
> **apiCancelFile**(`fileId`): `Promise`\<`void`\>
Defined in: [src/api.ts:539](../src/api.ts#L539)
Defined in: [src/api.ts:550](../src/api.ts#L550)
Cancel file.
Network usage: background.
@@ -201,7 +201,7 @@ Network usage: background.
> **apiChatItemReaction**(`chatType`, `chatId`, `chatItemId`, `add`, `reaction`): `Promise`\<`ACIReaction`\>
Defined in: [src/api.ts:512](../src/api.ts#L512)
Defined in: [src/api.ts:523](../src/api.ts#L523)
Add/remove message reaction.
Network usage: background.
@@ -238,7 +238,7 @@ Network usage: background.
> **apiConnect**(`userId`, `incognito`, `preparedLink`): `Promise`\<[`ConnReqType`](api.Enumeration.ConnReqType.md)\>
Defined in: [src/api.ts:718](../src/api.ts#L718)
Defined in: [src/api.ts:729](../src/api.ts#L729)
Connect via prepared SimpleX link. The link can be 1-time invitation link, contact address or group link
Network usage: interactive.
@@ -267,7 +267,7 @@ Network usage: interactive.
> **apiConnectActiveUser**(`connLink`): `Promise`\<[`ConnReqType`](api.Enumeration.ConnReqType.md)\>
Defined in: [src/api.ts:727](../src/api.ts#L727)
Defined in: [src/api.ts:738](../src/api.ts#L738)
Connect via SimpleX link as string in the active user profile.
Network usage: interactive.
@@ -288,7 +288,7 @@ Network usage: interactive.
> **apiConnectPlan**(`userId`, `connectionLink`): `Promise`\<\[`ConnectionPlan`, `CreatedConnLink`\]\>
Defined in: [src/api.ts:708](../src/api.ts#L708)
Defined in: [src/api.ts:719](../src/api.ts#L719)
Determine SimpleX link type and if the bot is already connected via this link.
Network usage: interactive.
@@ -313,7 +313,7 @@ Network usage: interactive.
> **apiCreateActiveUser**(`profile?`): `Promise`\<`User`\>
Defined in: [src/api.ts:886](../src/api.ts#L886)
Defined in: [src/api.ts:897](../src/api.ts#L897)
Create new user profile
Network usage: no.
@@ -334,7 +334,7 @@ Network usage: no.
> **apiCreateGroupLink**(`groupId`, `memberRole`): `Promise`\<`string`\>
Defined in: [src/api.ts:649](../src/api.ts#L649)
Defined in: [src/api.ts:660](../src/api.ts#L660)
Create group link.
Network usage: interactive.
@@ -359,7 +359,7 @@ Network usage: interactive.
> **apiCreateLink**(`userId`): `Promise`\<`string`\>
Defined in: [src/api.ts:695](../src/api.ts#L695)
Defined in: [src/api.ts:706](../src/api.ts#L706)
Create 1-time invitation link.
Network usage: interactive.
@@ -380,7 +380,7 @@ Network usage: interactive.
> **apiCreateMemberContact**(`groupId`, `groupMemberId`): `Promise`\<`Contact`\>
Defined in: [src/api.ts:952](../src/api.ts#L952)
Defined in: [src/api.ts:963](../src/api.ts#L963)
Create a direct message contact with a group member.
Returns the created contact.
@@ -427,7 +427,7 @@ Network usage: interactive.
> **apiDeleteChat**(`chatType`, `chatId`, `deleteMode?`): `Promise`\<`void`\>
Defined in: [src/api.ts:808](../src/api.ts#L808)
Defined in: [src/api.ts:819](../src/api.ts#L819)
Delete chat.
Network usage: background.
@@ -456,7 +456,7 @@ Network usage: background.
> **apiDeleteChatItems**(`chatType`, `chatId`, `chatItemIds`, `deleteMode`): `Promise`\<`ChatItemDeletion`[]\>
Defined in: [src/api.ts:487](../src/api.ts#L487)
Defined in: [src/api.ts:498](../src/api.ts#L498)
Delete message.
Network usage: background.
@@ -489,7 +489,7 @@ Network usage: background.
> **apiDeleteGroupLink**(`groupId`): `Promise`\<`void`\>
Defined in: [src/api.ts:671](../src/api.ts#L671)
Defined in: [src/api.ts:682](../src/api.ts#L682)
Delete group link.
Network usage: background.
@@ -510,7 +510,7 @@ Network usage: background.
> **apiDeleteMemberChatItem**(`groupId`, `chatItemIds`): `Promise`\<`ChatItemDeletion`[]\>
Defined in: [src/api.ts:502](../src/api.ts#L502)
Defined in: [src/api.ts:513](../src/api.ts#L513)
Moderate message. Requires Moderator role (and higher than message author's).
Network usage: background.
@@ -535,7 +535,7 @@ Network usage: background.
> **apiDeleteUser**(`userId`, `delSMPQueues`, `viewPwd?`): `Promise`\<`void`\>
Defined in: [src/api.ts:916](../src/api.ts#L916)
Defined in: [src/api.ts:927](../src/api.ts#L927)
Delete user profile.
Network usage: background.
@@ -585,7 +585,7 @@ Network usage: background.
> **apiGetActiveUser**(): `Promise`\<`User` \| `undefined`\>
Defined in: [src/api.ts:866](../src/api.ts#L866)
Defined in: [src/api.ts:877](../src/api.ts#L877)
Get active user profile
Network usage: no.
@@ -600,7 +600,7 @@ Network usage: no.
> **apiGetChat**(`chatType`, `chatId`, `count`): `Promise`\<`any`\>
Defined in: [src/api.ts:856](../src/api.ts#L856)
Defined in: [src/api.ts:867](../src/api.ts#L867)
Get chat items.
Network usage: no.
@@ -629,7 +629,7 @@ Network usage: no.
> **apiGetChats**(`userId`, `pagination`, `query?`, `pendingConnections?`): `Promise`\<`AChat`[]\>
Defined in: [src/api.ts:793](../src/api.ts#L793)
Defined in: [src/api.ts:804](../src/api.ts#L804)
Get chat previews (paginated).
Network usage: no.
@@ -666,7 +666,7 @@ on large databases.
> **apiGetGroupLink**(`groupId`): `Promise`\<`GroupLink`\>
Defined in: [src/api.ts:680](../src/api.ts#L680)
Defined in: [src/api.ts:691](../src/api.ts#L691)
Get group link.
Network usage: no.
@@ -687,7 +687,7 @@ Network usage: no.
> **apiGetGroupLinkStr**(`groupId`): `Promise`\<`string`\>
Defined in: [src/api.ts:686](../src/api.ts#L686)
Defined in: [src/api.ts:697](../src/api.ts#L697)
#### Parameters
@@ -726,7 +726,7 @@ Network usage: no.
> **apiJoinGroup**(`groupId`): `Promise`\<`GroupInfo`\>
Defined in: [src/api.ts:559](../src/api.ts#L559)
Defined in: [src/api.ts:570](../src/api.ts#L570)
Join group.
Network usage: interactive.
@@ -747,7 +747,7 @@ Network usage: interactive.
> **apiLeaveGroup**(`groupId`): `Promise`\<`GroupInfo`\>
Defined in: [src/api.ts:609](../src/api.ts#L609)
Defined in: [src/api.ts:620](../src/api.ts#L620)
Leave group.
Network usage: background.
@@ -768,7 +768,7 @@ Network usage: background.
> **apiListContacts**(`userId`): `Promise`\<`Contact`[]\>
Defined in: [src/api.ts:769](../src/api.ts#L769)
Defined in: [src/api.ts:780](../src/api.ts#L780)
Get contacts.
Network usage: no.
@@ -789,7 +789,7 @@ Network usage: no.
> **apiListGroups**(`userId`, `contactId?`, `search?`): `Promise`\<`GroupInfo`[]\>
Defined in: [src/api.ts:779](../src/api.ts#L779)
Defined in: [src/api.ts:790](../src/api.ts#L790)
Get groups.
Network usage: no.
@@ -818,7 +818,7 @@ Network usage: no.
> **apiListMembers**(`groupId`): `Promise`\<`GroupMember`[]\>
Defined in: [src/api.ts:619](../src/api.ts#L619)
Defined in: [src/api.ts:630](../src/api.ts#L630)
Get group members.
Network usage: no.
@@ -839,7 +839,7 @@ Network usage: no.
> **apiListUsers**(): `Promise`\<`UserInfo`[]\>
Defined in: [src/api.ts:896](../src/api.ts#L896)
Defined in: [src/api.ts:907](../src/api.ts#L907)
Get all user profiles
Network usage: no.
@@ -854,7 +854,7 @@ Network usage: no.
> **apiNewGroup**(`userId`, `groupProfile`): `Promise`\<`GroupInfo`\>
Defined in: [src/api.ts:629](../src/api.ts#L629)
Defined in: [src/api.ts:640](../src/api.ts#L640)
Create group.
Network usage: no.
@@ -879,7 +879,7 @@ Network usage: no.
> **apiReceiveFile**(`fileId`): `Promise`\<`AChatItem`\>
Defined in: [src/api.ts:528](../src/api.ts#L528)
Defined in: [src/api.ts:539](../src/api.ts#L539)
Receive file.
Network usage: no.
@@ -900,7 +900,7 @@ Network usage: no.
> **apiRejectContactRequest**(`contactReqId`): `Promise`\<`void`\>
Defined in: [src/api.ts:759](../src/api.ts#L759)
Defined in: [src/api.ts:770](../src/api.ts#L770)
Reject contact request. The user who sent the request is **not notified**.
Network usage: no.
@@ -921,7 +921,7 @@ Network usage: no.
> **apiRemoveMembers**(`groupId`, `memberIds`, `withMessages?`): `Promise`\<`GroupMember`[]\>
Defined in: [src/api.ts:599](../src/api.ts#L599)
Defined in: [src/api.ts:610](../src/api.ts#L610)
Remove members. Requires Admin role.
Network usage: background.
@@ -950,7 +950,7 @@ Network usage: background.
> **apiSendMemberContactInvitation**(`contactId`, `message?`): `Promise`\<`Contact`\>
Defined in: [src/api.ts:963](../src/api.ts#L963)
Defined in: [src/api.ts:974](../src/api.ts#L974)
Send a direct message invitation to a group member contact.
The contact must have been created with [apiCreateMemberContact](#apicreatemembercontact).
@@ -976,7 +976,7 @@ Network usage: interactive.
> **apiSendMessages**(`chat`, `messages`, `liveMessage?`): `Promise`\<`AChatItem`[]\>
Defined in: [src/api.ts:431](../src/api.ts#L431)
Defined in: [src/api.ts:442](../src/api.ts#L442)
Send messages.
Network usage: background.
@@ -1005,7 +1005,7 @@ Network usage: background.
> **apiSendTextMessage**(`chat`, `text`, `inReplyTo?`): `Promise`\<`AChatItem`[]\>
Defined in: [src/api.ts:454](../src/api.ts#L454)
Defined in: [src/api.ts:465](../src/api.ts#L465)
Send text message.
Network usage: background.
@@ -1034,7 +1034,7 @@ Network usage: background.
> **apiSendTextReply**(`chatItem`, `text`): `Promise`\<`AChatItem`[]\>
Defined in: [src/api.ts:462](../src/api.ts#L462)
Defined in: [src/api.ts:473](../src/api.ts#L473)
Send text message in reply to received message.
Network usage: background.
@@ -1059,7 +1059,7 @@ Network usage: background.
> **apiSetActiveUser**(`userId`, `viewPwd?`): `Promise`\<`User`\>
Defined in: [src/api.ts:906](../src/api.ts#L906)
Defined in: [src/api.ts:917](../src/api.ts#L917)
Set active user profile
Network usage: no.
@@ -1109,7 +1109,7 @@ Network usage: interactive.
> **apiSetAutoAcceptMemberContacts**(`userId`, `onOff`): `Promise`\<`void`\>
Defined in: [src/api.ts:845](../src/api.ts#L845)
Defined in: [src/api.ts:856](../src/api.ts#L856)
Set auto-accept member contacts.
Network usage: no.
@@ -1134,7 +1134,7 @@ Network usage: no.
> **apiSetContactCustomData**(`contactId`, `customData?`): `Promise`\<`void`\>
Defined in: [src/api.ts:835](../src/api.ts#L835)
Defined in: [src/api.ts:846](../src/api.ts#L846)
Set contact custom data.
Network usage: no.
@@ -1159,7 +1159,7 @@ Network usage: no.
> **apiSetContactPrefs**(`contactId`, `preferences`): `Promise`\<`void`\>
Defined in: [src/api.ts:942](../src/api.ts#L942)
Defined in: [src/api.ts:953](../src/api.ts#L953)
Configure chat preference overrides for the contact.
Network usage: background.
@@ -1184,7 +1184,7 @@ Network usage: background.
> **apiSetGroupCustomData**(`groupId`, `customData?`): `Promise`\<`void`\>
Defined in: [src/api.ts:825](../src/api.ts#L825)
Defined in: [src/api.ts:836](../src/api.ts#L836)
Set group custom data.
Network usage: no.
@@ -1209,7 +1209,7 @@ Network usage: no.
> **apiSetGroupLinkMemberRole**(`groupId`, `memberRole`): `Promise`\<`void`\>
Defined in: [src/api.ts:662](../src/api.ts#L662)
Defined in: [src/api.ts:673](../src/api.ts#L673)
Set member role for group link.
Network usage: no.
@@ -1234,7 +1234,7 @@ Network usage: no.
> **apiSetMembersRole**(`groupId`, `groupMemberIds`, `memberRole`): `Promise`\<`void`\>
Defined in: [src/api.ts:579](../src/api.ts#L579)
Defined in: [src/api.ts:590](../src/api.ts#L590)
Set members role. Requires Admin role.
Network usage: background.
@@ -1284,11 +1284,33 @@ Network usage: interactive.
***
### apiSetUserDomain()
> **apiSetUserDomain**(`userId`, `simplexDomain?`): `Promise`\<`User`\>
Defined in: [src/api.ts:427](../src/api.ts#L427)
#### Parameters
##### userId
`number`
##### simplexDomain?
`string`
#### Returns
`Promise`\<`User`\>
***
### apiUpdateChatItem()
> **apiUpdateChatItem**(`chatType`, `chatId`, `chatItemId`, `msgContent`, `liveMessage`): `Promise`\<`ChatItem`\>
Defined in: [src/api.ts:470](../src/api.ts#L470)
Defined in: [src/api.ts:481](../src/api.ts#L481)
Update message.
Network usage: background.
@@ -1325,7 +1347,7 @@ Network usage: background.
> **apiUpdateGroupProfile**(`groupId`, `groupProfile`): `Promise`\<`GroupInfo`\>
Defined in: [src/api.ts:639](../src/api.ts#L639)
Defined in: [src/api.ts:650](../src/api.ts#L650)
Update group profile.
Network usage: background.
@@ -1350,7 +1372,7 @@ Network usage: background.
> **apiUpdateProfile**(`userId`, `profile`): `Promise`\<`UserProfileUpdateSummary` \| `undefined`\>
Defined in: [src/api.ts:926](../src/api.ts#L926)
Defined in: [src/api.ts:937](../src/api.ts#L937)
Update user profile.
Network usage: background.
@@ -6,7 +6,7 @@
# Type Alias: EventSubscriberFunc\<K\>
> **EventSubscriberFunc**\<`K`\> = (`event`) => `void` \| `Promise`\<`void`\>
> **EventSubscriberFunc**\<`K`\> = (`event`, `chat`) => `void` \| `Promise`\<`void`\>
Defined in: [src/api.ts:50](../src/api.ts#L50)
@@ -22,6 +22,10 @@ Defined in: [src/api.ts:50](../src/api.ts#L50)
`ChatEvent` & `object`
### chat
[`ChatApi`](api.Class.ChatApi.md)
## Returns
`void` \| `Promise`\<`void`\>
@@ -8,7 +8,7 @@
> **run**(`__namedParameters`): `Promise`\<\[[`ChatApi`](api.Class.ChatApi.md), `User`, `UserContactLink` \| `undefined`\]\>
Defined in: [src/bot.ts:48](../src/bot.ts#L48)
Defined in: [src/bot.ts:49](../src/bot.ts#L49)
## Parameters
@@ -8,7 +8,7 @@
> **subscribeChatItems**(`bot`, `onMessage`, `commands`): `void`
Defined in: [src/bot.ts:108](../src/bot.ts#L108)
Defined in: [src/bot.ts:110](../src/bot.ts#L110)
## Parameters
@@ -18,7 +18,7 @@ Defined in: [src/bot.ts:108](../src/bot.ts#L108)
### onMessage
((`chatItem`, `content`) => `void` \| `Promise`\<`void`\>) \| `undefined`
((`chatItem`, `content`, `chat`) => `void` \| `Promise`\<`void`\>) \| `undefined`
### commands
@@ -14,7 +14,7 @@ Defined in: [src/bot.ts:36](../src/bot.ts#L36)
> **dbOpts**: [`BotDbOpts`](bot.TypeAlias.BotDbOpts.md)
Defined in: [src/bot.ts:38](../src/bot.ts#L38)
Defined in: [src/bot.ts:39](../src/bot.ts#L39)
***
@@ -22,7 +22,7 @@ Defined in: [src/bot.ts:38](../src/bot.ts#L38)
> `optional` **events?**: [`EventSubscribers`](api.TypeAlias.EventSubscribers.md)
Defined in: [src/bot.ts:45](../src/bot.ts#L45)
Defined in: [src/bot.ts:46](../src/bot.ts#L46)
***
@@ -30,19 +30,19 @@ Defined in: [src/bot.ts:45](../src/bot.ts#L45)
> `optional` **onCommands?**: `object`
Defined in: [src/bot.ts:42](../src/bot.ts#L42)
Defined in: [src/bot.ts:43](../src/bot.ts#L43)
#### Index Signature
\[`key`: `string`\]: ((`chatItem`, `command`) => `void` \| `Promise`\<`void`\>) \| `undefined`
\[`key`: `string`\]: ((`chatItem`, `command`, `chat`) => `void` \| `Promise`\<`void`\>) \| `undefined`
***
### onMessage?
> `optional` **onMessage?**: (`chatItem`, `content`) => `void` \| `Promise`\<`void`\>
> `optional` **onMessage?**: (`chatItem`, `content`, `chat`) => `void` \| `Promise`\<`void`\>
Defined in: [src/bot.ts:40](../src/bot.ts#L40)
Defined in: [src/bot.ts:41](../src/bot.ts#L41)
#### Parameters
@@ -54,6 +54,10 @@ Defined in: [src/bot.ts:40](../src/bot.ts#L40)
`MsgContent`
##### chat
[`ChatApi`](api.Class.ChatApi.md)
#### Returns
`void` \| `Promise`\<`void`\>
@@ -64,7 +68,7 @@ Defined in: [src/bot.ts:40](../src/bot.ts#L40)
> **options**: [`BotOptions`](bot.Interface.BotOptions.md)
Defined in: [src/bot.ts:39](../src/bot.ts#L39)
Defined in: [src/bot.ts:40](../src/bot.ts#L40)
***
@@ -73,3 +77,11 @@ Defined in: [src/bot.ts:39](../src/bot.ts#L39)
> **profile**: `Profile`
Defined in: [src/bot.ts:37](../src/bot.ts#L37)
***
### simplexDomain?
> `optional` **simplexDomain?**: `string` \| `null`
Defined in: [src/bot.ts:38](../src/bot.ts#L38)
@@ -1,12 +1,12 @@
(async () => {
const {bot} = await import("../dist/index.js")
const [chat, _user, _address] = await bot.run({
await bot.run({
profile: {displayName: "Squaring bot example", fullName: ""},
dbOpts: {type: "sqlite", filePrefix: "./squaring_bot"},
options: {
addressSettings: {welcomeMessage: "Send a number, I will square it."},
},
onMessage: async (ci, content) => {
onMessage: async (ci, content, chat) => {
const n = +content.text
const reply = typeof n === "number" && !isNaN(n)
? `${n} * ${n} = ${n * n}`
@@ -3,7 +3,7 @@ import {bot, util} from "../dist"
(async () => {
const welcomeMessage = "Hello! I am a simple squaring bot.\n\nIf you send me a number, I will calculate its square."
const [chat, _user, _address] = await bot.run({
await bot.run({
profile: {displayName: "Squaring bot example", fullName: ""},
dbOpts: {type: "sqlite", filePrefix: "./squaring_bot"},
options: {
@@ -15,7 +15,7 @@ import {bot, util} from "../dist"
logContacts: true,
logNetwork: false
},
onMessage: async (ci, content) => {
onMessage: async (ci, content, chat) => {
const n = +content.text
const reply = typeof n === "number" && !isNaN(n)
? `${n} * ${n} = ${n * n}`
@@ -23,11 +23,11 @@ import {bot, util} from "../dist"
await chat.apiSendTextReply(ci, reply)
},
onCommands: { // command handlers can be different from commands to be shown in client UI
"help": async (ci: T.AChatItem, _cmd: util.BotCommand) => {
"help": async (ci: T.AChatItem, _cmd: util.BotCommand, chat) => {
await chat.apiSendTextMessage(ci.chatInfo, welcomeMessage)
},
// fallback handler that will be called for all other commands
"": async (ci: T.AChatItem, _cmd: util.BotCommand) => {
"": async (ci: T.AChatItem, _cmd: util.BotCommand, chat) => {
await chat.apiSendTextReply(ci, "This command is not supported")
}
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "simplex-chat",
"version": "7.1.0-beta.4",
"version": "7.1.0-beta.6",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
+15 -4
View File
@@ -47,7 +47,7 @@ export const defaultBotAddressSettings: BotAddressSettings = {
businessAddress: false
}
export type EventSubscriberFunc<K extends CEvt.Tag> = (event: ChatEvent & {type: K}) => void | Promise<void>
export type EventSubscriberFunc<K extends CEvt.Tag> = (event: ChatEvent & {type: K}, chat: ChatApi) => void | Promise<void>
export type EventSubscribers = {[K in CEvt.Tag]?: EventSubscriberFunc<K>}
@@ -176,7 +176,7 @@ export class ChatApi {
if (subs) {
for (const {subscriber, once} of [...subs]) {
try {
const p = (subscriber as EventSubscriberFunc<typeof event.type>)(event)
const p = (subscriber as EventSubscriberFunc<typeof event.type>)(event, this)
if (p instanceof Promise) await p
} catch(e) {
console.log(`${event.type} event processing error`, e)
@@ -186,7 +186,7 @@ export class ChatApi {
}
for (const r of [...this.receivers]) {
try {
const p = r(event)
const p = r(event, this)
if (p instanceof Promise) await p
} catch(e) {
console.log(`${event.type} event processing error`, e)
@@ -421,7 +421,18 @@ export class ChatApi {
const r = await this.sendChatCmd(CC.APISetAddressSettings.cmdString({userId, settings}))
if (r.type !== "userContactLinkUpdated") {
throw new ChatCommandError("error changing user contact address settings", r)
}
}
}
async apiSetUserDomain(userId: number, simplexDomain?: string): Promise<T.User> {
const r = await this.sendChatCmd(CC.APISetUserDomain.cmdString({userId, simplexDomain}))
switch (r.type) {
case "userProfileUpdated":
case "userProfileNoChange":
return r.user
default:
throw new ChatCommandError("error setting SimpleX name", r)
}
}
/**
+31 -11
View File
@@ -35,17 +35,18 @@ const defaultOpts: Required<BotOptions> = {
export interface BotConfig {
profile: T.Profile,
simplexDomain?: string | null,
dbOpts: BotDbOpts,
options: BotOptions,
onMessage?: (chatItem: T.AChatItem, content: T.MsgContent) => void | Promise<void>,
onMessage?: (chatItem: T.AChatItem, content: T.MsgContent, chat: api.ChatApi) => void | Promise<void>,
// command handlers can be different from commands to be shown in client UI
onCommands?: {[K in string]?: ((chatItem: T.AChatItem, command: util.BotCommand) => void | Promise<void>)},
onCommands?: {[K in string]?: ((chatItem: T.AChatItem, command: util.BotCommand, chat: api.ChatApi) => void | Promise<void>)},
// If you use `onMessage` and to subscribe "newChatItems" event, exclude content messages from processing
// If you use `onCommands` and to subscribe "newChatItems" event, exclude commands from processing
events?: api.EventSubscribers
}
export async function run({profile, dbOpts, options = defaultOpts, onMessage, onCommands = {}, events = {}}: BotConfig): Promise<[api.ChatApi, T.User, T.UserContactLink | undefined]> {
export async function run({profile, simplexDomain, dbOpts, options = defaultOpts, onMessage, onCommands = {}, events = {}}: BotConfig): Promise<[api.ChatApi, T.User, T.UserContactLink | undefined]> {
const bot = await api.ChatApi.init(dbOpts, dbOpts.confirmMigrations || core.MigrationConfirmation.YesUp, dbOpts.queueSize)
const opts = fullOptions(options)
if (onMessage || Object.keys(onCommands).length > 0) subscribeChatItems(bot, onMessage, onCommands)
@@ -60,7 +61,8 @@ export async function run({profile, dbOpts, options = defaultOpts, onMessage, on
console.log(`Bot address: ${addressLink}`)
if (opts.useBotProfile) botProfile.contactLink = addressLink
}
await updateBotUserProfile(bot, user, botProfile, opts)
const namedUser = await updateBotSimplexDomain(bot, user, simplexDomain, opts)
await updateBotUserProfile(bot, namedUser, botProfile, opts)
return [bot, user, address]
}
@@ -107,8 +109,8 @@ function mkBotProfile(profile: T.Profile, opts: Required<BotOptions>): T.Profile
export function subscribeChatItems(
bot: api.ChatApi,
onMessage: ((chatItem: T.AChatItem, content: T.MsgContent) => void | Promise<void>) | undefined,
commands: {[K in string]?: ((chatItem: T.AChatItem, command: util.BotCommand) => void | Promise<void>)}
onMessage: ((chatItem: T.AChatItem, content: T.MsgContent, chat: api.ChatApi) => void | Promise<void>) | undefined,
commands: {[K in string]?: ((chatItem: T.AChatItem, command: util.BotCommand, chat: api.ChatApi) => void | Promise<void>)}
) {
bot.on("newChatItems", async ({chatItems}) => {
for (const ci of chatItems) {
@@ -117,8 +119,8 @@ export function subscribeChatItems(
const cmd = util.ciBotCommand(ci.chatItem)
const cmdFunc = cmd && (commands[cmd.keyword] || commands[""])
try {
if (cmd && cmdFunc) await cmdFunc(ci, cmd)
else if (onMessage) await onMessage(ci, content.msgContent)
if (cmd && cmdFunc) await cmdFunc(ci, cmd, bot)
else if (onMessage) await onMessage(ci, content.msgContent, bot)
} catch (e) {
console.log(cmd && cmdFunc ? `${cmd.keyword} command processing error` : "message processing error", e)
}
@@ -180,15 +182,33 @@ async function createOrUpdateAddress(bot: api.ChatApi, user: T.User, opts: Requi
}
}
return address
return address
}
async function updateBotSimplexDomain(bot: api.ChatApi, user: T.User, simplexDomain: string | null | undefined, opts: Required<BotOptions>): Promise<T.User> {
if (simplexDomain === undefined) return user
const domain = simplexDomain === null ? undefined : simplexDomain.toLowerCase()
if (user.profile.contactDomain?.domain === domain) return user
if (!opts.updateAddress) {
console.log("Bot SimpleX name changed")
return user
}
console.log("Bot SimpleX name changed, updating...")
try {
return await bot.apiSetUserDomain(user.userId, domain)
} catch (e) {
console.log("Error updating bot SimpleX name", e)
return user
}
}
async function updateBotUserProfile(bot: api.ChatApi, user: T.User, profile: T.Profile, opts: Required<BotOptions>): Promise<void> {
const {userId} = user
if (!equal(util.fromLocalProfile(user.profile), profile)) {
const {contactDomain, ...currentProfile} = util.fromLocalProfile(user.profile)
if (!equal(currentProfile, profile)) {
if (opts.updateProfile) {
console.log("Bot profile changed, updating...")
const summary = await bot.apiUpdateProfile(userId, profile)
const summary = await bot.apiUpdateProfile(userId, {...profile, contactDomain})
console.log(
summary
? `Bot profile updated: ${summary.updateSuccesses} updated contact(s), ${summary.updateFailures} failed contact update(s).`
+1 -1
View File
@@ -7,7 +7,7 @@ import {pipeline} from "stream/promises"
import extract = require("extract-zip")
import type {Backend} from "./core"
export const LIBS_VERSION = "7.1.0-beta.4"
export const LIBS_VERSION = "7.1.0-beta.6"
const GITHUB_REPO = "simplex-chat/simplex-chat-libs"
const REQUEST_TIMEOUT_MS = 60_000
+2 -2
View File
@@ -53,8 +53,8 @@ export function botAddressSettings({addressSettings}: T.UserContactLink): BotAdd
}
}
export function fromLocalProfile({displayName, fullName, shortDescr, image, contactLink, preferences, peerType}: T.LocalProfile): T.Profile {
const profile = {displayName, fullName, shortDescr, image, contactLink, preferences, peerType}
export function fromLocalProfile({displayName, fullName, shortDescr, image, contactLink, preferences, peerType, contactDomain}: T.LocalProfile): T.Profile {
const profile = {displayName, fullName, shortDescr, image, contactLink, preferences, peerType, contactDomain: contactDomain && {domain: contactDomain.domain}}
for (const key in profile) {
if (typeof (profile as any)[key] === "undefined") delete (profile as any)[key]
}
@@ -1,4 +1,4 @@
import {ChatResponse, T} from "@simplex-chat/types"
import {ChatEvent, ChatResponse, T} from "@simplex-chat/types"
import * as api from "../src/api"
import * as core from "../src/core"
@@ -31,6 +31,13 @@ describe("documented success responses", () => {
await expect(chat.apiSetProfileAddress(1, true)).resolves.toEqual({updateSuccesses: 0, updateFailures: 0, changedContacts: []})
})
it("apiSetUserDomain sets and removes the name", async () => {
const chat = await chatWithResponse({type: "userProfileNoChange", user})
await expect(chat.apiSetUserDomain(1, "calc.simplex")).resolves.toEqual(user)
await expect(chat.apiSetUserDomain(1)).resolves.toEqual(user)
expect(jest.mocked(core.chatSendCmd).mock.calls.map(([, cmd]) => cmd)).toEqual(["/_set domain 1 calc.simplex", "/_set domain 1"])
})
it("apiReceiveFile reports a file cancelled by sender", async () => {
const chat = await chatWithResponse({type: "rcvFileAcceptedSndCancelled", user, rcvFileTransfer: {}})
await expect(chat.apiReceiveFile(3)).rejects.toThrow("file cancelled by sender")
@@ -96,6 +103,15 @@ describe("startChat lifecycle", () => {
await chat.stopChat()
})
it("passes the chat api to event subscribers", async () => {
const chat = await chatWithResponses({type: "chatStarted"}, {type: "chatStopped"})
jest.mocked(core.chatRecvMsgWait).mockResolvedValueOnce({type: "hostConnected"} as ChatEvent)
const subscriberChat = new Promise(resolve => chat.on("hostConnected", (_event, c) => resolve(c)))
await chat.startChat()
await expect(subscriberChat).resolves.toBe(chat)
await chat.stopChat()
})
it("receives with a 500 ms wait", async () => {
const chat = await chatWithResponses()
await chat.recvChatEvent()
@@ -1,6 +1,6 @@
import {ChatEvent, T} from "@simplex-chat/types"
import * as api from "../src/api"
import {subscribeChatItems} from "../src/bot"
import {run, subscribeChatItems} from "../src/bot"
type Handler = (evt: ChatEvent) => Promise<void>
@@ -40,6 +40,14 @@ describe("subscribeChatItems", () => {
expect(calls).toEqual(["message:/unknown", "message:hello"])
})
it("passes the chat api to handlers", async () => {
const {bot, deliver} = fakeBot()
const chats: api.ChatApi[] = []
subscribeChatItems(bot, async (_ci, _content, chat) => { chats.push(chat) }, {help: async (_ci, _cmd, chat) => { chats.push(chat) }})
await deliver([item("rcvMsgContent", "/help"), item("rcvMsgContent", "hello")])
expect(chats).toEqual([bot, bot])
})
it("ignores sent items", async () => {
const {bot, deliver} = fakeBot()
const calls: string[] = []
@@ -48,3 +56,75 @@ describe("subscribeChatItems", () => {
expect(calls).toEqual([])
})
})
describe("run", () => {
const address = {
connLinkContact: {connFullLink: "full", connShortLink: "short"},
addressSettings: {businessAddress: false, autoAccept: {acceptIncognito: false}},
} as unknown as T.UserContactLink
function fakeChat(contactDomain?: T.SimplexDomainClaim) {
const user = {userId: 1, profile: {displayName: "Old", fullName: "", contactDomain}} as unknown as T.User
const chat = {
on: jest.fn(),
apiGetActiveUser: jest.fn().mockResolvedValue(user),
startChat: jest.fn(),
apiGetUserAddress: jest.fn().mockResolvedValue(address),
apiSetAddressSettings: jest.fn(),
apiSetUserDomain: jest.fn(async (_userId: number, domain?: string) => ({...user, profile: {...user.profile, contactDomain: domain && {domain}}})),
apiUpdateProfile: jest.fn().mockResolvedValue({updateSuccesses: 0, updateFailures: 0}),
}
jest.spyOn(api.ChatApi, "init").mockResolvedValue(chat as unknown as api.ChatApi)
return chat
}
const runBot = (simplexDomain?: string | null, options = {}) =>
run({profile: {displayName: "Calculator", fullName: ""}, simplexDomain, dbOpts: {type: "sqlite", filePrefix: "unused"}, options})
const updatedProfile = (chat: ReturnType<typeof fakeChat>) => chat.apiUpdateProfile.mock.calls[0][1]
beforeEach(() => jest.spyOn(console, "log").mockImplementation(() => {}))
afterEach(() => jest.restoreAllMocks())
it("sets the configured SimpleX name", async () => {
const chat = fakeChat()
await runBot("Calc.simplex")
expect(chat.apiSetUserDomain).toHaveBeenCalledWith(1, "calc.simplex")
expect(updatedProfile(chat).contactDomain).toEqual({domain: "calc.simplex"})
})
it("removes the SimpleX name set to null", async () => {
const chat = fakeChat({domain: "calc.simplex"})
await runBot(null)
expect(chat.apiSetUserDomain).toHaveBeenCalledWith(1, undefined)
expect(updatedProfile(chat).contactDomain).toBeUndefined()
})
it("keeps the stored SimpleX name when it is not configured", async () => {
const chat = fakeChat({domain: "calc.simplex"})
await runBot()
expect(chat.apiSetUserDomain).not.toHaveBeenCalled()
expect(updatedProfile(chat).contactDomain).toEqual({domain: "calc.simplex"})
})
it("keeps the SimpleX name when updating the profile", async () => {
const chat = fakeChat({domain: "calc.simplex", proof: {presHeader: "header", signature: "signature"}})
await runBot("calc.simplex")
expect(chat.apiSetUserDomain).not.toHaveBeenCalled()
expect(updatedProfile(chat).displayName).toBe("Calculator")
expect(updatedProfile(chat).contactDomain).toEqual({domain: "calc.simplex"})
})
it("continues when the SimpleX name cannot be set", async () => {
const chat = fakeChat()
chat.apiSetUserDomain.mockRejectedValue(new Error("simplexDomainNotReady"))
await expect(runBot("calc.simplex")).resolves.toBeDefined()
expect(updatedProfile(chat).contactDomain).toBeUndefined()
})
it("does not change the SimpleX name without updateAddress", async () => {
const chat = fakeChat()
await runBot("calc.simplex", {updateAddress: false})
expect(chat.apiSetUserDomain).not.toHaveBeenCalled()
})
})