├── .dockerignore ├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── PROVISIONING.md ├── README.md ├── config ├── database.json ├── sample.yaml └── schema.yml ├── db └── .gitkeep ├── docker-start.sh ├── index.js ├── migrations ├── 20170708201820-create-bot-account-data-table.js ├── 20170708235052-create-webhooks-table.js ├── 20170709024537-create-account-data-table.js ├── 20170709024544-drop-bot-account-data.js └── 20181019201945-support-labeled-webhooks.js ├── package-lock.json ├── package.json └── src ├── WebService.js ├── WebhookBridge.js ├── matrix └── AdminRoom.js ├── processing ├── WebhookReceiver.js └── layers │ ├── avatar │ ├── default.js │ ├── from_webhook.js │ ├── slack_icon_emoji.js │ └── slack_icon_url.js │ ├── displayName │ ├── default.js │ ├── emoji.js │ ├── from_webhook.js │ └── slack.js │ ├── message │ ├── emoji.js │ ├── from_slack_attachments.js │ ├── from_webhook.js │ ├── html.js │ ├── html_fallback.js │ ├── msgtype.js │ ├── slack_fallback.js │ └── slack_links.js │ └── postprocess │ └── upload_images.js ├── provisioning ├── InteractiveProvisioner.js └── ProvisioningService.js ├── storage ├── WebhookStore.js └── models │ ├── account_data.js │ └── webhooks.js └── utils.js /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | .gitignore 3 | README.md 4 | Dockerfile 5 | docker-compose.yml 6 | node_modules 7 | logs 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | 3 | room-store.db 4 | user-store.db 5 | 6 | db/*.db 7 | 8 | config/config.yaml 9 | scripts/config.json 10 | appservice-registration-webhooks.yaml 11 | rooms.db 12 | users.db 13 | docker-compose.yaml 14 | 15 | # Logs 16 | logs 17 | *.log 18 | npm-debug.log* 19 | yarn-debug.log* 20 | yarn-error.log* 21 | 22 | # Runtime data 23 | pids 24 | *.pid 25 | *.seed 26 | *.pid.lock 27 | 28 | # Directory for instrumented libs generated by jscoverage/JSCover 29 | lib-cov 30 | 31 | # Coverage directory used by tools like istanbul 32 | coverage 33 | 34 | # nyc test coverage 35 | .nyc_output 36 | 37 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 38 | .grunt 39 | 40 | # Bower dependency directory (https://bower.io/) 41 | bower_components 42 | 43 | # node-waf configuration 44 | .lock-wscript 45 | 46 | # Compiled binary addons (http://nodejs.org/api/addons.html) 47 | build/Release 48 | 49 | # Dependency directories 50 | node_modules/ 51 | jspm_packages/ 52 | 53 | # Typescript v1 declaration files 54 | typings/ 55 | 56 | # Optional npm cache directory 57 | .npm 58 | 59 | # Optional eslint cache 60 | .eslintcache 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | 74 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6" 4 | before_install: 5 | - npm i -g npm 6 | install: 7 | - npm install 8 | #script: 9 | # - npm run build 10 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:10-alpine 2 | 3 | COPY . / 4 | 5 | ENV NODE_ENV=development 6 | RUN apk add --no-cache -t build-deps make gcc g++ python libc-dev wget git dos2unix \ 7 | && apk add --no-cache ca-certificates \ 8 | && cd / \ 9 | && npm install \ 10 | && dos2unix docker-start.sh \ 11 | && chmod +x docker-start.sh \ 12 | && apk del build-deps \ 13 | && ls 14 | 15 | ENV NODE_ENV=production 16 | ENV WEBHOOKS_USER_STORE_PATH=/data/user-store.db 17 | ENV WEBHOOKS_ROOM_STORE_PATH=/data/room-store.db 18 | ENV WEBHOOKS_DB_CONFIG_PATH=/data/database.json 19 | ENV WEBHOOKS_ENV=docker 20 | 21 | WORKDIR / 22 | CMD /docker-start.sh 23 | 24 | EXPOSE 9000 25 | VOLUME ["/data"] 26 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | -------------------------------------------------------------------------------- /PROVISIONING.md: -------------------------------------------------------------------------------- 1 | # Webhooks Provisioning API 2 | 3 | **Note to users of the provisioning API:** The bridge will only work in rooms that it is able to see. Invite the bridge bot (`@_webhook:yourdomain.com`) to the room prior to modifying or querying state. 4 | 5 | ## Endpoints 6 | 7 | All endpoints use the following format for errors (anything not in the 2xx range): 8 | ``` 9 | { 10 | "success": false, 11 | "message": "Something went wrong" 12 | } 13 | ``` 14 | 15 | All endpoints also require the query parameter `token` with the value being the secret in the bridge's configuration. If this token is missing (or not changed from the default), the error will appear as a generic permissions failure. Inspect the response code to determine the nature of the failure (ie: 400 is bad request, 500 is something broken on our end, 403 is wrong token). 16 | 17 | ### `GET /api/v1/provision/info` 18 | 19 | Gets information about the bridge instance, such as the bridge bot user ID. 20 | 21 | **Inputs** 22 | 23 | * *None* 24 | 25 | **Successful Response (200)** 26 | 27 | ``` 28 | { 29 | "success": true, 30 | "botUserId": "@webhook:t2bot.io" 31 | } 32 | ``` 33 | 34 | **Possible Error Messages** 35 | 36 | * *None* 37 | 38 | ### `PUT /api/v1/provision/{roomId}/hook?userId={userId}` 39 | 40 | Creates a new incoming webhook for a room. Outgoing webhooks are not yet supported by the bridge. 41 | 42 | **Inputs** 43 | 44 | | Parameter | Description | Example | 45 | | --------- | ----------- | ------- | 46 | | roomId | The room's internal identifier | `!cURbafjkfsMDVwdRDQ:matrix.org` | 47 | | userId | The user attempting to create the webhook | `@travis:t2l.io` | 48 | 49 | *Request Body*: 50 | ``` 51 | { 52 | "label": "Optional label for the webhook" 53 | } 54 | ``` 55 | 56 | **Successful Response (200)** 57 | 58 | ``` 59 | { 60 | "success": true, 61 | "id": "some_long_string", 62 | "url": "https://webhook.t2bot.io/api/v1/matrix/hook/some_long_string", 63 | "userId": "@travis:t2l.io", 64 | "roomId": "!cURbafjkfsMDVwdRDQ:matrix.org", 65 | "type": "incoming" 66 | } 67 | ``` 68 | 69 | **Possible Error Messages** 70 | 71 | * `User does not have permission to manage webhooks in this room` - appears for invalid room, user, or simple permissions error. 72 | 73 | ### `GET /api/v1/provision/{roomId}/hooks?userId={userId}` 74 | 75 | Lists the webhooks created for a room. Will return an empty collection if no webhooks are configured. 76 | 77 | **Inputs** 78 | 79 | | Parameter | Description | Example | 80 | | --------- | ----------- | ------- | 81 | | roomId | The room's internal identifier | `!cURbafjkfsMDVwdRDQ:matrix.org` | 82 | | userId | The user attempting to view the webhooks | `@travis:t2l.io` | 83 | 84 | **Successful Response (200)** 85 | 86 | ``` 87 | { 88 | "success": true, 89 | "results": [ 90 | { 91 | "id": "some_long_string", 92 | "label": "First Webhook", 93 | "url": "https://webhook.t2bot.io/api/v1/matrix/hook/some_long_string", 94 | "userId": "@travis:t2l.io", 95 | "roomId": "!cURbafjkfsMDVwdRDQ:matrix.org", 96 | "type": "incoming" 97 | }, 98 | { 99 | "id": "another_long_string", 100 | "label": "Second Webhook", 101 | "url": "https://webhook.t2bot.io/api/v1/matrix/hook/another_long_string", 102 | "userId": "@turt2live:matrix.org", 103 | "roomId": "!cURbafjkfsMDVwdRDQ:matrix.org", 104 | "type": "incoming" 105 | } 106 | ] 107 | } 108 | ``` 109 | 110 | **Possible Error Messages** 111 | 112 | * `User does not have permission to manage webhooks in this room` - appears for invalid room, user, or simple permissions error. 113 | 114 | ### `GET /api/v1/provision/{roomId}/hook/{hookId}?userId={userId}` 115 | 116 | Gets the configuration for a given webhook in a room. 117 | 118 | **Inputs** 119 | 120 | | Parameter | Description | Example | 121 | | --------- | ----------- | ------- | 122 | | roomId | The room's internal identifier | `!cURbafjkfsMDVwdRDQ:matrix.org` | 123 | | hookId | The hook ID to get the configuration of | `some_long_string` | 124 | | userId | The user attempting to view the webhooks | `@travis:t2l.io` | 125 | 126 | **Successful Response (200)** 127 | 128 | ``` 129 | { 130 | "success": true, 131 | "id": "some_long_string", 132 | "label": "First Webhook", 133 | "url": "https://webhook.t2bot.io/api/v1/matrix/hook/some_long_string", 134 | "userId": "@travis:t2l.io", 135 | "roomId": "!cURbafjkfsMDVwdRDQ:matrix.org", 136 | "type": "incoming" 137 | } 138 | ``` 139 | 140 | ### `PUT /api/v1/provision/{roomId}/hook/{hookId}?userId={userId}` 141 | 142 | Updates the configuration for a webhook. 143 | 144 | **Inputs** 145 | 146 | | Parameter | Description | Example | 147 | | --------- | ----------- | ------- | 148 | | roomId | The room's internal identifier | `!cURbafjkfsMDVwdRDQ:matrix.org` | 149 | | hookId | The hook ID to set the configuration of | `some_long_string` | 150 | | userId | The user attempting to view the webhooks | `@travis:t2l.io` | 151 | 152 | *Request Body*: 153 | ``` 154 | { 155 | "label": "Optional label for the webhook" 156 | } 157 | ``` 158 | 159 | **Successful Response (200)** 160 | 161 | ``` 162 | { 163 | "success": true, 164 | "id": "some_long_string", 165 | "label": "New Webhook Label", 166 | "url": "https://webhook.t2bot.io/api/v1/matrix/hook/some_long_string", 167 | "userId": "@travis:t2l.io", 168 | "roomId": "!cURbafjkfsMDVwdRDQ:matrix.org", 169 | "type": "incoming" 170 | } 171 | ``` 172 | 173 | **Possible Error Messages** 174 | 175 | * `User does not have permission to manage webhooks in this room` - appears for invalid room, user, or simple permissions error. 176 | 177 | ### `DELETE /api/v1/provision/{roomId}/hook/{hookId}?userId={userId}` 178 | 179 | Deletes a webhook, rendering it useless. 180 | 181 | **Inputs** 182 | 183 | | Parameter | Description | Example | 184 | | --------- | ----------- | ------- | 185 | | roomId | The room's internal identifier | `!cURbafjkfsMDVwdRDQ:matrix.org` | 186 | | hookId | The hook ID to delete | `some_long_string` | 187 | | userId | The user attempting to delete the webhook | `@travis:t2l.io` | 188 | 189 | **Successful Response (200)** 190 | 191 | ``` 192 | { 193 | "success": true 194 | } 195 | ``` 196 | 197 | **Possible Error Messages** 198 | 199 | * `User does not have permission to manage webhooks in this room` - appears for invalid room, user, or simple permissions error. 200 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Planned obsolescence 2 | 3 | Check out [matrix-hookshot](https://github.com/Half-Shot/matrix-hookshot) as a replacement for this archaic bridge :) 4 | 5 | # matrix-appservice-webhooks 6 | 7 | [![TravisCI badge](https://travis-ci.org/turt2live/matrix-appservice-webhooks.svg?branch=master)](https://travis-ci.org/turt2live/matrix-appservice-webhooks) 8 | 9 | Slack-compatible webhooks for Matrix. Talk about it on Matrix: [#webhooks:t2bot.io](https://matrix.to/#/#webhooks:t2bot.io) 10 | 11 | # Usage 12 | 13 | Invite the webhook bridge to your room (`@_webhook:t2bot.io`) and send the message `!webhook`. The bridge bot will then send you a link to send messages to in a private message. You must be able to configure the room in order to set up webhooks. 14 | 15 | # JSON Body (for posting messages) 16 | 17 | ``` 18 | { 19 | "text": "Hello world!", 20 | "format": "plain", 21 | "displayName": "My Cool Webhook", 22 | "avatarUrl": "http://i.imgur.com/IDOBtEJ.png" 23 | } 24 | ``` 25 | 26 | Format can be `plain` or `html`. Emoji will be converted automatically(`:heart:` becomes ❤); set the `emoji` property to `false` to disable this conversion. 27 | To send a notice or emote, add `"msgtype" : "notice"` or `"msgtype" : "emote"` in your request. 28 | 29 | 30 | # Installation 31 | 32 | **Before you begin:** A matrix homeserver and Node 9 or higher are required. 33 | 34 | 1. Clone this repository and install the dependencies 35 | ``` 36 | git clone http://github.com/turt2live/matrix-appservice-webhooks 37 | cd matrix-appservice-webhooks 38 | npm install 39 | ``` 40 | 41 | 2. Copy `config/sample.yaml` to `config/config.yaml` and fill in the appropriate fields 42 | 3. Generate the registration file 43 | ``` 44 | node index.js -r -u "http://localhost:9000" -c config/config.yaml 45 | ``` 46 | *Note:* The default URL to run the appservice is `http://localhost:9000`. If you have other appservices, or other requirements, pick an appropriate hostname and port. 47 | 48 | 4. Copy/symlink the registration file to your Synapse directory 49 | ``` 50 | cd ~/.synapse 51 | ln -s ../matrix-appservice-webhooks/appservice-registration-webhooks.yaml appservice-registration-webhooks.yaml 52 | ``` 53 | 54 | 5. Add the registration file to your `homeserver.yaml` 55 | ``` 56 | ... 57 | app_service_config_files: ["appservice-registration-webhooks.yaml"] 58 | ... 59 | ``` 60 | 61 | 6. Restart Synapse (`synctl restart`, for example) 62 | 63 | # Running 64 | 65 | Using the port specified during the install (`9000` by default), use `node index.js -p 9000 -c config/config.yaml -f appservice-registration-webhooks.yaml` from the repository directory. 66 | 67 | The bridge should start working shortly afterwards. 68 | 69 | ### Docker 70 | 71 | A Docker image of the bridge is available to host the bridge yourself. The image can be built yourself with `docker build -t matrix-appservice-webhooks .` or you can use the image on docker.io: 72 | ``` 73 | docker run -p 9000:9000 -v /path/to/webhooks/dir:/data turt2live/matrix-appservice-webhooks 74 | ``` 75 | 76 | The `/path/to/webhooks/dir` should have an `appservice-registration-webhooks.yaml` file, `config.yaml`, and `database.json`. Additional bridge-related data will be stored here. 77 | 78 | #### Example `appservice-registration-webhooks.yaml` 79 | 80 | ```yaml 81 | id: webhooks 82 | hs_token: A_RANDOM_ALPHANUMERIC_STRING # CHANGE THIS 83 | as_token: ANOTHER_RANDOM_ALPHANUMERIC_STRING # CHANGE THIS 84 | namespaces: 85 | users: 86 | - exclusive: true 87 | regex: '@_webhook.*' 88 | aliases: [] 89 | rooms: [] 90 | url: 'http://localhost:9002' # you may need to change this (this should point at the bridge) 91 | sender_localpart: _webhook 92 | rate_limited: false 93 | protocols: null 94 | ``` 95 | -------------------------------------------------------------------------------- /config/database.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultEnv": { 3 | "ENV": "NODE_ENV" 4 | }, 5 | "development": { 6 | "driver": "sqlite3", 7 | "filename": "db/development.db" 8 | }, 9 | "production": { 10 | "driver": "sqlite3", 11 | "filename": "db/production.db" 12 | } 13 | } -------------------------------------------------------------------------------- /config/sample.yaml: -------------------------------------------------------------------------------- 1 | # Configuration specific to the application service. All fields (unless otherwise marked) are required. 2 | homeserver: 3 | # The domain for the client-server API calls. 4 | url: "http://localhost:8008" 5 | 6 | # The domain part for user IDs on this home server. Usually, but not always, this is the same as the 7 | # home server's URL. 8 | domain: "localhost" 9 | 10 | # Configuration specific to the bridge. All fields (unless otherwise marked) are required. 11 | webhookBot: 12 | # The localpart to use for the bot. May require re-registering the application service. 13 | localpart: "_webhook" 14 | 15 | # Appearance options for the Matrix bot 16 | appearance: 17 | displayName: "Webhook Bridge" 18 | avatarUrl: "http://i.imgur.com/IDOBtEJ.png" # webhook icon 19 | 20 | # Provisioning API options 21 | provisioning: 22 | # Your secret for the API. Required for all provisioning API requests. 23 | secret: 'CHANGE_ME' 24 | 25 | # Configuration related to the web portion of the bridge. Handles the inbound webhooks 26 | web: 27 | hookUrlBase: 'http://localhost:9000/' 28 | 29 | logging: 30 | file: logs/webhook.log 31 | console: true 32 | consoleLevel: info 33 | fileLevel: verbose 34 | writeFiles: true 35 | rotate: 36 | size: 52428800 # bytes, default is 50mb 37 | count: 5 38 | -------------------------------------------------------------------------------- /config/schema.yml: -------------------------------------------------------------------------------- 1 | "$schema": "http://json-schema.org/draft-04/schema#" 2 | type: "object" 3 | properties: 4 | provisioning: 5 | type: "object" 6 | properties: 7 | secret: 8 | type: "string" 9 | homeserver: 10 | type: "object" 11 | properties: 12 | domain: 13 | type: "string" 14 | url: 15 | type: "string" 16 | mediaUrl: 17 | type: "string" 18 | web: 19 | type: "object" 20 | properties: 21 | hookUrlBase: 22 | type: "string" 23 | webhookBot: 24 | type: "object" 25 | properties: 26 | localpart: 27 | type: "string" 28 | appearance: 29 | type: "object" 30 | properties: 31 | displayName: 32 | type: "string" 33 | avatarUrl: 34 | type: "string" 35 | logging: 36 | type: "object" 37 | properties: 38 | file: 39 | type: "string" 40 | console: 41 | type: "boolean" 42 | consoleLevel: 43 | type: "string" 44 | fileLevel: 45 | type: "string" 46 | writeFiles: 47 | type: "boolean" 48 | rotate: 49 | type: "object" 50 | properties: 51 | size: 52 | type: "number" 53 | count: 54 | type: "number" 55 | -------------------------------------------------------------------------------- /db/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/turt2live/matrix-appservice-webhooks/233a4e934f5090e5bd62b9e5e24b573845836a5a/db/.gitkeep -------------------------------------------------------------------------------- /docker-start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Migrate the registration file if possible 4 | if [ ! -f "/data/appservice-registration-webhooks.yaml" ]; then 5 | echo "Registration file does not exist - trying to copy old one" 6 | cp -v /data/appservice-webhooks-registration.yaml /data/appservice-registration-webhooks.yaml 7 | fi 8 | 9 | # Actually run the bridge 10 | node index.js -p 9000 -c /data/config.yaml -f /data/appservice-registration-webhooks.yaml -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const LogService = require("matrix-js-snippets").LogService; 2 | const Cli = require("matrix-appservice-bridge").Cli; 3 | const AppServiceRegistration = require("matrix-appservice-bridge").AppServiceRegistration; 4 | const path = require("path"); 5 | const WebhookStore = require("./src/storage/WebhookStore"); 6 | const WebhookBridge = require("./src/WebhookBridge"); 7 | const WebService = require("./src/WebService"); 8 | 9 | const cli = new Cli({ 10 | registrationPath: "appservice-registration-webhooks.yaml", 11 | enableRegistration: true, 12 | enableLocalpart: true, 13 | bridgeConfig: { 14 | affectsRegistration: true, 15 | schema: path.join(__dirname, "config/schema.yml"), 16 | defaults: { 17 | homeserver: { 18 | url: "http://localhost:8008", 19 | mediaUrl: "http://localhost:8008", 20 | domain: "localhost" 21 | }, 22 | webhookBot: { 23 | localpart: "_webhook", 24 | appearance: { 25 | displayName: "Webhook Bridge", 26 | avatarUrl: "http://i.imgur.com/IDOBtEJ.png" // webhook bridge icon 27 | } 28 | }, 29 | web: { 30 | hookUrlBase: 'http://localhost:9000', 31 | }, 32 | provisioning: { 33 | secret: 'CHANGE_ME' 34 | }, 35 | logging: { 36 | file: "logs/webhook.log", 37 | console: true, 38 | consoleLevel: 'info', 39 | fileLevel: 'verbose', 40 | rotate: { 41 | size: 52428800, 42 | count: 5 43 | } 44 | } 45 | } 46 | }, 47 | generateRegistration: function (registration, callback) { 48 | registration.setId(AppServiceRegistration.generateToken()); 49 | registration.setHomeserverToken(AppServiceRegistration.generateToken()); 50 | registration.setAppServiceToken(AppServiceRegistration.generateToken()); 51 | registration.setRateLimited(false); // disabled because webhooks can get spammy 52 | 53 | if (!registration.getSenderLocalpart()) { 54 | const config = cli.getConfig(); 55 | registration.setSenderLocalpart(config.webhookBot.localpart); 56 | } 57 | 58 | registration.addRegexPattern("users", "@_webhook.*", true); 59 | 60 | callback(registration); 61 | }, 62 | run: function (port, config, registration) { 63 | LogService.configure(config.logging); 64 | LogService.info("index", "Preparing database..."); 65 | let bridge = null; 66 | WebhookStore.prepare() 67 | .then(() => { 68 | LogService.info("index", "Preparing bridge..."); 69 | bridge = WebhookBridge.init(config, registration); 70 | return WebhookBridge.run(port); 71 | }) 72 | .then(() => { 73 | if (config.provisioning.secret !== "CHANGE_ME") WebService.setSharedToken(config.provisioning.secret); 74 | else LogService.warn("index", "No provisioning API token is set - the provisioning API will not work for this bridge"); 75 | 76 | WebService.setApp(bridge.appService.app); 77 | return WebService.start(config.web.hookUrlBase); 78 | }) 79 | .catch(err => { 80 | LogService.error("Init", "Failed to start bridge"); 81 | throw err; 82 | }); 83 | } 84 | }); 85 | cli.run(); 86 | -------------------------------------------------------------------------------- /migrations/20170708201820-create-bot-account-data-table.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | let dbm; 4 | let type; 5 | let seed; 6 | 7 | /** 8 | * We receive the dbmigrate dependency from dbmigrate initially. 9 | * This enables us to not have to rely on NODE_PATH. 10 | */ 11 | exports.setup = function (options, seedLink) { 12 | dbm = options.dbmigrate; 13 | type = dbm.dataType; 14 | seed = seedLink; 15 | }; 16 | 17 | exports.up = function (db) { 18 | return db.createTable("bot_account_data", { 19 | key: {type: 'string', primaryKey: true, notNull: true}, 20 | value: {type: 'string', notNull: true} 21 | }); 22 | }; 23 | 24 | exports.down = function (db) { 25 | return db.dropTable("bot_account_data"); 26 | }; 27 | 28 | exports._meta = { 29 | "version": 1 30 | }; 31 | -------------------------------------------------------------------------------- /migrations/20170708235052-create-webhooks-table.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | let dbm; 4 | let type; 5 | let seed; 6 | 7 | /** 8 | * We receive the dbmigrate dependency from dbmigrate initially. 9 | * This enables us to not have to rely on NODE_PATH. 10 | */ 11 | exports.setup = function (options, seedLink) { 12 | dbm = options.dbmigrate; 13 | type = dbm.dataType; 14 | seed = seedLink; 15 | }; 16 | 17 | exports.up = function (db) { 18 | return db.createTable("webhooks", { 19 | id: {type: 'string', primaryKey: true, notNull: true}, 20 | roomId: {type: 'string', notNull: true}, 21 | userId: {type: 'string', notNull: true} 22 | }); 23 | }; 24 | 25 | exports.down = function (db) { 26 | return db.dropTable("webhooks"); 27 | }; 28 | 29 | exports._meta = { 30 | "version": 1 31 | }; 32 | -------------------------------------------------------------------------------- /migrations/20170709024537-create-account-data-table.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | let dbm; 4 | let type; 5 | let seed; 6 | 7 | /** 8 | * We receive the dbmigrate dependency from dbmigrate initially. 9 | * This enables us to not have to rely on NODE_PATH. 10 | */ 11 | exports.setup = function (options, seedLink) { 12 | dbm = options.dbmigrate; 13 | type = dbm.dataType; 14 | seed = seedLink; 15 | }; 16 | 17 | exports.up = function (db) { 18 | return db.createTable("account_data", { 19 | id: {type: 'int', primaryKey: true, notNull: true, autoIncrement: true}, 20 | objectId: {type: 'string', notNull: true}, 21 | key: {type: 'string', notNull: true}, 22 | value: {type: 'string', notNull: true} 23 | }); 24 | }; 25 | 26 | exports.down = function (db) { 27 | return db.dropTable("account_data"); 28 | }; 29 | 30 | exports._meta = { 31 | "version": 1 32 | }; 33 | -------------------------------------------------------------------------------- /migrations/20170709024544-drop-bot-account-data.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | let dbm; 4 | let type; 5 | let seed; 6 | 7 | /** 8 | * We receive the dbmigrate dependency from dbmigrate initially. 9 | * This enables us to not have to rely on NODE_PATH. 10 | */ 11 | exports.setup = function (options, seedLink) { 12 | dbm = options.dbmigrate; 13 | type = dbm.dataType; 14 | seed = seedLink; 15 | }; 16 | 17 | exports.up = function (db) { 18 | return db.dropTable("bot_account_data"); 19 | }; 20 | 21 | exports.down = function (db) { 22 | return db.createTable("bot_account_data", { 23 | key: {type: 'string', primaryKey: true, notNull: true}, 24 | value: {type: 'string', notNull: true} 25 | }); 26 | }; 27 | 28 | exports._meta = { 29 | "version": 1 30 | }; 31 | -------------------------------------------------------------------------------- /migrations/20181019201945-support-labeled-webhooks.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | let dbm; 4 | let type; 5 | let seed; 6 | 7 | /** 8 | * We receive the dbmigrate dependency from dbmigrate initially. 9 | * This enables us to not have to rely on NODE_PATH. 10 | */ 11 | exports.setup = function (options, seedLink) { 12 | dbm = options.dbmigrate; 13 | type = dbm.dataType; 14 | seed = seedLink; 15 | }; 16 | 17 | exports.up = function (db) { 18 | return db.addColumn("webhooks", "label", {type: 'string', notNull: false}); 19 | }; 20 | 21 | exports.down = function (db) { 22 | return db.removeColumn("webhooks", "label"); 23 | }; 24 | 25 | exports._meta = { 26 | "version": 1 27 | }; 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "matrix-appservice-webhooks", 3 | "version": "1.0.0", 4 | "description": "Slack-compatible webhooks for Matrix", 5 | "main": "index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/turt2live/matrix-appservice-webhooks.git" 9 | }, 10 | "keywords": [ 11 | "matrix", 12 | "appservice", 13 | "webhook", 14 | "webhooks", 15 | "slack", 16 | "bridge", 17 | "integration" 18 | ], 19 | "author": "Travis Ralston (http://travisralston.me)", 20 | "license": "GPL-3.0", 21 | "bugs": { 22 | "url": "https://github.com/turt2live/matrix-appservice-webhooks/issues" 23 | }, 24 | "homepage": "https://github.com/turt2live/matrix-appservice-webhooks#readme", 25 | "dependencies": { 26 | "bluebird": "^3.5.2", 27 | "body-parser": "^1.18.3", 28 | "chalk": "^2.4.1", 29 | "cheerio": "^1.0.0-rc.2", 30 | "db-migrate": "^0.11.3", 31 | "db-migrate-sqlite3": "^0.3.1", 32 | "emojione": "^3.1.7", 33 | "express": "^4.16.4", 34 | "express-interceptor": "^1.2.0", 35 | "lodash": "^4.17.13", 36 | "matrix-appservice-bridge": "^2.6.0", 37 | "matrix-js-snippets": "^0.2.8", 38 | "mime": "^2.3.1", 39 | "mkdirp": "^0.5.1", 40 | "moment": "^2.29.2", 41 | "node-emoji": "^1.8.1", 42 | "parse-data-uri": "^0.2.0", 43 | "pubsub-js": "^1.7.0", 44 | "random-string": "^0.2.0", 45 | "request": "^2.88.0", 46 | "sequelize": "^4.40.0", 47 | "sqlite3": "^4.0.2", 48 | "striptags": "^3.1.1", 49 | "uuid": "^3.3.0", 50 | "winston": "^2.4.4" 51 | }, 52 | "optionalDependencies": {} 53 | } 54 | -------------------------------------------------------------------------------- /src/WebService.js: -------------------------------------------------------------------------------- 1 | const bodyParser = require("body-parser"); 2 | const PubSub = require('pubsub-js'); 3 | const LogService = require("matrix-js-snippets").LogService; 4 | const WebhookStore = require("./storage/WebhookStore"); 5 | const ProvisioningService = require("./provisioning/ProvisioningService"); 6 | const _ = require("lodash"); 7 | const interceptor = require("express-interceptor"); 8 | 9 | // TODO: Migrate provisioning API out of this class 10 | 11 | class WebService { 12 | constructor() { 13 | } 14 | 15 | setApp(app) { 16 | this._app = app; 17 | this._app.use(bodyParser.json()); 18 | this._app.use(bodyParser.urlencoded({extended: true})); 19 | 20 | // Logging incoming requests 21 | this._app.use((req, res, next) => { 22 | LogService.verbose("WebService", "Incoming: " + req.method + " " + req.url); 23 | next(); 24 | }); 25 | 26 | // Make sure everything we return is JSON 27 | this._installInterceptor(); 28 | this._app.use((err, req, res, next) => { 29 | LogService.error("WebService", err); 30 | 31 | let status = 500; 32 | let message = "Internal Server Error"; 33 | if (err.message.startsWith("Unexpected token ") && err.message.includes("in JSON at position")) { 34 | message = err.message; 35 | status = 400; 36 | } 37 | 38 | res.status(status); 39 | res.set('Content-Type', "application/json"); 40 | res.send(JSON.stringify(this._constructError(res, message))); 41 | next('Error encountered during hook processing'); 42 | }); 43 | 44 | this._app.post("/api/v1/matrix/hook/:hookId", this._postWebhook.bind(this)); 45 | 46 | // Provisioning API 47 | this._app.get("/api/v1/provision/info", this._getBridgeInfo.bind(this)); 48 | this._app.put("/api/v1/provision/:roomId/hook", this._provisionHook.bind(this)); 49 | this._app.get("/api/v1/provision/:roomId/hooks", this._listHooks.bind(this)); 50 | this._app.get("/api/v1/provision/:roomId/hook/:hookId", this._getHook.bind(this)); 51 | this._app.put("/api/v1/provision/:roomId/hook/:hookId", this._updateHook.bind(this)); 52 | this._app.delete("/api/v1/provision/:roomId/hook/:hookId", this._deleteHook.bind(this)); 53 | } 54 | 55 | _installInterceptor() { 56 | const finalParagraphInterceptor = interceptor((req, res) => { 57 | return { 58 | isInterceptable: () => { 59 | return res.get('Content-Type').startsWith("text/plain") || res.get('Content-Type').startsWith("text/html"); 60 | }, 61 | intercept: (body, send) => { 62 | res.set('Content-Type', "application/json"); 63 | send(JSON.stringify(this._constructError(res, body))); 64 | } 65 | }; 66 | }); 67 | this._app.use(finalParagraphInterceptor); 68 | } 69 | 70 | _constructError(res, body) { 71 | const contentType = res.get('Content-Type'); 72 | const statusCode = res.statusCode; 73 | 74 | return { 75 | statusCode: statusCode, 76 | success: !(statusCode < 200 || statusCode >= 300), 77 | error: body, 78 | originalMime: contentType 79 | }; 80 | } 81 | 82 | _postWebhook(request, response) { 83 | response.setHeader("Content-Type", "application/json"); 84 | 85 | const contentType = request.headers['content-type']; 86 | if (contentType && contentType.toLowerCase() === 'application/x-www-form-urlencoded') { 87 | request.body = JSON.parse(request.body.payload || "{}"); 88 | } else if (typeof(request.body) === "string") { 89 | request.body = JSON.parse(request.body); 90 | } 91 | 92 | let hookInfo = request.body; 93 | LogService.verbose("WebService [Hook " + request.params.hookId + "]", hookInfo); 94 | if (!hookInfo || !(hookInfo["text"] || (hookInfo["attachments"] && hookInfo["attachments"].length > 0))) { 95 | LogService.error("WebService [Hook " + request.params.hookId + "]", "Invalid message: missing text or attachments"); 96 | response.status(400).send({error: 'Missing message text or attachments', success: false}); 97 | return; 98 | } 99 | 100 | WebhookStore.getWebhook(request.params.hookId).then(hook => { 101 | if (!hook) { 102 | LogService.error("WebService [Hook " + request.params.hookId + "]", "Invalid hook ID"); 103 | response.status(400).send({error: 'Invalid hook ID', success: false}); 104 | return; 105 | } 106 | 107 | LogService.info("WebService [Hook " + request.params.hookId + "]", "Publishing webhook request for processing"); 108 | PubSub.publish("incoming_webhook", { 109 | hookId: request.params.hookId, 110 | hook: hook, 111 | payload: hookInfo 112 | }); 113 | response.status(200).send({success: true, queued: true}); 114 | }).catch(error => { 115 | LogService.error("WebService [Hook " + request.params.hookId + "]", error); 116 | response.status(500).send({error: 'Unknown error processing webhook', success: false}); 117 | }); 118 | } 119 | 120 | _provisioningApiTest(roomId, userId, token, response, hookId = null, expectingHookId = false) { 121 | if (!roomId || !userId || !token || (!hookId && expectingHookId)) { 122 | LogService.warn("WebService", "Request is missing a required parameter"); 123 | response.status(400).send({success: false, message: ProvisioningService.PERMISSION_ERROR_MESSAGE}); 124 | return false; 125 | } 126 | 127 | if (!this._token || this._token !== token) { 128 | LogService.warn("WebService", "Invalid token"); 129 | response.status(403).send({success: false, message: ProvisioningService.PERMISSION_ERROR_MESSAGE}); 130 | return false; 131 | } 132 | 133 | return true; 134 | } 135 | 136 | _provisioningApiWebhook(webhook) { 137 | return { 138 | id: webhook.id, 139 | label: webhook.label, 140 | userId: webhook.userId, 141 | roomId: webhook.roomId, 142 | url: this.getHookUrl(webhook.id), 143 | type: "incoming", // we don't actually support anything else, this is just in case we do in the future. 144 | }; 145 | } 146 | 147 | _provisioningApiCatch(error, response) { 148 | if (error === ProvisioningService.PERMISSION_ERROR_MESSAGE) { 149 | response.status(400).send({success: false, message: error}); 150 | return; 151 | } 152 | 153 | LogService.error("WebService", error); 154 | response.status(500).send({success: false, message: "Unknown error processing request"}); 155 | } 156 | 157 | _getBridgeInfo(request, response) { 158 | const token = request.query.token; 159 | 160 | if (!this._token || this._token !== token) { 161 | LogService.warn("WebService", "Invalid token"); 162 | response.status(403).send({success: false, message: ProvisioningService.PERMISSION_ERROR_MESSAGE}); 163 | } else { 164 | response.status(200).send({ 165 | success: true, 166 | botUserId: ProvisioningService.getBotUserId(), 167 | }); 168 | } 169 | } 170 | 171 | _provisionHook(request, response) { 172 | const roomId = request.params.roomId; 173 | const userId = request.query.userId; 174 | const token = request.query.token; 175 | 176 | if (typeof(request.body) === "string") { 177 | request.body = JSON.parse(request.body); 178 | } else if (!request.body) { 179 | request.body = {}; 180 | } 181 | 182 | const label = request.body["label"]; 183 | 184 | if (!this._provisioningApiTest(roomId, userId, token, response)) return; 185 | 186 | ProvisioningService.createWebhook(roomId, userId, label).then(webhook => { 187 | LogService.info("WebService", "Webhook created with provisioning api: " + webhook.id); 188 | response.status(200).send(this._provisioningApiWebhook(webhook)); 189 | }).catch(error => this._provisioningApiCatch(error, response)); 190 | } 191 | 192 | _getHook(request, response) { 193 | const roomId = request.params.roomId; 194 | const hookId = request.params.hookId; 195 | const userId = request.query.userId; 196 | const token = request.query.token; 197 | 198 | if (!this._provisioningApiTest(roomId, userId, token, response, hookId, true)) return; 199 | 200 | ProvisioningService.getWebhook(roomId, userId, hookId).then(webhook => { 201 | response.status(200).send(this._provisioningApiWebhook(webhook)); 202 | }).catch(error => this._provisioningApiCatch(error, response)); 203 | } 204 | 205 | _updateHook(request, response) { 206 | const roomId = request.params.roomId; 207 | const hookId = request.params.hookId; 208 | const userId = request.query.userId; 209 | const token = request.query.token; 210 | 211 | if (typeof(request.body) === "string") { 212 | request.body = JSON.parse(request.body); 213 | } else if (!request.body) { 214 | request.body = {}; 215 | } 216 | 217 | const newLabel = request.body["label"]; 218 | 219 | if (!this._provisioningApiTest(roomId, userId, token, response, hookId, true)) return; 220 | 221 | ProvisioningService.updateWebhook(roomId, userId, hookId, newLabel).then(webhook => { 222 | response.status(200).send(this._provisioningApiWebhook(webhook)); 223 | }).catch(error => this._provisioningApiCatch(error, response)); 224 | } 225 | 226 | _listHooks(request, response) { 227 | const roomId = request.params.roomId; 228 | const userId = request.query.userId; 229 | const token = request.query.token; 230 | 231 | if (!this._provisioningApiTest(roomId, userId, token, response)) return; 232 | 233 | ProvisioningService.getWebhooks(roomId, userId).then(webhooks => { 234 | response.status(200).send({ 235 | success: true, 236 | results: _.map(webhooks, h => this._provisioningApiWebhook(h)) 237 | }); 238 | }).catch(error => this._provisioningApiCatch(error, response)); 239 | } 240 | 241 | _deleteHook(request, response) { 242 | const hookId = request.params.hookId; 243 | const roomId = request.params.roomId; 244 | const userId = request.query.userId; 245 | const token = request.query.token; 246 | 247 | if (!this._provisioningApiTest(roomId, userId, token, response, hookId, true)) return; 248 | 249 | ProvisioningService.deleteWebhook(roomId, userId, hookId).then(() => { 250 | response.status(200).send({success: true}); 251 | }).catch(error => this._provisioningApiCatch(error, response)); 252 | } 253 | 254 | setSharedToken(token) { 255 | this._token = token; 256 | } 257 | 258 | start(baseAddress) { 259 | this._baseAddress = baseAddress; 260 | } 261 | 262 | getHookUrl(hookId) { 263 | if (this._baseAddress.endsWith("/")) 264 | this._baseAddress = this._baseAddress.substring(0, this._baseAddress.length - 1); 265 | return this._baseAddress + "/api/v1/matrix/hook/" + hookId; 266 | } 267 | } 268 | 269 | module.exports = new WebService(); 270 | -------------------------------------------------------------------------------- /src/WebhookBridge.js: -------------------------------------------------------------------------------- 1 | const Bridge = require("matrix-appservice-bridge").Bridge; 2 | const LogService = require("matrix-js-snippets").LogService; 3 | const AdminRoom = require("./matrix/AdminRoom"); 4 | const util = require("./utils"); 5 | const WebhookStore = require("./storage/WebhookStore"); 6 | const Promise = require('bluebird'); 7 | const _ = require('lodash'); 8 | const WebService = require("./WebService"); 9 | const ProvisioningService = require("./provisioning/ProvisioningService"); 10 | const InteractiveProvisioner = require("./provisioning/InteractiveProvisioner"); 11 | const WebhookReceiver = require("./processing/WebhookReceiver"); 12 | 13 | class WebhookBridge { 14 | constructor() { 15 | this._adminRooms = {}; // { roomId: AdminRoom } 16 | } 17 | 18 | init(config, registration) { 19 | LogService.info("WebhookBridge", "Constructing bridge"); 20 | 21 | this._config = config; 22 | this._registration = registration; 23 | 24 | this._bridge = new Bridge({ 25 | registration: this._registration, 26 | homeserverUrl: this._config.homeserver.url, 27 | domain: this._config.homeserver.domain, 28 | userStore: process.env["WEBHOOKS_USER_STORE_PATH"] || "user-store.db", 29 | roomStore: process.env["WEBHOOKS_ROOM_STORE_PATH"] || "room-store.db", 30 | controller: { 31 | onEvent: this._onEvent.bind(this), 32 | // none of these are used because the bridge doesn't allow users to create rooms or users 33 | // onUserQuery: this._onUserQuery.bind(this), 34 | // onAliasQuery: this._onAliasQuery.bind(this), 35 | // onAliasQueried: this._onAliasQueried.bind(this), 36 | onLog: (line, isError) => { 37 | const method = isError ? LogService.error : LogService.verbose; 38 | method("matrix-appservice-bridge", line); 39 | } 40 | }, 41 | suppressEcho: false, 42 | queue: { 43 | type: "none", 44 | perRequest: false 45 | }, 46 | intentOptions: { 47 | clients: { 48 | dontCheckPowerLevel: true 49 | }, 50 | bot: { 51 | dontCheckPowerLevel: true 52 | } 53 | } 54 | }); 55 | 56 | return this._bridge; 57 | } 58 | 59 | run(port) { 60 | LogService.info("WebhookBridge", "Starting bridge"); 61 | return this._bridge.run(port, this._config) 62 | // TODO: There must be a better way to do this 63 | .then(() => ProvisioningService.setClient(this.getBotIntent())) 64 | .then(() => InteractiveProvisioner.setBridge(this)) 65 | .then(() => WebhookReceiver.setBridge(this)) 66 | //.then(() => this._updateBotProfile()) 67 | .then(() => this._bridgeKnownRooms()) 68 | .catch(error => LogService.error("WebhookBridge", error)); 69 | } 70 | 71 | /** 72 | * Gets the bridge bot powering the bridge 73 | * @return {AppServiceBot} the bridge bot 74 | */ 75 | getBot() { 76 | return this._bridge.getBot(); 77 | } 78 | 79 | /** 80 | * Gets the bridge bot as an intent 81 | * @return {Intent} the bridge bot 82 | */ 83 | getBotIntent() { 84 | return this._bridge.getIntent(this._bridge.getBot().getUserId()); 85 | } 86 | 87 | /** 88 | * Gets the intent for an Webhook virtual user 89 | * @param {string} handle the Webhook username 90 | * @return {Intent} the virtual user intent 91 | */ 92 | getWebhookUserIntent(handle) { 93 | return this._bridge.getIntentFromLocalpart("_webhook_" + handle); 94 | } 95 | 96 | getOrCreateAdminRoom(userId) { 97 | const roomIds = _.keys(this._adminRooms); 98 | for (let roomId of roomIds) { 99 | if (!this._adminRooms[roomId]) continue; 100 | if (this._adminRooms[roomId].owner === userId) 101 | return Promise.resolve(this._adminRooms[roomId]); 102 | } 103 | 104 | return this.getBotIntent().createRoom({ 105 | createAsClient: false, // use bot 106 | options: { 107 | invite: [userId], 108 | is_direct: true, 109 | preset: "trusted_private_chat", 110 | visibility: "private", 111 | initial_state: [{content: {guest_access: "can_join"}, type: "m.room.guest_access", state_key: ""}] 112 | } 113 | }).then(room => { 114 | const newRoomId = room.room_id; 115 | return this._processRoom(newRoomId, /*adminRoomOwner=*/userId).then(() => { 116 | let room = this._adminRooms[newRoomId]; 117 | if (!room) throw new Error("Could not create admin room for " + userId); 118 | return room; 119 | }); 120 | }); 121 | } 122 | 123 | /** 124 | * Updates the bridge bot's appearance in matrix 125 | * @private 126 | */ 127 | _updateBotProfile() { 128 | return; 129 | LogService.info("WebhookBridge", "Updating appearance of bridge bot"); 130 | 131 | const desiredDisplayName = this._config.webhookBot.appearance.displayName || "Webhook Bridge"; 132 | const desiredAvatarUrl = this._config.webhookBot.appearance.avatarUrl || "http://i.imgur.com/IDOBtEJ.png"; // webhook icon 133 | 134 | const botIntent = this.getBotIntent(); 135 | 136 | WebhookStore.getAccountData('bridge').then(botProfile => { 137 | let avatarUrl = botProfile.avatarUrl; 138 | if (!avatarUrl || avatarUrl !== desiredAvatarUrl) { 139 | util.uploadContentFromUrl(this._bridge, desiredAvatarUrl, botIntent).then(mxcUrl => { 140 | LogService.verbose("WebhookBridge", "Avatar MXC URL = " + mxcUrl); 141 | LogService.info("WebhookBridge", "Updating avatar for bridge bot"); 142 | botIntent.setAvatarUrl(mxcUrl); 143 | botProfile.avatarUrl = desiredAvatarUrl; 144 | WebhookStore.setAccountData('bridge', botProfile); 145 | }); 146 | } 147 | botIntent.getProfileInfo(this._bridge.getBot().getUserId(), 'displayname').then(profile => { 148 | if (profile.displayname != desiredDisplayName) { 149 | LogService.info("WebhookBridge", "Updating display name from '" + profile.displayname + "' to '" + desiredDisplayName + "'"); 150 | botIntent.setDisplayName(desiredDisplayName); 151 | } 152 | }); 153 | }); 154 | } 155 | 156 | /** 157 | * Updates a webhook bot's appearance in matrix 158 | */ 159 | updateHookProfile(intent, desiredDisplayName, desiredAvatarUrl) { 160 | LogService.info("WebhookBridge", "Updating appearance of " + intent.getClient().credentials.userId); 161 | 162 | return WebhookStore.getAccountData(intent.getClient().credentials.userId).then(botProfile => { 163 | const promises = []; 164 | 165 | let avatarUrl = botProfile.avatarUrl; 166 | if ((!avatarUrl || avatarUrl !== desiredAvatarUrl) && desiredAvatarUrl) { 167 | let uploadPromise = Promise.resolve(desiredAvatarUrl); 168 | if (!desiredAvatarUrl.startsWith("mxc://")) 169 | uploadPromise = util.uploadContentFromUrl(this._bridge, desiredAvatarUrl, this.getBotIntent()); 170 | 171 | promises.push(uploadPromise.then(mxcUrl => { 172 | LogService.verbose("WebhookBridge", "Avatar MXC URL = " + mxcUrl); 173 | LogService.info("WebhookBridge", "Updating avatar for " + intent.getClient().credentials.userId); 174 | return intent.setAvatarUrl(mxcUrl).then(() => { 175 | botProfile.avatarUrl = desiredAvatarUrl; 176 | WebhookStore.setAccountData(intent.getClient().credentials.userId, botProfile); 177 | }); 178 | })); 179 | } 180 | 181 | promises.push(intent.getProfileInfo(intent.getClient().credentials.userId, 'displayname').then(profile => { 182 | if (profile.displayname != desiredDisplayName) { 183 | LogService.info("WebhookBridge", "Updating display name from '" + profile.displayname + "' to '" + desiredDisplayName + "' on " + intent.getClient().credentials.userId); 184 | intent.setDisplayName(desiredDisplayName); 185 | } 186 | })); 187 | 188 | return Promise.all(promises); 189 | }); 190 | } 191 | 192 | /** 193 | * Updates the bridge information on all rooms the bridge bot participates in 194 | * @private 195 | */ 196 | _bridgeKnownRooms() { 197 | const process = (roomId) => { 198 | this._processRoom(roomId).catch(e => { 199 | LogService.error("WebhookBridge", `Error bridging room ${roomId}:`); 200 | LogService.error("WebhookBridge", e); 201 | }); 202 | }; 203 | this._bridge.getBot().getJoinedRooms().then(rooms => { 204 | for (let roomId of rooms) { 205 | process(roomId); 206 | } 207 | }); 208 | } 209 | 210 | /** 211 | * Attempts to determine if a room is a bridged room or an admin room, based on the membership and other 212 | * room information. This will categorize the room accordingly and prepare it for it's purpose. 213 | * @param {string} roomId the matrix room ID to process 214 | * @param {String} [adminRoomOwner] the owner of the admin room. If provided, the room will be forced as an admin room 215 | * @return {Promise<>} resolves when processing is complete 216 | * @private 217 | */ 218 | _processRoom(roomId, adminRoomOwner = null) { 219 | LogService.info("WebhookBridge", "Request to bridge room " + roomId); 220 | return this._bridge.getBot().getJoinedMembers(roomId).then(members => { 221 | const roomMemberIds = _.keys(members); 222 | const botIdx = roomMemberIds.indexOf(this._bridge.getBot().getUserId()); 223 | 224 | if (roomMemberIds.length === 2 || adminRoomOwner) { 225 | const otherUserId = roomMemberIds[botIdx === 0 ? 1 : 0]; 226 | this._adminRooms[roomId] = new AdminRoom(roomId, this, otherUserId || adminRoomOwner); 227 | LogService.verbose("WebhookBridge", "Added admin room for user " + (otherUserId || adminRoomOwner)); 228 | } // else it is just a regular room 229 | }); 230 | } 231 | 232 | /** 233 | * Tries to find an appropriate admin room to send the given event to. If an admin room cannot be found, 234 | * this will do nothing. 235 | * @param {MatrixEvent} event the matrix event to send to any reasonable admin room 236 | * @private 237 | */ 238 | _tryProcessAdminEvent(event) { 239 | const roomId = event.room_id; 240 | 241 | if (this._adminRooms[roomId]) this._adminRooms[roomId].handleEvent(event); 242 | } 243 | 244 | /** 245 | * Destroys an admin room. This will not cause the bridge bot to leave. It will simply de-categorize it. 246 | * The room may be unintentionally restored when the bridge restarts, depending on the room conditions. 247 | * @param {string} roomId the room ID to destroy 248 | */ 249 | removeAdminRoom(roomId) { 250 | this._adminRooms[roomId] = null; 251 | } 252 | 253 | /** 254 | * Bridge handler for generic events 255 | * @private 256 | */ 257 | _onEvent(request, context) { 258 | const event = request.getData(); 259 | 260 | this._tryProcessAdminEvent(event); 261 | 262 | if (event.type === "m.room.member" && event.content.membership === "invite" && event.state_key === this.getBot().getUserId()) { 263 | LogService.info("WebhookBridge", event.state_key + " received invite to room " + event.room_id); 264 | const tryJoin = () => this._bridge.getIntent(event.state_key).join(event.room_id).then(() => this._processRoom(event.room_id)); 265 | return tryJoin().catch(err => { 266 | console.error(err); 267 | setTimeout(() => tryJoin(), 15000); // try to join the room again later 268 | }); 269 | } else if (event.type === "m.room.message" && event.sender !== this.getBot().getUserId()) { 270 | return this._processMessage(event); 271 | } 272 | 273 | // Default 274 | return Promise.resolve(); 275 | } 276 | 277 | _processMessage(event) { 278 | let message = event.content.body; 279 | if (!message || !message.startsWith("!webhook")) return; 280 | 281 | const parts = message.split(" "); 282 | let room = event.room_id; 283 | if (parts[1]) room = parts[1]; 284 | 285 | InteractiveProvisioner.createWebhook(event.sender, room, event.room_id); 286 | } 287 | } 288 | 289 | module.exports = new WebhookBridge(); 290 | -------------------------------------------------------------------------------- /src/matrix/AdminRoom.js: -------------------------------------------------------------------------------- 1 | const LogService = require("matrix-js-snippets").LogService; 2 | const _ = require("lodash"); 3 | 4 | /** 5 | * Processes user-admin related functions in Matrix. For example, this will allow 6 | * the Matrix user to authenticate with the bridge. 7 | * 8 | * An admin room must be comprised of 2 people: the bridge bot and the human. 9 | */ 10 | class AdminRoom { 11 | 12 | /** 13 | * Creates a new Matrix Admin Room 14 | * @param {string} roomId the Matrix room ID 15 | * @param {WebhookBridge} bridge the WebhookBridge bridge 16 | * @param {string} owner the owner of the room 17 | */ 18 | constructor(roomId, bridge, owner) { 19 | this.roomId = roomId; 20 | this._bridge = bridge; 21 | this._enabled = true; 22 | this.owner = owner; 23 | } 24 | 25 | /** 26 | * Processes an event intended for this admin room 27 | * @param {MatrixEvent} event the event to process 28 | */ 29 | handleEvent(event) { 30 | if (!this._enabled) return; 31 | 32 | const bridgeBot = this._bridge.getBotIntent(); 33 | if (event.type === "m.room.member") { 34 | this._bridge.getBot().getJoinedMembers(this.roomId).then(members => { 35 | const memberIds = _.keys(members); 36 | if (memberIds.length > 2) { // should be 2 people, but sometimes our join hasn't landed yet 37 | this._enabled = false; 38 | bridgeBot.sendMessage(this.roomId, { 39 | msgtype: 'm.notice', 40 | body: 'This room is no longer viable as an admin room. Please open a new direct conversation with me to maintain an admin room.' 41 | }).then(() => { 42 | return this._bridge.removeAdminRoom(this.roomId); 43 | }); 44 | } 45 | }).catch(e => { 46 | LogService.error("AdminRoom", "Error in handling room " + this.roomId + " - removing as an admin room"); 47 | LogService.error("AdminRoom", e); 48 | this._bridge.removeAdminRoom(this.roomId); 49 | }); 50 | } else if (event.type === "m.room.message") { 51 | if (event.sender === this._bridge.getBot().getUserId()) return; 52 | this._processMessage(event.sender, event.content.body); 53 | } 54 | } 55 | 56 | /** 57 | * Processes a message from the human in the room 58 | * @param {string} sender the sender of the message 59 | * @param {string} message the plain text message body 60 | * @private 61 | */ 62 | _processMessage(sender, message) { 63 | // Nothing to do (yet?) 64 | } 65 | } 66 | 67 | module.exports = AdminRoom; -------------------------------------------------------------------------------- /src/processing/WebhookReceiver.js: -------------------------------------------------------------------------------- 1 | const LogService = require("matrix-js-snippets").LogService; 2 | const PubSub = require("pubsub-js"); 3 | const Promise = require("bluebird"); 4 | 5 | class WebhookReceiver { 6 | constructor() { 7 | PubSub.subscribe("incoming_webhook", this._postMessage.bind(this)); 8 | } 9 | 10 | _getLayers() { 11 | if (!this._layers) { 12 | this._layers = [ 13 | // Avatar 14 | require("./layers/avatar/from_webhook"), 15 | require("./layers/avatar/slack_icon_url"), 16 | require("./layers/avatar/slack_icon_emoji"), 17 | require("./layers/avatar/default"), 18 | 19 | // Display Name 20 | require("./layers/displayName/from_webhook"), 21 | require("./layers/displayName/slack"), 22 | require("./layers/displayName/default"), 23 | require("./layers/displayName/emoji"), 24 | 25 | // Message 26 | require("./layers/message/from_webhook"), 27 | require("./layers/message/from_slack_attachments"), 28 | require("./layers/message/emoji"), 29 | require("./layers/message/slack_links"), 30 | require("./layers/message/html"), 31 | require("./layers/message/slack_fallback"), 32 | require("./layers/message/html_fallback"), 33 | 34 | // Misc 35 | require("./layers/message/msgtype"), 36 | 37 | // Post-processing 38 | require("./layers/postprocess/upload_images"), 39 | ]; 40 | } 41 | 42 | return this._layers; 43 | } 44 | 45 | /** 46 | * Sets the bridge to interact with 47 | * @param {WebhookBridge} bridge the bridge to use 48 | */ 49 | setBridge(bridge) { 50 | LogService.verbose("WebhookReceiver", "Received bridge."); 51 | this._bridge = bridge; 52 | } 53 | 54 | _postMessage(event, webhookEvent) { 55 | // Note: The payload is intentionally blank. This is for IDE autocomplete. The values will be populated by the layers. 56 | const matrixPayload = { 57 | event: { 58 | body: null, 59 | msgtype: "m.text", 60 | }, 61 | sender: { 62 | displayName: null, 63 | avatarUrl: null, 64 | } 65 | }; 66 | 67 | // Apply filtering on the content 68 | let layerChain = Promise.resolve(); 69 | this._getLayers().forEach(a => layerChain = layerChain.then(() => a(webhookEvent.payload, matrixPayload))); 70 | 71 | layerChain.then(() => { 72 | const localpart = (webhookEvent.hook.roomId + "_" + matrixPayload.sender.displayName).replace(/[^a-zA-Z0-9]/g, '_'); 73 | const intent = this._bridge.getWebhookUserIntent(localpart); 74 | 75 | // Update profile, try join, fall back to invite, and try to send message 76 | const postFn = () => intent.sendMessage(webhookEvent.hook.roomId, matrixPayload.event); 77 | this._bridge.updateHookProfile(intent, matrixPayload.sender.displayName, matrixPayload.sender.avatarUrl) 78 | .then(() => { 79 | return intent.join(webhookEvent.hook.roomId).then(postFn, err => { 80 | LogService.error("WebhookReceiver", err); 81 | return this._bridge.getBotIntent().invite(webhookEvent.hook.roomId, intent.getClient().credentials.userId).then(postFn); 82 | }); 83 | }).catch(error => LogService.error("WebhookReceiver", error)); 84 | }); 85 | } 86 | 87 | } 88 | 89 | module.exports = new WebhookReceiver(); 90 | -------------------------------------------------------------------------------- /src/processing/layers/avatar/default.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | // Note: this technically doesn't do anything and solely exists to make the structure sane 3 | if (!matrix.sender.avatarUrl) 4 | matrix.sender.avatarUrl = null; 5 | }; -------------------------------------------------------------------------------- /src/processing/layers/avatar/from_webhook.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (!matrix.sender.avatarUrl && webhook.avatarUrl) 3 | matrix.sender.avatarUrl = webhook.avatarUrl; 4 | }; -------------------------------------------------------------------------------- /src/processing/layers/avatar/slack_icon_emoji.js: -------------------------------------------------------------------------------- 1 | const emojione = require("emojione"); 2 | const cheerio = require("cheerio"); 3 | 4 | emojione.emojiSize = '128'; 5 | 6 | module.exports = (webhook, matrix) => { 7 | if (!matrix.sender.avatarUrl && webhook.icon_emoji) { 8 | // HACK: We really shouldn't have to do this element -> url conversion 9 | 10 | const imgElement = emojione.shortnameToImage(webhook.icon_emoji); 11 | if (imgElement == webhook.icon_emoji) return; 12 | 13 | const srcUrl = cheerio(imgElement).attr('src'); 14 | matrix.sender.avatarUrl = srcUrl; 15 | } 16 | }; -------------------------------------------------------------------------------- /src/processing/layers/avatar/slack_icon_url.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (!matrix.sender.avatarUrl && webhook.icon_url) 3 | matrix.sender.avatarUrl = webhook.icon_url; 4 | }; -------------------------------------------------------------------------------- /src/processing/layers/displayName/default.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (!matrix.sender.displayName) 3 | matrix.sender.displayName = "Incoming Webhook"; 4 | }; -------------------------------------------------------------------------------- /src/processing/layers/displayName/emoji.js: -------------------------------------------------------------------------------- 1 | const emoji = require('node-emoji'); 2 | 3 | module.exports = (webhook, matrix) => { 4 | if (webhook.emoji !== false && matrix.sender.displayName) { 5 | matrix.sender.displayName = emoji.emojify(matrix.sender.displayName, /*onMissing=*/null, /*format=*/null); 6 | } 7 | }; -------------------------------------------------------------------------------- /src/processing/layers/displayName/from_webhook.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (!matrix.sender.displayName) 3 | matrix.sender.displayName = webhook.displayName; 4 | }; -------------------------------------------------------------------------------- /src/processing/layers/displayName/slack.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (!matrix.sender.displayName) 3 | matrix.sender.displayName = webhook.username; 4 | }; -------------------------------------------------------------------------------- /src/processing/layers/message/emoji.js: -------------------------------------------------------------------------------- 1 | const emoji = require('node-emoji'); 2 | 3 | module.exports = (webhook, matrix) => { 4 | if (webhook.emoji !== false && matrix.event.body) { 5 | matrix.event.body = emoji.emojify(matrix.event.body, /*onMissing=*/null, /*format=*/null); 6 | } 7 | }; -------------------------------------------------------------------------------- /src/processing/layers/message/from_slack_attachments.js: -------------------------------------------------------------------------------- 1 | const COLOR_MAP = { 2 | danger: "#d9534f", 3 | warning: "#f0ad4e", 4 | good: "#5cb85c", 5 | }; 6 | 7 | module.exports = (webhook, matrix) => { 8 | if (!webhook.attachments) return; 9 | 10 | let combinedHtml = ""; 11 | for (let attachment of webhook.attachments) { 12 | let color = "#f7f7f7"; 13 | if (attachment.color) color = attachment.color; 14 | if (COLOR_MAP[attachment.color]) color = COLOR_MAP[attachment.color]; 15 | 16 | // Pretext 17 | if (attachment.pretext) { 18 | combinedHtml += attachment.pretext + "
"; 19 | } 20 | 21 | // Start the attachment block 22 | combinedHtml += "
"; 23 | 24 | // Process the author 25 | if (attachment.author_name) { 26 | combinedHtml += ""; 27 | if (attachment.author_icon) combinedHtml += ""; 28 | if (attachment.author_link) combinedHtml += "" + attachment.author_name + ""; 29 | else combinedHtml += attachment.author_name; 30 | combinedHtml += "
"; 31 | } 32 | 33 | // Title 34 | if (attachment.title) { 35 | combinedHtml += "

"; 36 | if (attachment.title_link) { 37 | combinedHtml += "" + attachment.title + ""; 38 | } else combinedHtml += attachment.title; 39 | combinedHtml += "

"; 40 | } 41 | 42 | // Text 43 | if (attachment.text) { 44 | combinedHtml += attachment.text + "
"; 45 | } 46 | 47 | // Fields 48 | if (attachment.fields) { 49 | for (let field of attachment.fields) { 50 | combinedHtml += "" + field.title + "
" + field.value + "
"; 51 | } 52 | } 53 | 54 | // Image 55 | if (attachment.image) { 56 | combinedHtml += "
"; 57 | } 58 | // TODO: Support thumb_url 59 | 60 | // Footer 61 | if (attachment.footer) { 62 | combinedHtml += ""; 63 | if (attachment.footer_icon) combinedHtml += ""; 64 | combinedHtml += attachment.footer + "
"; 65 | } 66 | 67 | combinedHtml += "
"; 68 | } 69 | 70 | webhook.format = "html"; // to force the HTML layer to process it 71 | if (matrix.event.body) combinedHtml = matrix.event.body + combinedHtml; 72 | matrix.event.body = combinedHtml; 73 | }; 74 | -------------------------------------------------------------------------------- /src/processing/layers/message/from_webhook.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (!matrix.event.body) 3 | matrix.event.body = webhook.text; 4 | }; -------------------------------------------------------------------------------- /src/processing/layers/message/html.js: -------------------------------------------------------------------------------- 1 | const striptags = require("striptags"); 2 | 3 | module.exports = (webhook, matrix) => { 4 | if (webhook.format === "html") { 5 | matrix.event.format = "org.matrix.custom.html"; 6 | matrix.event.formatted_body = matrix.event.body.replace("\n", "
"); 7 | matrix.event.body = striptags(matrix.event.formatted_body); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /src/processing/layers/message/html_fallback.js: -------------------------------------------------------------------------------- 1 | const striptags = require("striptags"); 2 | 3 | module.exports = (webhook, matrix) => { 4 | if (webhook.format === "html" && webhook.fallback) { 5 | matrix.event.body = webhook.fallback; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /src/processing/layers/message/msgtype.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (webhook.msgtype == 'notice' || webhook.msgtype == 'emote') 3 | matrix.event.msgtype = "m." + webhook.msgtype; 4 | }; 5 | -------------------------------------------------------------------------------- /src/processing/layers/message/slack_fallback.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | if (!webhook.attachments) return; 3 | let text = ""; 4 | 5 | for (let attachment of webhook.attachments) { 6 | if (!attachment.fallback) return; // Technically required, but we shouldn't break on not having it 7 | text += attachment.fallback + "\n"; 8 | } 9 | 10 | matrix.event.body = text.trim(); 11 | }; 12 | -------------------------------------------------------------------------------- /src/processing/layers/message/slack_links.js: -------------------------------------------------------------------------------- 1 | module.exports = (webhook, matrix) => { 2 | // Reference: https://api.slack.com/docs/message-formatting#linking_to_urls 3 | // Slack also accepts e.g. but that results in a relative path 4 | 5 | const linkRegex = /<([a-zA-Z]+):\/\/([^|>]+?)\|([^|>]+?)>/g; // Match 6 | const linkRegex2 = /<([a-zA-Z]+):\/\/([^|>]+?)>/g; // Match 7 | const mailtoRegex = /]+?)\|([^|>]+?)>/g; // Match 8 | const mailtoRegex2 = /]+?)>/g; // Match 9 | 10 | // Apply regex'es 11 | const before = matrix.event.body; 12 | matrix.event.body = matrix.event.body.replace(linkRegex, "$3"); 13 | matrix.event.body = matrix.event.body.replace(linkRegex2, "$1://$2"); 14 | matrix.event.body = matrix.event.body.replace(mailtoRegex, "$2"); 15 | matrix.event.body = matrix.event.body.replace(mailtoRegex2, "mailto:$1"); 16 | 17 | if (before !== matrix.event.body) { 18 | webhook.format = "html"; // to force the HTML layer to process it 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /src/processing/layers/postprocess/upload_images.js: -------------------------------------------------------------------------------- 1 | const cheerio = require("cheerio"); 2 | const util = require("../../../utils"); 3 | const WebhookBridge = require("../../../WebhookBridge"); 4 | const Promise = require("bluebird"); 5 | 6 | module.exports = (webhook, matrix) => { 7 | if (matrix.event.format !== "org.matrix.custom.html") return; 8 | 9 | const ev = cheerio.load(matrix.event.formatted_body); 10 | let images = ev("img"); 11 | if (!images) return; 12 | 13 | const promises = []; 14 | images.each((i, elem) => { 15 | const image = ev(elem); 16 | 17 | let src = image.attr("src"); 18 | if (!src || src.startsWith("mxc://")) return; 19 | 20 | promises.push(util.uploadContentFromUrl(WebhookBridge, src, WebhookBridge.getBotIntent()).then(mxc => { 21 | image.attr('src', mxc); 22 | })); 23 | }); 24 | 25 | return Promise.all(promises).then(() => { 26 | matrix.event.formatted_body = ev("body").html(); 27 | }); 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /src/provisioning/InteractiveProvisioner.js: -------------------------------------------------------------------------------- 1 | const ProvisioningService = require("./ProvisioningService"); 2 | const LogService = require("matrix-js-snippets").LogService; 3 | const WebService = require("../WebService"); 4 | const striptags = require("striptags"); 5 | 6 | /** 7 | * An in-chat way to create and manage webhooks 8 | */ 9 | class InteractiveProvisioner { 10 | constructor() { 11 | } 12 | 13 | /** 14 | * Sets the bridge to interact with 15 | * @param {WebhookBridge} bridge the bridge to use 16 | */ 17 | setBridge(bridge) { 18 | LogService.verbose("InteractiveProvisioner", "Received bridge. Using default bot intent"); 19 | this._bridge = bridge; 20 | this._intent = this._bridge.getBotIntent(); 21 | } 22 | 23 | /** 24 | * Processes a request to create a webhook 25 | * @param {string} userId the user ID requesting the webhook 26 | * @param {string} roomId the room ID the webhook is for 27 | * @param {string} inRoomId the room ID the request started in 28 | */ 29 | createWebhook(userId, roomId, inRoomId) { 30 | ProvisioningService.createWebhook(roomId, userId, null).then(webhook => { 31 | return this._bridge.getOrCreateAdminRoom(userId).then(adminRoom => { 32 | const url = WebService.getHookUrl(webhook.id); 33 | const htmlMessage = "Here's your webhook url for " + roomId + ": " + url + "
To send a message, POST the following JSON to that URL:" + 34 | "
" +
35 |                     "{\n" +
36 |                     "    \"text\": \"Hello world!\",\n" +
37 |                     "    \"format\": \"plain\",\n" +
38 |                     "    \"displayName\": \"My Cool Webhook\",\n" +
39 |                     "    \"avatarUrl\": \"http://i.imgur.com/IDOBtEJ.png\"\n" +
40 |                     "}" +
41 |                     "
" + 42 | "If you run into any issues, visit #webhooks:t2bot.io"; 43 | 44 | return this._intent.sendMessage(adminRoom.roomId, { 45 | msgtype: "m.notice", 46 | body: striptags(htmlMessage), 47 | format: "org.matrix.custom.html", 48 | formatted_body: htmlMessage 49 | }).then(() => { 50 | if (adminRoom.roomId !== inRoomId) { 51 | return this._intent.sendMessage(inRoomId, { 52 | msgtype: "m.notice", 53 | body: "I've sent you a private message with your hook information" 54 | }); 55 | } 56 | }); 57 | }); 58 | }).catch(error => { 59 | if (error === ProvisioningService.PERMISSION_ERROR_MESSAGE) { 60 | return this._intent.sendMessage(inRoomId, { 61 | msgtype: "m.notice", 62 | body: "Sorry, you don't have permission to create webhooks for " + (inRoomId === roomId ? "this room" : roomId) 63 | }); 64 | } 65 | 66 | LogService.error("InteractiveProvisioner", error); 67 | 68 | if (error.errcode === "M_GUEST_ACCESS_FORBIDDEN") { 69 | this._intent.sendMessage(inRoomId, { 70 | msgtype: "m.notice", 71 | body: "Room is not public or not found" 72 | }); 73 | } else { 74 | this._intent.sendMessage(inRoomId, { 75 | msgtype: "m.notice", 76 | body: "There was an error processing your command." 77 | }); 78 | } 79 | }); 80 | } 81 | } 82 | 83 | module.exports = new InteractiveProvisioner(); -------------------------------------------------------------------------------- /src/provisioning/ProvisioningService.js: -------------------------------------------------------------------------------- 1 | const WebhookStore = require("../storage/WebhookStore"); 2 | const Promise = require("bluebird"); 3 | const LogService = require("matrix-js-snippets").LogService; 4 | 5 | class ProvisioningService { 6 | 7 | constructor() { 8 | this.PERMISSION_ERROR_MESSAGE = "User does not have permission to manage webhooks in this room"; 9 | } 10 | 11 | /** 12 | * Sets the intent object to use for permission checking 13 | * @param {Intent} intent the intent to use 14 | */ 15 | setClient(intent) { 16 | LogService.verbose("ProvisioningService", "Received intent. Using account " + intent.getClient().credentials.userId); 17 | this._intent = intent; 18 | } 19 | 20 | /** 21 | * Gets the bot user ID for the bridge 22 | * @return {string} the bot user ID 23 | */ 24 | getBotUserId() { 25 | return this._intent.getClient().credentials.userId; 26 | } 27 | 28 | /** 29 | * Creates a new webhook for a room 30 | * @param {string} roomId the room ID the webhook belongs to 31 | * @param {string} userId the user trying to create the webhook 32 | * @param {String|null} label optional label for the webhook 33 | * @returns {Promise} resolves to the created webhook 34 | */ 35 | async createWebhook(roomId, userId, label) { 36 | LogService.info("ProvisioningService", "Processing create hook request for " + roomId + " by " + userId); 37 | await this._intent.join(roomId); 38 | return this.hasPermission(userId, roomId) 39 | .then(() => WebhookStore.createWebhook(roomId, userId, label), () => Promise.reject(this.PERMISSION_ERROR_MESSAGE)); 40 | } 41 | 42 | /*** 43 | * Updates a webhook's properties 44 | * @param {string} roomId the room ID the webhook belongs to 45 | * @param {string} userId the user trying to update the webhook 46 | * @param {string} hookId the webhook ID 47 | * @param {String|null} newLabel optional new label for the webhook 48 | * @returns {Promise} resolves to the updated webhook 49 | */ 50 | updateWebhook(roomId, userId, hookId, newLabel) { 51 | LogService.info("ProvisioningService", "Processing webhook update request for " + roomId + " by " + userId); 52 | return this.hasPermission(roomId, userId) 53 | .then(async () => { 54 | const webhook = await WebhookStore.getWebhook(hookId); 55 | if (webhook.roomId !== roomId) return Promise.reject(this.PERMISSION_ERROR_MESSAGE); 56 | 57 | let changed = false; 58 | if (webhook.label !== newLabel) { 59 | webhook.label = newLabel; 60 | changed = true; 61 | } 62 | 63 | if (changed) await webhook.save(); 64 | return webhook; 65 | }, () => Promise.reject(this.PERMISSION_ERROR_MESSAGE)); 66 | } 67 | 68 | /** 69 | * Gets a webhook 70 | * @param {string} roomId the room ID to search in 71 | * @param {string} userId the user trying to view the room's webhook 72 | * @param {string} hookId the webhook ID 73 | * @returns {Promise} resolves to the found webhook 74 | */ 75 | getWebhook(roomId, userId, hookId) { 76 | LogService.info("ProvisioningService", "Processing get hook request for " + roomId + " by " + userId); 77 | return this.hasPermission(userId, roomId) 78 | .then(async () => { 79 | const webhook = await WebhookStore.getWebhook(hookId); 80 | if (webhook.roomId !== roomId) return Promise.reject(this.PERMISSION_ERROR_MESSAGE); 81 | return webhook; 82 | }, () => Promise.reject(this.PERMISSION_ERROR_MESSAGE)); 83 | } 84 | 85 | /** 86 | * Gets a list of all webhooks in a room 87 | * @param {string} roomId the room ID to search in 88 | * @param {string} userId the user trying to view the room's webhooks 89 | * @returns {Promise} resolves to the list of webhooks 90 | */ 91 | getWebhooks(roomId, userId) { 92 | LogService.info("ProvisioningService", "Processing list hooks request for " + roomId + " by " + userId); 93 | return this.hasPermission(userId, roomId) 94 | .then(() => WebhookStore.listWebhooks(roomId), () => Promise.reject(this.PERMISSION_ERROR_MESSAGE)); 95 | } 96 | 97 | /** 98 | * Gets a list of all webhooks in a room 99 | * @param {string} roomId the room ID to search in 100 | * @param {string} userId the user trying to view the room's webhooks 101 | * @param {string} hookId the webhook ID 102 | * @returns {Promise<*>} resolves when deleted 103 | */ 104 | deleteWebhook(roomId, userId, hookId) { 105 | LogService.info("ProvisioningService", "Processing delete hook (" + hookId + ") request for " + roomId + " by " + userId); 106 | 107 | return this.hasPermission(userId, roomId) 108 | .then(async () => { 109 | const webhooks = await WebhookStore.listWebhooks(roomId); 110 | if (webhooks.length === 1 && webhooks[0].id === hookId) { 111 | await this._intent.leave(roomId); 112 | } 113 | return WebhookStore.deleteWebhook(roomId, hookId) 114 | }, () => Promise.reject(this.PERMISSION_ERROR_MESSAGE)); 115 | } 116 | 117 | /** 118 | * Checks to see if a user has permission to manage webhooks in a given room 119 | * @param {string} userId the user trying to manage webhooks 120 | * @param {string} roomId the room they are trying to manage webhooks in 121 | * @returns {Promise<*>} resolves if the user has permission, rejected otherwise 122 | */ 123 | hasPermission(userId, roomId) { 124 | LogService.verbose("ProvisioningService", "Checking permission for " + userId + " in " + roomId); 125 | if (!this._intent) { 126 | LogService.warn("ProvisioningService", "Unable to check permission for " + userId + " in " + roomId + " because there is no Intent assigned to this service"); 127 | return Promise.reject(); 128 | } 129 | return this._intent.getClient().getStateEvent(roomId, "m.room.power_levels", "").then(powerLevels => { 130 | if (!powerLevels) { 131 | LogService.warn("ProvisioningService", "Unable to check permission for " + userId + " in " + roomId + " because there is no powerlevel information in the room"); 132 | return Promise.reject(); 133 | } 134 | 135 | const userPowerLevels = powerLevels['users'] || {}; 136 | 137 | let powerLevel = userPowerLevels[userId]; 138 | if (!powerLevel) powerLevel = powerLevels['users_default']; 139 | if (!powerLevel) powerLevel = 0; // default 140 | 141 | let statePowerLevel = powerLevels["state_default"]; 142 | if (!statePowerLevel) { 143 | LogService.warn("ProvisioningService", "Unable to check permission for " + userId + " in " + roomId + " because the powerlevel requirement is missing for state_default"); 144 | return Promise.reject(); 145 | } 146 | 147 | const hasPermission = statePowerLevel <= powerLevel; 148 | 149 | LogService.verbose("ProvisioningService", "User " + userId + " in room " + roomId + " has permission? " + hasPermission + " (required powerlevel = " + statePowerLevel + ", user powerlevel = " + powerLevel + ")"); 150 | 151 | return hasPermission ? Promise.resolve() : Promise.reject(); 152 | }); 153 | } 154 | } 155 | 156 | module.exports = new ProvisioningService(); -------------------------------------------------------------------------------- /src/storage/WebhookStore.js: -------------------------------------------------------------------------------- 1 | const DBMigrate = require("db-migrate"); 2 | const LogService = require("matrix-js-snippets").LogService; 3 | const Sequelize = require('sequelize'); 4 | const _ = require("lodash"); 5 | const path = require("path"); 6 | const randomString = require('random-string'); 7 | 8 | /** 9 | * Primary storage for the Webhook Bridge 10 | */ 11 | class WebhookStore { 12 | 13 | /** 14 | * Creates a new Instagram store. Call `prepare` before use. 15 | */ 16 | constructor() { 17 | this._orm = null; 18 | } 19 | 20 | /** 21 | * Prepares the store for use 22 | */ 23 | prepare() { 24 | const env = process.env.NODE_ENV || "development"; 25 | LogService.info("WebhookStore", "Running migrations"); 26 | return new Promise((resolve, reject) => { 27 | const dbConfig = require.main.require(process.env["WEBHOOKS_DB_CONFIG_PATH"] || "./config/database.json"); 28 | const dbMigrate = DBMigrate.getInstance(true, { 29 | config: process.env["WEBHOOKS_DB_CONFIG_PATH"] || "./config/database.json", 30 | env: env 31 | }); 32 | dbMigrate.internals.argv.count = undefined; // HACK: Fix db-migrate from using `config/config.yaml` as the count. See https://github.com/turt2live/matrix-appservice-instagram/issues/11 33 | dbMigrate.up().then(() => { 34 | let dbConfigEnv = dbConfig[env]; 35 | if (!dbConfigEnv) throw new Error("Could not find DB config for " + env); 36 | 37 | if (process.env["WEBHOOKS_ENV"] === "docker") { 38 | const expectedPath = path.join("data", path.basename(dbConfigEnv.filename)); 39 | if (expectedPath !== dbConfigEnv.filename) { 40 | LogService.warn("WebhookStore", "Changing database path to be " + expectedPath + " to ensure data is persisted"); 41 | dbConfigEnv.filename = expectedPath; 42 | } 43 | } 44 | 45 | const opts = { 46 | host: dbConfigEnv.host || 'localhost', 47 | dialect: 'sqlite', 48 | storage: dbConfigEnv.filename, 49 | pool: { 50 | max: 5, 51 | min: 0, 52 | idle: 10000 53 | }, 54 | operatorsAliases: false, 55 | logging: i => LogService.verbose("WebhookStore [SQL]", i) 56 | }; 57 | 58 | this._orm = new Sequelize(dbConfigEnv.database || 'webhooks', dbConfigEnv.username, dbConfigEnv.password, opts); 59 | this._bindModels(); 60 | resolve(); 61 | }, err => { 62 | LogService.error("WebhookStore", err); 63 | reject(err); 64 | }).catch(err => { 65 | LogService.error("WebhookStore", err); 66 | reject(err); 67 | }); 68 | }); 69 | } 70 | 71 | /** 72 | * Binds all of the models to the ORM. 73 | * @private 74 | */ 75 | _bindModels() { 76 | // Models 77 | this.__AccountData = this._orm.import(__dirname + "/models/account_data"); 78 | this.__Webhooks = this._orm.import(__dirname + "/models/webhooks"); 79 | } 80 | 81 | /** 82 | * Gets the account data for the given object 83 | * @param {string} objectId the object that has account data to look for 84 | * @returns {Promise<*>} resolves to a json object representing the key/value pairs 85 | */ 86 | getAccountData(objectId) { 87 | return this.__AccountData.findAll({where: {objectId: objectId}}).then(rows => { 88 | const container = {}; 89 | for (let row of rows) { 90 | container[row.key] = row.value; 91 | } 92 | return container; 93 | }); 94 | } 95 | 96 | /** 97 | * Saves the object's account data. Takes the value verbatim, expecting a string. 98 | * @param {string} objectId the object this account data belongs to 99 | * @param {*} data the data to save 100 | * @returns {Promise<>} resolves when complete 101 | */ 102 | setAccountData(objectId, data) { 103 | return this.__AccountData.destroy({where: {objectId: objectId}, truncate: true}).then(() => { 104 | const promises = []; 105 | 106 | const keys = _.keys(data); 107 | for (let key of keys) { 108 | promises.push(this.__AccountData.create({objectId: objectId, key: key, value: data[key]})); 109 | } 110 | 111 | return Promise.all(promises); 112 | }); 113 | } 114 | 115 | /** 116 | * Creates a new webhook 117 | * @param {string} roomId the matrix room ID the webhook is for 118 | * @param {string} userId the matrix user who created the webhook 119 | * @param {string} label optional label for the webhook 120 | * @returns {Promise} resolves to the created webhook 121 | */ 122 | createWebhook(roomId, userId, label) { 123 | return this.__Webhooks.create({ 124 | id: randomString({length: 64}), 125 | roomId: roomId, 126 | userId: userId, 127 | label: label, 128 | }); 129 | } 130 | 131 | /** 132 | * Lists all of the webhooks for a given room 133 | * @param {string} roomId the room ID to search in 134 | * @returns {Promise} resolves to a list of webhooks, may be empty 135 | */ 136 | listWebhooks(roomId) { 137 | return this.__Webhooks.findAll({where: {roomId: roomId}}).then(hooks => _.map(hooks, h => new Webhook(h))); 138 | } 139 | 140 | /** 141 | * Deletes a webhook from the store 142 | * @param {string} roomId the room ID 143 | * @param {string} hookId the hook's ID 144 | * @returns {Promise<*>} resolves when the hook has been deleted 145 | */ 146 | deleteWebhook(roomId, hookId) { 147 | return this.__Webhooks.destroy({where: {roomId: roomId, id: hookId}}); 148 | } 149 | 150 | /** 151 | * Gets a webhook from the database by ID 152 | * @param {string} hookId the hook ID to lookup 153 | * @returns {Promise} resolves to the webhook, or null if not found 154 | */ 155 | getWebhook(hookId) { 156 | return this.__Webhooks.findById(hookId).then(hook => hook ? new Webhook(hook) : null); 157 | } 158 | } 159 | 160 | class Webhook { 161 | constructor(dbFields) { 162 | this.id = dbFields.id; 163 | this.roomId = dbFields.roomId; 164 | this.userId = dbFields.userId; 165 | this.label = dbFields.label; 166 | } 167 | } 168 | 169 | module.exports = new WebhookStore(); 170 | -------------------------------------------------------------------------------- /src/storage/models/account_data.js: -------------------------------------------------------------------------------- 1 | module.exports = function (sequelize, DataTypes) { 2 | return sequelize.define('account_data', { 3 | id: { 4 | type: DataTypes.INTEGER, 5 | allowNull: false, 6 | primaryKey: true, 7 | autoIncrement: true, 8 | field: 'id' 9 | }, 10 | objectId: { 11 | type: DataTypes.STRING, 12 | allowNull: false, 13 | field: 'objectId' 14 | }, 15 | key: { 16 | type: DataTypes.STRING, 17 | allowNull: false, 18 | field: 'key' 19 | }, 20 | value: { 21 | type: DataTypes.STRING, 22 | allowNull: false, 23 | field: 'value' 24 | } 25 | }, { 26 | tableName: 'account_data', 27 | underscored: false, 28 | timestamps: false 29 | }); 30 | }; 31 | -------------------------------------------------------------------------------- /src/storage/models/webhooks.js: -------------------------------------------------------------------------------- 1 | module.exports = function (sequelize, DataTypes) { 2 | return sequelize.define('webhooks', { 3 | id: { 4 | type: DataTypes.STRING, 5 | allowNull: false, 6 | primaryKey: true, 7 | field: 'id' 8 | }, 9 | roomId: { 10 | type: DataTypes.STRING, 11 | allowNull: false, 12 | field: 'roomId' 13 | }, 14 | userId: { 15 | type: DataTypes.STRING, 16 | allowNull: false, 17 | field: 'userId' 18 | }, 19 | label: { 20 | type: DataTypes.STRING, 21 | allowNull: true, 22 | field: 'label', 23 | }, 24 | }, { 25 | tableName: 'webhooks', 26 | underscored: false, 27 | timestamps: false 28 | }); 29 | }; 30 | -------------------------------------------------------------------------------- /src/utils.js: -------------------------------------------------------------------------------- 1 | // File based on the following implementation of utils.js in matrix-appservice-twitter by Half-Shot: 2 | // https://github.com/Half-Shot/matrix-appservice-twitter/blob/6fc01588e51a9eb9a32e14a6b0338abfd7cc32ea/src/util.js 3 | 4 | const https = require('https'); 5 | const http = require('http'); 6 | const Buffer = require("buffer").Buffer; 7 | const mime = require('mime'); 8 | const parseDataUri = require("parse-data-uri"); 9 | const request = require('request'); 10 | const fs = require('fs'); 11 | const mkdirp = require('mkdirp'); 12 | const uuidv4 = require("uuid/v4"); 13 | const path = require('path'); 14 | const LogService = require("matrix-js-snippets").LogService; 15 | 16 | /** 17 | Utility module for regularly used functions. 18 | */ 19 | 20 | /** 21 | * uploadContentFromUrl - Upload content from a given URL to the homeserver 22 | * and return a MXC URL. 23 | * 24 | * @param {Bridge} bridge the bridge object of this application 25 | * @param {string} url the URL to be downloaded from. 26 | * @param {string|Intent} [id] either the ID of the uploader, or a Intent object - optional. 27 | * @param {string} [name] name of the file. Will use the URL filename otherwise - optional. 28 | * @return {Promise} Promise resolving with a MXC URL. 29 | */ 30 | function uploadContentFromUrl(bridge, url, id, name) { 31 | LogService.verbose("utils", "Downloading image from " + url); 32 | let contenttype; 33 | id = id || null; 34 | name = name || null; 35 | return new Promise((resolve, reject) => { 36 | 37 | const ht = url.startsWith("https") ? https : http; 38 | 39 | ht.get((url), (res) => { 40 | if (res.headers.hasOwnProperty("content-type")) { 41 | contenttype = res.headers["content-type"]; 42 | } else { 43 | LogService.info("utils", "No content-type given by server, guessing based on file name."); 44 | contenttype = mime.getType(url); 45 | } 46 | 47 | if (name == null) { 48 | const parts = url.split("/"); 49 | name = parts[parts.length - 1]; 50 | } 51 | let size = parseInt(res.headers["content-length"]); 52 | if (isNaN(size)) { 53 | LogService.warn("UploadContentFromUrl", "Content-length is not valid. Assuming 512kb size"); 54 | size = 512 * 1024; 55 | } 56 | let buffer; 57 | if (Buffer.alloc) {//Since 5.10 58 | buffer = Buffer.alloc(size); 59 | } else {//Deprecated 60 | buffer = new Buffer(size); 61 | } 62 | 63 | let bsize = 0; 64 | res.on('data', (d) => { 65 | d.copy(buffer, bsize); 66 | bsize += d.length; 67 | }); 68 | res.on('error', () => { 69 | reject("Failed to download."); 70 | }); 71 | res.on('end', () => { 72 | resolve(buffer); 73 | }); 74 | }) 75 | }).then((buffer) => { 76 | if (typeof id === "string" || id == null) { 77 | id = bridge.getIntent(id); 78 | } 79 | return id.getClient().uploadContent({ 80 | stream: buffer, 81 | name: name, 82 | type: contenttype 83 | }); 84 | }).then((response) => { 85 | const content_uri = JSON.parse(response).content_uri; 86 | LogService.info("UploadContent", "Media uploaded to " + content_uri); 87 | return content_uri; 88 | }).catch(function (reason) { 89 | LogService.error("UploadContent", "Failed to upload content:\n" + reason) 90 | }); 91 | } 92 | 93 | /** 94 | * Uploads the content contained in a data uri string to the homeserver 95 | * 96 | * @param {Bridge} bridge the bridge object of this application 97 | * @param {string} uri the data URI to upload 98 | * @param {string} id either the ID of the uploader 99 | * @param {string} [name] name of the file. Defaults to 'file'. 100 | * @return {Promise} Promise resolving with a MXC URL. 101 | */ 102 | function uploadContentFromDataUri(bridge, id, uri, name) { 103 | if (!name || typeof(name) !== "string") name = "file"; 104 | const parsed = parseDataUri(uri); 105 | return bridge.getIntent(id).getClient().uploadContent({ 106 | stream: parsed.data, 107 | name: name, 108 | type: parsed.mimeType 109 | }).then(response=> { 110 | const content_uri = JSON.parse(response).content_uri; 111 | LogService.info("uploadContentFromDataUri", "Media uploaded to " + content_uri); 112 | return content_uri; 113 | }).catch(function (reason) { 114 | LogService.error("UploadContent", "Failed to upload content:\n" + reason) 115 | }); 116 | } 117 | 118 | /** 119 | * Downloads a file from a web address to the file system 120 | * @param {string} uri the web resource to download 121 | * @param {string} path the filesystem path to download to 122 | * @returns {Promise} resolves with true if successful, false otherwise 123 | */ 124 | function downloadFile(uri, path) { 125 | return new Promise((resolve, reject) => { 126 | let resolved = false; 127 | request(uri, (err, response, body) => { 128 | if (err) { 129 | resolved = true; 130 | resolve(false); 131 | } 132 | }).pipe(fs.createWriteStream(path)).on('close', () => { 133 | if (!resolved) resolve(true); 134 | }); 135 | }); 136 | } 137 | 138 | /** 139 | * Downloads a file from a web address to the file system 140 | * @param {string} uri the web resource to download 141 | * @param {string} [ext] optional extension for the filename 142 | * @returns {Promise} resolves to the file path, or null if something went wrong 143 | */ 144 | function downloadFileTemp(uri, ext = '.data') { 145 | const root = "temp"; 146 | const filename = uuidv4() + ext; 147 | const fullpath = path.join(root, filename); 148 | 149 | mkdirp.sync(root); 150 | return downloadFile(uri, fullpath).then(created => created ? fullpath : null); 151 | } 152 | 153 | module.exports = { 154 | uploadContentFromUrl: uploadContentFromUrl, 155 | uploadContentFromDataUri: uploadContentFromDataUri, 156 | downloadFile: downloadFile, 157 | downloadFileTemp: downloadFileTemp, 158 | }; --------------------------------------------------------------------------------