├── .gitignore ├── .npmignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── api.md ├── doc-gen ├── helpers.js └── scope.hbs ├── examples ├── initialize.js └── receive.js ├── index.js ├── package.json ├── src ├── cabal-details.js ├── channel-details.js ├── client.js ├── commands.js ├── initialization-callbacks.js ├── moderation.js ├── storage-browser.js ├── storage-node.js ├── user.js └── util.js └── test └── test.js /.gitignore: -------------------------------------------------------------------------------- 1 | #~top ignores~ 2 | node_modules/ 3 | *.css 4 | *.vim 5 | *bundle*.js 6 | /html/*.html 7 | *.swo 8 | config.conf 9 | config.js 10 | *.txt 11 | *.pdf 12 | archives 13 | 14 | # Cabal config files 15 | .cabal.yml 16 | 17 | ################# 18 | ## Eclipse 19 | ################# 20 | *.pydevproject 21 | .project 22 | .metadata 23 | bin/ 24 | tmp/ 25 | *.tmp 26 | *.bak 27 | *.swp 28 | *~.nib 29 | local.properties 30 | .classpath 31 | .settings/ 32 | .loadpath 33 | 34 | # External tool builders 35 | .externalToolBuilders/ 36 | 37 | # Locally stored "Eclipse launch configurations" 38 | *.launch 39 | 40 | # CDT-specific 41 | .cproject 42 | 43 | # PDT-specific 44 | .buildpath 45 | 46 | 47 | ################# 48 | ## Visual Studio 49 | ################# 50 | 51 | ## Ignore Visual Studio temporary files, build results, and 52 | ## files generated by popular Visual Studio add-ons. 53 | 54 | # User-specific files 55 | *.suo 56 | *.user 57 | *.sln.docstates 58 | 59 | # Build results 60 | 61 | [Dd]ebug/ 62 | [Rr]elease/ 63 | x64/ 64 | build/ 65 | [Bb]in/ 66 | [Oo]bj/ 67 | 68 | # MSTest test Results 69 | [Tt]est[Rr]esult*/ 70 | [Bb]uild[Ll]og.* 71 | 72 | *_i.c 73 | *_p.c 74 | *.ilk 75 | *.meta 76 | *.obj 77 | *.pch 78 | *.pdb 79 | *.pgc 80 | *.pgd 81 | *.rsp 82 | *.sbr 83 | *.tlb 84 | *.tli 85 | *.tlh 86 | *.tmp 87 | *.tmp_proj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.log 94 | *.scc 95 | 96 | # Visual C++ cache files 97 | ipch/ 98 | *.aps 99 | *.ncb 100 | *.opensdf 101 | *.sdf 102 | *.cachefile 103 | 104 | # Visual Studio profiler 105 | *.psess 106 | *.vsp 107 | *.vspx 108 | 109 | # Guidance Automation Toolkit 110 | *.gpState 111 | 112 | # ReSharper is a .NET coding add-in 113 | _ReSharper*/ 114 | *.[Rr]e[Ss]harper 115 | 116 | # TeamCity is a build add-in 117 | _TeamCity* 118 | 119 | # DotCover is a Code Coverage Tool 120 | *.dotCover 121 | 122 | # NCrunch 123 | *.ncrunch* 124 | .*crunch*.local.xml 125 | 126 | # Installshield output folder 127 | [Ee]xpress/ 128 | 129 | # DocProject is a documentation generator add-in 130 | DocProject/buildhelp/ 131 | DocProject/Help/*.HxT 132 | DocProject/Help/*.HxC 133 | DocProject/Help/*.hhc 134 | DocProject/Help/*.hhk 135 | DocProject/Help/*.hhp 136 | DocProject/Help/Html2 137 | DocProject/Help/html 138 | 139 | # Click-Once directory 140 | publish/ 141 | 142 | # Publish Web Output 143 | *.Publish.xml 144 | *.pubxml 145 | 146 | # NuGet Packages Directory 147 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 148 | #packages/ 149 | 150 | # Windows Azure Build Output 151 | csx 152 | *.build.csdef 153 | 154 | # Windows Store app package directory 155 | AppPackages/ 156 | 157 | # Others 158 | sql/ 159 | *.Cache 160 | ClientBin/ 161 | [Ss]tyle[Cc]op.* 162 | ~$* 163 | *~ 164 | *.dbmdl 165 | *.[Pp]ublish.xml 166 | *.pfx 167 | *.publishsettings 168 | 169 | # RIA/Silverlight projects 170 | Generated_Code/ 171 | 172 | # Backup & report files from converting an old project file to a newer 173 | # Visual Studio version. Backup files are not needed, because we have git ;-) 174 | _UpgradeReport_Files/ 175 | Backup*/ 176 | UpgradeLog*.XML 177 | UpgradeLog*.htm 178 | 179 | # SQL Server files 180 | App_Data/*.mdf 181 | App_Data/*.ldf 182 | 183 | ############# 184 | ## Windows detritus 185 | ############# 186 | 187 | # Windows image file caches 188 | Thumbs.db 189 | ehthumbs.db 190 | 191 | # Folder config file 192 | Desktop.ini 193 | 194 | # Recycle Bin used on file shares 195 | $RECYCLE.BIN/ 196 | 197 | # Mac crap 198 | .DS_Store 199 | 200 | 201 | ############# 202 | ## Python 203 | ############# 204 | 205 | *.py[co] 206 | 207 | # Packages 208 | *.egg 209 | *.egg-info 210 | dist/ 211 | build/ 212 | eggs/ 213 | parts/ 214 | var/ 215 | sdist/ 216 | develop-eggs/ 217 | .installed.cfg 218 | 219 | # Installer logs 220 | pip-log.txt 221 | 222 | # Unit test / coverage reports 223 | .coverage 224 | .tox 225 | 226 | #Translations 227 | *.mo 228 | 229 | #Mr Developer 230 | .mr.developer.cfg 231 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test/ 2 | examples/ 3 | .travis.yml 4 | wishlist.md 5 | doc-gen/ 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '10' 4 | - '12' 5 | os: 6 | - windows 7 | - osx 8 | - linux 9 | notifications: 10 | email: false 11 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [8.0.2] - 2024-01-25 4 | ### Fixed 5 | - Fix race condition preventing message listeners from being set. 6 | 7 | ## [8.0.0] - 2023-10-17 8 | ### Changed 9 | - Upgraded cabal-core to latest, to bring in hyperswarm changes. 10 | 11 | ## [7.3.2] - 2022-10-31 12 | ### Fixed 13 | 14 | - Fix unhandled promise rejection when initializing a Client instance with a cabal name that can't be resolved. (Handles case of being unable to resolve a key. ([#94](https://github.com/cabal-club/cabal-client/issues/94)) (Kira Oakley)) 15 | 16 | ## [7.3.1] - 2022-05-26 17 | ### Fixed 18 | 19 | - Fix crash when creating new PM (Reorder PM null check ([#91](https://github.com/cabal-club/cabal-client/issues/91)) (Daniel Chiquito)) 20 | 21 | The previous ordering would cause an exception even if the null check 22 | was triggered. 23 | 24 | 25 | ## [7.3.0] - 2022-05-24 26 | 27 | ### Changed 28 | 29 | - Use getter for PMChannelDetails.joined ([#89](https://github.com/cabal-club/cabal-client/issues/89)) (Daniel Chiquito). 30 | 31 | The getter refers to the CabalDetails instance which holds the settings 32 | for the cabal to determine if the private message channel should be 33 | considered joined or not. 34 | 35 | This has the side affect of requiring the CabalDetails when initializing 36 | the PMChannelDetails, which involves changing the constructor signature. 37 | 38 | This is technically a breaking change, however `ChannelDetails` is an internal implementation concern of 39 | cabal-details and not intended to be one of the public facing api functions. 40 | 41 | ### Added 42 | 43 | - Add methods to read/write a settings file ([#89](https://github.com/cabal-club/cabal-client/issues/89)) (Daniel Chiquito) 44 | - Add dependency on js-yaml ([#89](https://github.com/cabal-club/cabal-client/issues/89)) (Daniel Chiquito) 45 | - Leaving private messages functionality ([#89](https://github.com/cabal-club/cabal-client/issues/89)) (Daniel Chiquito & cblgh) 46 | 47 | ### Fixed 48 | 49 | - Potential issue upstream in cabal-core when receiving ill-formatted PMs ([`e6e7308`](https://github.com/cabal-club/cabal-client/commit/e6e7308)) (cblgh) 50 | 51 | ## [7.2.2] - 2021-12-16 52 | 53 | ### Fixed 54 | 55 | - remove duplication of channel events ([`0caff38`](https://github.com/cabal-club/cabal-client/commit/0caff38)) ([**@khubo**](https://github.com/khubo)) 56 | 57 | ## [7.2.1] - 2021-12-11 58 | 59 | ### Changed 60 | 61 | - getChannels: add onlyJoined param ([`1bb9d3d`](https://github.com/cabal-club/cabal-client/commit/1bb9d3d)) ([**@cblgh**](https://github.com/cblgh)) 62 | 63 | ## [7.2.0] - 2021-11-23 64 | 65 | ### Changed 66 | 67 | - bump cabal-core to 15.0.0 (only changes were to pm api) ([#82](https://github.com/cabal-club/cabal-client/issues/82)) ([**@cblgh**](https://github.com/cblgh)) 68 | - disallow channel names == hypercore key, support latest core pm format ([#82](https://github.com/cabal-club/cabal-client/issues/82)) ([**@cblgh**](https://github.com/cblgh)) 69 | - A new convention was introduced to limit malicious use in clients: Channel names conforming to the hypercore public key format are forbidden in cabal-client as names for regular channel names (i.e. no channel names that are 64 hex characters)—these are restricted to private channels only (namely: one per person you are chatting with, the name being their public key (or yours, from their perspective)) 70 | - Revert "only add message listener when we're adding a new channel" ([`1bf10a9`](https://github.com/cabal-club/cabal-client/commit/1bf10a9)) ([**@cblgh**](https://github.com/cblgh)). 71 | 72 | This reverts commit [`1dbd522`](https://github.com/cabal-club/cabal-client/commit/1dbd5227923aa9063b93b57cfa9dbed31e246dda). 73 | 74 | It seems this commit introduced a regression in functionality such that 75 | messages do not appear in channels 76 | ([#78](https://github.com/cabal-club/cabal-client/issues/78)) and might also be 77 | responsible for a similar bug in [cabal-desktop@6.0.8](mailto:cabal-desktop@6.0.8) 78 | 79 | It would be good to only add the relevant message listeners, instead of 80 | duplicates, but I think it will have to be done anew with fresh eyes. 81 | 82 | ### Added 83 | 84 | Adds support for [cabal-core's private message](https://github.com/cabal-club/cabal-core/#private-messages): 85 | 86 | - a new `CabalDetails.publishPrivateMessage` function has been added 87 | - `CabalDetails.getPrivateMessageList` returns a list of channel names corresponding to ongoing PMs for the local user 88 | - `CabalDetails.isChannelPrivate(channel)` returns true if the passed in channel is a private message channel, false otherwise 89 | - `CabalDetails.publishMessage` now redirects a published message to `publishPrivateMessage` if it is used to post a message to a private message channel 90 | - `publish-private-message`, `private-message` events are now emitted 91 | - the `PMChannelDetails` has been added to enable support for private message channels with minimal duplicated functionality 92 | - `CabalDetails.getChannels(opts)` was extended with an option `includePM` to include private message channels in the returned result 93 | - PMs are moderation aware: if you hide a user the channel is hidden and no subsequent PMs will be displayed in your client 94 | 95 | For more information, see the [API documentation](https://github.com/cabal-club/cabal-client/blob/master/api.md). 96 | 97 | ## [7.1.0] - 2021-10-23 98 | 99 | ### Changed 100 | 101 | - bump cabal-core to version with hyperswarm-web ([`a83493d`](https://github.com/cabal-club/cabal-client/commit/a83493d)) ([**@cblgh**](https://github.com/cblgh)) 102 | 103 | ### Added 104 | 105 | - make cabal-client work in the browser ([`3f7b9d3`](https://github.com/cabal-club/cabal-client/commit/3f7b9d3aa90c6eab80be1796f777d0926e664516)) ([**@cblgh**](https://github.com/cblgh)) 106 | 107 | ### Fixed 108 | 109 | - Update Client() docs with opts.aliases and opts.commands ([#81](https://github.com/cabal-club/cabal-client/issues/81)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) 110 | 111 | ## [7.0.0] - 2021-09-26 112 | 113 | _The updated version of `cabal-core` indirectly contains major changes to the underlying protocol. See the release of [`cabal-core@14.0.0`](https://github.com/cabal-club/cabal-core/blob/master/CHANGELOG.md#1400---2021-05-18) for more detailed information._ 114 | 115 | ### Changed 116 | 117 | - **Breaking:** upgrade `cabal-core` to `14.x` ([#79](https://github.com/cabal-club/cabal-client/issues/79)) (Lars-Magnus Skog) 118 | 119 | ## [6.3.2] - 2021-05-01 120 | 121 | _This is not the first version, but the first version in this changelog to save some time._ 122 | 123 | [7.3.1]: https://github.com/cabal-club/cabal-client/compare/v7.3.0...v7.3.1 124 | 125 | [7.3.0]: https://github.com/cabal-club/cabal-client/compare/v7.2.2...v7.3.0 126 | 127 | [7.2.2]: https://github.com/cabal-club/cabal-client/compare/v7.2.1...v7.2.2 128 | 129 | [7.2.1]: https://github.com/cabal-club/cabal-client/compare/v7.2.0...v7.2.1 130 | 131 | [7.2.0]: https://github.com/cabal-club/cabal-client/compare/v7.1.0...v7.2.0 132 | 133 | [7.1.0]: https://github.com/cabal-club/cabal-client/compare/v7.0.0...v7.1.0 134 | 135 | [7.0.0]: https://github.com/cabal-club/cabal-client/compare/v6.3.2...v7.0.0 136 | 137 | [6.3.2]: https://github.com/cabal-club/cabal-client/releases/tag/v6.3.2 138 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cabal-client 2 | 3 | `cabal-client` is a new type of client library for cabal chat clients. 4 | 5 | New chat clients can be implemented using _only_ this library, without having 6 | to mess around with [`cabal-core`](https://github.com/cabal-club/cabal-core/) 7 | anymore. 8 | 9 | Some of its features: 10 | 11 | - consolidates logic common to all chat clients 12 | - leaving and joining of channels 13 | - virtual messages (such as status messages) and virtual channels (currently only the `!status` channel) 14 | - handling multiple cabal instances 15 | - receiving unread notifications and mentions for channels 16 | - resolving of DNS shortnames (cabal.chat) to cabal keys 17 | 18 | For a couple of brief examples, see the [`examples/`](examples/) directory. 19 | 20 | ## Usage 21 | 22 | See [`cabal-cli`](https://github.com/cabal-club/cabal-cli/) for an example client implementation. 23 | 24 | [Read the API documentation](./api.md) 25 | 26 | ```js 27 | var Client = require('cabal-client') 28 | 29 | const client = new Client({ 30 | config: { 31 | dbdir: '/tmp/cabals' 32 | } 33 | }) 34 | 35 | client.createCabal() 36 | .then((cabal) => { 37 | // resolves when the cabal is ready, returns a CabalDetails instance 38 | }) 39 | ``` 40 | 41 | ## Concepts 42 | 43 | `cabal-client` has **three core abstractions**: 44 | [`Client`](https://github.com/cabal-club/cabal-client/blob/master/src/client.js), 45 | [`CabalDetails`](https://github.com/cabal-club/cabal-client/blob/master/src/cabal-details.js) and 46 | [`ChannelDetails`](https://github.com/cabal-club/cabal-client/blob/master/src/channel-details.js). 47 | 48 | [`Client`](https://github.com/cabal-club/cabal-client/blob/master/src/client.js) is the 49 | entrypoint. It has a list of `CabalDetails` (one `details` for each joined cabal) as well as an API for interacting with 50 | a cabal (getting a count of the new messages for a channel, the joined channels for the current peer etc). 51 | 52 | [`CabalDetails`](https://github.com/cabal-club/cabal-client/blob/master/src/cabal-details.js) is the 53 | instance that clients mostly operate on, as it encapsulates all information for a particular cabal. (joined channels, 54 | users in that channel, the topic). **It also emits events.** 55 | 56 | When a change has happened, a `CabalDetails` instance will call `this._emitUpdate()`. When a client receives this 57 | event, they should update their state & rerender. (Check out [how the cli does 58 | it](https://github.com/cabal-club/cabal-cli/pull/126).) 59 | 60 | [`ChannelDetails`](https://github.com/cabal-club/cabal-client/blob/master/src/channel-details.js) 61 | encapsulates everything channels (mentions in that channel, status messages for the channel (like having called a 62 | command eg `/names`, when it was last read, if it's currently being viewed, if it's joined and so on). It also has a 63 | barebones implementation for virtual channels, which currently is only the `!status` channel. 64 | 65 | ## Install 66 | 67 | With [npm](https://npmjs.org/) installed, run 68 | 69 | ``` 70 | $ npm install cabal-client 71 | ``` 72 | 73 | ## Developing 74 | 75 | ### Changelog 76 | 77 | See the instructions for generating the changelog in the [cabal-core readme](https://github.com/cabal-club/cabal-core/#developing). 78 | 79 | ## License 80 | 81 | AGPL-3.0-or-later 82 | -------------------------------------------------------------------------------- /api.md: -------------------------------------------------------------------------------- 1 | ## Classes 2 | 3 |
4 |
Client
5 |
6 |
CabalDetails
7 |
8 |
9 | 10 | 11 | 12 | ## Client 13 | 14 | * [Client](#Client) 15 | * [new Client([opts])](#new_Client_new) 16 | * _instance_ 17 | * [.readCabalSettingsFile()](#Client+readCabalSettingsFile) ⇒ object 18 | * [.getCabalSettings(key)](#Client+getCabalSettings) ⇒ object 19 | * [.writeCabalSettings(key, settings)](#Client+writeCabalSettings) 20 | * [.resolveName(name, [cb])](#Client+resolveName) 21 | * [.createCabal()](#Client+createCabal) ⇒ Promise 22 | * [.addCabal(key, opts, cb)](#Client+addCabal) ⇒ Promise 23 | * [.focusCabal(key)](#Client+focusCabal) 24 | * [.removeCabal(key, cb)](#Client+removeCabal) 25 | * [.getDetails()](#Client+getDetails) ⇒ [CabalDetails](#CabalDetails) 26 | * [.getCabalKeys()](#Client+getCabalKeys) ⇒ Array.<string> 27 | * [.getCurrentCabal()](#Client+getCurrentCabal) ⇒ [CabalDetails](#CabalDetails) 28 | * [.addCommand([name], [cmd])](#Client+addCommand) 29 | * [.removeCommand([name])](#Client+removeCommand) 30 | * [.getCommands()](#Client+getCommands) 31 | * [.addAlias([longCmd], [shortCmd])](#Client+addAlias) 32 | * [.cabalToDetails([cabal])](#Client+cabalToDetails) ⇒ [CabalDetails](#CabalDetails) 33 | * [.addStatusMessage(message, channel, [cabal])](#Client+addStatusMessage) 34 | * [.clearStatusMessages(channel, [cabal])](#Client+clearStatusMessages) 35 | * [.getUsers([cabal])](#Client+getUsers) ⇒ Array.<Object> 36 | * [.getJoinedChannels([cabal])](#Client+getJoinedChannels) ⇒ Array.<Object> 37 | * [.getChannels([cabal])](#Client+getChannels) ⇒ Array.<Object> 38 | * [.subscribe(listener, [cabal])](#Client+subscribe) 39 | * [.unsubscribe(listener, [cabal])](#Client+unsubscribe) 40 | * [.getMessages([opts], [cb], [cabal])](#Client+getMessages) 41 | * [.searchMessages([searchString], [opts], [cabal])](#Client+searchMessages) ⇒ Promise 42 | * [.getNumberUnreadMessages(channel, [cabal])](#Client+getNumberUnreadMessages) ⇒ number 43 | * [.getNumberMentions([channel], [cabal])](#Client+getNumberMentions) 44 | * [.getMentions([channel], [cabal])](#Client+getMentions) 45 | * [.focusChannel([channel], [keepUnread], [cabal])](#Client+focusChannel) 46 | * [.unfocusChannel([channel], [newChannel], [cabal])](#Client+unfocusChannel) 47 | * [.getCurrentChannel()](#Client+getCurrentChannel) ⇒ string 48 | * [.markChannelRead(channel, [cabal])](#Client+markChannelRead) 49 | * _static_ 50 | * [.getDatabaseVersion()](#Client.getDatabaseVersion) ⇒ string 51 | * [.generateKey()](#Client.generateKey) ⇒ string 52 | * [.scrubKey(key)](#Client.scrubKey) ⇒ string 53 | * [.getCabalDirectory()](#Client.getCabalDirectory) ⇒ string 54 | * [.getCabalSettingsFile()](#Client.getCabalSettingsFile) ⇒ string 55 | 56 | 57 | * * * 58 | 59 | 60 | 61 | ### new Client([opts]) 62 | Create a client instance from which to manage multiple 63 | [`cabal-core`](https://github.com/cabal-club/cabal-core/) instances. 64 | 65 | **Params** 66 | 67 | - *opts* object 68 | - aliases object - key/value pairs of `alias` -> `command name` 69 | - commands object - key/value pairs of `command name` -> `command object`, which has the following properties: 70 | - call function - command function with the following signature `command.call(cabal, res, arg)` 71 | - help function - return the help string for this command 72 | - category Array.<string> - a list of categories this commands belongs to 73 | - alias Array.<string> - a list of command aliases 74 | - config object 75 | - temp boolean - if `temp` is true no data is persisted to disk. 76 | - *dbdir* string - the directory to store the cabal data 77 | - *preferredPort* string - the port cabal will listen on for traffic 78 | - *maxFeeds* number = 1000 - max amount of feeds to sync 79 | - *persistentCache* object - specify a `read` and `write` to create a persistent DNS cache 80 | - read function - async cache lookup function 81 | - write function - async cache write function 82 | 83 | 84 | * * * 85 | 86 | 87 | 88 | ### client.readCabalSettingsFile() ⇒ object 89 | Read and parse the contents of the settings.yml file. 90 | If the file doesn't exist, return {}. 91 | 92 | **Returns**: object - the contents of the settings file 93 | 94 | * * * 95 | 96 | 97 | 98 | ### client.getCabalSettings(key) ⇒ object 99 | Get the settings for a given cabal from the settings.yml file. 100 | If the file doesn't exist or the given cabal has no settings, return the default settings. 101 | 102 | **Returns**: object - the cabal settings 103 | **Params** 104 | 105 | - key string - the cabal 106 | 107 | 108 | * * * 109 | 110 | 111 | 112 | ### client.writeCabalSettings(key, settings) 113 | Reads the settings from the settings.yml file, updates the settings for the given cabal, then 114 | writes the revised settings to the settings.yml file. 115 | 116 | **Params** 117 | 118 | - key string - the cabal 119 | - settings object - the cabal settings 120 | 121 | 122 | * * * 123 | 124 | 125 | 126 | ### client.resolveName(name, [cb]) 127 | Resolve the DNS shortname `name`. If `name` is already a cabal key, it will 128 | be returned and the DNS lookup is aborted. 129 | If `name` is a whisper:// key, a DHT lookup for the passed-in key will occur. 130 | Once a match is found, it is assumed to be a cabal key, which is returned. 131 | Returns the cabal key in `cb`. If `cb` is null a Promise is returned. 132 | 133 | **Params** 134 | 135 | - name string - the DNS shortname, or whisper:// shortname 136 | - *cb* function - The callback to be called when lookup succeeds 137 | 138 | 139 | * * * 140 | 141 | 142 | 143 | ### client.createCabal() ⇒ Promise 144 | Create a new cabal. 145 | 146 | **Returns**: Promise - a promise that resolves into a `CabalDetails` instance. 147 | 148 | * * * 149 | 150 | 151 | 152 | ### client.addCabal(key, opts, cb) ⇒ Promise 153 | Add/load the cabal at `key`. 154 | 155 | **Returns**: Promise - a promise that resolves into a `CabalDetails` instance. 156 | **Params** 157 | 158 | - key string 159 | - opts object 160 | - cb function - a function to be called when the cabal has been initialized. 161 | 162 | 163 | * * * 164 | 165 | 166 | 167 | ### client.focusCabal(key) 168 | Focus the cabal at `key`, used when you want to switch from one open cabal to another. 169 | 170 | **Params** 171 | 172 | - key string 173 | 174 | 175 | * * * 176 | 177 | 178 | 179 | ### client.removeCabal(key, cb) 180 | Remove the cabal `key`. Destroys everything related to it 181 | (the data is however still persisted to disk, fret not!). 182 | 183 | **Params** 184 | 185 | - key string 186 | - cb function 187 | 188 | 189 | * * * 190 | 191 | 192 | 193 | ### client.getDetails() ⇒ [CabalDetails](#CabalDetails) 194 | Returns the details of a cabal for the given key. 195 | 196 | 197 | * * * 198 | 199 | 200 | 201 | ### client.getCabalKeys() ⇒ Array.<string> 202 | Returns a list of cabal keys, one for each open cabal. 203 | 204 | 205 | * * * 206 | 207 | 208 | 209 | ### client.getCurrentCabal() ⇒ [CabalDetails](#CabalDetails) 210 | Get the current cabal. 211 | 212 | 213 | * * * 214 | 215 | 216 | 217 | ### client.addCommand([name], [cmd]) 218 | Add a command to the set of supported commands. 219 | 220 | **Params** 221 | 222 | - *name* string - the long-form command name 223 | - *cmd* object - the command object 224 | - *help* function - function returning help text 225 | - *alias* array - array of string aliases 226 | - *call* function - implementation of the command receiving (cabal, res, arg) arguments 227 | 228 | 229 | * * * 230 | 231 | 232 | 233 | ### client.removeCommand([name]) 234 | Remove a command. 235 | 236 | **Params** 237 | 238 | - *name* string - the command name 239 | 240 | 241 | * * * 242 | 243 | 244 | 245 | ### client.getCommands() 246 | Get an object mapping command names to command objects. 247 | 248 | 249 | * * * 250 | 251 | 252 | 253 | ### client.addAlias([longCmd], [shortCmd]) 254 | Add an alias `shortCmd` for `longCmd` 255 | 256 | **Params** 257 | 258 | - *longCmd* string - command to be aliased 259 | - *shortCmd* string - alias 260 | 261 | 262 | * * * 263 | 264 | 265 | 266 | ### client.cabalToDetails([cabal]) ⇒ [CabalDetails](#CabalDetails) 267 | Returns a `CabalDetails` instance for the passed in `cabal-core` instance. 268 | 269 | **Params** 270 | 271 | - *cabal* Cabal = this.currentCabal 272 | 273 | 274 | * * * 275 | 276 | 277 | 278 | ### client.addStatusMessage(message, channel, [cabal]) 279 | Add a status message, displayed client-side only, to the specified channel and cabal. 280 | If no cabal is specified, the currently focused cabal is used. 281 | 282 | **Params** 283 | 284 | - message object 285 | - channel string 286 | - *cabal* Cabal = this.currentCabal 287 | 288 | 289 | * * * 290 | 291 | 292 | 293 | ### client.clearStatusMessages(channel, [cabal]) 294 | Clear status messages for the specified channel. 295 | 296 | **Params** 297 | 298 | - channel string 299 | - *cabal* Cabal = this.currentCabal 300 | 301 | 302 | * * * 303 | 304 | 305 | 306 | ### client.getUsers([cabal]) ⇒ Array.<Object> 307 | Returns a list of all the users for the specified cabal. 308 | If no cabal is specified, the currently focused cabal is used. 309 | 310 | **Returns**: Array.<Object> - the list of users 311 | **Params** 312 | 313 | - *cabal* Cabal = this.currentCabal 314 | 315 | 316 | * * * 317 | 318 | 319 | 320 | ### client.getJoinedChannels([cabal]) ⇒ Array.<Object> 321 | Returns a list of channels the user has joined for the specified cabal. 322 | If no cabal is specified, the currently focused cabal is used. 323 | 324 | **Returns**: Array.<Object> - the list of Channels 325 | **Params** 326 | 327 | - *cabal* Cabal = this.currentCabal 328 | 329 | 330 | * * * 331 | 332 | 333 | 334 | ### client.getChannels([cabal]) ⇒ Array.<Object> 335 | Returns a list of all channels for the specified cabal. 336 | If no cabal is specified, the currently focused cabal is used. 337 | 338 | **Returns**: Array.<Object> - the list of Channels 339 | **Params** 340 | 341 | - *cabal* Cabal = this.currentCabal 342 | 343 | 344 | * * * 345 | 346 | 347 | 348 | ### client.subscribe(listener, [cabal]) 349 | Add a new listener for the `update` event. 350 | 351 | **Params** 352 | 353 | - listener function 354 | - *cabal* Cabal = this.currentCabal 355 | 356 | 357 | * * * 358 | 359 | 360 | 361 | ### client.unsubscribe(listener, [cabal]) 362 | Remove a previously added listener. 363 | 364 | **Params** 365 | 366 | - listener function 367 | - *cabal* Cabal = this.currentCabal 368 | 369 | 370 | * * * 371 | 372 | 373 | 374 | ### client.getMessages([opts], [cb], [cabal]) 375 | Returns a list of messages according to `opts`. If `cb` is null, a Promise is returned. 376 | 377 | **Params** 378 | 379 | - *opts* Object 380 | - *olderThan* number - timestamp in epoch time. we want to get messages that are *older* than this ts 381 | - *newerThan* number - timestamp in epoch time. we want to get messages that are *newer* than this ts 382 | - *amount* number - amount of messages to get 383 | - *channel* string - channel to get messages from. defaults to currently focused channel 384 | - *cb* function - the callback to be called when messages are retreived 385 | - *cabal* Cabal = this.currentCabal 386 | 387 | 388 | * * * 389 | 390 | 391 | 392 | ### client.searchMessages([searchString], [opts], [cabal]) ⇒ Promise 393 | Searches for messages that include the search string according to `opts`. 394 | Each returned match contains a message string and a matchedIndexes array containing the indexes at which the search string was found in the message 395 | 396 | **Returns**: Promise - a promise that resolves into a list of matches. 397 | **Params** 398 | 399 | - *searchString* string - string to match messages against 400 | - *opts* Object 401 | - *olderThan* number - timestamp in epoch time. we want to search through messages that are *older* than this ts 402 | - *newerThan* number - timestamp in epoch time. we want to search through messages that are *newer* than this ts 403 | - *amount* number - amount of messages to be search through 404 | - *channel* string - channel to get messages from. defaults to currently focused channel 405 | - *cabal* Cabal = this.currentCabal 406 | 407 | 408 | * * * 409 | 410 | 411 | 412 | ### client.getNumberUnreadMessages(channel, [cabal]) ⇒ number 413 | Returns the number of unread messages for `channel`. 414 | 415 | **Params** 416 | 417 | - channel string 418 | - *cabal* Cabal = this.currentCabal 419 | 420 | 421 | * * * 422 | 423 | 424 | 425 | ### client.getNumberMentions([channel], [cabal]) 426 | Returns the number of mentions in `channel`. 427 | 428 | **Params** 429 | 430 | - *channel* string = "this.getCurrentChannel()" 431 | - *cabal* Cabal = this.currentCabal 432 | 433 | 434 | * * * 435 | 436 | 437 | 438 | ### client.getMentions([channel], [cabal]) 439 | Returns a list of messages that triggered a mention in channel. 440 | 441 | **Params** 442 | 443 | - *channel* string = "this.getCurrentChannel()" 444 | - *cabal* Cabal = this.currentCabal 445 | 446 | 447 | * * * 448 | 449 | 450 | 451 | ### client.focusChannel([channel], [keepUnread], [cabal]) 452 | View `channel`, closing the previously focused channel. 453 | 454 | **Params** 455 | 456 | - *channel* \* = this.getCurrentChannel() 457 | - *keepUnread* boolean = false 458 | - *cabal* Cabal = this.currentCabal 459 | 460 | 461 | * * * 462 | 463 | 464 | 465 | ### client.unfocusChannel([channel], [newChannel], [cabal]) 466 | Close `channel`. 467 | 468 | **Params** 469 | 470 | - *channel* string = "this.getCurrentChannel()" 471 | - *newChannel* string = null 472 | - *cabal* Cabal = this.currentCabal 473 | 474 | 475 | * * * 476 | 477 | 478 | 479 | ### client.getCurrentChannel() ⇒ string 480 | Returns the currently focused channel name. 481 | 482 | 483 | * * * 484 | 485 | 486 | 487 | ### client.markChannelRead(channel, [cabal]) 488 | Mark the channel as read. 489 | 490 | **Params** 491 | 492 | - channel string 493 | - *cabal* Cabal = this.currentCabal 494 | 495 | 496 | * * * 497 | 498 | 499 | 500 | ### Client.getDatabaseVersion() ⇒ string 501 | Get the current database version. 502 | 503 | 504 | * * * 505 | 506 | 507 | 508 | ### Client.generateKey() ⇒ string 509 | Returns a 64 character hex string i.e. a newly generated cabal key. 510 | Useful if you want to programmatically create a new cabal as part of a shell pipeline. 511 | 512 | 513 | * * * 514 | 515 | 516 | 517 | ### Client.scrubKey(key) ⇒ string 518 | Removes URI scheme, URI search params (if present), and returns the cabal key as a 64 character hex string 519 | 520 | **Returns**: string - the scrubbed key 521 | **Params** 522 | 523 | - key string - the key to scrub 524 | 525 | **Example** 526 | ```js 527 | Client.scrubKey('cabal://12345678...?admin=7331b4b..') 528 | // => '12345678...' 529 | ``` 530 | 531 | * * * 532 | 533 | 534 | 535 | ### Client.getCabalDirectory() ⇒ string 536 | Returns a string path of where all of the cabals are stored on the hard drive. 537 | 538 | **Returns**: string - the cabal directory 539 | 540 | * * * 541 | 542 | 543 | 544 | ### Client.getCabalSettingsFile() ⇒ string 545 | Returns a string path of where the cabal settings are stored on the hard drive. 546 | 547 | **Returns**: string - the cabal settings file path 548 | 549 | * * * 550 | 551 | 552 | 553 | ## CabalDetails 554 | **Emits**: [update](#CabalDetails+event_update), [init](#CabalDetails+event_init), [info](#CabalDetails+event_info), [user-updated](#CabalDetails+event_user-updated), [new-channel](#CabalDetails+event_new-channel), [new-message](#CabalDetails+event_new-message), [private-message](#CabalDetails+event_private-message), [publish-message](#CabalDetails+event_publish-message), [publish-private-message](#CabalDetails+event_publish-private-message), [publish-nick](#CabalDetails+event_publish-nick), [status-message](#CabalDetails+event_status-message), [topic](#CabalDetails+event_topic), [channel-focus](#CabalDetails+event_channel-focus), [channel-join](#CabalDetails+event_channel-join), [channel-leave](#CabalDetails+event_channel-leave), [cabal-focus](#CabalDetails+event_cabal-focus), [started-peering](#CabalDetails+event_started-peering), [stopped-peering](#CabalDetails+event_stopped-peering) 555 | 556 | * [CabalDetails](#CabalDetails) 557 | * [new CabalDetails({, done)](#new_CabalDetails_new) 558 | * [.processLine([line], [cb])](#CabalDetails+processLine) 559 | * [.publishMessage(msg, [opts], [cb])](#CabalDetails+publishMessage) 560 | * [.publishNick(nick, [cb])](#CabalDetails+publishNick) 561 | * [.publishChannelTopic([channel], topic, cb)](#CabalDetails+publishChannelTopic) 562 | * [.getTopic([channel])](#CabalDetails+getTopic) ⇒ string 563 | * [.getChannelMembers([channel])](#CabalDetails+getChannelMembers) ⇒ Array.<object> 564 | * [.addStatusMessage(message, [channel])](#CabalDetails+addStatusMessage) 565 | * [.getChannels([opts])](#CabalDetails+getChannels) ⇒ Array.<string> 566 | * [.getCurrentChannel()](#CabalDetails+getCurrentChannel) ⇒ string 567 | * [.getCurrentChannelDetails()](#CabalDetails+getCurrentChannelDetails) ⇒ ChannelDetails 568 | * [.clearVirtualMessages([channel])](#CabalDetails+clearVirtualMessages) 569 | * [.getPrivateMessageList()](#CabalDetails+getPrivateMessageList) 570 | * [.isChannelPrivate()](#CabalDetails+isChannelPrivate) 571 | * [.joinPrivateMessage(channel)](#CabalDetails+joinPrivateMessage) 572 | * [.leavePrivateMessage(channel)](#CabalDetails+leavePrivateMessage) 573 | * [.publishPrivateMessage(msg, recipientKey, [cb])](#CabalDetails+publishPrivateMessage) 574 | * [.getJoinedChannels()](#CabalDetails+getJoinedChannels) ⇒ Array.<string> 575 | * [.getLocalUser()](#CabalDetails+getLocalUser) ⇒ user 576 | * [.getLocalName()](#CabalDetails+getLocalName) ⇒ string 577 | * [.joinChannel(channel)](#CabalDetails+joinChannel) 578 | * [.leaveChannel(channel)](#CabalDetails+leaveChannel) 579 | * [.archiveChannel(channel, [reason], cb(err))](#CabalDetails+archiveChannel) 580 | * [.unarchiveChannel(channel, [reason], cb(err))](#CabalDetails+unarchiveChannel) 581 | * [.getUsers()](#CabalDetails+getUsers) ⇒ object 582 | * [._destroy()](#CabalDetails+_destroy) 583 | * ["update"](#CabalDetails+event_update) 584 | * ["init"](#CabalDetails+event_init) 585 | * ["user-updated"](#CabalDetails+event_user-updated) 586 | * ["new-channel"](#CabalDetails+event_new-channel) 587 | * ["new-message"](#CabalDetails+event_new-message) 588 | * ["private-message"](#CabalDetails+event_private-message) 589 | * ["publish-message"](#CabalDetails+event_publish-message) 590 | * ["publish-private-message"](#CabalDetails+event_publish-private-message) 591 | * ["publish-nick"](#CabalDetails+event_publish-nick) 592 | * ["status-message"](#CabalDetails+event_status-message) 593 | * ["topic"](#CabalDetails+event_topic) 594 | * ["channel-focus"](#CabalDetails+event_channel-focus) 595 | * ["channel-join"](#CabalDetails+event_channel-join) 596 | * ["channel-leave"](#CabalDetails+event_channel-leave) 597 | * ["cabal-focus"](#CabalDetails+event_cabal-focus) 598 | * ["started-peering"](#CabalDetails+event_started-peering) 599 | * ["stopped-peering"](#CabalDetails+event_stopped-peering) 600 | * ["update"](#CabalDetails+event_update) 601 | * ["info"](#CabalDetails+event_info) 602 | 603 | 604 | * * * 605 | 606 | 607 | 608 | ### new CabalDetails({, done) 609 | **Params** 610 | 611 | - { object - cabal , commands, aliases } 612 | - done function - the function to be called after the cabal is initialized 613 | 614 | 615 | * * * 616 | 617 | 618 | 619 | ### cabalDetails.processLine([line], [cb]) 620 | Interpret a line of input from the user. 621 | This may involve running a command or publishing a message to the current 622 | channel. 623 | 624 | **Params** 625 | 626 | - *line* string - input from the user 627 | - *cb* function - callback called when the input is processed 628 | 629 | 630 | * * * 631 | 632 | 633 | 634 | ### cabalDetails.publishMessage(msg, [opts], [cb]) 635 | Publish a message up to consumer. See 636 | [`cabal-core`](https://github.com/cabal-club/cabal-core/) 637 | for the full list of options. 638 | 639 | **Params** 640 | 641 | - msg object - the full message object 642 | - *opts* object - options passed down to cabal.publish 643 | - *cb* function - callback function called when message is published 644 | 645 | **Example** 646 | ```js 647 | cabalDetails.publishMessage({ 648 | type: 'chat/text', 649 | content: { 650 | text: 'hello world', 651 | channel: 'cabal-dev' 652 | } 653 | }) 654 | ``` 655 | 656 | * * * 657 | 658 | 659 | 660 | ### cabalDetails.publishNick(nick, [cb]) 661 | Announce a new nickname. 662 | 663 | **Params** 664 | 665 | - nick string 666 | - *cb* function - will be called after the nick is published 667 | 668 | 669 | * * * 670 | 671 | 672 | 673 | ### cabalDetails.publishChannelTopic([channel], topic, cb) 674 | Publish a new channel topic to `channel`. 675 | 676 | **Params** 677 | 678 | - *channel* string = "this.chname" 679 | - topic string 680 | - cb function - will be called when publishing has finished. 681 | 682 | 683 | * * * 684 | 685 | 686 | 687 | ### cabalDetails.getTopic([channel]) ⇒ string 688 | **Returns**: string - The current topic of `channel` as a string 689 | **Params** 690 | 691 | - *channel* string = "this.chname" 692 | 693 | 694 | * * * 695 | 696 | 697 | 698 | ### cabalDetails.getChannelMembers([channel]) ⇒ Array.<object> 699 | Return the list of users that have joined `channel`. 700 | Note: this can be a subset of all of the users in a cabal. 701 | 702 | **Params** 703 | 704 | - *channel* string = "this.chname" 705 | 706 | 707 | * * * 708 | 709 | 710 | 711 | ### cabalDetails.addStatusMessage(message, [channel]) 712 | Add a status message, visible locally only. 713 | 714 | **Params** 715 | 716 | - message object 717 | - *channel* string = "this.chname" 718 | 719 | 720 | * * * 721 | 722 | 723 | 724 | ### cabalDetails.getChannels([opts]) ⇒ Array.<string> 725 | **Returns**: Array.<string> - a list of all the channels in this cabal. Does not return channels with 0 members. 726 | **Params** 727 | 728 | - *opts* object 729 | 730 | **Properties** 731 | 732 | | Name | Type | Description | 733 | | --- | --- | --- | 734 | | includeArchived | boolean | Determines whether to include archived channels or not. Defaults to false. | 735 | | includePM | boolean | Determines whether to include private message channels or not. Defaults to false. | 736 | | onlyJoined | boolean | Determines whether to limit returned channels to only those that are joined or not. Defaults to false. | 737 | 738 | 739 | * * * 740 | 741 | 742 | 743 | ### cabalDetails.getCurrentChannel() ⇒ string 744 | **Returns**: string - The name of the current channel 745 | 746 | * * * 747 | 748 | 749 | 750 | ### cabalDetails.getCurrentChannelDetails() ⇒ ChannelDetails 751 | **Returns**: ChannelDetails - A ChannelDetails object for the current chanel 752 | 753 | * * * 754 | 755 | 756 | 757 | ### cabalDetails.clearVirtualMessages([channel]) 758 | Remove all of the virtual (i.e. status) messages associated with this channel. 759 | Virtual messages are local only. 760 | 761 | **Params** 762 | 763 | - *channel* string = "this.chname" 764 | 765 | 766 | * * * 767 | 768 | 769 | 770 | ### cabalDetails.getPrivateMessageList() 771 | Get the list of currently opened private message channels. 772 | 773 | **Returns{string[]}**: A list of all public keys you have an open PM with (hidden users are removed from list). 774 | 775 | * * * 776 | 777 | 778 | 779 | ### cabalDetails.isChannelPrivate() 780 | Query if the passed in channel name is private or not 781 | 782 | **Returns{boolean}**: true if channel is private, false if not (or if it doesn't exist) 783 | 784 | * * * 785 | 786 | 787 | 788 | ### cabalDetails.joinPrivateMessage(channel) 789 | Join a private message channel if it is not already joined. 790 | 791 | **Params** 792 | 793 | - channel string - the key of the PM to join 794 | 795 | 796 | * * * 797 | 798 | 799 | 800 | ### cabalDetails.leavePrivateMessage(channel) 801 | Leave a private message channel if it has not already been left. 802 | 803 | **Params** 804 | 805 | - channel string - the key of the PM to leave 806 | 807 | 808 | * * * 809 | 810 | 811 | 812 | ### cabalDetails.publishPrivateMessage(msg, recipientKey, [cb]) 813 | Send a private message to a recipient. Open and focus a new private message channel if one doesn't exist already. 814 | 815 | **Params** 816 | 817 | - msg string - a message object conforming to any type of chat message (e.g. `chat/text` or `chat/emote`), 818 | see CabalDetails.publishMessage for more information 819 | - recipientKey string - the public key of the recipient 820 | - *cb* function - optional callback triggered after trying to publish (returns err if failed) 821 | 822 | 823 | * * * 824 | 825 | 826 | 827 | ### cabalDetails.getJoinedChannels() ⇒ Array.<string> 828 | **Returns**: Array.<string> - A list of all of the channel names the user has joined. Excludes private message channels. 829 | 830 | * * * 831 | 832 | 833 | 834 | ### cabalDetails.getLocalUser() ⇒ user 835 | **Returns**: user - The local user for this cabal. 836 | 837 | * * * 838 | 839 | 840 | 841 | ### cabalDetails.getLocalName() ⇒ string 842 | **Returns**: string - The local user's username (or their truncated public key, if their 843 | username is not set) 844 | 845 | * * * 846 | 847 | 848 | 849 | ### cabalDetails.joinChannel(channel) 850 | Join a channel. This is distinct from focusing a channel, as this actually tracks changes 851 | and publishes a message announcing that you have joined the channel 852 | 853 | **Params** 854 | 855 | - channel string 856 | 857 | 858 | * * * 859 | 860 | 861 | 862 | ### cabalDetails.leaveChannel(channel) 863 | Leave a joined channel. This publishes a message announcing 864 | that you have left the channel. 865 | 866 | **Params** 867 | 868 | - channel string 869 | 870 | 871 | * * * 872 | 873 | 874 | 875 | ### cabalDetails.archiveChannel(channel, [reason], cb(err)) 876 | Archive a channel. Publishes a message announcing 877 | that you have archived the channel, applying it to the views of others who have you as a moderator/admin. 878 | 879 | **Params** 880 | 881 | - channel string 882 | - *reason* string 883 | - cb(err) function - callback invoked when the operation has finished, with error as its only parameter 884 | 885 | 886 | * * * 887 | 888 | 889 | 890 | ### cabalDetails.unarchiveChannel(channel, [reason], cb(err)) 891 | Unarchive a channel. Publishes a message announcing 892 | that you have unarchived the channel. 893 | 894 | **Params** 895 | 896 | - channel string 897 | - *reason* string 898 | - cb(err) function - callback invoked when the operation has finished, with error as its only parameter 899 | 900 | 901 | * * * 902 | 903 | 904 | 905 | ### cabalDetails.getUsers() ⇒ object 906 | **Returns**: object - all of the users in this cabal. Each key is the public key of its 907 | corresponding user. 908 | 909 | * * * 910 | 911 | 912 | 913 | ### cabalDetails.\_destroy() 914 | Destroy all of the listeners associated with this `details` instance 915 | 916 | 917 | * * * 918 | 919 | 920 | 921 | ### "update" 922 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 923 | **Properties** 924 | 925 | | Name | Type | Description | 926 | | --- | --- | --- | 927 | | local | boolean | | 928 | | online | boolean | | 929 | | name | string | The user's username | 930 | | key | string | The user's public key | 931 | | flags | Map.<string, string> | The user's array of flags per channel ("@" means cabal-wide"). Possible flags include {"admin", "mod", "normal", "hide", "mute", "block"}. | 932 | 933 | 934 | * * * 935 | 936 | 937 | 938 | ### "init" 939 | Fires when the cabal has finished initialization 940 | 941 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 942 | 943 | * * * 944 | 945 | 946 | 947 | ### "user-updated" 948 | Fires when a user has updated their nickname 949 | 950 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 951 | **Properties** 952 | 953 | | Name | Type | Description | 954 | | --- | --- | --- | 955 | | key | string | Public key of the updated user | 956 | | user | object | Object containing user information | 957 | | user.name | string | Current nickname of the updated user | 958 | 959 | 960 | * * * 961 | 962 | 963 | 964 | ### "new-channel" 965 | Fires when a new channel has been created 966 | 967 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 968 | **Properties** 969 | 970 | | Name | Type | Description | 971 | | --- | --- | --- | 972 | | channel | string | Name of the created channel | 973 | 974 | 975 | * * * 976 | 977 | 978 | 979 | ### "new-message" 980 | Fires when a new message has been posted 981 | 982 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 983 | **Properties** 984 | 985 | | Name | Type | Description | 986 | | --- | --- | --- | 987 | | channel | string | Name of the channel the message was posted to | 988 | | author | object | Object containing the user that posted the message | 989 | | author.name | string | Nickname of the user | 990 | | author.key | string | Public key of the user | 991 | | author.local | boolean | True if user is the local user (i.e. at the keyboard and not someone else in the cabal) | 992 | | author.online | boolean | True if the user is currently online | 993 | | message | object | The message that was posted. See `cabal-core` for more complete message documentation. | 994 | | message.key | string | Public key of the user posting the message (again, it's a quirk) | 995 | | message.seq | number | Sequence number of the message in the user's append-only log | 996 | | message.value | object | Message content, see `cabal-core` documentation for more information. | 997 | 998 | 999 | * * * 1000 | 1001 | 1002 | 1003 | ### "private-message" 1004 | Fires when a new private message has been posted 1005 | 1006 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1007 | **Properties** 1008 | 1009 | | Name | Type | Description | 1010 | | --- | --- | --- | 1011 | | channel | string | The public key corresponding to the private message channel | 1012 | | author | object | Object containing the user that posted the message | 1013 | | author.name | string | Nickname of the user | 1014 | | author.key | string | Public key of the user | 1015 | | author.local | boolean | True if user is the local user (i.e. at the keyboard and not someone else in the cabal) | 1016 | | author.online | boolean | True if the user is currently online | 1017 | | message | object | The message that was posted. See `cabal-core` for more complete message documentation. | 1018 | | message.key | string | Public key of the user posting the message (again, it's a quirk) | 1019 | | message.seq | number | Sequence number of the message in the user's append-only log | 1020 | | message.value | object | Message content, see `cabal-core` documentation for more information. | 1021 | 1022 | 1023 | * * * 1024 | 1025 | 1026 | 1027 | ### "publish-message" 1028 | Fires when the local user has published a new message 1029 | 1030 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1031 | **Properties** 1032 | 1033 | | Name | Type | Description | 1034 | | --- | --- | --- | 1035 | | message | object | The message that was posted. See `cabal-core` for more complete message documentation. | 1036 | | message.type | string | Message type that was posted, e.g. `chat/text` or `chat/emote` | 1037 | | message.content | string | Message contents, e.g. channel and text if `chat/text` | 1038 | | message.timestamp | number | The time the message was published | 1039 | 1040 | 1041 | * * * 1042 | 1043 | 1044 | 1045 | ### "publish-private-message" 1046 | Fires when the local user has published a new private message 1047 | 1048 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1049 | **Properties** 1050 | 1051 | | Name | Type | Description | 1052 | | --- | --- | --- | 1053 | | message | object | The message that was posted. See `cabal-core` for more complete message documentation. | 1054 | | message.type | string | Message type that was posted, e.g. `chat/text` or `chat/emote` | 1055 | | message.content | string | Message contents, e.g. channel and text if `chat/text` | 1056 | | message.timestamp | number | The time the message was published | 1057 | 1058 | 1059 | * * * 1060 | 1061 | 1062 | 1063 | ### "publish-nick" 1064 | Fires when the local user has published a new nickname 1065 | 1066 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1067 | **Properties** 1068 | 1069 | | Name | Type | Description | 1070 | | --- | --- | --- | 1071 | | name | string | The nickname that was published | 1072 | 1073 | 1074 | * * * 1075 | 1076 | 1077 | 1078 | ### "status-message" 1079 | Fires when a status message has been created. These are only visible by the local user. 1080 | 1081 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1082 | **Properties** 1083 | 1084 | | Name | Type | Description | 1085 | | --- | --- | --- | 1086 | | channel | string | Name of the channel the message was published to | 1087 | | message | object | | 1088 | | message.timestamp | number | Publish timestamp | 1089 | | message.text | string | The published status message contents | 1090 | 1091 | 1092 | * * * 1093 | 1094 | 1095 | 1096 | ### "topic" 1097 | Fires when a new channel topic has been set 1098 | 1099 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1100 | **Properties** 1101 | 1102 | | Name | Type | Description | 1103 | | --- | --- | --- | 1104 | | channel | string | Name of the channel with the new topic | 1105 | | topic | string | Name of the channel with the new topic | 1106 | 1107 | 1108 | * * * 1109 | 1110 | 1111 | 1112 | ### "channel-focus" 1113 | Fires when the user has focused (i.e. switched to) a new channel 1114 | 1115 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1116 | **Properties** 1117 | 1118 | | Name | Type | Description | 1119 | | --- | --- | --- | 1120 | | channel | string | Name of the focused channel | 1121 | 1122 | 1123 | * * * 1124 | 1125 | 1126 | 1127 | ### "channel-join" 1128 | Fires when a user has joined a channel 1129 | 1130 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1131 | **Properties** 1132 | 1133 | | Name | Type | Description | 1134 | | --- | --- | --- | 1135 | | channel | string | Name of the joined channel | 1136 | | key | string | Public key of the user joining the channel | 1137 | | isLocal | boolean | True if it was the local user joining a new channel | 1138 | 1139 | 1140 | * * * 1141 | 1142 | 1143 | 1144 | ### "channel-leave" 1145 | Fires when a user has leaveed a channel 1146 | 1147 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1148 | **Properties** 1149 | 1150 | | Name | Type | Description | 1151 | | --- | --- | --- | 1152 | | channel | string | Name of the leaved channel | 1153 | | key | string | Public key of the user leaving the channel | 1154 | | isLocal | boolean | True if it was the local user leaving a new channel | 1155 | 1156 | 1157 | * * * 1158 | 1159 | 1160 | 1161 | ### "cabal-focus" 1162 | Fires when another cabal has been focused 1163 | 1164 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1165 | **Properties** 1166 | 1167 | | Name | Type | Description | 1168 | | --- | --- | --- | 1169 | | key | string | Key of the focused cabal | 1170 | 1171 | 1172 | * * * 1173 | 1174 | 1175 | 1176 | ### "started-peering" 1177 | Fires when the local user has connected directly with another peer 1178 | 1179 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1180 | **Properties** 1181 | 1182 | | Name | Type | Description | 1183 | | --- | --- | --- | 1184 | | key | string | Public key of the other peer | 1185 | | name- | string | Name of the other peer | 1186 | 1187 | 1188 | * * * 1189 | 1190 | 1191 | 1192 | ### "stopped-peering" 1193 | Fires when the local user has disconnected with another peer 1194 | 1195 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1196 | **Properties** 1197 | 1198 | | Name | Type | Description | 1199 | | --- | --- | --- | 1200 | | key | string | Public key of the other peer | 1201 | | name- | string | Name of the other peer | 1202 | 1203 | 1204 | * * * 1205 | 1206 | 1207 | 1208 | ### "update" 1209 | Fires when any kind of change has happened to the cabal. 1210 | 1211 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1212 | 1213 | * * * 1214 | 1215 | 1216 | 1217 | ### "info" 1218 | Fires when a valid slash-command (/) emits output. See src/commands.js for all commands & their payloads. 1219 | 1220 | **Kind**: event emitted by [CabalDetails](#CabalDetails) 1221 | **Properties** 1222 | 1223 | | Name | Type | Description | 1224 | | --- | --- | --- | 1225 | | command | string | The command that triggered the event & has emitted output | 1226 | 1227 | 1228 | * * * 1229 | 1230 | -------------------------------------------------------------------------------- /doc-gen/helpers.js: -------------------------------------------------------------------------------- 1 | /* override helper.params from the default jsdoc template(dmd) 2 | so we can use italics instead of brackets to mark optional parameters */ 3 | 4 | function params (options) { 5 | if (this.params) { 6 | var list = this.params.map(function (param) { 7 | var nameSplit = param.name.split('.') 8 | var name = nameSplit[nameSplit.length - 1] 9 | if (param.variable) name = '...' + name 10 | if (param.optional) name = '*' + name + '*' 11 | return { 12 | indent: ' '.repeat(nameSplit.length - 1), 13 | name: name, 14 | type: param.type, 15 | defaultvalue: param.defaultvalue, 16 | description: param.description, 17 | optional: param.optional 18 | } 19 | }) 20 | return options.fn(list) 21 | } 22 | } 23 | 24 | exports.params = params 25 | -------------------------------------------------------------------------------- /doc-gen/scope.hbs: -------------------------------------------------------------------------------- 1 | {{#if scope}} 2 | {{#if (equal kind "event") ~}} 3 | **Kind**: event emitted{{#if memberof}} by {{>link to=memberof}}{{/if}} 4 | {{/if~}} 5 | {{/if~}} -------------------------------------------------------------------------------- /examples/initialize.js: -------------------------------------------------------------------------------- 1 | var Client = require('../src/client') // normally require('cabal-client') 2 | 3 | const client = new Client() 4 | 5 | // the client is the interface for initializing cabals while 6 | // cabalDetails contains all information and methods for one specific cabal 7 | client.createCabal().then((cabalDetails) => { 8 | // each cabal is an event emitter 9 | cabalDetails.on('init', () => { 10 | console.log('Yay, I\'m ready!') 11 | // the key is the unique identifier of this cabal 12 | console.log('My key: ' + cabalDetails.key) 13 | }) 14 | }) 15 | -------------------------------------------------------------------------------- /examples/receive.js: -------------------------------------------------------------------------------- 1 | var Client = require('../src/client') // normally require('cabal-client') 2 | 3 | // we have two clients in this example, one for sending and one for receiving 4 | const client = new Client() 5 | const client2 = new Client() 6 | 7 | client.createCabal().then((cabalDetails) => { 8 | cabalDetails.on('new-message', ({ channel, author, message }) => { 9 | console.log('Received: "' + message.value.content.text + '" in channel ' + channel) 10 | }) 11 | 12 | cabalDetails.on('init', () => { 13 | client2.addCabal(cabalDetails.key).then((cabalDetails2) => { 14 | // both clients are now connected to the cabal 15 | cabalDetails2.on('init', () => { 16 | // this tells the other clients how we want to be called 17 | cabalDetails2.publishNick('CabalUser10', () => { 18 | // every new cabal has a channel named default 19 | cabalDetails2.publishMessage({ 20 | type: 'chat/text', 21 | content: { 22 | text: 'Hey there!', 23 | channel: 'default' 24 | } 25 | }) 26 | 27 | // other channels will be created when we start using them 28 | cabalDetails2.publishMessage({ 29 | type: 'chat/text', 30 | content: { 31 | text: 'People call me ' + cabalDetails2.getLocalName(), 32 | channel: 'introduction' 33 | } 34 | }) 35 | }) 36 | }) 37 | }) 38 | }) 39 | }) 40 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./src/client') 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cabal-client", 3 | "description": "helper module for cabal clients", 4 | "author": "Cabal Club", 5 | "version": "8.0.2", 6 | "repository": { 7 | "url": "git://github.com/cabal-club/cabal-client.git" 8 | }, 9 | "homepage": "https://github.com/cabal-club/cabal-client", 10 | "bugs": "https://github.com/cabal-club/cabal-client/issues", 11 | "main": "index.js", 12 | "browser": { 13 | "mkdirp": false, 14 | "./src/storage-node.js": "./src/storage-browser.js" 15 | }, 16 | "scripts": { 17 | "test": "tape test/*.js", 18 | "lint": "standard", 19 | "doc": "jsdoc2md --files src/client.js src/cabal-details.js --param-list-format list --separators --partial doc-gen/scope.hbs --helper doc-gen/helpers.js > api.md", 20 | "build": "browserify index.js --standalone CabalClient > bundle.js", 21 | "changelog:patch": "hallmark bump patch -i api.md", 22 | "changelog:minor": "hallmark bump minor -i api.md", 23 | "changelog:major": "hallmark bump major -i api.md", 24 | "changelog:fix": "hallmark --fix README.md CHANGELOG.md" 25 | }, 26 | "keywords": [], 27 | "dependencies": { 28 | "cabal-core": "^16.0.2", 29 | "collect-stream": "^1.2.1", 30 | "dat-dns": "^4.1.2", 31 | "debug": "^4.1.1", 32 | "hypercore-crypto": "^2.1.0", 33 | "js-yaml": "^4.1.0", 34 | "level": "^6.0.1", 35 | "memdb": "^1.3.1", 36 | "mkdirp": "^1.0.4", 37 | "monotonic-timestamp": "0.0.9", 38 | "paperslip": "^3.1.0", 39 | "pump": "^3.0.0", 40 | "qrcode": "^1.4.4", 41 | "random-access-memory": "^3.1.1", 42 | "random-access-web": "^2.0.3", 43 | "strftime": "^0.10.0", 44 | "to2": "^1.0.0" 45 | }, 46 | "devDependencies": { 47 | "browserify": "^17.0.0", 48 | "hallmark": "^3.1.0", 49 | "jsdoc-to-markdown": "^5.0.2", 50 | "rimraf": "^3.0.2", 51 | "standard": "~12.0.0", 52 | "tape": "~4.9.1", 53 | "tmp": "^0.2.1" 54 | }, 55 | "license": "AGPL-3.0-or-later" 56 | } 57 | -------------------------------------------------------------------------------- /src/cabal-details.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events') 2 | const Cabal = require('cabal-core') 3 | const debug = require('debug')('cabal-client') 4 | const { VirtualChannelDetails, ChannelDetails, PMChannelDetails } = require('./channel-details') 5 | const User = require('./user') 6 | const to = require('to2') 7 | const pump = require('pump') 8 | const Moderation = require('./moderation') 9 | const timestamp = require('monotonic-timestamp') 10 | const collect = require('collect-stream') 11 | const init = require('./initialization-callbacks') 12 | const { nextTick } = process 13 | 14 | /** 15 | * @typedef user 16 | * @property {boolean} local 17 | * @property {boolean} online 18 | * @property {string} name The user's username 19 | * @property {string} key The user's public key 20 | * @property {Map} flags The user's array of flags per channel 21 | * ("@" means cabal-wide"). Possible flags include 22 | * {"admin", "mod", "normal", "hide", "mute", "block"}. 23 | * 24 | * @event CabalDetails#update 25 | * @type {CabalDetails} 26 | */ 27 | 28 | class CabalDetails extends EventEmitter { 29 | /** 30 | * 31 | * @constructor 32 | * @fires CabalDetails#update 33 | * @fires CabalDetails#init 34 | * @fires CabalDetails#info 35 | * @fires CabalDetails#user-updated 36 | * @fires CabalDetails#new-channel 37 | * @fires CabalDetails#new-message 38 | * @fires CabalDetails#private-message 39 | * @fires CabalDetails#publish-message 40 | * @fires CabalDetails#publish-private-message 41 | * @fires CabalDetails#publish-nick 42 | * @fires CabalDetails#status-message 43 | * @fires CabalDetails#topic 44 | * @fires CabalDetails#channel-focus 45 | * @fires CabalDetails#channel-join 46 | * @fires CabalDetails#channel-leave 47 | * @fires CabalDetails#cabal-focus 48 | * @fires CabalDetails#started-peering 49 | * @fires CabalDetails#stopped-peering 50 | * @param {object} { cabal , commands, aliases } 51 | * @param {function} done the function to be called after the cabal is initialized 52 | */ 53 | constructor ({ cabal, client, commands, aliases }, done) { 54 | super() 55 | this._cabal = cabal 56 | this.core = cabal 57 | this.client = client 58 | this._commands = commands || {} 59 | this._aliases = aliases || {} 60 | /* _res takes a command (cabal event type, a string) and returns an object with the functions: info, error, end */ 61 | this._res = function (command) { // command: the type of event emitting information (e.g. channel-join, new-message, topic etc) 62 | let seq = 0 // tracks # of sent info messages 63 | const uid = `${timestamp()}` // id uniquely identifying this stream of events 64 | return { 65 | info: (msg, obj) => { 66 | let payload = (typeof msg === "string") ? { text: msg } : { ...msg } 67 | if (typeof obj !== "undefined") payload = { ...payload, ...obj } 68 | payload["meta"] = { uid, command, seq: seq++ } 69 | 70 | this._emitUpdate('info', payload) 71 | }, 72 | error: (err) => { 73 | this._emitUpdate('error', err) 74 | }, 75 | end: () => { 76 | // emits an event to indicate the command has finished 77 | this._emitUpdate('end', { uid, command, seq }) 78 | } 79 | } 80 | } 81 | this.key = cabal.key 82 | this.moderation = new Moderation(this.core) 83 | 84 | this.channels = { 85 | '!status': new VirtualChannelDetails('!status') 86 | } 87 | this.chname = '!status' 88 | this.channel = this.chname // alias for commands. keep chname for backwards compat 89 | this.showIds = false 90 | 91 | this.name = '' 92 | this.topic = '' 93 | this.users = {} // public keys -> cabal-core use 94 | this.listeners = [] // keep track of listeners so we can remove them when we remove a cabal 95 | this.user = undefined 96 | this.settings = client.getCabalSettings(this.key) 97 | this._initialize(done) 98 | } 99 | 100 | _handleMention (message) { 101 | if (message.value.type !== 'chat/text') return null 102 | const name = this.user.name || this.user.key.slice(0, 8) 103 | const line = message.value.content.text.trim() 104 | // a direct mention is if you're mentioned at the start of the message 105 | // an indirect (or not direct) mention is if you're mentioned somewhere in the message 106 | const directMention = (line.slice(0, name.length) === name) 107 | message.directMention = directMention 108 | return line.includes(name) ? message : null 109 | } 110 | 111 | messageListener (message) { 112 | let channel = message.value.content.channel 113 | const mention = this._handleMention(message) 114 | if (message.value.private) { 115 | const isPrivate = message.value.private 116 | if (isPrivate || isPrivate === "true") { 117 | // PM channel should always be that of the pubkey that we are chatting with 118 | // (and not our own pubkey—unless we are chattin with ourselves, bien sûr) 119 | channel = this.user.key === message.key ? channel : message.key 120 | const details = this.channels[channel] 121 | if (!details) { // incoming PM & no pm channel?! instantiate a pm channel asap! 122 | this.channels[channel] = new PMChannelDetails(this, this.core, channel) 123 | // join it by default (separate setting to control this behaviour to be introduced) 124 | this.joinPrivateMessage(channel) 125 | } 126 | this._emitUpdate('private-message', { 127 | channel, 128 | author: this.users[message.key] || { key: message.key, name: message.key, local: false, online: false }, 129 | message: Object.assign({}, message) 130 | }) 131 | } 132 | } 133 | 134 | this.channels[channel].handleMessage(message) 135 | if (mention) this.channels[channel].addMention(message) 136 | 137 | this._emitUpdate('new-message', { 138 | channel, 139 | author: this.users[message.key] || { key: message.key, name: message.key, local: false, online: false }, 140 | message: Object.assign({}, message) 141 | }) 142 | } 143 | 144 | /** 145 | * Interpret a line of input from the user. 146 | * This may involve running a command or publishing a message to the current 147 | * channel. 148 | * @param {string} [line] input from the user 149 | * @param {function} [cb] callback called when the input is processed 150 | */ 151 | processLine (line, cb) { 152 | if (!cb) { cb = noop } 153 | var m = /^\/\s*(\w+)(?:\s+(.*))?/.exec(line.trimRight()) 154 | if (m && this._commands[m[1]] && typeof this._commands[m[1]].call === 'function') { 155 | this._commands[m[1]].call(this, this._res(m[1]), m[2]) 156 | } else if (m && this._aliases[m[1]]) { 157 | var key = this._aliases[m[1]] 158 | if (this._commands[key]) { 159 | this._commands[key].call(this, this._res(key), m[2]) 160 | } else { 161 | this._res("warn").info(`command for alias ${m[1]} => ${key} not found`) 162 | cb() 163 | } 164 | } else if (m) { 165 | this._res("warn").info(`${m[1]} is not a command. type /help for commands`) 166 | } else if (this.chname !== '!status' && /\S/.test(line)) { // disallow typing to !status 167 | this.publishMessage({ 168 | type: 'chat/text', 169 | content: { 170 | channel: this.chname, 171 | text: line.trimRight() 172 | } 173 | }, {}, cb) 174 | } 175 | } 176 | 177 | // publish message up to consumer 178 | /* `message` is of type 179 | { 180 | key: '', 181 | seq: 454, 182 | value: 183 | { 184 | content: { channel: 'testing', text: 'umm well' }, 185 | type: 'chat/text', 186 | timestamp: 1560999208134 187 | } 188 | } 189 | */ 190 | 191 | /** 192 | * Publish a message up to consumer. See 193 | * [`cabal-core`](https://github.com/cabal-club/cabal-core/) 194 | * for the full list of options. 195 | * @param {object} msg the full message object 196 | * @param {object} [opts] options passed down to cabal.publish 197 | * @param {function} [cb] callback function called when message is published 198 | * @example 199 | * cabalDetails.publishMessage({ 200 | * type: 'chat/text', 201 | * content: { 202 | * text: 'hello world', 203 | * channel: 'cabal-dev' 204 | * } 205 | * }) 206 | */ 207 | publishMessage (msg, opts, cb) { 208 | if (!cb) { cb = noop } 209 | if (!msg.content.channel) { 210 | msg.content.channel = this.chname 211 | } 212 | // no typing to !status 213 | if (msg.content.channel === "!status") return cb(new Error("not allowed to post to !status"), null) 214 | if (!msg.type) msg.type = 'chat/text' 215 | 216 | // detect if published-to channel is private, if so change message type & redirect contents 217 | // rationale: we're trying to catch cases where a PM is incorrectly being sent to a public channel 218 | // (i.e. msg.content.channel === a user's pubkey; dis bad, might even be malicious) 219 | // 220 | // note: the latter conditional guards against someone maliciously trying to create a channel conforming 221 | // to an existing-but-not-synced-on-the-local-client public key; implicitly, we now treat all channel names that conform to the public key 222 | // format (64ch hex) as private message channels 223 | if (this.isChannelPrivate(msg.content.channel) || Cabal.isHypercoreKey(msg.content.channel)) { 224 | return this._redirectAsPrivateMessage(msg, opts, cb) 225 | } 226 | this.core.publish(msg, opts, (err, m) => { 227 | this._emitUpdate('publish-message', { message: msg }) 228 | cb(err, m) 229 | }) 230 | } 231 | 232 | /** 233 | * Announce a new nickname. 234 | * @param {string} nick 235 | * @param {function} [cb] will be called after the nick is published 236 | */ 237 | publishNick (nick, cb) { 238 | if (!cb) { cb = noop } 239 | this.core.publishNick(nick, (err) => { 240 | if (err) return cb(err) 241 | this.user.name = nick 242 | this._emitUpdate('publish-nick', { name: nick }) 243 | cb() 244 | }) 245 | } 246 | 247 | /** 248 | * Publish a new channel topic to `channel`. 249 | * @param {string} [channel=this.chname] 250 | * @param {string} topic 251 | * @param {function} cb will be called when publishing has finished. 252 | */ 253 | publishChannelTopic (channel = this.chname, topic, cb) { 254 | if (!cb) { cb = noop } 255 | // make sure we don't publish topic messages for PMs 256 | if (this.channels[channel] && this.channels[channel].isPrivate) { 257 | // TODO (2021-11-17): for the future, look into setting up a pipeline for handling topics on encrypted/PM channels 258 | return nextTick(cb, new Error("setting topics on PMs is currently not enabled—sorry!")) 259 | } 260 | this.core.publishChannelTopic(channel, topic, cb) 261 | } 262 | 263 | /** 264 | * @param {string} [channel=this.chname] 265 | * @returns {string} The current topic of `channel` as a string 266 | */ 267 | getTopic (channel = this.chname) { 268 | return this.channels[channel].topic || '' 269 | } 270 | 271 | /** 272 | * Return the list of users that have joined `channel`. 273 | * Note: this can be a subset of all of the users in a cabal. 274 | * @param {string} [channel=this.chname] 275 | * @returns {object[]} 276 | */ 277 | getChannelMembers (channel = this.chname) { 278 | var details = this.channels[channel] 279 | if (!details) return [] 280 | if (channel === '!status') return this.getUsers() 281 | return details.getMembers().map((ukey) => this.users[ukey]).filter((u) => u) 282 | } 283 | 284 | focusChannel (channel = this.chname, keepUnread = false) { 285 | let currentChannel = this.channels[this.chname] 286 | if (channel === currentChannel.name) return // don't focus the already focused channel 287 | if (currentChannel) { 288 | // mark previous as read 289 | if (!keepUnread) currentChannel.markAsRead() 290 | currentChannel.unfocus() 291 | } 292 | this.chname = channel 293 | this.channel = this.chname 294 | currentChannel = this.channels[channel] 295 | // mark new channel as read 296 | if (!keepUnread) currentChannel.markAsRead() 297 | currentChannel.focus() 298 | this._emitUpdate('channel-focus', { channel }) 299 | } 300 | 301 | unfocusChannel (channel = this.chname, newChannel) { 302 | this.channels[channel].unfocus() 303 | // open a new channel after closing `channel` 304 | if (newChannel) this.focusChannel(newChannel) 305 | } 306 | 307 | /** 308 | * Add a status message, visible locally only. 309 | * @param {object} message 310 | * @param {string} [channel=this.chname] 311 | */ 312 | addStatusMessage (message, channel = this.chname) { 313 | if (!this.channels[channel]) return 314 | debug(channel) 315 | this.channels[channel].addVirtualMessage(message) 316 | this._emitUpdate('status-message', { channel, message }) 317 | } 318 | 319 | /** 320 | * @param {object} [opts] 321 | * @property {boolean} includeArchived - Determines whether to include archived channels or not. Defaults to false. 322 | * @property {boolean} includePM - Determines whether to include private message channels or not. Defaults to false. 323 | * @property {boolean} onlyJoined - Determines whether to limit returned channels to only those that are joined or not. Defaults to false. 324 | * @returns {string[]} a list of all the channels in this cabal. Does not return channels with 0 members. 325 | */ 326 | getChannels (opts) { 327 | if (!opts || typeof opts !== "object" || opts[Symbol.iterator]) { 328 | opts = { includeArchived: false, includePM: false, onlyJoined: false} 329 | } 330 | // sort regular channels and PMs separately, then concat them together (if including PM) before returning 331 | const sortedChannels = Object.keys(this.channels) 332 | .filter(ch => 333 | ch != "!status" /* exclude status, it's included later */ 334 | && this.channels[ch].members.size > 0 335 | && (!this.channels[ch].isPrivate) 336 | && (opts.includeArchived || !this.channels[ch].archived) 337 | && (!opts.onlyJoined || opts.onlyJoined && this.channels[ch].joined) 338 | ) 339 | .sort() 340 | // get all PMs with non-hidden users && sort them 341 | const sortedPMs = Object.keys(this.channels) 342 | .filter(ch => this.channels[ch].isPrivate && this.channels[ch].joined && !this.users[ch].isHidden()) 343 | .sort() 344 | return Array.prototype.concat(["!status"], opts.includePM ? sortedPMs : [], sortedChannels) 345 | } 346 | 347 | // returns a ChannelDetails object 348 | getChannel (channel = this.chname) { 349 | return this.channels[channel] 350 | } 351 | 352 | /** 353 | * @returns {string} The name of the current channel 354 | */ 355 | getCurrentChannel () { 356 | return this.chname 357 | } 358 | 359 | /** 360 | * @returns {ChannelDetails} A ChannelDetails object for the current chanel 361 | */ 362 | getCurrentChannelDetails () { 363 | return this.channels[this.chname] 364 | } 365 | 366 | /** 367 | * Remove all of the virtual (i.e. status) messages associated with this channel. 368 | * Virtual messages are local only. 369 | * @param {string} [channel=this.chname] 370 | */ 371 | clearVirtualMessages (channel = this.chname) { 372 | return this.channels[channel].clearVirtualMessages() 373 | } 374 | 375 | /** 376 | * Get the list of currently opened private message channels. 377 | * @returns{string[]} A list of all public keys you have an open PM with (hidden users are removed from list). 378 | */ 379 | getPrivateMessageList () { 380 | return Object.keys(this.channels).filter(ch => this.channels[ch].isPrivate && (ch in this.users && !this.users[ch].isHidden())) 381 | } 382 | 383 | /** 384 | * Query if the passed in channel name is private or not 385 | * @returns{boolean} true if channel is private, false if not (or if it doesn't exist) 386 | */ 387 | isChannelPrivate (channel) { 388 | const details = this.channels[channel] 389 | if (!details) { return false } 390 | return details.isPrivate 391 | } 392 | 393 | /** 394 | * Join a private message channel if it is not already joined. 395 | * @param {string} channel the key of the PM to join 396 | */ 397 | joinPrivateMessage (channel) { 398 | this.settings.joinedPrivateMessages.push(channel) 399 | this.settings.joinedPrivateMessages = Array.from(new Set(this.settings.joinedPrivateMessages)) // dedupe array entries 400 | this.client.writeCabalSettings(this.key, this.settings) 401 | } 402 | 403 | /** 404 | * Leave a private message channel if it has not already been left. 405 | * @param {string} channel the key of the PM to leave 406 | */ 407 | leavePrivateMessage (channel) { 408 | if (this.settings.joinedPrivateMessages.includes(channel)) { 409 | // Remove the private message from the joined setting 410 | this.settings.joinedPrivateMessages = this.settings.joinedPrivateMessages.filter((pm) => pm !== channel) 411 | } 412 | this.client.writeCabalSettings(this.key, this.settings) 413 | } 414 | 415 | // redirects private messages posted via cabalDetails.publishMessage() 416 | _redirectAsPrivateMessage (msg, opts, cb) { 417 | const recipient = msg.content.channel 418 | switch (msg.type) { 419 | case "chat/emote": 420 | case "chat/text": 421 | // these types are definitely supported : ) 422 | break 423 | default: 424 | debug("redirectAsPM received msg type", msg.content.type) 425 | return cb(new Error("private messages currently lacks support for message type: " + msg.type)) 426 | break 427 | } 428 | this.publishPrivateMessage(msg, recipient, cb) 429 | } 430 | /** 431 | * Send a private message to a recipient. Open and focus a new private message channel if one doesn't exist already. 432 | * @param {string} msg - a message object conforming to any type of chat message (e.g. `chat/text` or `chat/emote`), 433 | * see CabalDetails.publishMessage for more information 434 | * @param {string} recipientKey - the public key of the recipient 435 | * @param {function} [cb] - optional callback triggered after trying to publish (returns err if failed) 436 | */ 437 | publishPrivateMessage (msg, recipientKey, cb) { 438 | if (!cb) cb = noop 439 | // validate that the recipientKey exactly matches the requirements imposed on user public keys 440 | if (!Cabal.isHypercoreKey(recipientKey)) { 441 | return cb(new Error("tried to publish a private message to a key that does not match the public key format")) 442 | } 443 | // check to see make sure we know of a user with recipientKey 444 | if (!recipientKey in this.users) { 445 | return cb(new Error("tried to publish a private message to unknown public key")) 446 | } 447 | // check to see if we have opened a pm with this person before 448 | if (!this.channels[recipientKey]) { 449 | // if not: add a new PMChannelDetails instance to channels 450 | this.channels[recipientKey] = new PMChannelDetails(this, this.core, recipientKey) 451 | } 452 | let pmInstance = this.channels[recipientKey] 453 | // focus it if we're opening a new PM (or reopening a previously closed instance) 454 | if (!pmInstance.joined) { 455 | this.focusChannel(recipientKey) 456 | this.joinPrivateMessage(recipientKey) 457 | } 458 | if (!pmInstance.isPrivate) { // pm channel is not an actual pm instance! this should probably never happen, though 459 | return cb(new Error("tried to publish a private message to a non-private message channel")) 460 | } 461 | 462 | // publish message to cabal-core, where it will be encrypted 463 | this.core.publishPrivate(msg, recipientKey, (err) => { 464 | // publishing failed somehow 465 | if (err) { 466 | return cb(err) 467 | } 468 | this._emitUpdate('publish-private-message', { ...msg }) 469 | cb() 470 | }) 471 | } 472 | 473 | /** 474 | * @returns {string[]} A list of all of the channel names the user has joined. Excludes private message channels. 475 | */ 476 | getJoinedChannels () { 477 | return Object.keys(this.channels).filter(c => this.channels[c].joined && !this.channels[c].isPrivate).sort() 478 | } 479 | 480 | /** 481 | * @returns {user} The local user for this cabal. 482 | */ 483 | getLocalUser () { 484 | return this.user 485 | } 486 | 487 | /** 488 | * @returns {string} The local user's username (or their truncated public key, if their 489 | * username is not set) 490 | */ 491 | getLocalName () { 492 | return this.user.name || this.user.key.slice(0, 8) 493 | } 494 | 495 | /** 496 | * Join a channel. This is distinct from focusing a channel, as this actually tracks changes 497 | * and publishes a message announcing that you have joined the channel 498 | * @param {string} channel 499 | */ 500 | joinChannel (channel, cb) { 501 | if (!cb) cb = noop 502 | if (channel === '@' || /^!/.test(channel)) { 503 | return nextTick(cb, new Error('cannot join invalid channel name')) 504 | } 505 | var details = this.channels[channel] 506 | // disallow joining a channel that is exactly another peer's public key 507 | if ((details && details.isPrivate) || Cabal.isHypercoreKey(channel)) { 508 | if (details && details.isPrivate) { 509 | // the private message already exists, rejoin it 510 | this.joinPrivateMessage(details.recipient) 511 | return nextTick(cb, null) 512 | } else { 513 | return nextTick(cb, new Error("tried to join a new private message channel (start a pm using /pm )")) 514 | } 515 | } 516 | // we created a channel 517 | if (!details) { 518 | details = new ChannelDetails(this.core, channel) 519 | this.channels[channel] = details 520 | } 521 | 522 | // we weren't already in the channel, join 523 | if (!details.join()) { 524 | var joinMsg = { 525 | type: 'channel/join', 526 | content: { channel } 527 | } 528 | // publish a join message to the cabal to signify our presence 529 | this.core.publish(joinMsg, (err) => { 530 | if (err) return cb(err) 531 | // we probably always want to open a joined channel? 532 | this.focusChannel(channel) 533 | return cb(null) 534 | }) 535 | } else nextTick(cb, null) 536 | } 537 | 538 | /** 539 | * Leave a joined channel. This publishes a message announcing 540 | * that you have left the channel. 541 | * @param {string} channel 542 | */ 543 | leaveChannel (channel, cb) { 544 | if (!cb) { cb = noop } 545 | if (typeof channel === 'function') { 546 | cb = channel 547 | channel = this.chname 548 | } else if (!channel) { 549 | channel = this.chname 550 | } 551 | if (channel === '!status') { 552 | return nextTick(cb, new Error('cannot leave the !status channel')) 553 | } 554 | if ((details && details.isPrivate) || Cabal.isHypercoreKey(channel)) { 555 | this.leavePrivateMessage(channel) 556 | // switch back to the !status channel after leaving 557 | this.unfocusChannel(channel, '!status') 558 | cb(null) 559 | return 560 | } 561 | var joined = this.getJoinedChannels() 562 | var details = this.channels[channel] 563 | if (!details) { 564 | return nextTick(cb, new Error('cannot leave a non-existent channel')) 565 | } 566 | var left = details.leave() 567 | // we were in the channel, leave 568 | if (left) { 569 | var leaveMsg = { 570 | type: 'channel/leave', 571 | content: { channel } 572 | } 573 | this.core.publish(leaveMsg, (err) => { 574 | if (err) return cb(err) 575 | var indexOldChannel = joined.indexOf(channel) 576 | var newChannel 577 | // open up another channel if we left the one we were viewing 578 | if (channel === this.chname) { 579 | let newIndex = indexOldChannel + 1 580 | if (indexOldChannel >= joined.length) newIndex = 0 581 | newChannel = joined[newIndex] || '!status' 582 | } 583 | this.unfocusChannel(channel, newChannel) 584 | cb(null) 585 | }) 586 | } 587 | } 588 | 589 | /** 590 | * Archive a channel. Publishes a message announcing 591 | * that you have archived the channel, applying it to the views of others who have you as a moderator/admin. 592 | * @param {string} channel 593 | * @param {string} [reason] 594 | * @param {function} cb(err) - callback invoked when the operation has finished, with error as its only parameter 595 | */ 596 | archiveChannel (channel, reason = "", cb) { 597 | if (!cb) cb = noop 598 | const details = this.channels[channel] 599 | 600 | if (channel === '!status') { 601 | const err = new Error('cannot archive the !status channel') 602 | debug(err) 603 | return nextTick(cb, err) 604 | } 605 | if (!details) { 606 | const err = new Error('cannot archive non-existent channel') 607 | debug(err) 608 | return nextTick(cb, err) 609 | } 610 | if (details.isPrivate) { 611 | return nextTick(cb, new Error('cannot archive private message channels')) 612 | } 613 | this.channels[channel].archive() 614 | this.publishMessage({ 615 | type: 'channel/archive', 616 | content: { 617 | channel, 618 | reason 619 | } 620 | }, {}, cb) 621 | } 622 | 623 | /** 624 | * Unarchive a channel. Publishes a message announcing 625 | * that you have unarchived the channel. 626 | * @param {string} channel 627 | * @param {string} [reason] 628 | * @param {function} cb(err) - callback invoked when the operation has finished, with error as its only parameter 629 | */ 630 | unarchiveChannel (channel, reason = "", cb) { 631 | if (!cb) cb = noop 632 | const details = this.channels[channel] 633 | 634 | if (channel === '!status') { 635 | const err = new Error('cannot unarchive the !status channel') 636 | debug(err) 637 | return nextTick(cb, err) 638 | } 639 | if (!details) { 640 | const err = new Error('cannot unarchive non-existent channel') 641 | debug(err) 642 | return nextTick(cb, err) 643 | } 644 | if (details.isPrivate) { 645 | return nextTick(cb, new Error('cannot archive or unarchive private message channels')) 646 | } 647 | this.channels[channel].unarchive() 648 | this.publishMessage({ 649 | type: 'channel/unarchive', 650 | content: { 651 | channel, 652 | reason 653 | } 654 | }, {}, cb) 655 | } 656 | 657 | isChannelArchived(channel) { 658 | if (!this.channels[channel]) return false 659 | return this.channels[channel].archived 660 | } 661 | 662 | /** 663 | * @returns {object} all of the users in this cabal. Each key is the public key of its 664 | * corresponding user. 665 | */ 666 | getUsers () { 667 | return Object.assign({}, this.users) 668 | } 669 | 670 | /** 671 | * 672 | * Fires when the cabal has finished initialization 673 | * @event CabalDetails#init 674 | */ 675 | 676 | /** 677 | * 678 | * Fires when a user has updated their nickname 679 | * @event CabalDetails#user-updated 680 | * @type {object} 681 | * @property {string} key - Public key of the updated user 682 | * @property {object} user - Object containing user information 683 | * @prop {string} user.name - Current nickname of the updated user 684 | */ 685 | 686 | /** 687 | * 688 | * Fires when a new channel has been created 689 | * @event CabalDetails#new-channel 690 | * @type {object} 691 | * @property {string} channel - Name of the created channel 692 | */ 693 | 694 | /** 695 | * 696 | * Fires when a new message has been posted 697 | * @event CabalDetails#new-message 698 | * @type {object} 699 | * @property {string} channel - Name of the channel the message was posted to 700 | * @property {object} author - Object containing the user that posted the message 701 | * @prop {string} author.name - Nickname of the user 702 | * @prop {string} author.key - Public key of the user 703 | * @prop {boolean} author.local - True if user is the local user (i.e. at the keyboard and not someone else in the cabal) 704 | * @prop {boolean} author.online - True if the user is currently online 705 | * @prop {object} message - The message that was posted. See `cabal-core` for more complete message documentation. 706 | * @prop {string} message.key - Public key of the user posting the message (again, it's a quirk) 707 | * @prop {number} message.seq - Sequence number of the message in the user's append-only log 708 | * @prop {object} message.value - Message content, see `cabal-core` documentation for more information. 709 | * 710 | */ 711 | 712 | /** 713 | * 714 | * Fires when a new private message has been posted 715 | * @event CabalDetails#private-message 716 | * @type {object} 717 | * @property {string} channel - The public key corresponding to the private message channel 718 | * @property {object} author - Object containing the user that posted the message 719 | * @prop {string} author.name - Nickname of the user 720 | * @prop {string} author.key - Public key of the user 721 | * @prop {boolean} author.local - True if user is the local user (i.e. at the keyboard and not someone else in the cabal) 722 | * @prop {boolean} author.online - True if the user is currently online 723 | * @prop {object} message - The message that was posted. See `cabal-core` for more complete message documentation. 724 | * @prop {string} message.key - Public key of the user posting the message (again, it's a quirk) 725 | * @prop {number} message.seq - Sequence number of the message in the user's append-only log 726 | * @prop {object} message.value - Message content, see `cabal-core` documentation for more information. 727 | * 728 | */ 729 | 730 | /** 731 | * 732 | * Fires when the local user has published a new message 733 | * @event CabalDetails#publish-message 734 | * @type {object} 735 | * @prop {object} message - The message that was posted. See `cabal-core` for more complete message documentation. 736 | * @prop {string} message.type - Message type that was posted, e.g. `chat/text` or `chat/emote` 737 | * @prop {string} message.content - Message contents, e.g. channel and text if `chat/text` 738 | * @prop {number} message.timestamp - The time the message was published 739 | * 740 | */ 741 | 742 | /** 743 | * 744 | * Fires when the local user has published a new private message 745 | * @event CabalDetails#publish-private-message 746 | * @type {object} 747 | * @prop {object} message - The message that was posted. See `cabal-core` for more complete message documentation. 748 | * @prop {string} message.type - Message type that was posted, e.g. `chat/text` or `chat/emote` 749 | * @prop {string} message.content - Message contents, e.g. channel and text if `chat/text` 750 | * @prop {number} message.timestamp - The time the message was published 751 | * 752 | */ 753 | 754 | /** 755 | * 756 | * Fires when the local user has published a new nickname 757 | * @event CabalDetails#publish-nick 758 | * @type {object} 759 | * @property {string} name - The nickname that was published 760 | */ 761 | 762 | /** 763 | * 764 | * Fires when a status message has been created. These are only visible by the local user. 765 | * @event CabalDetails#status-message 766 | * @type {object} 767 | * @property {string} channel - Name of the channel the message was published to 768 | * @prop {object} message 769 | * @prop {number} message.timestamp - Publish timestamp 770 | * @prop {string} message.text - The published status message contents 771 | */ 772 | 773 | /** 774 | * 775 | * Fires when a new channel topic has been set 776 | * @event CabalDetails#topic 777 | * @type {object} 778 | * @property {string} channel - Name of the channel with the new topic 779 | * @property {string} topic - Name of the channel with the new topic 780 | */ 781 | 782 | /** 783 | * 784 | * Fires when the user has focused (i.e. switched to) a new channel 785 | * @event CabalDetails#channel-focus 786 | * @type {object} 787 | * @property {string} channel - Name of the focused channel 788 | */ 789 | 790 | /** 791 | * 792 | * Fires when a user has joined a channel 793 | * @event CabalDetails#channel-join 794 | * @type {object} 795 | * @property {string} channel - Name of the joined channel 796 | * @property {string} key - Public key of the user joining the channel 797 | * @property {boolean} isLocal - True if it was the local user joining a new channel 798 | */ 799 | 800 | /** 801 | * 802 | * Fires when a user has leaveed a channel 803 | * @event CabalDetails#channel-leave 804 | * @type {object} 805 | * @property {string} channel - Name of the leaved channel 806 | * @property {string} key - Public key of the user leaving the channel 807 | * @property {boolean} isLocal - True if it was the local user leaving a new channel 808 | */ 809 | 810 | /** 811 | * 812 | * Fires when another cabal has been focused 813 | * @event CabalDetails#cabal-focus 814 | * @type {object} 815 | * @property {string} key - Key of the focused cabal 816 | */ 817 | 818 | /** 819 | * 820 | * Fires when the local user has connected directly with another peer 821 | * @event CabalDetails#started-peering 822 | * @type {object} 823 | * @property {string} key - Public key of the other peer 824 | * @property {string} name- Name of the other peer 825 | */ 826 | 827 | /** 828 | * 829 | * Fires when the local user has disconnected with another peer 830 | * @event CabalDetails#stopped-peering 831 | * @type {object} 832 | * @property {string} key - Public key of the other peer 833 | * @property {string} name- Name of the other peer 834 | */ 835 | 836 | /** 837 | * 838 | * Fires when any kind of change has happened to the cabal. 839 | * @event CabalDetails#update 840 | */ 841 | 842 | /** 843 | * 844 | * Fires when a valid slash-command (/) emits output. See src/commands.js for all commands & their payloads. 845 | * @event CabalDetails#info 846 | * @type {object} 847 | * @property {string} command - The command that triggered the event & has emitted output 848 | */ 849 | 850 | _emitUpdate (type, payload = null) { 851 | this.emit('update', this) 852 | if (type) { 853 | if (payload) { debug('%s %o', type, payload) } else { debug('%s', type) } 854 | this.emit(type, payload) 855 | } else { 856 | debug('update (no assigned type)') 857 | } 858 | } 859 | 860 | registerListener (source, event, listener) { 861 | this.listeners.push({ source, event, listener }) 862 | source.on(event, listener) 863 | } 864 | 865 | /** 866 | * Destroy all of the listeners associated with this `details` instance 867 | */ 868 | _destroy (cb) { 869 | if (!cb) cb = noop 870 | this.listeners.forEach((obj) => { obj.source.removeListener(obj.event, obj.listener) }) 871 | this.core.close(() => { 872 | this.core.db.close(cb) 873 | }) 874 | } 875 | 876 | _initializeLocalUser (cb) { 877 | if (!cb) cb = noop 878 | this.core.getLocalKey((err, lkey) => { 879 | if (err) return cb(err) 880 | this.user = new User() 881 | this.user.key = lkey 882 | this.user.local = true 883 | this.user.online = true 884 | this.users[lkey] = this.user 885 | // try to get more data for user 886 | this.core.users.get(lkey, (err, user) => { 887 | if (err || !user) { 888 | cb(null) 889 | return 890 | } 891 | this.user = new User(user) 892 | // restore `user.local` and `user.online` as they don't come from cabal-core 893 | this.user.key = lkey 894 | this.user.local = true 895 | this.user.online = true 896 | this.users[lkey] = this.user 897 | cb(null) 898 | }) 899 | }) 900 | } 901 | 902 | _initialize (done) { 903 | const cabal = this.core 904 | let finished = 0 905 | let asyncBlocks = 0 906 | 907 | this._finish = () => { 908 | finished += 1 909 | if (finished >= asyncBlocks) done() 910 | } 911 | 912 | const invoke = (self, fn, cb) => { 913 | asyncBlocks += 1 914 | // the line below converts (as an example): 915 | // invoke(cabal.archives, "get", init.getArchivesCallback) 916 | // into: 917 | // cabal.archives.get(getArchivesCallback) 918 | // with proper `this` arguments for the respectively called functions 919 | self[fn].bind(self)(cb.bind(this)) 920 | } 921 | 922 | /* invoke one-time functions to populate & initialize the local state from data on disk */ 923 | invoke(cabal.archives, "get", init.getArchivesCallback) 924 | invoke(cabal, "getLocalKey", init.getLocalKeyCallback) 925 | invoke(cabal.users, "getAll", init.getAllUsersCallback) 926 | invoke(cabal.privateMessages, "list", init.getOpenedPMs) 927 | 928 | /* register all the listeners we'll be using */ 929 | this.registerListener(cabal.users.events, 'update', (key) => { 930 | cabal.users.get(key, (err, user) => { 931 | if (err) return 932 | this.users[key] = new User(Object.assign(this.users[key] || {}, user)) 933 | if (this.user && key === this.user.key) this.user = this.users[key] 934 | this._emitUpdate('user-updated', { key, user }) 935 | }) 936 | }) 937 | 938 | this.registerListener(cabal.topics.events, 'update', (msg) => { 939 | var { channel, text } = msg.value.content 940 | if (!this.channels[channel]) { this.channels[channel] = new ChannelDetails(this.core, channel) } 941 | this.channels[channel].topic = text || '' 942 | this._emitUpdate('topic', { channel, topic: text || '' }) 943 | }) 944 | 945 | this.registerListener(cabal, 'peer-added', (key) => { 946 | if (this.users[key]) { 947 | this.users[key].online = true 948 | } else { 949 | this.users[key] = new User({ key, online: true }) 950 | } 951 | this._emitUpdate('started-peering', { key, name: this.users[key].name || key }) 952 | }) 953 | 954 | this.registerListener(cabal, 'peer-dropped', (key) => { 955 | Object.keys(this.users).forEach((k) => { 956 | if (k === key) { 957 | this.users[k].online = false 958 | } 959 | }) 960 | this._emitUpdate('stopped-peering', { key, name: this.users[key].name || key }) 961 | }) 962 | 963 | // notify when a user has archived a channel 964 | this.registerListener(cabal.archives.events, 'archive', (channel, reason, key) => { 965 | const user = this.users[key] 966 | const isLocal = key === this.user.key 967 | if (!isLocal && (!user || !user.canModerate())) { return } 968 | if (!this.channels[channel]) { 969 | this.channels[channel] = new ChannelDetails(this.core, channel) 970 | } 971 | this.channels[channel].archive() 972 | this._emitUpdate('channel-archive', { channel, reason, key, isLocal }) 973 | }) 974 | 975 | // notify when a user has restored an archived channel 976 | this.registerListener(cabal.archives.events, 'unarchive', (channel, reason, key) => { 977 | const user = this.users[key] 978 | const isLocal = key === this.user.key 979 | if (!isLocal && (!user || !user.canModerate())) { return } 980 | if (!this.channels[channel]) { 981 | this.channels[channel] = new ChannelDetails(this.core, channel) 982 | } 983 | this.channels[channel].unarchive() 984 | this._emitUpdate('channel-unarchive', { channel, reason, key, isLocal }) 985 | }) 986 | 987 | // notify when a user has joined a channel 988 | this.registerListener(cabal.memberships.events, 'add', (channel, user) => { 989 | if (!this.channels[channel]) { 990 | this.channels[channel] = new ChannelDetails(this.core, channel) 991 | } 992 | this.channels[channel].addMember(user) 993 | this._emitUpdate('channel-join', { channel, key: user, isLocal: user === this.user.key }) 994 | }) 995 | 996 | // notify when a user has left a channel 997 | this.registerListener(cabal.memberships.events, 'remove', (channel, user) => { 998 | if (!this.channels[channel]) { 999 | this.channels[channel] = new ChannelDetails(this.core, channel) 1000 | } 1001 | this.channels[channel].removeMember(user) 1002 | this._emitUpdate('channel-leave', { channel, key: user, isLocal: user === this.user.key }) 1003 | }) 1004 | 1005 | // register to be notified of new channels as they are created 1006 | this.registerListener(cabal.channels.events, 'add', (channel) => { 1007 | const details = this.channels[channel] 1008 | if (!details && !Cabal.isHypercoreKey(channel)) { 1009 | this.channels[channel] = new ChannelDetails(cabal, channel) 1010 | } 1011 | // TODO: only do this for our joined channels, instead of all channels 1012 | // Calls fn with every new message that arrives in channel. 1013 | cabal.messages.events.on(channel, this.messageListener.bind(this)) 1014 | this._emitUpdate('new-channel', { channel }) 1015 | }) 1016 | } 1017 | } 1018 | 1019 | function noop () {} 1020 | 1021 | module.exports = CabalDetails 1022 | -------------------------------------------------------------------------------- /src/channel-details.js: -------------------------------------------------------------------------------- 1 | const collect = require('collect-stream') 2 | const timestamp = require('monotonic-timestamp') 3 | const { stableSort, merge } = require('./util') 4 | 5 | class ChannelDetailsBase { 6 | constructor (channelName) { 7 | this.name = channelName 8 | 9 | this.isPrivate = false 10 | this.members = new Set() 11 | this.mentions = [] 12 | /* archived channels are not visible in channel listings */ 13 | this.archived = false 14 | this.virtualMessages = [] 15 | this.newMessageCount = 0 16 | this.datesSeen = new Set() 17 | /* TODO: 18 | use cursor to remember scrollback state and fetch 19 | from leveldb. 20 | maybe store a negative offset to look up? */ 21 | this.lastRead = 0 /* timestamp in epoch time */ 22 | this.joined = false 23 | this.focused = false 24 | this.topic = '' 25 | } 26 | 27 | toString () { 28 | return this.name 29 | } 30 | 31 | archive () { 32 | this.archived = true 33 | } 34 | 35 | unarchive () { 36 | this.archived = false 37 | } 38 | 39 | addMember (key) { 40 | this.members.add(key) 41 | } 42 | 43 | removeMember (key) { 44 | this.members.delete(key) 45 | } 46 | 47 | getMembers () { 48 | return Array.from(this.members) 49 | } 50 | 51 | addMention (mention) { 52 | if (!this.focused) { 53 | this.mentions.push(mention) 54 | } 55 | } 56 | 57 | getMentions () { 58 | return this.mentions.slice() // return copy 59 | } 60 | 61 | handleMessage (message) { 62 | if (!this.focused) { 63 | // ++var is an optimization: 64 | // var++ creates a temporary variable while ++var doesn't 65 | ++this.newMessageCount 66 | } 67 | } 68 | 69 | getNewMessageCount () { 70 | return this.newMessageCount 71 | } 72 | 73 | markAsRead () { 74 | this.lastRead = Date.now() 75 | this.newMessageCount = 0 76 | this.mentions = [] 77 | } 78 | 79 | focus () { 80 | this.focused = true 81 | } 82 | 83 | unfocus () { 84 | this.focused = false 85 | } 86 | 87 | clearVirtualMessages () { 88 | this.virtualMessages = [] 89 | } 90 | 91 | getVirtualMessages (opts) { 92 | const limit = opts.limit 93 | const newerThan = parseFloat(opts.gt || 0) 94 | const olderThan = parseFloat(opts.lt || Infinity) 95 | var filtered = this.virtualMessages.filter((m) => { 96 | return (parseFloat(m.value.timestamp) > newerThan && parseFloat(m.value.timestamp) < olderThan) 97 | }) 98 | return stableSort(filtered, v => parseFloat(v.value.timestamp)).slice(-limit) 99 | } 100 | 101 | interleaveVirtualMessages (messages, opts) { 102 | const virtualMessages = this.getVirtualMessages(opts) 103 | var cmp = (a, b) => { 104 | // sort by timestamp 105 | const diff = parseFloat(a.value.timestamp) - parseFloat(b.value.timestamp) 106 | // if timestamp was the same, and messages are by same author, sort by seqno 107 | if (diff === 0 && 108 | a.key && b.key && a.key === b.key && 109 | a.hasOwnProperty('seq') && b.hasOwnProperty('seq')) { 110 | return a.seq - b.seq 111 | } 112 | return diff 113 | } 114 | return virtualMessages.concat(messages).sort(cmp).slice(-opts.limit) 115 | } 116 | 117 | /* 118 | addVirtualMessage({ timestamp: Date.now(), type: "status", text: "" }}) 119 | */ 120 | addVirtualMessage (msg) { 121 | /* 122 | msg will be on the format of 123 | {timestamp, type, text} 124 | but we convert it to the format that cabal expects messages to conform to 125 | msg = { 126 | key: '' 127 | value: { 128 | timestamp: '' 129 | type: '' 130 | content: { 131 | text: '' 132 | } 133 | } 134 | } 135 | */ 136 | if (!msg.value) { 137 | msg = { 138 | key: this.name, 139 | value: { 140 | timestamp: msg.timestamp || timestamp(), 141 | type: msg.type || 'status', 142 | content: { 143 | text: msg.text 144 | } 145 | } 146 | } 147 | } 148 | this.virtualMessages.push(msg) 149 | } 150 | 151 | // returns false if we were already in the channel, otherwise true 152 | join () { 153 | var joined = this.joined 154 | this.joined = true 155 | return joined 156 | } 157 | 158 | // returns true if we were previously in the channel, otherwise false 159 | leave () { 160 | var joined = this.joined 161 | this.joined = false 162 | return joined 163 | } 164 | } 165 | 166 | class ChannelDetails extends ChannelDetailsBase { 167 | constructor (cabal, channelName) { 168 | super(channelName) 169 | this.messages = cabal.messages 170 | } 171 | 172 | getPage (opts) { 173 | opts = opts || {} 174 | const OGopts = Object.assign({}, opts) 175 | return new Promise((resolve, reject) => { 176 | const rs = this.messages.read(this.name, opts) 177 | collect(rs, (err, msgs) => { 178 | if (err) { 179 | return reject(err) 180 | } 181 | const reversed = [] 182 | for (let i = msgs.length - 1; i >= 0; --i) { 183 | const msg = msgs[i] 184 | reversed.push(msg) 185 | const msgTime = msg.value.timestamp 186 | const dayTimestamp = msgTime - (msgTime % (24 * 60 * 60 * 1000)) 187 | if (!this.datesSeen.has(dayTimestamp)) { 188 | this.datesSeen.add(dayTimestamp) 189 | this.addVirtualMessage({ 190 | key: this.name, 191 | value: { 192 | timestamp: dayTimestamp, 193 | type: 'status/date-changed' 194 | } 195 | }) 196 | } 197 | } 198 | resolve(this.interleaveVirtualMessages(reversed, OGopts)) 199 | }) 200 | }) 201 | } 202 | } 203 | 204 | class VirtualChannelDetails extends ChannelDetailsBase { 205 | constructor (channelName) { 206 | super(channelName) 207 | this.joined = true 208 | } 209 | 210 | getPage (opts) { 211 | return Promise.resolve(this.interleaveVirtualMessages([], opts)) 212 | } 213 | } 214 | 215 | class PMChannelDetails extends ChannelDetails { 216 | constructor (details, cabal, pubkey) { 217 | super(cabal, pubkey) 218 | // change cabal api we read from to be private messages (not messages api) 219 | this.messages = cabal.privateMessages 220 | this.recipient = pubkey 221 | this.isPrivate = true 222 | this.topic = "private message with " + pubkey 223 | Object.defineProperty(this, 'joined', { 224 | get: function() { 225 | return details.settings.joinedPrivateMessages.includes(pubkey) 226 | } 227 | }) 228 | this.members.add(this.recipientKey) // makes sure # members > 0 :) 229 | } 230 | 231 | toString () { 232 | return `PM-${this.recipient.slice(0,8)}` 233 | } 234 | } 235 | 236 | module.exports = { ChannelDetails, VirtualChannelDetails, PMChannelDetails } 237 | -------------------------------------------------------------------------------- /src/client.js: -------------------------------------------------------------------------------- 1 | const Cabal = require('cabal-core') 2 | const CabalDetails = require('./cabal-details') 3 | const collect = require('collect-stream') 4 | const crypto = require('hypercore-crypto') 5 | const DatDns = require('dat-dns') 6 | const fs = require('fs') 7 | const yaml = require('js-yaml') 8 | const ram = require('random-access-memory') 9 | const memdb = require('memdb') 10 | const level = require('level') 11 | const path = require('path') 12 | const mkdirp = require('mkdirp') 13 | const os = require('os') 14 | const defaultCommands = require('./commands') 15 | const paperslip = require("paperslip") 16 | const getStorage = require("./storage-node") // replaced with `storage-browser.js` if browserified 17 | 18 | class Client { 19 | /** 20 | * Create a client instance from which to manage multiple 21 | * [`cabal-core`](https://github.com/cabal-club/cabal-core/) instances. 22 | * @constructor 23 | * @param {object} [opts] 24 | * @param {object} opts.aliases key/value pairs of `alias` -> `command name` 25 | * @param {object} opts.commands key/value pairs of `command name` -> `command object`, which has the following properties: 26 | * @param {function} opts.commands[].call command function with the following signature `command.call(cabal, res, arg)` 27 | * @param {function} opts.commands[].help return the help string for this command 28 | * @param {string[]} opts.commands[].category a list of categories this commands belongs to 29 | * @param {string[]} opts.commands[].alias a list of command aliases 30 | * @param {object} opts.config 31 | * @param {boolean} opts.config.temp if `temp` is true no data is persisted to disk. 32 | * @param {string} [opts.config.dbdir] the directory to store the cabal data 33 | * @param {string} [opts.config.preferredPort] the port cabal will listen on for traffic 34 | * @param {number} [opts.maxFeeds=1000] max amount of feeds to sync 35 | * @param {object} [opts.persistentCache] specify a `read` and `write` to create a persistent DNS cache 36 | * @param {function} opts.persistentCache.read async cache lookup function 37 | * @param {function} opts.persistentCache.write async cache write function 38 | */ 39 | constructor (opts) { 40 | if (!(this instanceof Client)) return new Client(opts) 41 | if (!opts) { 42 | opts = { 43 | config: { 44 | temp: true, 45 | dbdir: null, 46 | storage: null, 47 | swarm: null, // typically null or passed hyperswarm-web options 48 | preferredPort: 0 // use cabal-core's default port 49 | } 50 | } 51 | } 52 | // This is redundant, but we might want to keep the cabal map around 53 | // in the case the user has access to cabal instances 54 | this._keyToCabal = {} 55 | // maps a cabal-core instance to a CabalDetails object 56 | this.cabals = new Map() 57 | this.currentCabal = null 58 | this.config = opts.config 59 | this.maxFeeds = opts.maxFeeds || 1000 60 | this.aliases = opts.aliases || {} 61 | this.commands = Object.assign({}, defaultCommands, opts.commands) 62 | Object.keys(this.commands).forEach(key => { 63 | ;(this.commands[key].alias || []).forEach(alias => { 64 | this.aliases[alias] = key 65 | }) 66 | }) 67 | 68 | const cabalDnsOpts = { 69 | hashRegex: /^[0-9a-f]{64}?$/i, 70 | recordName: 'cabal', 71 | protocolRegex: /^(cabal:\/\/[0-9A-Fa-f]{64}\b.*)/i, 72 | txtRegex: /^"?cabalkey=(cabal:\/\/[0-9A-Fa-f]{64}\b.*)"?$/i 73 | } 74 | // also takes opts.persistentCache which has a read and write function 75 | // read: async function () // aka cache lookup function 76 | // write: async function () // aka cache write function 77 | if (opts.persistentCache) cabalDnsOpts.persistentCache = opts.persistentCache 78 | this.cabalDns = DatDns(cabalDnsOpts) 79 | } 80 | 81 | /** 82 | * Get the current database version. 83 | * @returns {string} 84 | */ 85 | static getDatabaseVersion () { 86 | return Cabal.databaseVersion 87 | } 88 | 89 | /** 90 | * Returns a 64 character hex string i.e. a newly generated cabal key. 91 | * Useful if you want to programmatically create a new cabal as part of a shell pipeline. 92 | * @returns {string} 93 | */ 94 | static generateKey () { 95 | return crypto.keyPair().publicKey.toString('hex') 96 | } 97 | 98 | /** 99 | * Removes URI scheme, URI search params (if present), and returns the cabal key as a 64 character hex string 100 | * @param {string} key the key to scrub 101 | * @returns {string} the scrubbed key 102 | * @example 103 | * Client.scrubKey('cabal://12345678...?admin=7331b4b..') 104 | * // => '12345678...' 105 | */ 106 | static scrubKey (key) { 107 | if (!key || typeof key !== 'string') return '' 108 | // remove url search params; indexOf returns -1 if no params => would chop off the last character if used w/ slice 109 | if (key.indexOf("?") >= 0) { 110 | return key.slice(0, key.indexOf("?")).replace('cabal://', '').replace('cbl://', '').replace('dat://', '').replace(/\//g, '') 111 | } 112 | return key.replace('cabal://', '').replace('cbl://', '').replace('dat://', '').replace(/\//g, '') 113 | } 114 | 115 | /** 116 | * Returns a string path of where all of the cabals are stored on the hard drive. 117 | * @returns {string} the cabal directory 118 | */ 119 | static getCabalDirectory () { 120 | return path.join(os.homedir(), '.cabal', `v${Client.getDatabaseVersion()}`) 121 | } 122 | 123 | /** 124 | * Returns a string path of where the cabal settings are stored on the hard drive. 125 | * @returns {string} the cabal settings file path 126 | */ 127 | static getCabalSettingsFile () { 128 | return path.join(Client.getCabalDirectory(), 'settings.yml') 129 | } 130 | 131 | /** 132 | * Read and parse the contents of the settings.yml file. 133 | * If the file doesn't exist, return {}. 134 | * @returns {object} the contents of the settings file 135 | */ 136 | readCabalSettingsFile () { 137 | var settingsFilePath = Client.getCabalSettingsFile() 138 | if (fs.existsSync(settingsFilePath)) { 139 | return yaml.load(fs.readFileSync(settingsFilePath, 'utf8')) 140 | } else { 141 | return {} 142 | } 143 | } 144 | 145 | /** 146 | * Get the settings for a given cabal from the settings.yml file. 147 | * If the file doesn't exist or the given cabal has no settings, return the default settings. 148 | * @param {string} key the cabal 149 | * @returns {object} the cabal settings 150 | */ 151 | getCabalSettings (key) { 152 | return this.readCabalSettingsFile()[key] || { 153 | joinedPrivateMessages: [] 154 | } 155 | } 156 | 157 | /** 158 | * Reads the settings from the settings.yml file, updates the settings for the given cabal, then 159 | * writes the revised settings to the settings.yml file. 160 | * @param {string} key the cabal 161 | * @param {object} settings the cabal settings 162 | */ 163 | writeCabalSettings (key, settings) { 164 | // make sure settings is well-formatted 165 | if (!settings.joinedPrivateMessages) { 166 | settings.joinedPrivateMessages = [] 167 | } else { 168 | settings.joinedPrivateMessages = Array.from(new Set(settings.joinedPrivateMessages)) // dedupe array entries 169 | } 170 | 171 | var baseSettings = this.readCabalSettingsFile() 172 | baseSettings[key] = settings 173 | 174 | const data = yaml.dump(baseSettings, { 175 | sortKeys: true 176 | }) 177 | fs.writeFileSync(Client.getCabalSettingsFile(), data, 'utf8') 178 | } 179 | 180 | /** 181 | * Resolve the DNS shortname `name`. If `name` is already a cabal key, it will 182 | * be returned and the DNS lookup is aborted. 183 | * If `name` is a whisper:// key, a DHT lookup for the passed-in key will occur. 184 | * Once a match is found, it is assumed to be a cabal key, which is returned. 185 | * Returns the cabal key in `cb`. If `cb` is null a Promise is returned. 186 | * @param {string} name the DNS shortname, or whisper:// shortname 187 | * @param {function(string)} [cb] The callback to be called when lookup succeeds 188 | */ 189 | resolveName (name, cb) { 190 | if (name.startsWith('whisper://') || 191 | // whisperlink heuristic: ends with - 192 | name.slice(-4).toLowerCase().match(/-[0-9a-f]{3}/)) { 193 | return new Promise((resolve, reject) => { 194 | let key = '' 195 | const topic = name.startsWith('whisper://') ? name.slice(10) : name 196 | const stream = paperslip.read(topic) 197 | stream.on('data', (data) => { 198 | if (data) { key += data.toString() } 199 | }) 200 | stream.on('end', () => { resolve(key) }) 201 | stream.once('error', (err) => { reject(err) }) 202 | }) 203 | } else { 204 | if (Cabal.isHypercoreKey(Client.scrubKey(name))) { 205 | return Promise.resolve(name) 206 | } 207 | return this.cabalDns.resolveName(name).then((key) => { 208 | if (key === null) return null 209 | if (!cb) return key 210 | else cb(key) 211 | }) 212 | } 213 | } 214 | 215 | /** 216 | * Create a new cabal. 217 | * @returns {Promise} a promise that resolves into a `CabalDetails` instance. 218 | */ 219 | createCabal (cb, opts) { 220 | opts = opts || {} 221 | const key = Client.generateKey() 222 | return this.addCabal(key, opts, cb) 223 | } 224 | 225 | /** 226 | * Add/load the cabal at `key`. 227 | * @param {string} key 228 | * @param {object} opts 229 | * @param {function(string)} cb a function to be called when the cabal has been initialized. 230 | * @returns {Promise} a promise that resolves into a `CabalDetails` instance. 231 | */ 232 | addCabal (key, opts, cb) { 233 | if (typeof key === 'object' && !opts) { 234 | opts = key 235 | key = undefined 236 | } 237 | if (typeof opts === 'function' && !cb) { 238 | cb = opts 239 | opts = {} 240 | } 241 | opts = opts || {} 242 | if (!cb || typeof cb !== 'function') cb = function noop () {} 243 | let cabalPromise 244 | let dnsFailed = false 245 | if (typeof key === 'string') { 246 | cabalPromise = this.resolveName(key.trim()).then((resolvedKey) => { 247 | // discard uri scheme and search params of cabal key, if present. returns 64 chr hex string 248 | const scrubbedKey = Client.scrubKey(resolvedKey) 249 | 250 | // verify that scrubbedKey is 64 ch hex string 251 | if (scrubbedKey === '' || !Cabal.isHypercoreKey(scrubbedKey)) { 252 | dnsFailed = true 253 | return 254 | } 255 | 256 | let { temp, dbdir, preferredPort, storage } = this.config 257 | preferredPort = preferredPort || 0 258 | dbdir = dbdir || path.join(Client.getCabalDirectory(), 'archives') 259 | // if opts.config.storage passed in, use it. otherwise use decent defaults 260 | storage = storage || temp ? ram : getStorage(path.join(dbdir, scrubbedKey)) 261 | if (!temp) try { mkdirp.sync(path.join(dbdir, scrubbedKey, 'views')) } catch (e) {} 262 | var db = temp ? memdb() : level(path.join(dbdir, scrubbedKey, 'views')) 263 | 264 | if (!resolvedKey.startsWith('cabal://')) resolvedKey = 'cabal://' + resolvedKey 265 | const uri = new URL(resolvedKey) 266 | const modKeys = uri.searchParams.getAll('mod') 267 | const adminKeys = uri.searchParams.getAll('admin') 268 | 269 | var cabal = Cabal(storage, scrubbedKey, { modKeys, adminKeys, db, preferredPort, maxFeeds: this.maxFeeds }) 270 | this._keyToCabal[scrubbedKey] = cabal 271 | return cabal 272 | }) 273 | } else { // a cabal instance was passed in, instead of a cabal key string 274 | cabalPromise = new Promise((resolve, reject) => { 275 | var cabal = key 276 | this._keyToCabal[Client.scrubKey(cabal.key)] = cabal 277 | resolve(cabal) 278 | }) 279 | } 280 | return new Promise((resolve, reject) => { 281 | cabalPromise.then((cabal) => { 282 | if (dnsFailed) return reject(new Error('dns failed to resolve')) 283 | cabal = this._coerceToCabal(cabal) 284 | cabal.ready(() => { 285 | if (!this.currentCabal) { 286 | this.currentCabal = cabal 287 | } 288 | const details = new CabalDetails({ 289 | cabal, 290 | client: this, 291 | commands: this.commands, 292 | aliases: this.aliases 293 | }, done) 294 | this.cabals.set(cabal, details) 295 | if (!opts.noSwarm) cabal.swarm(this.config.swarm) 296 | function done () { 297 | details._emitUpdate('init') 298 | cb() 299 | resolve(details) 300 | } 301 | }) 302 | }, err => { 303 | cb(err) 304 | reject(err) 305 | }) 306 | }) 307 | } 308 | 309 | /** 310 | * Focus the cabal at `key`, used when you want to switch from one open cabal to another. 311 | * @param {string} key 312 | */ 313 | focusCabal (key) { 314 | const cabal = this._coerceToCabal(key) 315 | if (!cabal) { 316 | return false 317 | } 318 | this.currentCabal = cabal 319 | const details = this.cabalToDetails(cabal) 320 | details._emitUpdate('cabal-focus', { key }) 321 | return details 322 | } 323 | 324 | /** 325 | * Remove the cabal `key`. Destroys everything related to it 326 | * (the data is however still persisted to disk, fret not!). 327 | * @param {string} key 328 | * @param {function} cb 329 | */ 330 | removeCabal (key, cb) { 331 | const cabal = this._coerceToCabal(key) 332 | if (!cabal) { 333 | return false 334 | } 335 | 336 | const details = this.cabalToDetails(cabal) 337 | details._destroy(cb) 338 | 339 | // burn everything we know about the cabal 340 | delete this._keyToCabal[Client.scrubKey(key)] 341 | return this.cabals.delete(cabal) 342 | } 343 | 344 | /** 345 | * Returns the details of a cabal for the given key. 346 | * @returns {CabalDetails} 347 | */ 348 | getDetails (key) { 349 | const cabal = this._coerceToCabal(key) 350 | if (!cabal) { return null } 351 | return this.cabalToDetails(cabal) 352 | } 353 | 354 | /** 355 | * Returns a list of cabal keys, one for each open cabal. 356 | * @returns {string[]} 357 | */ 358 | getCabalKeys () { 359 | return Object.keys(this._keyToCabal).sort() 360 | } 361 | 362 | /** 363 | * Get the current cabal. 364 | * @returns {CabalDetails} 365 | */ 366 | getCurrentCabal () { 367 | return this.cabalToDetails(this.currentCabal) 368 | } 369 | 370 | /** 371 | * Add a command to the set of supported commands. 372 | * @param {string} [name] the long-form command name 373 | * @param {object} [cmd] the command object 374 | * @param {function} [cmd.help] function returning help text 375 | * @param {array} [cmd.alias] array of string aliases 376 | * @param {function} [cmd.call] implementation of the command receiving (cabal, res, arg) arguments 377 | */ 378 | addCommand (name, cmd) { 379 | this.commands[name] = cmd 380 | ;(cmd.alias || []).forEach(alias => { 381 | this.aliases[alias] = name 382 | }) 383 | } 384 | 385 | /** 386 | * Remove a command. 387 | * @param {string} [name] the command name 388 | */ 389 | removeCommand (name) { 390 | var cmd = this.commands[name] 391 | ;(cmd.alias || []).forEach(alias => { 392 | delete this.aliases[alias] 393 | }) 394 | delete this.commands[name] 395 | } 396 | 397 | /** 398 | * Get an object mapping command names to command objects. 399 | */ 400 | getCommands () { 401 | return this.commands 402 | } 403 | 404 | /** 405 | * Add an alias `shortCmd` for `longCmd` 406 | * @param {string} [longCmd] command to be aliased 407 | * @param {string} [shortCmd] alias 408 | */ 409 | addAlias (longCmd, shortCmd) { 410 | this.aliases[shortCmd] = longCmd 411 | this.commands[longCmd].alias.push(shortCmd) 412 | } 413 | 414 | /** 415 | * Returns the `cabal-core` instance corresponding to the cabal key `key`. `key` is scrubbed internally. 416 | * @method 417 | * @param {string} key 418 | * @returns {Cabal} the `cabal-core` instance 419 | * @access private 420 | */ 421 | _getCabalByKey (key) { 422 | key = Client.scrubKey(key) 423 | if (!key) { 424 | return this.currentCabal 425 | } 426 | return this._keyToCabal[key] 427 | } 428 | 429 | /** 430 | * Returns a `CabalDetails` instance for the passed in `cabal-core` instance. 431 | * @param {Cabal} [cabal=this.currentCabal] 432 | * @returns {CabalDetails} 433 | */ 434 | cabalToDetails (cabal = this.currentCabal) { 435 | if (!cabal) { return null } 436 | const details = this.cabals.get(cabal) 437 | if (details) { 438 | return details 439 | } 440 | // Could not resolve cabal to details, did you pass in a cabal instance? 441 | return null 442 | } 443 | 444 | /** 445 | * Add a status message, displayed client-side only, to the specified channel and cabal. 446 | * If no cabal is specified, the currently focused cabal is used. 447 | * @param {object} message 448 | * @param {string} channel 449 | * @param {Cabal} [cabal=this.currentCabal] 450 | */ 451 | addStatusMessage (message, channel, cabal = this.currentCabal) { 452 | this.cabalToDetails(cabal).addStatusMessage(message, channel) 453 | } 454 | 455 | /** 456 | * Clear status messages for the specified channel. 457 | * @param {string} channel 458 | * @param {Cabal} [cabal=this.currentCabal] 459 | */ 460 | clearStatusMessages (channel, cabal = this.currentCabal) { 461 | this.cabalToDetails(cabal).clearVirtualMessages(channel) 462 | } 463 | 464 | /** 465 | * Returns a list of all the users for the specified cabal. 466 | * If no cabal is specified, the currently focused cabal is used. 467 | * @param {Cabal} [cabal=this.currentCabal] 468 | * @returns {Object[]} the list of users 469 | */ 470 | getUsers (cabal = this.currentCabal) { 471 | return this.cabalToDetails(cabal).getUsers() 472 | } 473 | 474 | /** 475 | * Returns a list of channels the user has joined for the specified cabal. 476 | * If no cabal is specified, the currently focused cabal is used. 477 | * @param {Cabal} [cabal=this.currentCabal] 478 | * @returns {Object[]} the list of Channels 479 | */ 480 | getJoinedChannels (cabal = this.currentCabal) { 481 | return this.cabalToDetails(cabal).getJoinedChannels() 482 | } 483 | 484 | /** 485 | * Returns a list of all channels for the specified cabal. 486 | * If no cabal is specified, the currently focused cabal is used. 487 | * @param {Cabal} [cabal=this.currentCabal] 488 | * @returns {Object[]} the list of Channels 489 | */ 490 | getChannels (cabal = this.currentCabal) { 491 | return this.cabalToDetails(cabal).getChannels() 492 | } 493 | 494 | _coerceToCabal (key) { 495 | if (key instanceof Cabal) { 496 | return key 497 | } 498 | return this._keyToCabal[Client.scrubKey(key)] 499 | } 500 | 501 | /** 502 | * Add a new listener for the `update` event. 503 | * @param {function} listener 504 | * @param {Cabal} [cabal=this.currentCabal] 505 | */ 506 | subscribe (listener, cabal = this.currentCabal) { 507 | this.cabalToDetails(cabal).on('update', listener) 508 | } 509 | 510 | /** 511 | * Remove a previously added listener. 512 | * @param {function} listener 513 | * @param {Cabal} [cabal=this.currentCabal] 514 | */ 515 | unsubscribe (listener, cabal = this.currentCabal) { 516 | this.cabalToDetails(cabal).removeListener('update', listener) 517 | } 518 | 519 | /** 520 | * Returns a list of messages according to `opts`. If `cb` is null, a Promise is returned. 521 | * @param {Object} [opts] 522 | * @param {number} [opts.olderThan] timestamp in epoch time. we want to get messages that are *older* than this ts 523 | * @param {number} [opts.newerThan] timestamp in epoch time. we want to get messages that are *newer* than this ts 524 | * @param {number} [opts.amount] amount of messages to get 525 | * @param {string} [opts.channel] channel to get messages from. defaults to currently focused channel 526 | * @param {function} [cb] the callback to be called when messages are retreived 527 | * @param {Cabal} [cabal=this.currentCabal] 528 | */ 529 | getMessages (opts, cb, cabal = this.currentCabal) { 530 | var details = this.cabalToDetails(cabal) 531 | if (typeof opts === 'function') { 532 | cb = opts 533 | opts = {} 534 | } 535 | opts = opts || {} 536 | var pageOpts = {} 537 | if (opts.olderThan) pageOpts.lt = parseInt(opts.olderThan) - 1 // - 1 because leveldb.lt seems to include the value we send it? 538 | if (opts.newerThan) pageOpts.gt = parseInt(opts.newerThan) // if you fix the -1 hack above, make sure that backscroll in cabal-cli works 539 | if (opts.amount) pageOpts.limit = parseInt(opts.amount) 540 | if (!opts.channel) { opts.channel = details.getCurrentChannel() } 541 | 542 | const channel = details.getChannel(opts.channel) 543 | const prom = (!channel) ? Promise.resolve([]) : channel.getPage(pageOpts) 544 | if (!cb) { return prom } 545 | prom.then(cb) 546 | } 547 | 548 | /** 549 | * Searches for messages that include the search string according to `opts`. 550 | * Each returned match contains a message string and a matchedIndexes array containing the indexes at which the search string was found in the message 551 | * @param {string} [searchString] string to match messages against 552 | * @param {Object} [opts] 553 | * @param {number} [opts.olderThan] timestamp in epoch time. we want to search through messages that are *older* than this ts 554 | * @param {number} [opts.newerThan] timestamp in epoch time. we want to search through messages that are *newer* than this ts 555 | * @param {number} [opts.amount] amount of messages to be search through 556 | * @param {string} [opts.channel] channel to get messages from. defaults to currently focused channel 557 | * @param {Cabal} [cabal=this.currentCabal] 558 | * @returns {Promise} a promise that resolves into a list of matches. 559 | */ 560 | searchMessages (searchString, opts, cabal = this.currentCabal) { 561 | return new Promise((resolve, reject) => { 562 | if (!searchString || searchString === '') { 563 | return reject(new Error('search string must be set')) 564 | } 565 | 566 | const searchBuffer = Buffer.from(searchString) 567 | 568 | const matches = [] 569 | 570 | this.getMessages(opts, null, cabal).then((messages) => { 571 | messages.forEach(message => { 572 | const messageContent = message.value.content 573 | if (messageContent) { 574 | const textBuffer = Buffer.from(messageContent.text) 575 | 576 | /* positions at which the string was found, can be used for highlighting for example */ 577 | const matchedIndexes = [] 578 | 579 | /* use a labeled for-loop to cleanly continue top-level iteration */ 580 | charIteration: 581 | for (let charIndex = 0; charIndex <= textBuffer.length - searchBuffer.length; charIndex++) { 582 | if (textBuffer[charIndex] == searchBuffer[0]) { 583 | for (let searchIndex = 0; searchIndex < searchBuffer.length; searchIndex++) { 584 | if (!(textBuffer[charIndex + searchIndex] == searchBuffer[searchIndex])) { continue charIteration } 585 | } 586 | matchedIndexes.push(charIndex) 587 | } 588 | } 589 | 590 | if (matchedIndexes.length > 0) { 591 | matches.push({ message, matchedIndexes }) 592 | } 593 | } 594 | }) 595 | resolve(matches) 596 | }) 597 | }) 598 | } 599 | 600 | /** 601 | * Returns the number of unread messages for `channel`. 602 | * @param {string} channel 603 | * @param {Cabal} [cabal=this.currentCabal] 604 | * @returns {number} 605 | */ 606 | getNumberUnreadMessages (channel, cabal = this.currentCabal) { 607 | var details = this.cabalToDetails(cabal) 608 | if (!channel) { channel = details.getCurrentChannel() } 609 | const count = this.cabalToDetails(cabal).getChannel(channel).getNewMessageCount() 610 | return count 611 | } 612 | 613 | /** 614 | * Returns the number of mentions in `channel`. 615 | * @param {string} [channel=this.getCurrentChannel()] 616 | * @param {Cabal} [cabal=this.currentCabal] 617 | */ 618 | getNumberMentions (channel, cabal = this.currentCabal) { 619 | return this.cabalToDetails(cabal).getChannel(channel).getMentions().length 620 | } 621 | 622 | /** 623 | * Returns a list of messages that triggered a mention in channel. 624 | * @param {string} [channel=this.getCurrentChannel()] 625 | * @param {Cabal} [cabal=this.currentCabal] 626 | */ 627 | getMentions (channel, cabal = this.currentCabal) { 628 | return this.cabalToDetails(cabal).getChannel(channel).getMentions() 629 | } 630 | 631 | /** 632 | * View `channel`, closing the previously focused channel. 633 | * @param {*} [channel=this.getCurrentChannel()] 634 | * @param {boolean} [keepUnread=false] 635 | * @param {Cabal} [cabal=this.currentCabal] 636 | */ 637 | focusChannel (channel, keepUnread = false, cabal = this.currentCabal) { 638 | this.cabalToDetails(cabal).focusChannel(channel, keepUnread) 639 | } 640 | 641 | /** 642 | * Close `channel`. 643 | * @param {string} [channel=this.getCurrentChannel()] 644 | * @param {string} [newChannel=null] 645 | * @param {Cabal} [cabal=this.currentCabal] 646 | */ 647 | unfocusChannel (channel, newChannel, cabal = this.currentCabal) { 648 | return this.cabalToDetails(cabal).unfocusChannel(channel, newChannel) 649 | } 650 | 651 | /** 652 | * Returns the currently focused channel name. 653 | * @returns {string} 654 | */ 655 | getCurrentChannel () { 656 | return this.cabalToDetails(this.currentCabal).getCurrentChannel() 657 | } 658 | 659 | /** 660 | * Mark the channel as read. 661 | * @param {string} channel 662 | * @param {Cabal} [cabal=this.currentCabal] 663 | */ 664 | markChannelRead (channel, cabal = this.currentCabal) { 665 | var details = this.cabalToDetails(cabal) 666 | if (!channel) { channel = details.getCurrentChannel() } 667 | this.cabalToDetails(cabal).getChannel(channel).markAsRead() 668 | } 669 | } 670 | 671 | module.exports = Client 672 | -------------------------------------------------------------------------------- /src/commands.js: -------------------------------------------------------------------------------- 1 | const qr = require('qrcode') 2 | const pump = require('pump') 3 | const to = require('to2') 4 | const strftime = require('strftime') 5 | const paperslip = require("paperslip") 6 | const hrinames = require("human-readable-ids").hri // transitive dep via paperslip 7 | 8 | module.exports = { 9 | add: { 10 | help: () => 'add a cabal', 11 | category: ["misc"], 12 | alias: ['cabal'], 13 | call: (cabal, res, arg) => { 14 | if (arg === '') { 15 | res.info('Usage example: /add ') 16 | res.end() 17 | } else { 18 | cabal.client.addCabal(arg, (err) => { 19 | if (err) res.error(err) 20 | else res.end() 21 | }) 22 | } 23 | } 24 | }, 25 | pm: { 26 | help: () => 'send a private message to a user', 27 | category: ["pm", "basics"], 28 | alias: ["w"], 29 | call: (cabal, res, arg) => { 30 | var args = arg ? arg.split(/\s+/) : [] 31 | if (args.length < 2) { 32 | res.info('usage: /pm NICK{.PUBKEY} ') 33 | return res.end() 34 | } 35 | var keys = parseNameToKeys(cabal, args[0]) 36 | 37 | var id = args[0] 38 | var keys = parseNameToKeys(cabal, id) 39 | if (keys.length === 0) { 40 | res.info(`no matching user found for ${id}`) 41 | return res.end() 42 | } 43 | if (keys.length > 1) { 44 | res.info('more than one key matches:') 45 | keys.forEach(key => { 46 | res.info(` /$pm ${id.split('.')[0]}.${key}`) 47 | }) 48 | return res.end() 49 | } 50 | id = keys[0] 51 | const text = args.slice(1).join(" ") 52 | const msg = { 53 | type: "chat/text", 54 | content: { 55 | text, 56 | channel: id 57 | } 58 | } 59 | cabal.publishPrivateMessage(msg, id) 60 | } 61 | }, 62 | archive: { 63 | help: () => 'archive a channel', 64 | category: ["channels"], 65 | call: (cabal, res, arg) => { 66 | if (typeof arg === "undefined" || arg.length <= 0) { 67 | return res.error("you need to specify the channel to archive") 68 | } 69 | 70 | // if no --channel: assume everything up to the first opt is the reason 71 | const defaultChannel = arg.indexOf("--") >= 0 ? arg.slice(0, arg.indexOf("--")).trim() : arg 72 | let { channel, reason } = extractChannelReasonOptions(arg, defaultChannel) 73 | 74 | if (typeof cabal.channels[channel] === "undefined") { 75 | return res.error(`${arg} does not exist`) 76 | } else if (channel === "!status") { 77 | return res.error("the !status channel cannot be archived") 78 | } else if (cabal.isChannelArchived(channel)) { 79 | return res.error(`channel ${channel} is already archived`) 80 | } 81 | 82 | res.info(`archived ${channel}`) 83 | cabal.archiveChannel(channel, reason, (err) => { 84 | if (err) res.error(err) 85 | else res.end() 86 | }) 87 | } 88 | }, 89 | unarchive: { 90 | help: () => 'unarchive a channel', 91 | category: ["channels"], 92 | alias: ['restore'], 93 | call: (cabal, res, arg) => { 94 | if (typeof arg === "undefined" || arg.length <= 0) { 95 | return res.error("you need to specify the channel to unarchive") 96 | } 97 | 98 | // if no --channel: assume everything up to the first opt is the reason 99 | const defaultChannel = arg.indexOf("--") >= 0 ? arg.slice(0, arg.indexOf("--")).trim() : arg 100 | let { channel, reason } = extractChannelReasonOptions(arg, defaultChannel) 101 | 102 | if (typeof cabal.channels[channel] === "undefined") { 103 | return res.error(`${channel} does not exist`) 104 | } else if (channel === "!status") { 105 | return res.error("the !status channel cannot be archived (and so neither unarchived)") 106 | } else if (!cabal.isChannelArchived(channel)) { 107 | return res.error(`channel ${channel} is not archived`) 108 | } 109 | 110 | res.info(`restored ${channel}`) 111 | cabal.unarchiveChannel(channel, reason, (err) => { 112 | if (err) res.error(err) 113 | else res.end() 114 | }) 115 | } 116 | }, 117 | archives: { 118 | help: () => 'list the currently archived channels', 119 | category: ["channels"], 120 | alias: ["archived"], 121 | call: (cabal, res, arg) => { 122 | const archivedChannels = cabal.getChannels({ includeArchived: true }).filter(ch => cabal.channels[ch].archived) 123 | 124 | res.info("all archived channels:") 125 | archivedChannels.forEach(channel => res.info(` ${channel}`, { channel })) 126 | if (archivedChannels.length === 0) { 127 | res.info("no channels are archived") 128 | } 129 | 130 | cabal.core.archives.getUnarchived(cabal.user.key, (err, unarchivedChannels) => { 131 | res.info("channels you have restored:") 132 | unarchivedChannels.forEach(channel => res.info(` ${channel}`, { channel })) 133 | if (unarchivedChannels.length === 0) { 134 | res.info("there are no restored channels. restore an archived channel with /unarchive ") 135 | } 136 | res.end() 137 | }) 138 | } 139 | }, 140 | whisper: { 141 | help: () => 'create a whisper link, a shortlived shortname alias for this cabal\'s key', 142 | category: ["sharing"], 143 | call: (cabal, res, arg) => { 144 | if (typeof arg === "undefined" || arg === '') { 145 | arg = hrinames.random() 146 | } 147 | const topic = `${arg}-${cabal.key.slice(0,3)}` 148 | const link = `whisper://${topic}` 149 | const minutes = 5 150 | const ttl = minutes * 60 * 1000 // time to live (how long the link is active) 151 | res.info({ text: `whispering on ${link} for the next ${minutes} minutes`, link, ttl }) 152 | // NOTE: currently this will log which ip addresses join via the whisperlink 153 | const swarm = paperslip.write(topic, `cabal://${cabal.key}`, res.info) 154 | setTimeout(() => { 155 | paperslip.stop(swarm) 156 | res.info(`stopped whispering ${link}`) 157 | res.end() 158 | }, ttl) 159 | } 160 | }, 161 | new: { 162 | help: () => 'create a new cabal', 163 | category: ["misc"], 164 | call: (cabal, res, arg) => { 165 | cabal.client.createCabal((err) => { 166 | if (err) res.error(err) 167 | else res.end() 168 | }) 169 | } 170 | }, 171 | nick: { 172 | help: () => 'change your display name', 173 | category: ["basics"], 174 | alias: ['n'], 175 | call: (cabal, res, arg) => { 176 | if (arg === '') { 177 | res.info(cabal.user.name) 178 | return res.end() 179 | } 180 | cabal.publishNick(arg, (err) => { 181 | if (err) return res.error(err) 182 | res.info("you're now known as " + arg) 183 | res.end() 184 | }) 185 | } 186 | }, 187 | share: { 188 | help: () => 'print a cabal key with you as admin. useful for sending to friends', 189 | category: ["sharing"], 190 | call: (cabal, res, arg) => { 191 | const adminkey = `cabal://${cabal.key}?admin=${cabal.user.key}` 192 | res.info(adminkey, { data: { adminkey } }) 193 | res.end() 194 | } 195 | }, 196 | ids: { 197 | help: () => 'toggle showing ids at the end of nicks. useful for moderation', 198 | category: ["moderation"], 199 | call: (cabal, res, arg) => { 200 | cabal.showIds = !cabal.showIds 201 | res.info(`toggled identifiers ${cabal.showIds ? 'on' : 'off'}`) 202 | res.end() 203 | } 204 | }, 205 | emote: { 206 | help: () => 'write an old-school text emote', 207 | category: ["basics"], 208 | alias: ['me'], 209 | call: (cabal, res, arg) => { 210 | cabal.publishMessage({ 211 | type: 'chat/emote', 212 | content: { 213 | channel: cabal.channel, 214 | text: arg 215 | } 216 | }, {}, (err) => { 217 | if (err) res.error(err) 218 | else res.end() 219 | }) 220 | } 221 | }, 222 | say: { 223 | help: () => 'write a message to the current channel, useful for escaping a typed /', 224 | category: ["misc"], 225 | call: (cabal, res, arg) => { 226 | cabal.publishMessage({ 227 | type: 'chat/text', 228 | content: { 229 | channel: cabal.channel, 230 | text: arg || '' 231 | } 232 | }, {}, (err) => { 233 | if (err) res.error(err) 234 | else res.end() 235 | }) 236 | } 237 | }, 238 | search: { 239 | help: () => 'search the backlog for messages; /search (--ch )', 240 | category: ["misc"], 241 | call: (cabal, res, arg) => { 242 | if (!arg) { 243 | return res.error(`/search (--ch )`) 244 | } 245 | const opts = {} 246 | if (arg.indexOf("--ch") >= 0) { 247 | let [term, channel] = arg.split("--ch") 248 | if (!term || term.length === 0) { 249 | return res.error(`/search (--ch )`) 250 | } 251 | term = term.trim() 252 | channel = channel.trim() 253 | if (!cabal.channels[channel]) { 254 | res.error(`channel ${channel} does not exist`) 255 | res.error(`/search (--ch )`) 256 | return 257 | } 258 | opts.channel = channel.trim() 259 | arg = term 260 | } 261 | cabal.client.searchMessages(arg, opts).then((matches) => { 262 | const users = cabal.getUsers() 263 | res.info(`${matches.length} matching ${matches.length === 1 ? "log" : "logs"} found`) 264 | matches.forEach((envelope) => { 265 | let { message } = envelope 266 | if (message && message.value && message.value.type === "chat/text") { 267 | const user = users[message.key].name || message.key.slice(0, 8) 268 | const output = `<${user}> ${message.value.content.text}` 269 | res.info(output) 270 | } 271 | }) 272 | }) 273 | } 274 | }, 275 | names: { 276 | help: () => 'display the names and unique ids of the cabal\'s peers', 277 | category: ["basics"], 278 | call: (cabal, res, arg) => { 279 | var users = cabal.getUsers() 280 | var userkeys = Object.keys(users).map((key) => users[key]).sort(cmpUser) 281 | res.info('history of peers in cabal') 282 | userkeys.map((u, i) => { 283 | var username = u.name || 'conspirator' 284 | var spaces = ' '.repeat(15) 285 | var paddedName = (username + spaces).slice(0, spaces.length) 286 | res.info(`${i+1}. ${paddedName} ${u.key}`) 287 | }) 288 | } 289 | }, 290 | channels: { 291 | help: () => "display the cabal's channels", 292 | category: ["basics", "channels"], 293 | call: (cabal, res, arg) => { 294 | var joinedChannels = cabal.getJoinedChannels() 295 | var channels = cabal.getChannels() 296 | res.info(`there are currently ${channels.length} channels `) 297 | channels.map((c) => { 298 | var topic = cabal.getTopic(c) 299 | var shortTopic = topic.length > 40 ? topic.slice(0, 40) + '..' : topic || '' 300 | var count = cabal.getChannelMembers(c).length 301 | var userPart = count ? `: ${count} ${count === 1 ? 'person' : 'people'}` : '' 302 | res.info({ 303 | text: ` ${joinedChannels.includes(c) ? '*' : ' '} ${c}${userPart} ${shortTopic}`, 304 | channel: c, 305 | userCount: count, 306 | topic, 307 | joined: joinedChannels.includes(c) 308 | }) 309 | }) 310 | res.end() 311 | } 312 | }, 313 | join: { 314 | help: () => 'join a new channel', 315 | category: ["basics", "channels"], 316 | alias: ['j'], 317 | call: (cabal, res, arg) => { 318 | arg = (arg.trim() || '').replace(/^#/, '') 319 | if (arg === '') arg = 'default' 320 | cabal.joinChannel(arg, (err) => { 321 | if (err) return res.error(err) 322 | cabal.focusChannel(arg) 323 | res.end() 324 | }) 325 | } 326 | }, 327 | leave: { 328 | help: () => 'leave a channel', 329 | category: ["basics", "channels"], 330 | alias: ['l', 'part'], 331 | call: (cabal, res, arg) => { 332 | arg = (arg || '').trim().replace(/^#/, '') 333 | if (arg === '!status') return 334 | /* TODO: update `cabal.channel` with next channel */ 335 | cabal.leaveChannel(arg, (err) => { 336 | if (err) return res.error(err) 337 | res.end() 338 | }) 339 | } 340 | }, 341 | clear: { 342 | help: () => 'clear the current backscroll', 343 | category: ["basics", "misc"], 344 | call: (cabal, res, arg) => { 345 | cabal.client.clearStatusMessages() 346 | res.end() 347 | } 348 | }, 349 | // qr: { // commented out as it doesn't work as of 2010-10-02 / after moz sprint 350 | // help: () => "generate a qr code with the current cabal's address", 351 | // category: ["sharing"], 352 | // call: (cabal, res, arg) => { 353 | // const cabalKey = `cabal://${cabal.key}` 354 | // qr.toString(cabalKey, { type: 'terminal' }, (err, qrcode) => { 355 | // if (err) return 356 | // res.info(`QR code for ${cabalKey}\n\n${qrcode}`) 357 | // res.end() 358 | // }) 359 | // } 360 | // }, 361 | topic: { 362 | help: () => 'set the topic/description/`message of the day` for a channel', 363 | category: ["channels", "basics"], 364 | alias: ['motd'], 365 | call: (cabal, res, arg) => { 366 | cabal.publishChannelTopic(cabal.channel, arg, (err) => { 367 | if (err) res.error(err) 368 | else res.end() 369 | }) 370 | } 371 | }, 372 | whoami: { 373 | help: () => 'display your local user key', 374 | category: ["basics", "misc"], 375 | alias: ['key'], 376 | call: (cabal, res, arg) => { 377 | res.info('Local user key: ' + cabal.getLocalUser().key) 378 | res.end() 379 | } 380 | }, 381 | whois: { 382 | help: () => 'display the public keys associated with the passed in nick', 383 | category: ["moderation", "misc"], 384 | call: (cabal, res, arg) => { 385 | if (!arg) { 386 | res.info('usage: /whois ') 387 | res.end() 388 | return 389 | } 390 | const users = cabal.getUsers() 391 | const whoisKeys = Object.keys(users).filter((k) => users[k].name && users[k].name === arg) 392 | if (whoisKeys.length === 0) { 393 | res.info(`there's currently no one named ${arg}`) 394 | res.end() 395 | return 396 | } 397 | res.info(`${arg}'s public keys:`) 398 | // list all of arg's public keys in list 399 | for (var key of whoisKeys) { 400 | res.info(` ${key}`) 401 | } 402 | res.end() 403 | } 404 | }, 405 | whoiskey: { 406 | help: () => 'display the user associated with the passed in public key', 407 | category: ["moderation", "misc"], 408 | call: (cabal, res, arg) => { 409 | if (!arg) { 410 | res.info('usage: /whoiskey ') 411 | res.end() 412 | return 413 | } 414 | arg = arg.trim().replace("\"", "") 415 | const users = cabal.getUsers() 416 | if (typeof users[arg] === "undefined") { 417 | res.error("no user associated with key", arg) 418 | return 419 | } 420 | res.info(`${arg} is currently known as: ${users[arg].name || ""}`) 421 | res.end() 422 | } 423 | }, 424 | read: { 425 | help: () => 'show raw information about a message from a KEY@SEQ', 426 | category: ["misc"], 427 | call: (cabal, res, arg) => { 428 | var args = (arg || '').split(/\s+/) 429 | if (args[0].length === 0) { 430 | res.info('usage: /read KEY@SEQ') 431 | return res.end() 432 | } 433 | cabal.core.getMessage(args[0], function (err, doc) { 434 | if (err) return res.error(err) 435 | res.info(Object.assign({}, doc, { 436 | text: JSON.stringify(doc, 2, null) 437 | })) 438 | res.end() 439 | }) 440 | } 441 | }, 442 | moderation: { 443 | help: () => 'display additional information on moderation commands', 444 | category: ["moderation"], 445 | call: (cabal, res, arg) => { 446 | const baseCmds = ['hide', 'mod', 'admin'] 447 | const extraCmds = ['ids', 'actions', 'roles', 'inspect'] 448 | const debugCmds = ['flag', 'flags'] 449 | res.info('moderation commands') 450 | res.info('\nbasic actions. the basic actions will be published to your log') 451 | res.info('USAGE / NICK{.PUBKEY} {REASON...}') 452 | res.info(' / NICK{.PUBKEY} --channel --reason ') 453 | baseCmds.forEach((base) => { 454 | res.info(`/${base}: ${module.exports[base].help()}`) 455 | const reverse = `un${base}` 456 | res.info(`/${reverse}: ${module.exports[reverse].help()}`) 457 | }) 458 | res.info('\nlisting applied moderation actions. local actions (i.e. not published)') 459 | baseCmds.forEach((base) => { 460 | const list = `${base}s` 461 | res.info(`/${list}: ${module.exports[list].help()}`) 462 | }) 463 | res.info('\nadditional commands. local actions') 464 | extraCmds.forEach((cmd) => { 465 | res.info(`/${cmd}: ${module.exports[cmd].help()}`) 466 | }) 467 | res.info('\ndebug commands') 468 | debugCmds.forEach((cmd) => { 469 | res.info(`/${cmd}: ${module.exports[cmd].help()}`) 470 | }) 471 | res.end() 472 | } 473 | }, 474 | hide: { 475 | help: () => 'hide a user\'s message across the whole cabal', 476 | category: ["moderation", "basics"], 477 | call: (cabal, res, arg) => { 478 | flagCmd('hide', cabal, res, arg) 479 | } 480 | }, 481 | unhide: { 482 | help: () => 'unhide a user across the entire cabal', 483 | category: ["moderation", "basics"], 484 | call: (cabal, res, arg) => { 485 | flagCmd('unhide', cabal, res, arg) 486 | } 487 | }, 488 | hides: { 489 | help: () => 'list hides', 490 | category: ["moderation"], 491 | call: (cabal, res, arg) => { 492 | listCmd('hide', cabal, res, arg) 493 | } 494 | }, 495 | block: { 496 | help: () => 'block a user', 497 | category: ["moderation"], 498 | call: (cabal, res, arg) => { 499 | flagCmd('block', cabal, res, arg) 500 | } 501 | }, 502 | unblock: { 503 | help: () => 'unblock a user', 504 | category: ["moderation"], 505 | call: (cabal, res, arg) => { 506 | flagCmd('unblock', cabal, res, arg) 507 | } 508 | }, 509 | blocks: { 510 | help: () => 'list blocks', 511 | category: ["moderation"], 512 | call: (cabal, res, arg) => { 513 | listCmd('block', cabal, res, arg) 514 | } 515 | }, 516 | mod: { 517 | help: () => 'add a user as a moderator', 518 | category: ["moderation"], 519 | call: (cabal, res, arg) => { 520 | flagCmd('mod', cabal, res, arg) 521 | } 522 | }, 523 | unmod: { 524 | help: () => 'remove a user as a moderator', 525 | category: ["moderation"], 526 | call: (cabal, res, arg) => { 527 | flagCmd('unmod', cabal, res, arg) 528 | } 529 | }, 530 | mods: { 531 | help: () => 'list mods', 532 | category: ["moderation"], 533 | call: (cabal, res, arg) => { 534 | listCmd('mod', cabal, res, arg) 535 | } 536 | }, 537 | admin: { 538 | help: () => 'add a user as an admin', 539 | category: ["moderation"], 540 | call: (cabal, res, arg) => { 541 | flagCmd('admin', cabal, res, arg) 542 | } 543 | }, 544 | unadmin: { 545 | help: () => 'remove a user as an admin', 546 | category: ["moderation"], 547 | call: (cabal, res, arg) => { 548 | flagCmd('unadmin', cabal, res, arg) 549 | } 550 | }, 551 | admins: { 552 | help: () => 'list admins', 553 | category: ["moderation"], 554 | call: (cabal, res, arg) => { 555 | listCmd('admin', cabal, res, arg) 556 | } 557 | }, 558 | actions: { 559 | help: () => 'print out a historic log of the moderation actions applied by you, and your active moderators & admins', 560 | category: ["moderation"], 561 | call: (cabal, res, arg) => { 562 | const promises = [cabal.moderation.getAdmins(), cabal.moderation.getMods()] 563 | // get all moderation actions issued by our current mods & admins 564 | const messages = [] 565 | function processMessages (messages) { 566 | res.info('moderation actions') 567 | if (messages.length === 0) { 568 | res.info('no recorded historic moderation actions') 569 | } 570 | messages.sort((a, b) => { return a.timestamp - b.timestamp }) 571 | messages.forEach((message) => { 572 | res.info(message.text) 573 | }) 574 | } 575 | Promise.all(promises).then(results => { 576 | const keys = results[0].concat(results[1]) 577 | listNextKey() 578 | function listNextKey () { 579 | if (keys.length === 0) { 580 | processMessages(messages) 581 | return res.end() 582 | } 583 | var key = keys.shift() 584 | const write = (row, enc, next) => { 585 | if (!row) return 586 | const name = cabal.users[key] ? cabal.users[key].name : key.slice(0, 8) 587 | const target = cabal.users[row.content.id] ? cabal.users[row.content.id].name : row.content.id.slice(0, 8) 588 | const type = row.type.split('/')[1] 589 | const reason = row.content.reason 590 | const role = row.content.flags[0] 591 | const datestr = strftime('[%F %T] ', new Date(row.timestamp)) 592 | let text, action 593 | if (['admin', 'mod'].includes(role)) { action = (type === 'add' ? 'added' : 'removed') } 594 | if (role === 'hide') { action = (type === 'add' ? 'hid' : 'unhid') } 595 | if (role === 'hide') { 596 | text = `${datestr} ${name} ${action} ${target} ${reason}` 597 | } else { 598 | text = `${datestr} ${name} ${action} ${target} as ${role} ${reason}` 599 | } 600 | messages.push({ text, timestamp: parseFloat(row.timestamp) }) 601 | next() 602 | } 603 | const end = (next) => { 604 | listNextKey() 605 | next() 606 | } 607 | pump(cabal.core.moderation.listModerationBy(key), to.obj(write, end)) 608 | } 609 | }) 610 | } 611 | }, 612 | roles: { 613 | help: () => 'list all your current moderators and admins', 614 | category: ["moderation"], 615 | call: (cabal, res, arg) => { 616 | const promises = [cabal.moderation.getAdmins(), cabal.moderation.getMods()] 617 | Promise.all(promises).then(results => { 618 | const keys = results[0].concat(results[1]) 619 | const print = (type) => { 620 | return (k) => { 621 | res.info(`${cabal.users[k] ? cabal.users[k].name : k.slice(0, 8)}: ${type}`) 622 | } 623 | } 624 | res.info('moderation roles') 625 | if (keys.length === 1 && keys[0] === cabal.getLocalUser().key) { 626 | res.info('you currently have no applied moderators or admins, other than yourself') 627 | res.info('see /moderation, for how to add some') 628 | return res.end() 629 | } 630 | const printMods = print('moderator') 631 | const printAdmins = print('admin') 632 | results[0].map(printAdmins) 633 | results[1].map(printMods) 634 | res.end() 635 | }) 636 | } 637 | }, 638 | inspect: { 639 | help: () => 'view moderation actions published by a user', 640 | category: ["moderation"], 641 | call: (cabal, res, arg) => { 642 | var args = arg ? arg.split(/\s+/) : [] 643 | if (args.length === 0) { 644 | res.info('usage: /inspect NICK{.PUBKEY}') 645 | return res.end() 646 | } 647 | var keys = parseNameToKeys(cabal, args[0]) 648 | listNextKey() 649 | function listNextKey () { 650 | if (keys.length === 0) return res.end() 651 | var key = keys.shift() 652 | res.info(`# moderation for ${getPeerName(cabal, key)}.${key.slice(0, 8)}`) 653 | pump(cabal.core.moderation.listModerationBy(key), to.obj(write, end)) 654 | function write (row, enc, next) { 655 | var c = { 656 | 'flags/add': '+', 657 | 'flags/remove': '-', 658 | 'flags/set': '=' 659 | }[row.type] || '?' 660 | var f = (row.content && row.content.flags || []).join(',') 661 | var id = row.content && row.content.id || '???' 662 | res.info(Object.assign({}, row, { 663 | text: `${c}${f} ${getPeerName(cabal, id)}.${id.slice(0, 8)} ` + 664 | (row.timestamp ? strftime('[%F %T] ', new Date(row.timestamp)) : '') + 665 | (row.content && row.content.reason || '') 666 | })) 667 | next() 668 | } 669 | function end (next) { 670 | listNextKey() 671 | next() 672 | } 673 | } 674 | } 675 | }, 676 | flag: { 677 | help: () => 'update and read flags set for a given account', 678 | category: ["moderation"], 679 | call: (cabal, res, arg) => { 680 | var args = arg ? arg.split(/\s+/) : [] 681 | if (args.length === 0) { 682 | res.info('usage: /flag (add|remove|set) NICK{.PUBKEY} [flags...]') 683 | res.info('usage: /flag get NICK{.PUBKEY}') 684 | res.info('usage: /flag list') 685 | return res.end() 686 | } 687 | var channel = '@' 688 | var cmd = args[0] 689 | if (/^(add|remove|set)$/.test(cmd)) { 690 | var keys = parseNameToKeys(cabal, args[1]) 691 | var flags = args.slice(2) 692 | if (keys.length > 1) { 693 | res.info('more than one key matches:') 694 | keys.forEach(key => { 695 | res.info(` /flag ${cmd} ${args[1]}.${key} ${flags}`) 696 | }) 697 | return res.end() 698 | } 699 | var id = keys[0] 700 | cabal.core.moderation[cmd + 'Flags']({ id, channel, flags }, (err) => { 701 | if (err) res.error(err) 702 | else res.end() 703 | }) 704 | } else if (args[0] === 'get') { 705 | var keys = parseNameToKeys(cabal, args[1]) 706 | var flags = args.slice(2) 707 | keys.forEach(id => { 708 | cabal.core.moderation.getFlags({ id, channel }, (err, flags) => { 709 | if (err) return res.error(err) 710 | res.info({ 711 | text: `${id}: ` + 712 | flags.map(flag => /\s/.test(flag) ? JSON.stringify(flag) : flag) 713 | .sort().join(' '), 714 | key: id, 715 | flags 716 | }) 717 | res.end() 718 | }) 719 | }) 720 | } else if (args[0] === 'list') { 721 | module.exports.flags.call(cabal, res, arg) 722 | } 723 | } 724 | }, 725 | flags: { 726 | help: () => 'list flags set for accounts', 727 | category: ["moderation"], 728 | call: (cabal, res, arg) => { 729 | var args = arg ? arg.split(/\s+/) : [] 730 | cabal.core.moderation.list((err, list) => { 731 | if (err) return res.error(err) 732 | list.forEach(data => { 733 | res.info({ 734 | text: JSON.stringify(data), 735 | data 736 | }) 737 | }) 738 | res.end() 739 | }) 740 | } 741 | } 742 | } 743 | 744 | function getNameKeyMatchesFromDetails (details, name) { 745 | const lastDot = name.lastIndexOf('.') 746 | const keyPrefix = name.slice(lastDot + 1) 747 | const namePrefix = name.slice(0, lastDot) 748 | if (!keyPrefix.length || !namePrefix.length) return [] 749 | 750 | const keys = Object.values(details.getUsers()) 751 | return keys 752 | .filter((u) => u.name.startsWith(namePrefix) && u.key.startsWith(keyPrefix)) 753 | .map(u => u.key) 754 | } 755 | 756 | function parseNameToKeys (details, name) { 757 | if (!name) return null 758 | 759 | const keys = [] 760 | 761 | // If it's a 64-character key, use JUST this, since it's unambiguous. 762 | if (/^[0-9a-f]{64}$/.test(name)) { 763 | return [name] 764 | } 765 | 766 | // Is it NAME.KEYPREFIX (with exactly one match)? 767 | if (/\./.test(name)) { 768 | const matches = getNameKeyMatchesFromDetails(details, name) 769 | Array.prototype.push.apply(keys, matches) 770 | } 771 | 772 | // Is it a name? 773 | const users = details.getUsers() 774 | Object.keys(users).forEach(key => { 775 | if (users[key].name === name) { 776 | keys.push(key) 777 | } 778 | }) 779 | 780 | // Is name actually just a pubkey (i.e. a peer w/o name set)? 781 | if (keys.length === 0) { // check that keys === 0 to prevent impersonation by setting pubkey as their name 782 | Object.keys(users).forEach(key => { 783 | if (key.substring(0, name.length) === name && users[key].name === "") { 784 | keys.push(key) 785 | } 786 | }) 787 | } 788 | 789 | return keys 790 | } 791 | 792 | function getPeerName (details, key) { 793 | const users = details.getUsers() 794 | if (key in users) { 795 | return users[key].name || key 796 | } 797 | return key 798 | } 799 | 800 | function parseOptions (input) { 801 | const output = {} 802 | const options = input.slice(input.indexOf("--")).split(/(\s+|^)--/).map(s => s.trim()).filter(s => s !== "") 803 | options.forEach(option => { 804 | const i = option.indexOf(" ") 805 | const optionType = option.slice(0, i) 806 | output[optionType] = option.slice(i).trim() 807 | }) 808 | return output 809 | } 810 | 811 | // extract --