├── .gitignore ├── .nvmrc ├── LICENSE ├── Procfile ├── README.md ├── config ├── helpers.ts ├── karma.conf.ts ├── karma.entry.js ├── webpack.common.ts ├── webpack.development.ts ├── webpack.production.ts └── webpack.test.ts ├── nodemon.json ├── package-lock.json ├── package.json ├── postcss.config.js ├── src ├── README.md ├── app │ ├── app.component.html │ ├── app.component.scss │ ├── app.component.ts │ ├── app.module.ts │ ├── control │ │ ├── control.component.html │ │ ├── control.component.scss │ │ ├── control.component.ts │ │ └── index.ts │ ├── core │ │ ├── core.module.ts │ │ ├── index.ts │ │ ├── room.service.ts │ │ ├── socket.service.ts │ │ └── user.service.ts │ ├── header │ │ ├── header.component.html │ │ ├── header.component.scss │ │ ├── header.component.ts │ │ └── index.ts │ ├── nickname │ │ ├── index.ts │ │ ├── nickname.component.html │ │ ├── nickname.component.scss │ │ └── nickname.component.ts │ ├── room │ │ ├── index.ts │ │ ├── message.service.ts │ │ ├── room.component.html │ │ ├── room.component.scss │ │ └── room.component.ts │ ├── rooms │ │ ├── index.ts │ │ ├── rooms.component.html │ │ ├── rooms.component.scss │ │ └── rooms.component.ts │ └── shared │ │ ├── index.ts │ │ ├── order-by.pipe.ts │ │ └── shared.module.ts ├── backend │ ├── index.ts │ └── socket │ │ ├── index.ts │ │ ├── message.ts │ │ └── room.ts ├── index.html ├── main.ts ├── models │ ├── index.ts │ ├── message.model.ts │ └── room.model.ts ├── polyfills.ts ├── server.ts └── vendor.ts ├── tsconfig.json └── webpack.config.ts /.gitignore: -------------------------------------------------------------------------------- 1 | **/node_modules/ 2 | /target 3 | tmp/ 4 | __MACOSX/ 5 | .DS_Store 6 | Thumbs.db 7 | .env 8 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 7 2 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: npm start 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # angular-socket-io-chat 2 | 3 | An example chat application made with Angular and Socket.io (and NodeJS, ExpressJS and MongoDB). 4 | 5 | ## Highlights 6 | 7 | - Angular 4.1.1 or later 8 | - Webpack 2.5.1 or later 9 | - TypeScript 2.3.2 or later 10 | - Styles with [SCSS](http://sass-lang.com/) 11 | - Full stack compilation on Heroku build process 12 | 13 | ## Prequisities 14 | 15 | The projects needs that you have the following things installed: 16 | 17 | - [NodeJS](https://nodejs.org/) (version 7 or greater, tested with v7.10.0) 18 | - [MongoDB](https://www.mongodb.com/) (tested with version 3.4.2) 19 | - [Heroku Cli](https://devcenter.heroku.com/articles/heroku-cli) (latest) 20 | 21 | All of the prequisities are available on Linux, Windows and Mac OS X systems with their own installers (just go to links above and download package). 22 | 23 | ### Installing prequisities on Mac OS X 24 | 25 | You might wish to install the prequisities with Homebrew, so here're quick guide to do that. 26 | 27 | #### Install Homebrew 28 | 29 | You can install [Homebrew](http://brew.sh/) with this command: 30 | 31 | ``` 32 | /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 33 | ``` 34 | 35 | #### NodeJS 36 | 37 | You can install NodeJS simply by giving command: 38 | 39 | ``` 40 | brew install node 41 | ``` 42 | 43 | #### Node Version Manager (recommended) 44 | 45 | If you wish to run multiple NodeJS versions (to avoid problems with old NodeJS modules, you might want to use 4.2 as default, and NodeJS 6 on newer projects, you should install [NVM](https://github.com/creationix/nvm) (Node Version Manager) for managing multiple NodeJS versions. 46 | 47 | NVM can be installed by the following command: 48 | 49 | ``` 50 | brew install nvm 51 | ``` 52 | 53 | Note! Follow the instructions after installing NVM, so that you'll get the shell extended (basically adding stuff to your `.bash_profile`). 54 | 55 | Then you can just install and use specific NodeJS version like: 56 | 57 | ``` 58 | nvm install v7 59 | nvm use v7 60 | ``` 61 | 62 | Note! This project is tested currently with NodeJS v7.10.0. 63 | 64 | #### Heroku Cli 65 | 66 | ``` 67 | brew install heroku-cli 68 | ``` 69 | 70 | #### MongoDB 71 | 72 | ``` 73 | brew install mongodb 74 | ln -sf /usr/local/opt/mongodb/homebrew.mxcl.mongodb.plist ~/Library/LaunchAgents 75 | launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist 76 | ``` 77 | 78 | #### Redis 79 | 80 | ``` 81 | brew install redis 82 | ln -sf /usr/local/opt/redis/homebrew.mxcl.redis.plist ~/Library/LaunchAgents 83 | launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist 84 | ``` 85 | 86 | ### Installing prequisities on Windows 87 | 88 | You should install installer packages of [NodeJS](https://nodejs.org/en/download/current/), [MongoDB](https://www.mongodb.com/download-center) and [Heroku Toolbelt](https://toolbelt.heroku.com/windows), either 32bit or 64bit depending on your system. 89 | 90 | #### MongoDB 91 | 92 | When MongoDB is installed, you should create (or ensure) that you have `C:\Data` -directory created: 93 | 94 | ``` 95 | dir C:\Data 96 | ``` 97 | 98 | After ensuring or creating the directory, you can just launch MongoDB from command line: 99 | 100 | ``` 101 | mongod.exe 102 | ``` 103 | 104 | #### Redis 105 | 106 | You could use [Microsoft's port of Redis](https://github.com/MSOpenTech/redis/releases), which provides an easy to use installer. 107 | 108 | #### Other notes 109 | 110 | On Windows installations, it will ease the task if you use PowerShell and add all the necessary paths to utilities to Windows environment path. To do so, you can right-click the *Start* -button, select *Advanced System Settings* and finally select *Environment Variables*. You need to restart the PowerShell (or possibly logout and login) to get the environment variables going. 111 | 112 | ## Installation 113 | 114 | ### Install node modules and type definitions 115 | 116 | ``` 117 | npm install 118 | ``` 119 | 120 | Note! Type definitions were earlier installed with `typings`, however, due switching to TypeScript 2.0 the type definitions are managed with `npm` and more specifically `@types/***` name space. 121 | 122 | ## Local development 123 | 124 | ### Build 125 | 126 | ``` 127 | npm run build 128 | ``` 129 | 130 | ### Start web server 131 | 132 | ``` 133 | npm start 134 | ``` 135 | 136 | ### Open local app in browser 137 | 138 | [http://localhost:5000/](http://localhost:5000/) 139 | 140 | ### Continuous development 141 | 142 | ``` 143 | npm run dev 144 | ``` 145 | 146 | This runs Webpack in watch mode, which updates both client and server assets. Server is loaded automatically, client needs manual refreshing. TBD: HMR or livereloading. 147 | 148 | ## Configuration 149 | 150 | - `MONGODB_URI=mongodb://user:pass@hostname:port/database` MongoDB URI (you can leave empty if you use MongoDB on localhost) 151 | 152 | For local development, you can save the environment to `.env` -file on project root: 153 | 154 | ``` 155 | MONGODB_URI=mongodb://user:pass@hostname:port/database 156 | ``` 157 | 158 | ## Heroku 159 | 160 | ### Create a Heroku app first (if you don't have already one) 161 | 162 | ``` 163 | heroku create --region eu mycoolapp 164 | ``` 165 | 166 | ### Add MongoDB 167 | 168 | You can use a free plan of [MongoLab](https://elements.heroku.com/addons/mongolab) for data storage: 169 | 170 | ``` 171 | heroku addons:create mongolab:sandbox 172 | ``` 173 | 174 | ### Add Redis 175 | 176 | You can use a free plan of [Heroku Redis](https://elements.heroku.com/addons/heroku-redis) for fast memory cache. 177 | 178 | ``` 179 | heroku addons:create heroku-redis:hobby-dev 180 | ``` 181 | 182 | ### Deploy 183 | 184 | ``` 185 | git push heroku master 186 | ``` 187 | 188 | ### Open Heroku app in browser 189 | 190 | ``` 191 | heroku open 192 | ``` 193 | 194 | -------------------------------------------------------------------------------- /config/helpers.ts: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | // Helpers 4 | export function includeClientPackages(packages, localModule?: string[]) { 5 | return function(context, request, cb) { 6 | if (localModule instanceof RegExp && localModule.test(request)) { 7 | return cb(); 8 | } 9 | if (packages instanceof RegExp && packages.test(request)) { 10 | return cb(); 11 | } 12 | if (Array.isArray(packages) && packages.indexOf(request) !== -1) { 13 | return cb(); 14 | } 15 | if (!path.isAbsolute(request) && request.charAt(0) !== '.') { 16 | return cb(null, 'commonjs ' + request); 17 | } 18 | return cb(); 19 | }; 20 | } 21 | 22 | export function root(args) { 23 | var basePath = path.join(__dirname, '..'); 24 | args = Array.prototype.slice.call(arguments, 0); 25 | return path.join.apply(path, [basePath].concat(args)); 26 | } 27 | -------------------------------------------------------------------------------- /config/karma.conf.ts: -------------------------------------------------------------------------------- 1 | const testWebpackConfig = require('./webpack.test'); 2 | 3 | const karmaConfig = (config) => { 4 | config.set({ 5 | basePath: '', 6 | 7 | frameworks: ['jasmine'], 8 | 9 | files: [ { pattern: './config/karma.entry.js', watched: false } ], 10 | 11 | preprocessors: { './config/karma.entry.js': ['webpack', 'sourcemap'] }, 12 | 13 | // webpack config 14 | webpack: testWebpackConfig, 15 | 16 | // webpack server config 17 | webpackServer: { noInfo: true }, 18 | 19 | webpackMiddleware: { stats: 'errors-only' }, 20 | 21 | reporters: ['dots'], 22 | 23 | logLevel: config.LOG_INFO, 24 | 25 | autoWatch: false, 26 | 27 | singleRun: true, 28 | 29 | customLaunchers: { 30 | TRAVIS_CHROME: { 31 | base: 'Chrome', 32 | flags: ['--no-sandbox'] 33 | } 34 | }, 35 | 36 | browsers: process.env.TRAVIS ? ['TRAVIS_CHROME'] : ['Chrome'] 37 | }); 38 | }; 39 | 40 | module.exports = karmaConfig; -------------------------------------------------------------------------------- /config/karma.entry.js: -------------------------------------------------------------------------------- 1 | Error.stackTraceLimit = Infinity; 2 | 3 | require('core-js/client/shim'); 4 | 5 | require('ts-helpers'); 6 | 7 | require('zone.js/dist/zone'); 8 | require('zone.js/dist/long-stack-trace-zone'); 9 | require('zone.js/dist/proxy'); 10 | require('zone.js/dist/sync-test'); 11 | require('zone.js/dist/jasmine-patch'); 12 | require('zone.js/dist/async-test'); 13 | require('zone.js/dist/fake-async-test'); 14 | 15 | /* 16 | Ok, this is kinda crazy. We can use the the context method on 17 | require that webpack created in order to tell webpack 18 | what files we actually want to require or import. 19 | Below, context will be a function/object with file names as keys. 20 | using that regex we are saying look in client/app and find 21 | any file that ends with '.spec.ts' and get its path. By passing in true 22 | we say do this recursively 23 | */ 24 | var appContext = require.context('../src', true, /\.spec\.ts/); 25 | 26 | // get all the files, for each file, call the context function 27 | // that will require the file and load it up here. Context will 28 | // loop and require those spec files here 29 | appContext.keys().forEach(appContext); 30 | 31 | // Select BrowserDomAdapter. 32 | // see https://github.com/AngularClass/angular2-webpack-starter/issues/124 33 | // Somewhere in the test setup 34 | var testing = require('@angular/core/testing'); 35 | var browser = require('@angular/platform-browser-dynamic/testing'); 36 | 37 | testing.TestBed.initTestEnvironment( 38 | browser.BrowserDynamicTestingModule, 39 | browser.platformBrowserDynamicTesting() 40 | ); -------------------------------------------------------------------------------- /config/webpack.common.ts: -------------------------------------------------------------------------------- 1 | const autoprefixer = require('autoprefixer'); 2 | const clone = require('js.clone'); 3 | const webpack = require('webpack'); 4 | const webpackMerge = require('webpack-merge'); 5 | 6 | const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; 7 | const ContextReplacementPlugin = webpack.ContextReplacementPlugin; 8 | const DefinePlugin = webpack.DefinePlugin; 9 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 10 | const LoaderOptionsPlugin = webpack.LoaderOptionsPlugin; 11 | 12 | import { root, includeClientPackages } from './helpers'; 13 | 14 | // Common 15 | export const commonPlugins = [ 16 | new ContextReplacementPlugin( 17 | /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/, 18 | root('./src'), 19 | {} 20 | ), 21 | 22 | new LoaderOptionsPlugin({ 23 | debug: false, 24 | options: { 25 | postcss: [ 26 | autoprefixer({ browsers: ['last 3 versions', 'Firefox ESR'] }) 27 | ], 28 | resolve: {} 29 | } 30 | }) 31 | ]; 32 | 33 | export const commonConfig = { 34 | devtool: 'source-map', 35 | 36 | resolve: { 37 | extensions: ['.ts', '.js', '.json'], 38 | modules: [ root('node_modules') ] 39 | }, 40 | 41 | context: root('./'), 42 | 43 | module: { 44 | exprContextCritical: false, 45 | rules: [ 46 | { 47 | test: /\.ts$/, 48 | exclude: [/\.(spec|e2e|d)\.ts$/], 49 | use: ['ts-loader', 'angular2-template-loader'] 50 | }, 51 | { 52 | test: /\.html$/, 53 | use: ['html-loader'] 54 | }, 55 | { 56 | test: /\.scss$/, 57 | use: ['raw-loader', 'postcss-loader', 'sass-loader'] 58 | }, 59 | { 60 | test: /\.json$/, 61 | use: ['json-loader'] 62 | } 63 | ], 64 | } 65 | }; 66 | 67 | // Client 68 | export const clientPlugins = [ 69 | new CommonsChunkPlugin({ 70 | names: ['vendor', 'polyfills'], 71 | filename: 'assets/js/[name].[hash].js', 72 | minChunks: Infinity 73 | }), 74 | 75 | new HtmlWebpackPlugin({ 76 | chunksSortMode: 'dependency', 77 | filename: 'index.html', 78 | hash: true, 79 | inject: 'body', 80 | template: './src/index.html' 81 | }) 82 | ]; 83 | 84 | export const clientConfig = { 85 | target: 'web', 86 | 87 | entry: { 88 | main: './src/main', 89 | vendor: './src/vendor', 90 | polyfills: './src/polyfills' 91 | }, 92 | 93 | output: { 94 | filename: 'assets/js/[name].[hash].js', 95 | path: root('./target'), 96 | publicPath: '/' 97 | }, 98 | 99 | node: { 100 | global: true, 101 | crypto: 'empty', 102 | __dirname: true, 103 | __filename: true, 104 | process: true, 105 | Buffer: false 106 | } 107 | }; 108 | 109 | 110 | // Server. 111 | export const serverPlugins = []; 112 | 113 | export const serverConfig = { 114 | target: 'node', 115 | 116 | entry: './src/server', 117 | 118 | output: { 119 | filename: 'server.js', 120 | path: root('./target'), 121 | publicPath: '/', 122 | libraryTarget: 'commonjs2' 123 | }, 124 | 125 | externals: includeClientPackages( 126 | /@angularclass|@angular|angular2-|ng2-|ng-|@ng-|angular-|@ngrx|ngrx-|@angular2|ionic|@ionic|-angular2|-ng2|-ng/ 127 | ), 128 | 129 | node: { 130 | global: true, 131 | crypto: true, 132 | __dirname: true, 133 | __filename: true, 134 | process: true, 135 | Buffer: false 136 | } 137 | }; -------------------------------------------------------------------------------- /config/webpack.development.ts: -------------------------------------------------------------------------------- 1 | const clone = require('js.clone'); 2 | const webpack = require('webpack'); 3 | const webpackMerge = require('webpack-merge'); 4 | 5 | const DefinePlugin = webpack.DefinePlugin; 6 | 7 | import { root, includeClientPackages } from './helpers'; 8 | import * as commonWebpackConfig from './webpack.common'; 9 | 10 | 11 | export const commonPlugins = []; 12 | 13 | export const commonConfig = { 14 | devtool: 'cheap-source-map' 15 | }; 16 | 17 | 18 | // Client. 19 | export const clientPlugins = [ 20 | new DefinePlugin({ 21 | 'process.env': { 22 | 'NODE_ENV': JSON.stringify('development') 23 | } 24 | }) 25 | ]; 26 | 27 | export const clientConfig = {}; 28 | 29 | 30 | // Server. 31 | export const serverPlugins = []; 32 | 33 | export const serverConfig = {}; 34 | 35 | 36 | export default [ 37 | // Client 38 | webpackMerge( 39 | clone(commonWebpackConfig.commonConfig), 40 | commonWebpackConfig.clientConfig, 41 | clone(commonConfig), 42 | clientConfig, 43 | { plugins: [ 44 | ...commonWebpackConfig.commonPlugins, 45 | ...commonWebpackConfig.clientPlugins, 46 | ...commonPlugins, 47 | ...clientPlugins 48 | ]} 49 | ), 50 | 51 | // Server 52 | webpackMerge( 53 | clone(commonWebpackConfig.commonConfig), 54 | commonWebpackConfig.serverConfig, 55 | clone(commonConfig), 56 | serverConfig, 57 | { plugins: [ 58 | ...commonWebpackConfig.commonPlugins, 59 | ...commonWebpackConfig.serverPlugins, 60 | ...commonPlugins, 61 | ...serverPlugins 62 | ]} 63 | ) 64 | ]; 65 | -------------------------------------------------------------------------------- /config/webpack.production.ts: -------------------------------------------------------------------------------- 1 | const clone = require('js.clone'); 2 | const webpack = require('webpack'); 3 | const webpackMerge = require('webpack-merge'); 4 | 5 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; 6 | const DefinePlugin = webpack.DefinePlugin; 7 | const LoaderOptionsPlugin = webpack.LoaderOptionsPlugin; 8 | const NormalModuleReplacementPlugin = webpack.NormalModuleReplacementPlugin; 9 | const NoEmitOnErrorsPlugin = webpack.NoEmitOnErrorsPlugin; 10 | const UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; 11 | 12 | import { root } from './helpers'; 13 | import * as commonWebpackConfig from './webpack.common'; 14 | 15 | 16 | export const commonPlugins = [ 17 | // No errors 18 | new NoEmitOnErrorsPlugin(), 19 | 20 | // Loader options 21 | new LoaderOptionsPlugin({ 22 | //minimize: false, 23 | debug: false 24 | }), 25 | 26 | // Replacements 27 | new NormalModuleReplacementPlugin( 28 | /facade(\\|\/)async/, 29 | root('node_modules/@angular/core/src/facade/async.js') 30 | ), 31 | new NormalModuleReplacementPlugin( 32 | /facade(\\|\/)collection/, 33 | root('node_modules/@angular/core/src/facade/collection.js') 34 | ), 35 | new NormalModuleReplacementPlugin( 36 | /facade(\\|\/)errors/, 37 | root('node_modules/@angular/core/src/facade/errors.js') 38 | ), 39 | new NormalModuleReplacementPlugin( 40 | /facade(\\|\/)lang/, 41 | root('node_modules/@angular/core/src/facade/lang.js') 42 | ), 43 | new NormalModuleReplacementPlugin( 44 | /facade(\\|\/)math/, 45 | root('node_modules/@angular/core/src/facade/math.js') 46 | ) 47 | ]; 48 | 49 | export const commonConfig = {}; 50 | 51 | 52 | // Client. 53 | export const clientPlugins = [ 54 | new DefinePlugin({ 55 | 'process.env': { 56 | 'NODE_ENV': JSON.stringify('production') 57 | } 58 | }), 59 | 60 | new BundleAnalyzerPlugin({ 61 | analyzerMode: 'disabled', // change it to `server` to view bundle stats 62 | reportFilename: 'report.html', 63 | generateStatsFile: true, 64 | statsFilename: 'stats.json', 65 | }), 66 | 67 | // Uglify 68 | new UglifyJsPlugin({ 69 | sourceMap: true, 70 | mangle: { 71 | keep_fnames: true 72 | } 73 | }) 74 | ]; 75 | 76 | export const clientConfig = {}; 77 | 78 | 79 | // Server. 80 | export const serverPlugins = []; 81 | 82 | export const serverConfig = {}; 83 | 84 | 85 | export default [ 86 | // Client 87 | webpackMerge( 88 | clone(commonWebpackConfig.commonConfig), 89 | commonWebpackConfig.clientConfig, 90 | clone(commonConfig), 91 | clientConfig, 92 | { plugins: [ 93 | ...commonWebpackConfig.commonPlugins, 94 | ...commonWebpackConfig.clientPlugins, 95 | ...commonPlugins, 96 | ...clientPlugins 97 | ]} 98 | ), 99 | 100 | // Server 101 | webpackMerge( 102 | clone(commonWebpackConfig.commonConfig), 103 | commonWebpackConfig.serverConfig, 104 | clone(commonConfig), 105 | serverConfig, 106 | { plugins: [ 107 | ...commonWebpackConfig.commonPlugins, 108 | ...commonWebpackConfig.serverPlugins, 109 | ...commonPlugins, 110 | ...serverPlugins 111 | ]} 112 | ) 113 | ]; 114 | -------------------------------------------------------------------------------- /config/webpack.test.ts: -------------------------------------------------------------------------------- 1 | const autoprefixer = require('autoprefixer'); 2 | const webpack = require('webpack'); 3 | const webpackMerge = require('webpack-merge'); 4 | 5 | const DefinePlugin = webpack.DefinePlugin; 6 | const LoaderOptionsPlugin = webpack.LoaderOptionsPlugin; 7 | 8 | import { root } from './helpers'; 9 | import * as commonWebpackConfig from './webpack.common'; 10 | 11 | export const config = { 12 | devtool: 'cheap-source-map', 13 | 14 | resolve: commonWebpackConfig.commonConfig.resolve, 15 | 16 | module: { 17 | exprContextCritical: false, 18 | rules: [ 19 | { 20 | test: /\.ts$/, 21 | use: [ 22 | { 23 | loader: 'ts-loader', 24 | query: { 25 | // use inline sourcemaps for "karma-remap-coverage" reporter 26 | sourceMap: false, 27 | inlineSourceMap: true, 28 | compilerOptions: { 29 | // Remove TypeScript helpers to be injected 30 | // below by DefinePlugin 31 | removeComments: true 32 | } 33 | } 34 | }, 35 | 'angular2-template-loader' 36 | ] 37 | }, 38 | { 39 | test: /\.html$/, 40 | use: ['raw-loader', 'html-loader'] 41 | }, 42 | { 43 | test: /\.scss$/, 44 | use: ['raw-loader', 'postcss-loader', 'sass-loader'] 45 | }, 46 | { 47 | test: /\.json$/, 48 | use: ['json-loader'] 49 | } 50 | ] 51 | } 52 | }; 53 | 54 | export const plugins = [ 55 | new DefinePlugin({ 56 | 'process.env': { 57 | 'NODE_ENV': JSON.stringify('development') 58 | } 59 | }), 60 | 61 | new LoaderOptionsPlugin({ 62 | debug: false, 63 | options: { 64 | postcss: [ 65 | autoprefixer({ browsers: ['last 3 versions', 'Firefox ESR'] }) 66 | ], 67 | resolve: {} 68 | } 69 | }) 70 | ]; 71 | 72 | module.exports = webpackMerge( 73 | config, 74 | { plugins } 75 | ); 76 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "script": "target/server/index.js", 3 | "watch": ["target/server"], 4 | "ext": "js", 5 | "env": { "NODE_ENV": "development" }, 6 | "ignore": ["target/assets"] 7 | } 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-socket-io-chat-example", 3 | "version": "1.1.3", 4 | "description": "An example Angular chat app, made on top of ExpressJS & Socket.io.", 5 | "homepage": "https://github.com/jussikinnula/", 6 | "repository": "https://github.com/jussikinnula/angular-socket-io-chat", 7 | "author": { 8 | "name": "Jussi Kinnula", 9 | "email": "jussi.kinnula@gmail.com" 10 | }, 11 | "license": "GPL-3.0", 12 | "engines": { 13 | "node": "^8.0.0", 14 | "npm": "^5.0.0" 15 | }, 16 | "scripts": { 17 | "prebuild:prod": "npm run clean", 18 | "build:prod": "webpack --config config/webpack.production.ts --progress", 19 | "prebuild:dev": "npm run clean", 20 | "build:dev": "webpack --config config/webpack.development.ts --progress", 21 | "build": "npm run build:prod", 22 | "clean": "rimraf target", 23 | "predev": "npm run clean && npm run build:dev", 24 | "dev": "concurrently \"npm run server:dev\" \"npm run watch\"", 25 | "postinstall": "npm run build", 26 | "server:prod": "node target/server.js", 27 | "server:dev": "nodemon target/server.js", 28 | "server": "npm run server:prod", 29 | "start": "npm run server", 30 | "watch": "webpack --config config/webpack.development.ts --watch" 31 | }, 32 | "dependencies": { 33 | "@angular/common": "^4.3.1", 34 | "@angular/compiler": "^4.3.1", 35 | "@angular/core": "^4.3.1", 36 | "@angular/forms": "^4.3.1", 37 | "@angular/platform-browser": "^4.3.1", 38 | "@angular/platform-browser-dynamic": "^4.3.1", 39 | "@types/express": "^4.0.36", 40 | "@types/hammerjs": "^2.0.34", 41 | "@types/jasmine": "^2.5.53", 42 | "@types/mime": "^1.3.1", 43 | "@types/moment": "^2.13.0", 44 | "@types/mongodb": "^2.2.7", 45 | "@types/mongoose": "^4.7.19", 46 | "@types/node": "^8.0.14", 47 | "@types/serve-static": "^1.7.31", 48 | "@types/socket.io": "^1.4.29", 49 | "@types/socket.io-client": "^1.4.29", 50 | "@types/socket.io-redis": "^1.0.21", 51 | "angular2-template-loader": "^0.6.2", 52 | "autoprefixer": "^7.1.2", 53 | "core-js": "^2.4.1", 54 | "css-loader": "^0.28.4", 55 | "express": "^4.15.3", 56 | "html-loader": "^0.4.5", 57 | "html-webpack-plugin": "^2.29.0", 58 | "immutable": "^3.8.1", 59 | "js.clone": "^0.0.3", 60 | "json-loader": "^0.5.4", 61 | "moment": "^2.18.1", 62 | "mongoose": "^4.11.3", 63 | "node-sass": "^4.5.3", 64 | "postcss-loader": "^2.0.6", 65 | "raw-loader": "^0.5.1", 66 | "reflect-metadata": "^0.1.10", 67 | "rimraf": "^2.6.1", 68 | "rxjs": "5.4.2", 69 | "sass-loader": "^6.0.6", 70 | "serve-static": "^1.12.3", 71 | "socket.io": "^2.0.3", 72 | "socket.io-client": "^2.0.3", 73 | "socket.io-redis": "^5.1.0", 74 | "style-loader": "^0.18.2", 75 | "ts-helpers": "^1.1.2", 76 | "ts-loader": "^2.3.1", 77 | "ts-node": "^3.2.1", 78 | "typescript": "^2.4.2", 79 | "webpack": "3.3.0", 80 | "webpack-bundle-analyzer": "^2.8.3", 81 | "webpack-merge": "^4.1.0", 82 | "zone.js": "^0.8.14" 83 | }, 84 | "devDependencies": { 85 | "@types/webpack": "^3.0.4", 86 | "concurrently": "^3.5.0", 87 | "dotenv-cli": "^1.4.0", 88 | "jasmine-core": "^2.6.4", 89 | "karma": "^1.7.0", 90 | "karma-chrome-launcher": "^2.2.0", 91 | "karma-jasmine": "^1.1.0", 92 | "karma-sourcemap-loader": "^0.3.7", 93 | "karma-webpack": "^2.0.4", 94 | "nodemon": "^1.11.0", 95 | "webpack-dev-server": "^2.5.1" 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = {}; -------------------------------------------------------------------------------- /src/README.md: -------------------------------------------------------------------------------- 1 | # angular2-socketio-chat-example 2 | 3 | ## Entrypoints 4 | 5 | On this directory you will see *entrypoints* for the code. WebPack uses the these to transpile and create ES5 bundles (e.g. `target/assets/js/main.js`, `target/assets/js/vendor.js`, `target/assets/js/polyfills.js` and `target/assets/js/server.js`). 6 | 7 | - `main.ts` is the main application (frontend) 8 | - `index.html` is the SPA (single page app) HTML 9 | - `vendor.ts` contains the dependencies for libraries to be bundled 10 | - `polyfills.ts` contains the dependencies for polyfills 11 | - `server.ts` is the NodeJS backend 12 | 13 | # Subdirectories 14 | 15 | - `app/` contains frontend-only code parts 16 | - `models/` contains models shared with frontend and backend 17 | - `backend/` contains the backend code 18 | - `styles/` contains shared SCSS files 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 0; 3 | margin: 0; 4 | font-family: 'Arimo', sans-serif; 5 | } 6 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ViewEncapsulation } from '@angular/core'; 2 | 3 | import { UserService } from './core'; 4 | 5 | @Component({ 6 | encapsulation: ViewEncapsulation.None, 7 | selector: 'app', 8 | styleUrls: ['./app.component.scss'], 9 | templateUrl: './app.component.html' 10 | }) 11 | 12 | export class AppComponent { 13 | constructor(public userService: UserService) {} 14 | } 15 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { FormsModule } from '@angular/forms'; 4 | 5 | // App component 6 | import { AppComponent } from './app.component'; 7 | 8 | // Core module 9 | import { CoreModule } from './core'; 10 | 11 | // Shared module 12 | import { SharedModule } from './shared'; 13 | 14 | // Other components 15 | import { ControlComponent } from './control'; 16 | import { HeaderComponent } from './header'; 17 | import { NicknameComponent } from './nickname'; 18 | import { RoomComponent } from './room'; 19 | import { RoomsComponent } from './rooms'; 20 | 21 | @NgModule({ 22 | imports: [ 23 | CoreModule, 24 | SharedModule 25 | ], 26 | declarations: [ 27 | AppComponent, 28 | ControlComponent, 29 | HeaderComponent, 30 | NicknameComponent, 31 | RoomComponent, 32 | RoomsComponent 33 | ], 34 | exports: [ 35 | CoreModule 36 | ], 37 | bootstrap: [ 38 | AppComponent 39 | ] 40 | }) 41 | export class AppModule {} 42 | -------------------------------------------------------------------------------- /src/app/control/control.component.html: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | New room: 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/app/control/control.component.scss: -------------------------------------------------------------------------------- 1 | :host { 2 | display: block; 3 | background-color: chocolate; 4 | padding: 0.5em; 5 | margin: 0; 6 | } 7 | 8 | span { 9 | padding: 0; 10 | margin: 0 3em 0 0; 11 | } -------------------------------------------------------------------------------- /src/app/control/control.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import { RoomService } from '../core'; 4 | import { IRoom } from '../../models'; 5 | 6 | @Component({ 7 | selector: 'control', 8 | styleUrls: ['./control.component.scss'], 9 | templateUrl: './control.component.html' 10 | }) 11 | 12 | export class ControlComponent { 13 | room: string = ''; 14 | newRoom: string = ''; 15 | 16 | constructor(public roomService: RoomService) {} 17 | 18 | // Join room, when Join-button is pressed 19 | join(): void { 20 | this.roomService.join(this.room); 21 | this.room = ''; 22 | } 23 | 24 | // Create room, when Create-button is pressed and empty newRoom text input 25 | create(): void { 26 | this.roomService.create(this.newRoom); 27 | this.newRoom = ''; 28 | } 29 | 30 | // Remove room, when Remove-button is pressed and unset selected room 31 | remove(): void { 32 | this.roomService.remove(this.room); 33 | this.room = ''; 34 | } 35 | 36 | // Handle keypress event (for creating a new room) 37 | eventHandler(event: KeyboardEvent): void { 38 | if (event.key === 'Enter') { 39 | this.create(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/app/control/index.ts: -------------------------------------------------------------------------------- 1 | export * from './control.component'; -------------------------------------------------------------------------------- /src/app/core/core.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | 4 | import { RoomService } from './room.service'; 5 | import { UserService } from './user.service'; 6 | 7 | @NgModule({ 8 | imports: [ 9 | BrowserModule, 10 | ], 11 | providers: [ 12 | RoomService, 13 | UserService 14 | ] 15 | }) 16 | export class CoreModule {} 17 | -------------------------------------------------------------------------------- /src/app/core/index.ts: -------------------------------------------------------------------------------- 1 | export * from './core.module'; 2 | export * from './room.service'; 3 | export * from './socket.service'; 4 | export * from './user.service'; -------------------------------------------------------------------------------- /src/app/core/room.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ReplaySubject } from 'rxjs'; 3 | import { List } from 'immutable'; 4 | 5 | import { SocketService } from './socket.service'; 6 | import { UserService } from './user.service'; 7 | 8 | import { IRoom } from '../../models'; 9 | 10 | @Injectable() 11 | export class RoomService { 12 | rooms: ReplaySubject = new ReplaySubject(1); 13 | private list: IRoom[] = []; 14 | private socketService: SocketService; 15 | 16 | constructor(private userService: UserService) { 17 | // Open room socket 18 | this.socketService = new SocketService('room'); 19 | 20 | // Subscribe to room list updates 21 | this.socketService.items().subscribe( 22 | rooms => { 23 | this.list = rooms; 24 | this.rooms.next(this.list); 25 | }, 26 | error => console.log(error) 27 | ); 28 | 29 | // Get initial list 30 | this.socketService.list(); 31 | } 32 | 33 | // Join room 34 | join(name: string): void { 35 | const matches = this.list.filter(room => room.name === name); 36 | const alreadyJoined = this.userService.rooms.filter(room => room.name === name); 37 | if (matches[0] && !alreadyJoined[0]) { 38 | this.userService.rooms.push(matches[0]); 39 | } 40 | } 41 | 42 | // Leave room 43 | leave(name: string) { 44 | this.userService.rooms = this.userService.rooms.filter(room => room.name !== name); 45 | } 46 | 47 | // Create room 48 | create(name: string) { 49 | this.socketService.create(name); 50 | } 51 | 52 | // Remove room 53 | remove(name: string) { 54 | // Leave room 55 | this.leave(name); 56 | 57 | // Send signal to remove the room 58 | this.socketService.remove(name); 59 | } 60 | } -------------------------------------------------------------------------------- /src/app/core/socket.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import * as io from 'socket.io-client'; 4 | 5 | import { IMessage } from '../../models'; 6 | 7 | export class SocketService { 8 | private host: string = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port; 9 | socket: SocketIOClient.Socket; 10 | 11 | constructor(private name: string) { 12 | let socketUrl = this.host + '/' + this.name; 13 | this.socket = io.connect(socketUrl); 14 | } 15 | 16 | // Get items observable 17 | items(): Observable { 18 | return Observable.create(observer => { 19 | this.socket.on('item', (item: any) => observer.next(item)); 20 | }); 21 | } 22 | 23 | // Request initial list when connected 24 | list(): void { 25 | this.socket.emit('list'); 26 | } 27 | 28 | 29 | // Create signal 30 | create(params: any) { 31 | this.socket.emit('create', params); 32 | } 33 | 34 | // Remove signal 35 | remove(params: any) { 36 | this.socket.emit('remove', params); 37 | } 38 | 39 | onConnect(): Observable { 40 | return new Observable(observer => { 41 | this.socket.on('connect', () => observer.complete()); 42 | }) 43 | } 44 | 45 | onDisconnect(): Observable { 46 | return new Observable(observer => { 47 | this.socket.on('disconnect', () => observer.complete()); 48 | }) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/app/core/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | import { IRoom } from '../../models'; 4 | 5 | @Injectable() 6 | export class UserService { 7 | nickname: string = ''; 8 | rooms: IRoom[] = []; 9 | 10 | constructor() {} 11 | } -------------------------------------------------------------------------------- /src/app/header/header.component.html: -------------------------------------------------------------------------------- 1 |

Angular Chat

-------------------------------------------------------------------------------- /src/app/header/header.component.scss: -------------------------------------------------------------------------------- 1 | h1 { 2 | background-color: orange; 3 | padding: 0.5em 1em; 4 | margin: 0; 5 | font-size: 1.2em; 6 | font-weight: normal; 7 | text-transform: uppercase; 8 | letter-spacing: 0.2em; 9 | } 10 | -------------------------------------------------------------------------------- /src/app/header/header.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'header', 5 | styleUrls: ['./header.component.scss'], 6 | templateUrl: './header.component.html' 7 | }) 8 | 9 | export class HeaderComponent {} 10 | -------------------------------------------------------------------------------- /src/app/header/index.ts: -------------------------------------------------------------------------------- 1 | export * from './header.component'; -------------------------------------------------------------------------------- /src/app/nickname/index.ts: -------------------------------------------------------------------------------- 1 | export * from './nickname.component'; -------------------------------------------------------------------------------- /src/app/nickname/nickname.component.html: -------------------------------------------------------------------------------- 1 |

Nickname

2 | 3 |

4 | Please set your nick name in order to start chatting! 5 |

6 | 7 |

8 | 9 | 10 |

-------------------------------------------------------------------------------- /src/app/nickname/nickname.component.scss: -------------------------------------------------------------------------------- 1 | :host { 2 | display: block; 3 | padding: 1em; 4 | } -------------------------------------------------------------------------------- /src/app/nickname/nickname.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; 2 | 3 | import { UserService } from '../core'; 4 | 5 | @Component({ 6 | selector: 'nickname', 7 | styleUrls: ['./nickname.component.scss'], 8 | templateUrl: './nickname.component.html' 9 | }) 10 | 11 | export class NicknameComponent implements AfterViewInit { 12 | @ViewChild('focus') private focus: ElementRef; 13 | nickname: string; 14 | 15 | constructor(public userService: UserService) { 16 | this.nickname = userService.nickname; 17 | } 18 | 19 | // After view initialised, focus on nickname text input 20 | ngAfterViewInit(): void { 21 | this.focus.nativeElement.focus(); 22 | } 23 | 24 | // Save nickname to user store 25 | save(): void { 26 | this.userService.nickname = this.nickname; 27 | } 28 | 29 | // Handle keypress event, for saving nickname 30 | eventHandler(event: KeyboardEvent): void { 31 | if (event.key === 'Enter') { 32 | this.save(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/app/room/index.ts: -------------------------------------------------------------------------------- 1 | export * from './room.component'; -------------------------------------------------------------------------------- /src/app/room/message.service.ts: -------------------------------------------------------------------------------- 1 | import { ReplaySubject } from 'rxjs'; 2 | 3 | import { SocketService, UserService } from '../core'; 4 | import { IMessage } from '../../models'; 5 | 6 | export class MessageService { 7 | messages: ReplaySubject = new ReplaySubject(1); 8 | private list: IMessage[] = []; 9 | private socketService: SocketService; 10 | 11 | constructor(private userService: UserService, private room: string) { 12 | // Connect to room nsp 13 | this.socketService = new SocketService('messages/' + encodeURIComponent(this.room)); 14 | 15 | // Get initial items 16 | this.socketService.items() 17 | .subscribe( 18 | message => { 19 | this.list.push(message); 20 | this.messages.next(this.list); 21 | }, 22 | error => console.log(error) 23 | ); 24 | 25 | // Send user joined message 26 | this.socketService.onConnect().subscribe( 27 | x => {}, 28 | e => {}, 29 | () => this.send(`${this.userService.nickname} joined the channel`) 30 | ); 31 | 32 | // Send user leave message 33 | this.socketService.onDisconnect().subscribe( 34 | x => {}, 35 | e => {}, 36 | () => this.send(`${this.userService.nickname} left the channel`) 37 | ); 38 | } 39 | 40 | // Emit message using socket service 41 | send(message: string): void { 42 | this.socketService.create({ 43 | room: this.room, 44 | created: new Date(), 45 | from: this.userService.nickname, 46 | to: '', 47 | message: message 48 | }); 49 | } 50 | 51 | leave(): void { 52 | this.socketService.socket.disconnect(); 53 | } 54 | } -------------------------------------------------------------------------------- /src/app/room/room.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |

4 | {{room.name}} 5 |

6 |

Created: {{room.created}}

7 |
8 |
9 | {{item.created}} 10 | <{{item.from}}> 11 | {{item.message}} 12 |
13 |
14 |

15 | <{{userService.nickname}}> 16 | 17 | 18 |

19 |
-------------------------------------------------------------------------------- /src/app/room/room.component.scss: -------------------------------------------------------------------------------- 1 | :host { 2 | width: 100%; 3 | display: inline-block; 4 | @media (min-width: 700px) and (max-width: 999px) { 5 | width: 50%; 6 | float: left; 7 | } 8 | @media (min-width: 1000px) and (max-width: 1299px) { 9 | width: 33.333333%; 10 | float: left; 11 | } 12 | @media (min-width: 1300px) and (max-width: 1599px) { 13 | width: 25%; 14 | float: left; 15 | } 16 | @media (min-width: 1600px) and (max-width: 1899px) { 17 | width: 20%; 18 | float: left; 19 | } 20 | @media (min-width: 1900px) and (max-width: 2199px) { 21 | width: 16.666666%; 22 | float: left; 23 | } 24 | @media (min-width: 2200px) { 25 | width: 14.285714%; 26 | float: left; 27 | } 28 | } 29 | 30 | .box { 31 | border: 1px solid black; 32 | padding: 0; 33 | margin: 0.25em; 34 | background-color: white; 35 | box-shadow: 0.25em 0.25em 0.5em rgba(0, 0, 0, 0.5); 36 | } 37 | 38 | h1 { 39 | color: white; 40 | background-color: black; 41 | margin: 0; 42 | padding: 0.25em; 43 | font-size: 1em; 44 | } 45 | 46 | h2 { 47 | color: white; 48 | background-color: gray; 49 | margin: 0; 50 | padding: 0.25em; 51 | font-size: 0.7em; 52 | } 53 | 54 | h3 { 55 | color: white; 56 | background-color: gray; 57 | margin: 0; 58 | padding: 0.25em; 59 | font-size: 1em; 60 | } 61 | 62 | .leave { 63 | float: right; 64 | margin: 0.25em; 65 | } 66 | 67 | .dimmed { 68 | color: silver; 69 | } 70 | 71 | .messages { 72 | overflow-y: scroll; 73 | overflow-x: hidden; 74 | height: 20em; 75 | padding: 0; 76 | margin: 0; 77 | font-size: 0.8em; 78 | } 79 | 80 | .message { 81 | margin: 0 0 0.2em 0; 82 | padding: 0; 83 | } -------------------------------------------------------------------------------- /src/app/room/room.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit, AfterViewInit, OnDestroy, ElementRef, ViewChild } from '@angular/core'; 2 | 3 | import { RoomService, UserService } from '../core'; 4 | import { IMessage, IRoom } from '../../models'; 5 | import { MessageService } from './message.service'; 6 | 7 | @Component({ 8 | selector: 'room', 9 | styleUrls: ['./room.component.scss'], 10 | templateUrl: './room.component.html' 11 | }) 12 | 13 | export class RoomComponent implements OnInit, AfterViewInit, OnDestroy { 14 | @ViewChild('scroll') private scroll: ElementRef; 15 | @ViewChild('focus') private focus: ElementRef; 16 | @Input() room: IRoom; 17 | message: string = ''; 18 | messages: IMessage[]; 19 | private messageService: MessageService; 20 | private alreadyLeftChannel: boolean = false; 21 | 22 | constructor(private roomService: RoomService, public userService: UserService) {} 23 | 24 | // Handle keypress event, for saving nickname 25 | ngOnInit(): void { 26 | this.messageService = new MessageService(this.userService, this.room.name); 27 | this.messageService.messages.subscribe(messages => { 28 | this.messages = messages; 29 | setTimeout( () => { 30 | this.scrollToBottom(); 31 | }, 200); 32 | }); 33 | } 34 | 35 | // After view initialized, focus on chat message text input 36 | ngAfterViewInit(): void { 37 | this.focus.nativeElement.focus(); 38 | } 39 | 40 | // When component is destroyed, ensure that leave message is sent 41 | ngOnDestroy(): void { 42 | if (!this.alreadyLeftChannel) { 43 | this.leave(); 44 | } 45 | } 46 | 47 | // Send chat message, and reset message text input 48 | send(): void { 49 | this.messageService.send(this.message); 50 | this.message = ''; 51 | } 52 | 53 | // Leave room gracefully 54 | leave(): void { 55 | this.alreadyLeftChannel = true; 56 | this.messageService.leave(); 57 | this.roomService.leave(this.room.name); 58 | } 59 | 60 | //* Scroll to bottom (this is called when new message is received) 61 | scrollToBottom(): void { 62 | try { 63 | this.scroll.nativeElement.scrollTop = this.scroll.nativeElement.scrollHeight; 64 | } catch(error) { 65 | console.log('ERROR:', error); 66 | } 67 | } 68 | 69 | // Handle keypress event, for sending chat message 70 | eventHandler(event: KeyboardEvent): void { 71 | if (event.key === 'Enter') { 72 | this.send(); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/app/rooms/index.ts: -------------------------------------------------------------------------------- 1 | export * from './rooms.component'; -------------------------------------------------------------------------------- /src/app/rooms/rooms.component.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/app/rooms/rooms.component.scss: -------------------------------------------------------------------------------- 1 | :host { 2 | display: block; 3 | padding: 0.25em; 4 | margin: 0; 5 | &:after { 6 | content: ' '; 7 | clear: both; 8 | } 9 | } -------------------------------------------------------------------------------- /src/app/rooms/rooms.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import { UserService } from '../core'; 4 | import { IRoom } from '../../models'; 5 | 6 | @Component({ 7 | selector: 'rooms', 8 | styleUrls: ['./rooms.component.scss'], 9 | templateUrl: './rooms.component.html' 10 | }) 11 | 12 | export class RoomsComponent { 13 | constructor(public userService: UserService) {} 14 | } 15 | -------------------------------------------------------------------------------- /src/app/shared/index.ts: -------------------------------------------------------------------------------- 1 | export * from './shared.module'; -------------------------------------------------------------------------------- /src/app/shared/order-by.pipe.ts: -------------------------------------------------------------------------------- 1 | import { Pipe, PipeTransform } from '@angular/core'; 2 | 3 | @Pipe({ 4 | name: 'orderBy' 5 | }) 6 | export class OrderByPipe implements PipeTransform { 7 | transform(input: any, orderer: string, reverse: boolean = false): any { 8 | if (input && orderer) { 9 | let output = input.sort(this.dynamicSort(orderer)); 10 | if (reverse) { 11 | return output.reverse(); 12 | } else { 13 | return output; 14 | } 15 | } else { 16 | return input; 17 | } 18 | } 19 | 20 | private dynamicSort(property: string): any { 21 | return (a: any, b: any) => { 22 | return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /src/app/shared/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { FormsModule } from '@angular/forms'; 4 | 5 | import { OrderByPipe } from './order-by.pipe'; 6 | 7 | @NgModule({ 8 | imports: [ 9 | CommonModule, 10 | FormsModule 11 | ], 12 | declarations: [ 13 | OrderByPipe 14 | ], 15 | exports: [ 16 | CommonModule, 17 | FormsModule, 18 | OrderByPipe 19 | ] 20 | }) 21 | export class SharedModule {} 22 | -------------------------------------------------------------------------------- /src/backend/index.ts: -------------------------------------------------------------------------------- 1 | import * as express from 'express'; 2 | import * as http from 'http'; 3 | import * as serveStatic from 'serve-static'; 4 | import * as path from 'path'; 5 | import * as socket from 'socket.io'; 6 | import * as mongoose from 'mongoose'; 7 | import * as redis from 'socket.io-redis'; 8 | 9 | import { RoomSocket } from './socket'; 10 | 11 | declare var process, __dirname; 12 | 13 | export class Backend { 14 | private app: express.Application; 15 | private server: any; 16 | private io: any; 17 | private mongo: mongoose.MongooseThenable; 18 | private port: number; 19 | 20 | constructor() { 21 | // Create expressjs application 22 | this.app = express(); 23 | 24 | // Setup routes 25 | this.routes(); 26 | 27 | // Create server 28 | this.server = http.createServer(this.app); 29 | 30 | // Create database connections 31 | this.databases(); 32 | 33 | // Handle websockets 34 | this.sockets(); 35 | } 36 | 37 | // Configure routes 38 | private routes(): void { 39 | // Setup router 40 | let router: express.Router; 41 | router = express.Router(); 42 | 43 | // Root path 44 | const root = path.join(path.resolve(__dirname, '../../target')); 45 | 46 | // Static assets 47 | this.app.use('/assets', serveStatic(path.resolve(root, 'assets'))); 48 | 49 | // Set router to serve index.html (e.g. single page app) 50 | router.get('/', (request: express.Request, result: express.Response) => { 51 | result.sendFile(path.join(root, '/index.html')); 52 | }); 53 | 54 | // Set app to use router as the default route 55 | this.app.use('*', router); 56 | } 57 | 58 | // Configure databases 59 | private databases(): void { 60 | // MongoDB URL 61 | const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost/chat'; 62 | 63 | // Get MongoDB handle 64 | this.mongo = mongoose.connect(MONGODB_URI, { useMongoClient: true }); 65 | (mongoose).Promise = global.Promise; 66 | } 67 | 68 | // Configure sockets 69 | private sockets(): void { 70 | // Get socket.io handle 71 | this.io = socket(this.server); 72 | 73 | // Set Redis adapter 74 | const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379'; 75 | this.io.adapter(redis(REDIS_URL)); 76 | 77 | // Set room socket 78 | let roomSocket = new RoomSocket(this.io); 79 | } 80 | 81 | public listen(): void { 82 | // Get port 83 | const port = process.env.PORT || 5000; 84 | 85 | // Start listening 86 | this.server.listen(port); 87 | 88 | // add error handler 89 | this.server.on('error', error => { 90 | console.log('ERROR', error); 91 | }); 92 | 93 | // start listening on port 94 | this.server.on('listening', () => { 95 | console.log(`==> Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`); 96 | }); 97 | } 98 | } -------------------------------------------------------------------------------- /src/backend/socket/index.ts: -------------------------------------------------------------------------------- 1 | export * from './message'; 2 | export * from './room'; -------------------------------------------------------------------------------- /src/backend/socket/message.ts: -------------------------------------------------------------------------------- 1 | import { IMessage, Message, Room } from "../../models"; 2 | 3 | export class MessageSocket { 4 | nsp: any; 5 | data: any; 6 | socket: any; 7 | 8 | constructor(io: any, public room: Room) { 9 | this.nsp = io.of("/messages/" + encodeURIComponent(this.room.name)); 10 | this.nsp.on("connection", (socket: any) => { 11 | console.log("Client connected to room:", this.room.name); 12 | this.socket = socket; 13 | this.listen(); 14 | }); 15 | } 16 | 17 | // Add signal 18 | private listen(): void { 19 | this.socket.on("disconnect", () => this.disconnect()); 20 | this.socket.on("create", message => this.create(message)); 21 | this.socket.on("list", () => this.list()); 22 | } 23 | 24 | // Handle disconnect 25 | private disconnect(): void { 26 | console.log("Client disconnected from room:", this.room.name); 27 | } 28 | 29 | // Create a message in a room 30 | private create(params: IMessage): void { 31 | params.room = this.room.name; 32 | Message.create(params).subscribe( 33 | message => this.nsp.emit('item', message), 34 | error => console.error('Message sending failed', error) 35 | ); 36 | } 37 | 38 | // List all messages in a room 39 | private list(): void { 40 | this.room.messages() 41 | .map(messages => messages.reverse()) 42 | .subscribe(messages => messages.map(message => this.socket.emit(message))); 43 | } 44 | } -------------------------------------------------------------------------------- /src/backend/socket/room.ts: -------------------------------------------------------------------------------- 1 | import { Room, Message } from '../../models'; 2 | import { MessageSocket } from './message'; 3 | 4 | export class RoomSocket { 5 | nsp: any; 6 | name: string; 7 | data: any; 8 | socket: any; 9 | rooms: Room[] = []; 10 | messageSockets: MessageSocket[] = []; 11 | 12 | constructor(private io: any) { 13 | this.nsp = this.io.of('/room'); 14 | this.nsp.on('connection', (socket: any) => { 15 | console.log('Client connected'); 16 | this.socket = socket; 17 | this.updateMessageSockets(); 18 | this.listen(); 19 | }); 20 | } 21 | 22 | // Add signal 23 | private listen(): void { 24 | this.socket.on('disconnect', () => this.disconnect()); 25 | this.socket.on('create', (name: string) => this.create(name)); 26 | this.socket.on('remove', (name: string) => this.remove(name)); 27 | this.socket.on('list', () => this.list()); 28 | } 29 | 30 | // Handle disconnect 31 | private disconnect(): void { 32 | console.log('Client disconnected'); 33 | } 34 | 35 | // Create a room 36 | private create(name: string): void { 37 | Room.create(name).subscribe( 38 | room => this.list(), 39 | error => console.error('Room creation failed', error) 40 | ); 41 | } 42 | 43 | // Remove a room 44 | private remove(name: string): void { 45 | Room.find(name).subscribe( 46 | room => room.remove().subscribe(x => {}, e => {}, () => this.list()), 47 | error => console.error('Room removal failed', error) 48 | ); 49 | } 50 | 51 | // List all rooms 52 | private list(): void { 53 | Room.list().subscribe(rooms => { 54 | this.rooms = rooms; 55 | this.updateMessageSockets(); 56 | this.nsp.emit('item', rooms); 57 | }); 58 | } 59 | 60 | // Update message sockets 61 | private updateMessageSockets(): void { 62 | // Add message sockets for new rooms 63 | let validRooms = {}; 64 | for (const room of this.rooms) { 65 | validRooms[room.name] = true; 66 | const matches = this.messageSockets.filter(messageSocket => messageSocket.room.name === room.name); 67 | if (matches.length == 0) { 68 | console.log('creating new namespace for', room.name); 69 | this.messageSockets.push(new MessageSocket(this.io, room)); 70 | } 71 | } 72 | 73 | // Destroy sockets for removed rooms 74 | for (const index in this.messageSockets) { 75 | const messageSocket = this.messageSockets[index]; 76 | if (!validRooms[messageSocket.room.name]) { 77 | this.messageSockets.splice(parseInt(index, 10), 1); 78 | } 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Angular Chat 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from "@angular/core"; 2 | import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; 3 | 4 | // root component 5 | import { AppModule } from "./app/app.module"; 6 | 7 | // Declare process variable (so that type checker doesn't nag about it) 8 | declare var process; 9 | 10 | if (process.env.NODE_ENV === "production") { 11 | enableProdMode(); 12 | } 13 | 14 | platformBrowserDynamic().bootstrapModule(AppModule); -------------------------------------------------------------------------------- /src/models/index.ts: -------------------------------------------------------------------------------- 1 | export * from './message.model'; 2 | export * from './room.model'; 3 | -------------------------------------------------------------------------------- /src/models/message.model.ts: -------------------------------------------------------------------------------- 1 | import { Observable } from 'rxjs'; 2 | import * as mongoose from 'mongoose'; 3 | import * as moment from 'moment'; 4 | 5 | import { Room } from './room.model'; 6 | 7 | export interface IMessage { 8 | room: string; 9 | created: Date; 10 | from: string; 11 | to: string; 12 | message: string; 13 | } 14 | 15 | interface IMessageModel extends IMessage, mongoose.Document {} 16 | 17 | const MessageSchema = new mongoose.Schema({ 18 | room: { 19 | type: String, 20 | index: true 21 | }, 22 | created: Date, 23 | from: String, 24 | to: String, 25 | message: String 26 | }); 27 | 28 | const MessageModel = mongoose.model('Message', MessageSchema); 29 | 30 | export class Message { 31 | room: string; 32 | created: Date; 33 | from: string; 34 | to: string; 35 | message: string; 36 | 37 | constructor(message: IMessageModel) { 38 | this.room = message.room; 39 | this.created = moment(message.created).toDate(); 40 | this.from = message.from; 41 | this.to = message.to; 42 | this.message = message.message; 43 | } 44 | 45 | public static create(message: IMessage): Observable { 46 | return new Observable(observer => { 47 | Room.find(message.room).subscribe( 48 | room => { 49 | message.created = new Date(); 50 | MessageModel.create(message, (error, message) => { 51 | if (!error && message) { 52 | observer.next(new Message(message)); 53 | } 54 | observer.complete(); 55 | }); 56 | }, 57 | error => observer.error(new Error()) 58 | ); 59 | }); 60 | } 61 | 62 | public static list(room: string): Observable { 63 | return new Observable(observer => { 64 | MessageModel.find({ room }, (error, messages) => { 65 | if (!error && messages) { 66 | observer.next(messages.map(message => new Message(message))); 67 | } else { 68 | observer.next([]); 69 | } 70 | observer.complete(); 71 | }); 72 | }); 73 | } 74 | 75 | public static remove(room: string): Observable { 76 | return new Observable(observer => { 77 | MessageModel.remove({ room }, (error) => { 78 | if (!error) { 79 | observer.complete(); 80 | } else { 81 | observer.error(new Error(error)); 82 | } 83 | }); 84 | }); 85 | } 86 | } -------------------------------------------------------------------------------- /src/models/room.model.ts: -------------------------------------------------------------------------------- 1 | import { Observable } from 'rxjs'; 2 | import * as mongoose from 'mongoose'; 3 | import * as moment from 'moment'; 4 | 5 | import { IMessage, Message } from './message.model'; 6 | 7 | export interface IRoom { 8 | name: string; 9 | created: Date; 10 | } 11 | 12 | interface IRoomModel extends IRoom, mongoose.Document {} 13 | 14 | const RoomSchema = new mongoose.Schema({ 15 | name: { 16 | type: String, 17 | unique: true 18 | }, 19 | created: Date 20 | }); 21 | 22 | const RoomModel = mongoose.model('Room', RoomSchema); 23 | 24 | export class Room { 25 | name: string; 26 | created: Date; 27 | 28 | constructor(room: IRoomModel) { 29 | this.name = room.name; 30 | this.created = moment(room.created).toDate(); 31 | } 32 | 33 | public static find(name: string): Observable { 34 | return new Observable(observer => { 35 | RoomModel.findOne({ name }, (error, room) => { 36 | if (!error && room) { 37 | observer.next(new Room(room)); 38 | } 39 | observer.complete(); 40 | }); 41 | }); 42 | } 43 | 44 | public static create(name: string): Observable { 45 | return new Observable(observer => { 46 | const created = new Date(); 47 | RoomModel.create({ name, created }, (error, room) => { 48 | if (!error && room) { 49 | observer.next(new Room(room)); 50 | observer.complete(); 51 | } else { 52 | observer.error(new Error()); 53 | } 54 | }); 55 | }); 56 | } 57 | 58 | public static list(): Observable { 59 | return new Observable(observer => { 60 | RoomModel.find({}, (error, rooms) => { 61 | if (!error && rooms) { 62 | observer.next(rooms.map(room => new Room(room))); 63 | } else { 64 | observer.next([]); 65 | } 66 | observer.complete(); 67 | }); 68 | }); 69 | } 70 | 71 | remove(): Observable { 72 | return new Observable(observer => { 73 | RoomModel.remove({ name: this.name }).exec(); 74 | Message.remove(this.name).subscribe( 75 | x => {}, 76 | error => observer.error(new Error(error)), 77 | () => observer.complete() 78 | ); 79 | }); 80 | } 81 | 82 | messages() { 83 | return Message.list(this.name); 84 | } 85 | } -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | import 'core-js/client/shim'; 2 | import 'reflect-metadata'; 3 | require('zone.js/dist/zone'); 4 | 5 | import 'ts-helpers'; 6 | 7 | if (process.env.NODE_ENV !== 'production') { 8 | Error['stackTraceLimit'] = Infinity; 9 | require('zone.js/dist/long-stack-trace-zone'); 10 | } -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | // Instantiate server app 2 | import { Backend } from './backend'; 3 | const backend = new Backend(); 4 | backend.listen(); -------------------------------------------------------------------------------- /src/vendor.ts: -------------------------------------------------------------------------------- 1 | // Angular 2 | import '@angular/common'; 3 | import '@angular/core'; 4 | import '@angular/forms'; 5 | import '@angular/platform-browser'; 6 | import '@angular/platform-browser-dynamic'; 7 | 8 | // ImmutableJS 9 | import 'immutable'; 10 | 11 | // Socket.io client 12 | import 'socket.io-client'; 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "declaration": false, 4 | "emitDecoratorMetadata": true, 5 | "experimentalDecorators": true, 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "outDir": "dist", 9 | "sourceMap": true, 10 | "sourceRoot": "src", 11 | "noEmitHelpers": true, 12 | "target": "es5", 13 | "typeRoots": [ 14 | "node_modules/@types" 15 | ], 16 | "lib": ["es6", "dom"] 17 | }, 18 | "exclude": [ 19 | "node_modules", 20 | "vendor" 21 | ], 22 | "angularCompilerOptions": { 23 | "debug": false 24 | }, 25 | "compileOnSave": false, 26 | "buildOnSave": false, 27 | "atom": { "rewriteTsconfig": false } 28 | } 29 | -------------------------------------------------------------------------------- /webpack.config.ts: -------------------------------------------------------------------------------- 1 | module.exports = require('./config/webpack.development'); 2 | --------------------------------------------------------------------------------