├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── deck ├── deck.go └── deck_test.go ├── game ├── game.go └── game_test.go ├── go.mod ├── go.sum ├── k8s ├── configmap.yaml ├── deployment.yaml └── service.yaml ├── main.go ├── name ├── name.go └── name_test.go ├── resources └── sibyl-screenshot.png ├── server ├── client.go ├── client_test.go └── server.go ├── static ├── favicon.ico ├── images │ ├── logo.png │ ├── synacor-bg.png │ └── synacor-gray.svg ├── javascripts │ ├── index.js │ └── room.js └── stylesheets │ └── styles.css └── templates ├── index.html ├── room.html └── template.html /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.swo 3 | *.bak 4 | config.json 5 | sibyl 6 | coverage.out 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.12 AS build 2 | WORKDIR /build 3 | COPY . /build 4 | RUN go get github.com/GeertJohan/go.rice/... \ 5 | && CGO_ENABLED=0 go build -o sibyl \ 6 | && rice append --exec sibyl 7 | 8 | FROM alpine:latest 9 | COPY --from=build /build/sibyl /bin/sibyl 10 | ENTRYPOINT [ "/bin/sibyl" ] 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | IMG ?= synacor/sibyl 2 | 3 | bin/sibyl: test 4 | go get ./... 5 | go get github.com/GeertJohan/go.rice/rice/... 6 | go build -o bin/sibyl 7 | rice append --exec bin/sibyl 8 | 9 | install: bin/sibyl 10 | install bin/sibyl /usr/local/bin/sibyl 11 | sudo setcap cap_net_bind_service=+ep /usr/local/bin/sibyl 12 | 13 | docker-build: test 14 | docker build -t $(IMG) . 15 | 16 | clean: 17 | rm bin/* 18 | 19 | test: 20 | go test -coverprofile=coverage.out ./... 21 | 22 | coverage: test 23 | go tool cover -html=coverage.out 24 | 25 | .PHONY: sibyl install docker-build clean test coverage 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sibyl - Rapid Agile Estimations 2 | 3 | [![Build Status](https://travis-ci.org/synacor/sibyl.svg?branch=master)](https://travis-ci.org/synacor/sibyl) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/synacor/sibyl)](https://goreportcard.com/report/github.com/synacor/sibyl) 5 | 6 | **Sibyl** is an online agile estimation tool that doesn't require sign-ups, entering user stories, or any other time consuming steps that keeps you from doing what matters: estimating on stories. 7 | 8 | This repo contains both the back-end and front-end code for running Sibyl. 9 | 10 | ![Sibyl Screenshot](resources/sibyl-screenshot.png) 11 | 12 | ## Getting started 13 | 14 | ### Get Sibyl 15 | 16 | To get **sibyl**: 17 | 18 | ``` 19 | % go get github.com/synacor/sibyl 20 | ``` 21 | 22 | ### Run Sibyl 23 | 24 | As long as `$GOPATH/bin` is in your `$PATH`, you can now run `sibyl`. 25 | 26 | ``` 27 | % sibyl 28 | ``` 29 | 30 | ### Build Sibyl for Distribution 31 | 32 | **Sibyl** uses the [rice.go](https://github.com/GeertJohan/go.rice) package to bundle in the templates and that static directory. When running on your local server, it will automatically pull it from the installed directory. If you 33 | want to distribute your binary to other servers, you'll want to bundle up those assets. First, you'll need to install the `rice` command. 34 | 35 | ``` 36 | % go get github.com/GeertJohan/go.rice/rice 37 | ``` 38 | 39 | Now you can bundle up the assets in the binary. 40 | 41 | ``` 42 | % cd $GOPATH/src/github.com/synacor/sibyl 43 | % go build 44 | % rice append --exec sibyl 45 | ``` 46 | 47 | The binary `./sibyl` can now be distributed. 48 | 49 | ## Configuration 50 | 51 | Sibyl uses [viper](https://github.com/spf13/viper) for configuration. The following environment variales are supported: 52 | 53 | * `SIB_PORT`: Specify the port to run sibyl on. Defaults to `5000`. 54 | * `SIB_TLS_PORT`: Specify the TLS port to run sibyl on. By default, Sibyl does not use TLS. 55 | * `SIB_DEBUG`: Outputs additional log details. 56 | 57 | Extended configuration can be supplied by created a `config.json` file in either of the following two locations: 58 | 59 | * `./config.json` 60 | * `/etc/sibyl/config.json` 61 | 62 | Only the first config file found will be used. 63 | 64 | The following example JSON file contains all the options and their defaults: 65 | 66 | ``` 67 | { 68 | "debug": false, 69 | "log_level": "INFO", 70 | "port": 5000, 71 | "tls_port": 0, 72 | "force_tls": false, 73 | "tls_private_key": "", 74 | "tls_public_key": "" 75 | } 76 | ``` 77 | 78 | * `debug`: Output additional debugging information to STDERR. 79 | * `log_level`: Specifies what level of logging should be outputted to STDERR. If `debug` is on, you probably want this to `DEBUG`. 80 | * `port`: The port to use for HTTP (non-TLS) traffic. 81 | * `tls_port`: The port to use for HTTPS (TLS) traffic. Will only turn on TLS support if specified. If you use this option, you need to also specify `tls_private_key` and `tls_public_key`. 82 | * `force_tls`: If using TLS, redirect non-TLS traffic to use TLS with a permanent redirect. 83 | * `tls_private_key`: Path to the private key file. 84 | * `tls_public_key`: Path to the public key file. 85 | 86 | ## Known Issues 87 | 88 | * When running the server over HTTP (non-TLS), some antivirus applications that buffer http connections, such as Kaspersky, may cause the web socket connection to disconnect. The workaround is to either run the server with HTTPS, or to disable port 80 filtering in your antivirus. 89 | * The app does not currently horizontally scale because everything is kept in-memory. Will need to add routing capabailities so that all rooms hit the same instance, or add pub/sub features. 90 | 91 | ## Contributing 92 | 93 | All ideas and contributions are appreciated. 94 | 95 | ## License 96 | 97 | GNU AGPLv3 License, please see [LICENSE](LICENSE) for details. 98 | -------------------------------------------------------------------------------- /deck/deck.go: -------------------------------------------------------------------------------- 1 | // Package deck provides various deck capabilities 2 | package deck 3 | 4 | import "errors" 5 | 6 | // Deck represents an individual deck of cards 7 | type Deck struct { 8 | Name string `json:"name"` 9 | Cards []string `json:"cards"` 10 | } 11 | 12 | // ErrCardNotFound is an error when a user asks for a card not found within a deck. 13 | var ErrCardNotFound = errors.New("card not found with that index") 14 | 15 | // ModifiedFibonacci is the standard deck for agile estimations. 16 | var ModifiedFibonacci = &Deck{"Modified Fibonacci", []string{"0", "1", "2", "3", "5", "8", "13", "20", "40", "100", "?", "☕"}} 17 | 18 | // Fibonacci uses the actual Fibonacci numbers. 19 | var Fibonacci = &Deck{"Fibonacci", []string{"0", "1", "2", "3", "5", "8", "13", "21", "34", "55", "89", "?", "☕"}} 20 | 21 | // TShirtSizes uses a number of shirt sizes for estimates. 22 | var TShirtSizes = &Deck{"T-Shirt Sizes", []string{"XS", "S", "M", "L", "XL", "XXL", "?", "☕"}} 23 | 24 | var Hours = &Deck{"Hours", []string{"0", ".5", "1", "2", "4", "8", "12", "16", "20", "24", "?", "☕"}} 25 | 26 | // AllDecks contains a mapping of deck names to decks 27 | var AllDecks = map[string]*Deck{ 28 | ModifiedFibonacci.Name: ModifiedFibonacci, 29 | Fibonacci.Name: Fibonacci, 30 | TShirtSizes.Name: TShirtSizes, 31 | Hours.Name: Hours, 32 | } 33 | 34 | // GetCard returns the card for the specified index. 35 | func (d *Deck) GetCard(i int) (string, error) { 36 | if i < 0 || i >= len(d.Cards) { 37 | return "", ErrCardNotFound 38 | } 39 | 40 | return d.Cards[i], nil 41 | } 42 | -------------------------------------------------------------------------------- /deck/deck_test.go: -------------------------------------------------------------------------------- 1 | package deck 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestDeck(t *testing.T) { 10 | d := &Deck{"Test", []string{"A", "B", "C"}} 11 | 12 | c, err := d.GetCard(0) 13 | assert.Equal(t, "A", c) 14 | assert.NoError(t, err) 15 | 16 | c, err = d.GetCard(2) 17 | assert.Equal(t, "C", c) 18 | assert.NoError(t, err) 19 | 20 | c, err = d.GetCard(3) 21 | assert.Equal(t, "", c) 22 | assert.Error(t, err) 23 | assert.Equal(t, err, ErrCardNotFound) 24 | } 25 | 26 | func TestSpotCheck(t *testing.T) { 27 | c, _ := ModifiedFibonacci.GetCard(7) 28 | assert.Equal(t, "20", c) 29 | 30 | c, _ = Fibonacci.GetCard(7) 31 | assert.Equal(t, "21", c) 32 | 33 | c, _ = TShirtSizes.GetCard(0) 34 | assert.Equal(t, "XS", c) 35 | 36 | c, _ = Hours.GetCard(1) 37 | assert.Equal(t, ".5", c) 38 | } 39 | 40 | func TestAllDecks(t *testing.T) { 41 | for k, d := range AllDecks { 42 | assert.Equal(t, k, d.Name) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /game/game.go: -------------------------------------------------------------------------------- 1 | // Package game provides capabilities for an individual estimation session. 2 | package game 3 | 4 | import ( 5 | "crypto/rand" 6 | "encoding/base64" 7 | "errors" 8 | "fmt" 9 | "regexp" 10 | "sync" 11 | "time" 12 | 13 | log "github.com/sirupsen/logrus" 14 | "github.com/synacor/sibyl/deck" 15 | ) 16 | 17 | const ( 18 | // RoomNameValidDescription A description on how the room name should be constructed 19 | RoomNameValidDescription = "A room name must contain 1-20 characters with at least one being a letter or number. All characters must be letters, numbers, spaces, underscores, or hyphens" 20 | 21 | // RoomNameMaxLength is the max length a room name may be 22 | RoomNameMaxLength = 20 23 | 24 | // TopicMaxLength is the max length a topic may be. 25 | TopicMaxLength = 100 26 | ) 27 | 28 | // waitToDestroy is the number of milliseconds to wait after last client to destroy the channel 29 | const waitToDestroy = 10000 // 10 seconds 30 | 31 | // ErrInvalidRoomName is returned when the room name is not valid. 32 | var ErrInvalidRoomName = errors.New("sibyl: room name is invalid") 33 | 34 | // Golang doesn't allow \p{Letter}, so we have to use the shorthand. 35 | // L = Letter, M = Mark, N = Number, P = Punctuation 36 | var validTopixRx = regexp.MustCompile(`^[\p{L}\p{M}\p{S}\p{N}\p{P} ]{1,100}\z`) 37 | var validRoomRx = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,20}\z`) 38 | var withLetterOrNumberRx = regexp.MustCompile(`[\p{L}\p{N}]`) 39 | 40 | type client interface { 41 | Send(interface{}) 42 | ID() int 43 | Name() string 44 | CloseChannel() 45 | RemoteAddr() string 46 | } 47 | 48 | type safeClients struct { 49 | clients map[client]bool 50 | mutex sync.RWMutex 51 | } 52 | 53 | type safeCards struct { 54 | deck *deck.Deck 55 | cards map[client]int 56 | reveal bool 57 | mutex sync.RWMutex 58 | } 59 | 60 | type safeTopic struct { 61 | topic string 62 | mutex sync.RWMutex 63 | } 64 | 65 | type safeDestroyAttempt struct { 66 | attempt int 67 | mutex sync.RWMutex 68 | } 69 | 70 | type safeClientLastID struct { 71 | lastID int 72 | mutex sync.RWMutex 73 | } 74 | 75 | type safeClock struct { 76 | clock time.Time 77 | mutex sync.RWMutex 78 | } 79 | 80 | // Game represents an individual estimation session game 81 | type Game struct { 82 | safeClients safeClients 83 | safeCards safeCards 84 | safeTopic safeTopic 85 | safeClock safeClock 86 | 87 | // Room is the name of the room 88 | Room string 89 | 90 | // Token is a unique token to ensure a user doesn't join a stale game 91 | Token string 92 | 93 | onComplete chan *Game 94 | waitToDestroy int 95 | safeDestroyAttempt safeDestroyAttempt 96 | safeClientLastID safeClientLastID 97 | } 98 | 99 | type wsCard struct { 100 | Card int `json:"card"` 101 | PlayerID int `json:"playerID"` 102 | Player string `json:"player"` 103 | } 104 | 105 | // wsUpdate is an update that will be sent via websocket to the client. 106 | type wsUpdate struct { 107 | Topic string `json:"topic"` 108 | Players map[int]string `json:"players"` 109 | Cards []*wsCard `json:"cards"` 110 | Deck string `json:"deck"` 111 | Revealed bool `json:"reveal"` 112 | Reset bool `json:"reset"` 113 | Username string `json:"username"` 114 | Elapsed int `json:"elapsed"` 115 | } 116 | 117 | // wsError is providers error information to the client 118 | type wsError struct { 119 | Error string `json:"error"` 120 | } 121 | 122 | // RoomNameIsValid validates a room name. 123 | func RoomNameIsValid(room string) bool { 124 | return validRoomRx.MatchString(room) && withLetterOrNumberRx.MatchString(room) 125 | } 126 | 127 | // New instanties a new game. 128 | // The onComplete chan should be used when the game is no longer active. 129 | func New(room string, defaultDeck string, onComplete chan *Game) (*Game, error) { 130 | if !RoomNameIsValid(room) { 131 | return nil, ErrInvalidRoomName 132 | } 133 | 134 | token, err := generateToken() 135 | if err != nil { 136 | return nil, err 137 | } 138 | 139 | useDeck := deck.ModifiedFibonacci 140 | if d, found := deck.AllDecks[defaultDeck]; found { 141 | useDeck = d 142 | } 143 | 144 | g := &Game{ 145 | safeClients: safeClients{ 146 | clients: make(map[client]bool), 147 | mutex: sync.RWMutex{}, 148 | }, 149 | safeCards: safeCards{ 150 | deck: useDeck, 151 | cards: make(map[client]int), 152 | reveal: false, 153 | mutex: sync.RWMutex{}, 154 | }, 155 | safeTopic: safeTopic{ 156 | topic: fmt.Sprintf("%s Estimation Session", room), 157 | mutex: sync.RWMutex{}, 158 | }, 159 | safeClock: safeClock{ 160 | clock: time.Now(), 161 | }, 162 | 163 | Room: room, 164 | Token: token, 165 | 166 | onComplete: onComplete, 167 | waitToDestroy: waitToDestroy, 168 | safeDestroyAttempt: safeDestroyAttempt{ 169 | attempt: 0, 170 | mutex: sync.RWMutex{}, 171 | }, 172 | } 173 | 174 | return g, nil 175 | } 176 | 177 | // NextClientID returns the next available ID to use for a client. 178 | func (g *Game) NextClientID() int { 179 | g.safeClientLastID.mutex.Lock() 180 | defer g.safeClientLastID.mutex.Unlock() 181 | 182 | g.safeClientLastID.lastID++ 183 | return g.safeClientLastID.lastID 184 | } 185 | 186 | // RegisterClient registers a client with the game. 187 | func (g *Game) RegisterClient(client client) { 188 | g.safeClients.mutex.Lock() 189 | g.safeClients.clients[client] = true 190 | g.safeClients.mutex.Unlock() 191 | 192 | log.WithFields(log.Fields{"room": g.Room, "client": client.RemoteAddr()}).Info("registered client") 193 | 194 | g.SendUpdate() 195 | } 196 | 197 | // UnregisterClient registers a client from the game. 198 | func (g *Game) UnregisterClient(client client) { 199 | g.safeClients.mutex.Lock() 200 | delete(g.safeClients.clients, client) 201 | nclients := len(g.safeClients.clients) 202 | g.safeClients.mutex.Unlock() 203 | 204 | shouldReset := false 205 | g.safeCards.mutex.RLock() 206 | _, found := g.safeCards.cards[client] 207 | ncards := len(g.safeCards.cards) 208 | g.safeCards.mutex.RUnlock() 209 | 210 | if found { 211 | g.safeCards.mutex.Lock() 212 | delete(g.safeCards.cards, client) 213 | g.safeCards.mutex.Unlock() 214 | 215 | // was at 1, now will be at zero. reset the game 216 | if ncards == 1 { 217 | shouldReset = true 218 | } 219 | } 220 | 221 | client.CloseChannel() 222 | log.WithFields(log.Fields{"room": g.Room, "client": client.RemoteAddr()}).Info("unregistered client") 223 | 224 | if nclients == 0 { 225 | g.reset() 226 | 227 | g.safeDestroyAttempt.mutex.Lock() 228 | g.safeDestroyAttempt.attempt++ 229 | attempt := g.safeDestroyAttempt.attempt 230 | g.safeDestroyAttempt.mutex.Unlock() 231 | 232 | go func() { 233 | t := time.NewTimer(time.Millisecond * time.Duration(g.waitToDestroy)) 234 | <-t.C 235 | 236 | g.safeDestroyAttempt.mutex.RLock() 237 | currentAttempt := g.safeDestroyAttempt.attempt 238 | g.safeDestroyAttempt.mutex.RUnlock() 239 | 240 | if attempt != currentAttempt { 241 | return 242 | } 243 | 244 | g.safeClients.mutex.RLock() 245 | defer g.safeClients.mutex.RUnlock() 246 | 247 | if len(g.safeClients.clients) == 0 { 248 | g.onComplete <- g 249 | } 250 | }() 251 | 252 | return 253 | } 254 | 255 | if shouldReset { 256 | g.Reset() 257 | return 258 | } 259 | 260 | g.SendUpdate() 261 | } 262 | 263 | // SendUpdate will send an update to all clients 264 | func (g *Game) SendUpdate() { 265 | g.broadcast(g.updatePayload(false)) 266 | } 267 | 268 | // broadcast will send a message to all registered clients. 269 | func (g *Game) broadcast(obj interface{}) { 270 | g.safeClients.mutex.RLock() 271 | defer g.safeClients.mutex.RUnlock() 272 | 273 | for client := range g.safeClients.clients { 274 | if o, ok := obj.(wsUpdate); ok { 275 | o.Username = client.Name() 276 | obj = o 277 | } 278 | 279 | client.Send(obj) 280 | } 281 | } 282 | 283 | // errorPayload returns an object which can be sent to the client which holds an error. 284 | func (g *Game) errorPayload(errstr string) *wsError { 285 | return &wsError{errstr} 286 | } 287 | 288 | // updatePayload returns a game update object which can be broadcasted to clients. 289 | func (g *Game) updatePayload(reset bool) wsUpdate { 290 | var u wsUpdate 291 | 292 | g.safeCards.mutex.RLock() 293 | cards := make([]*wsCard, 0, len(g.safeCards.cards)) 294 | for c, card := range g.safeCards.cards { 295 | cards = append(cards, &wsCard{ 296 | Card: card, 297 | Player: c.Name(), 298 | PlayerID: c.ID(), 299 | }) 300 | } 301 | u.Topic = g.Topic() 302 | u.Players = g.players() 303 | u.Deck = g.safeCards.deck.Name 304 | u.Cards = cards 305 | u.Revealed = g.safeCards.reveal 306 | u.Reset = reset 307 | g.safeCards.mutex.RUnlock() 308 | 309 | g.safeClock.mutex.RLock() 310 | u.Elapsed = int(time.Now().Sub(g.safeClock.clock).Seconds()) 311 | g.safeClock.mutex.RUnlock() 312 | 313 | return u 314 | } 315 | 316 | func (g *Game) players() map[int]string { 317 | g.safeClients.mutex.RLock() 318 | defer g.safeClients.mutex.RUnlock() 319 | 320 | players := make(map[int]string) 321 | for client := range g.safeClients.clients { 322 | players[client.ID()] = client.Name() 323 | } 324 | 325 | return players 326 | } 327 | 328 | // SetTopic will set the topic of the room in a concurrency-safe manner. 329 | func (g *Game) SetTopic(topic string) { 330 | if !validTopixRx.MatchString(topic) || !withLetterOrNumberRx.MatchString(topic) { 331 | return 332 | } 333 | 334 | g.safeTopic.mutex.Lock() 335 | 336 | didChange := false 337 | if topic != g.safeTopic.topic { 338 | didChange = true 339 | 340 | g.safeTopic.topic = topic 341 | } 342 | 343 | g.safeTopic.mutex.Unlock() 344 | 345 | if didChange { 346 | g.SendUpdate() 347 | } 348 | } 349 | 350 | // Topic will return the topic of the room in a concurrency-safe manner. 351 | func (g *Game) Topic() string { 352 | g.safeTopic.mutex.RLock() 353 | defer g.safeTopic.mutex.RUnlock() 354 | 355 | return g.safeTopic.topic 356 | } 357 | 358 | // SetDeck changes the active deck being used. 359 | func (g *Game) SetDeck(deck *deck.Deck) { 360 | g.safeCards.mutex.Lock() 361 | if deck == g.safeCards.deck { 362 | g.safeCards.mutex.Unlock() 363 | return 364 | } 365 | g.safeCards.deck = deck 366 | g.safeCards.mutex.Unlock() 367 | 368 | g.Reset() 369 | } 370 | 371 | // Deck returns the active deck being used. 372 | func (g *Game) Deck() *deck.Deck { 373 | g.safeCards.mutex.RLock() 374 | defer g.safeCards.mutex.RUnlock() 375 | return g.safeCards.deck 376 | } 377 | 378 | // AddCard is when a client has selected an individual card. 379 | func (g *Game) AddCard(c client, card int, deck string) { 380 | g.safeCards.mutex.Lock() 381 | 382 | if deck != g.safeCards.deck.Name { 383 | log.WithFields(log.Fields{"room": g.Room, "client": c.RemoteAddr()}).Warnf("client is out of sync: got %s, expects %s", deck, g.safeCards.deck.Name) 384 | c.Send(g.errorPayload("Your game is out of sync. Please refresh your browser.")) 385 | g.safeCards.mutex.Unlock() 386 | return 387 | } 388 | 389 | if _, err := g.safeCards.deck.GetCard(card); err != nil { 390 | log.WithFields(log.Fields{"room": g.Room, "client": c.RemoteAddr()}).Warnf("client submitted an invalid card (%d) for deck \"%s\"", card, g.safeCards.deck.Name) 391 | c.Send(g.errorPayload("Your game had an invalid card. Please refresh your browser.")) 392 | g.safeCards.mutex.Unlock() 393 | return 394 | } 395 | 396 | g.safeCards.cards[c] = card 397 | ncards := len(g.safeCards.cards) 398 | g.safeCards.mutex.Unlock() 399 | 400 | g.safeClients.mutex.RLock() 401 | nclients := len(g.safeClients.clients) 402 | g.safeClients.mutex.RUnlock() 403 | 404 | if ncards == nclients { 405 | g.safeCards.mutex.Lock() 406 | g.safeCards.reveal = true 407 | g.safeCards.mutex.Unlock() 408 | } 409 | 410 | g.SendUpdate() 411 | } 412 | 413 | // Reveal is when a client has requested to show all the cards. 414 | func (g *Game) Reveal() { 415 | g.safeCards.mutex.Lock() 416 | g.safeCards.reveal = true 417 | g.safeCards.mutex.Unlock() 418 | 419 | g.SendUpdate() 420 | } 421 | 422 | // Reset is when a client has request that the entire game be reset. 423 | func (g *Game) Reset() { 424 | g.reset() 425 | g.broadcast(g.updatePayload(true)) 426 | } 427 | 428 | func (g *Game) reset() { 429 | g.safeCards.mutex.Lock() 430 | g.safeCards.reveal = false 431 | g.safeCards.cards = make(map[client]int) 432 | g.safeCards.mutex.Unlock() 433 | 434 | g.safeClock.mutex.Lock() 435 | g.safeClock.clock = time.Now() 436 | g.safeClock.mutex.Unlock() 437 | } 438 | 439 | // RegisteredClientsCount returns the number of active registered clients 440 | func (g *Game) RegisteredClientsCount() int { 441 | g.safeClients.mutex.RLock() 442 | defer g.safeClients.mutex.RUnlock() 443 | 444 | return len(g.safeClients.clients) 445 | } 446 | 447 | func generateToken() (string, error) { 448 | b := make([]byte, 30) 449 | if _, err := rand.Read(b); err != nil { 450 | return "", err 451 | } 452 | 453 | return base64.StdEncoding.EncodeToString(b), nil 454 | } 455 | -------------------------------------------------------------------------------- /game/game_test.go: -------------------------------------------------------------------------------- 1 | package game 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | "strings" 7 | "testing" 8 | "time" 9 | 10 | "github.com/stretchr/testify/assert" 11 | "github.com/synacor/sibyl/deck" 12 | ) 13 | 14 | func TestRoomNameIsValid(t *testing.T) { 15 | assert.True(t, RoomNameIsValid("Test Room")) 16 | assert.True(t, RoomNameIsValid("ÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉ")) 17 | assert.False(t, RoomNameIsValid("Room name is too long")) 18 | } 19 | 20 | func TestGame(t *testing.T) { 21 | g, err := New("Room name is too long", "", nil) 22 | assert.Nil(t, g) 23 | assert.Equal(t, ErrInvalidRoomName, err) 24 | 25 | g, _ = New("Test Room", "bad", nil) 26 | assert.Equal(t, "Test Room", g.Room) 27 | assert.Equal(t, 40, len(g.Token)) 28 | assert.Equal(t, deck.ModifiedFibonacci, g.Deck()) 29 | assert.Equal(t, 0, g.RegisteredClientsCount()) 30 | 31 | g, _ = New("Test Room", "T-Shirt Sizes", nil) 32 | assert.Equal(t, deck.TShirtSizes, g.Deck()) 33 | } 34 | 35 | func TestRegisterClients(t *testing.T) { 36 | g, _ := New("Test", "", nil) 37 | 38 | c1, c2 := newClientTest(1), newClientTest(2) 39 | 40 | g.RegisterClient(c1) 41 | g.RegisterClient(c2) 42 | assert.Equal(t, 2, g.RegisteredClientsCount()) 43 | 44 | assert.Equal(t, 2, len(c1.send)) 45 | assert.Equal(t, 1, len(c2.send)) 46 | 47 | send := append(c1.send, c2.send...) 48 | for _, s := range send { 49 | u := s.(wsUpdate) 50 | assert.Equal(t, "Test Estimation Session", u.Topic) 51 | assert.Equal(t, deck.ModifiedFibonacci.Name, u.Deck) 52 | assert.Equal(t, false, u.Reset) 53 | assert.Equal(t, false, u.Revealed) 54 | assert.Equal(t, []*wsCard{}, u.Cards) 55 | } 56 | 57 | assert.Equal(t, 1, len(send[0].(wsUpdate).Players)) 58 | assert.Equal(t, 2, len(send[1].(wsUpdate).Players)) 59 | assert.Equal(t, 2, len(send[2].(wsUpdate).Players)) 60 | } 61 | 62 | func TestAddCard(t *testing.T) { 63 | g, _ := New("Test", "", nil) 64 | c1, c2 := newClientTest(1), newClientTest(2) 65 | g.RegisterClient(c1) 66 | g.RegisterClient(c2) 67 | 68 | g.AddCard(c1, 0, g.Deck().Name) 69 | g.AddCard(c1, 1, g.Deck().Name) 70 | g.AddCard(c2, 2, g.Deck().Name) 71 | 72 | // c1 = 2 client registers + 3 cards 73 | // c2 = 1 client registers + 3 cards 74 | assert.Equal(t, 5, len(c1.send)) 75 | assert.Equal(t, 4, len(c2.send)) 76 | 77 | u := c2.send[3].(wsUpdate) 78 | sort.Sort(byID(u.Cards)) 79 | 80 | assert.Equal(t, []*wsCard{ 81 | {1, 1, ""}, 82 | {2, 2, ""}, 83 | }, u.Cards) 84 | 85 | assert.Equal(t, false, u.Reset) 86 | 87 | // only one card sent 88 | assert.Equal(t, false, c2.send[1].(wsUpdate).Revealed) 89 | // two cards sent, but both from same client 90 | assert.Equal(t, false, c2.send[2].(wsUpdate).Revealed) 91 | // all clients sent a card, reveal 92 | assert.Equal(t, true, u.Revealed) 93 | } 94 | 95 | func TestAddCardWithOutOfSyncDeck(t *testing.T) { 96 | g, _ := New("Test", "", nil) 97 | c1, c2 := newClientTest(1), newClientTest(2) 98 | g.RegisterClient(c1) 99 | g.RegisterClient(c2) 100 | 101 | g.AddCard(c1, 0, "Bad") 102 | assert.Equal(t, 3, len(c1.send)) // 2 reg + 1 error 103 | assert.Equal(t, 1, len(c2.send)) // 1 reg 104 | assert.Equal(t, "Your game is out of sync. Please refresh your browser.", c1.send[2].(*wsError).Error) 105 | } 106 | 107 | func TestAddCardWithIncorrectCard(t *testing.T) { 108 | g, _ := New("Test", "", nil) 109 | c1, c2 := newClientTest(1), newClientTest(2) 110 | g.RegisterClient(c1) 111 | g.RegisterClient(c2) 112 | 113 | g.AddCard(c1, 9999, "Modified Fibonacci") 114 | assert.Equal(t, 3, len(c1.send)) // 2 reg + 1 error 115 | assert.Equal(t, 1, len(c2.send)) // 1 reg 116 | assert.Equal(t, "Your game had an invalid card. Please refresh your browser.", c1.send[2].(*wsError).Error) 117 | } 118 | 119 | func TestReveal(t *testing.T) { 120 | g, _ := New("Test", "", nil) 121 | c1 := newClientTest(1) 122 | g.RegisterClient(c1) 123 | 124 | g.Reveal() 125 | 126 | assert.Equal(t, 2, len(c1.send)) 127 | 128 | u := c1.send[1].(wsUpdate) 129 | assert.Equal(t, true, u.Revealed) 130 | assert.Equal(t, false, u.Reset) 131 | } 132 | 133 | func TestReset(t *testing.T) { 134 | g, _ := New("Test", "", nil) 135 | g.safeCards.reveal = true 136 | g.safeCards.cards = map[client]int{newClientTest(1): 0, newClientTest(2): 1, newClientTest(3): 2} 137 | 138 | c1 := newClientTest(1) 139 | g.RegisterClient(c1) 140 | 141 | assert.True(t, time.Now().After(g.safeClock.clock)) 142 | clock := g.safeClock.clock 143 | 144 | g.Reset() 145 | 146 | // make sure clock is updated on reset 147 | assert.True(t, time.Now().After(g.safeClock.clock)) 148 | assert.True(t, clock.Before(g.safeClock.clock)) 149 | 150 | assert.Equal(t, 2, len(c1.send)) 151 | 152 | u1 := c1.send[0].(wsUpdate) 153 | assert.Equal(t, true, u1.Revealed) 154 | assert.Equal(t, false, u1.Reset) 155 | sort.Sort(byID(u1.Cards)) 156 | assert.Equal(t, []*wsCard{ 157 | {0, 1, ""}, 158 | {1, 2, ""}, 159 | {2, 3, ""}, 160 | }, u1.Cards) 161 | 162 | u2 := c1.send[1].(wsUpdate) 163 | assert.Equal(t, false, u2.Revealed) 164 | assert.Equal(t, true, u2.Reset) 165 | assert.Equal(t, []*wsCard{}, u2.Cards) 166 | } 167 | 168 | func TestSetDeck(t *testing.T) { 169 | g, _ := New("Test", "", nil) 170 | c1 := newClientTest(1) 171 | 172 | g.RegisterClient(c1) 173 | 174 | // default, so it shouldn't change 175 | g.SetDeck(deck.ModifiedFibonacci) 176 | assert.Equal(t, deck.ModifiedFibonacci, g.Deck()) 177 | assert.Equal(t, 1, len(c1.send)) 178 | 179 | g.SetDeck(deck.TShirtSizes) 180 | assert.Equal(t, deck.TShirtSizes.Name, g.Deck().Name) 181 | assert.Equal(t, 2, len(c1.send)) 182 | assert.Equal(t, deck.TShirtSizes.Name, c1.send[1].(wsUpdate).Deck) 183 | } 184 | 185 | func TestSetTopic(t *testing.T) { 186 | g, _ := New("Test", "", nil) 187 | c1 := newClientTest(1) 188 | g.RegisterClient(c1) 189 | 190 | g.SetTopic("Should be invalid: \t") 191 | assert.Equal(t, "Test Estimation Session", g.Topic()) 192 | assert.Equal(t, 1, len(c1.send)) 193 | 194 | g.SetTopic(strings.Repeat("É", 101)) 195 | assert.Equal(t, "Test Estimation Session", g.Topic()) 196 | assert.Equal(t, 1, len(c1.send)) 197 | 198 | g.SetTopic("New Topic") 199 | assert.Equal(t, "New Topic", g.Topic()) 200 | assert.Equal(t, 2, len(c1.send)) 201 | assert.Equal(t, "New Topic", c1.send[1].(wsUpdate).Topic) 202 | } 203 | 204 | func TestUnregisterClient(t *testing.T) { 205 | onComplete := make(chan *Game) 206 | 207 | g, _ := New("Test", "", onComplete) 208 | g.waitToDestroy = 1 209 | 210 | c1, c2 := newClientTest(1), newClientTest(2) 211 | g.RegisterClient(c1) 212 | g.RegisterClient(c2) 213 | 214 | // make sure everything is in good state first 215 | assert.Equal(t, 2, len(c1.send)) 216 | assert.Equal(t, 1, len(c2.send)) 217 | 218 | g.UnregisterClient(c2) 219 | assert.Equal(t, 3, len(c1.send)) 220 | assert.Equal(t, 1, len(c2.send)) 221 | 222 | timer := time.NewTimer(time.Millisecond * time.Duration(5)) 223 | select { 224 | case <-onComplete: 225 | assert.Fail(t, "should not have been hit") 226 | case <-timer.C: 227 | } 228 | 229 | g.UnregisterClient(c1) 230 | assert.Equal(t, 3, len(c1.send)) 231 | assert.Equal(t, 1, len(c2.send)) 232 | 233 | timer = time.NewTimer(time.Millisecond * time.Duration(5)) 234 | select { 235 | case g2 := <-onComplete: 236 | assert.Equal(t, g, g2) 237 | case <-timer.C: 238 | assert.Fail(t, "should not have been hit") 239 | } 240 | timer.Stop() 241 | } 242 | 243 | func TestNextClientID(t *testing.T) { 244 | g, _ := New("Test", "", nil) 245 | assert.Equal(t, 1, g.NextClientID()) 246 | assert.Equal(t, 2, g.NextClientID()) 247 | assert.Equal(t, 3, g.NextClientID()) 248 | } 249 | 250 | type clientTest struct { 251 | send []interface{} 252 | closeChannelInvoked int 253 | port int 254 | id int 255 | name string 256 | } 257 | 258 | func newClientTest(id int) *clientTest { 259 | return &clientTest{ 260 | send: make([]interface{}, 0), 261 | port: id, 262 | id: id, 263 | } 264 | } 265 | 266 | func (c *clientTest) Send(o interface{}) { 267 | c.send = append(c.send, o) 268 | } 269 | 270 | func (c *clientTest) CloseChannel() { 271 | c.closeChannelInvoked++ 272 | } 273 | 274 | func (c *clientTest) RemoteAddr() string { 275 | return fmt.Sprintf("1.2.3.4:%d", c.port) 276 | } 277 | 278 | func (c *clientTest) ID() int { 279 | return c.id 280 | } 281 | 282 | func (c *clientTest) Name() string { 283 | return c.name 284 | } 285 | 286 | type byID []*wsCard 287 | 288 | func (b byID) Len() int { return len(b) } 289 | func (b byID) Less(i, j int) bool { return b[i].PlayerID < b[j].PlayerID } 290 | func (b byID) Swap(i, j int) { b[i], b[j] = b[j], b[i] } 291 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/synacor/sibyl 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/GeertJohan/go.rice v1.0.0 7 | github.com/gorilla/handlers v1.4.0 8 | github.com/gorilla/websocket v1.4.0 9 | github.com/sirupsen/logrus v1.4.1 10 | github.com/spf13/viper v1.3.2 11 | github.com/stretchr/testify v1.3.0 12 | ) 13 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/GeertJohan/go.incremental v1.0.0/go.mod h1:6fAjUhbVuX1KcMD3c8TEgVUqmo4seqhv0i0kdATSkM0= 2 | github.com/GeertJohan/go.rice v1.0.0 h1:KkI6O9uMaQU3VEKaj01ulavtF7o1fWT7+pk/4voiMLQ= 3 | github.com/GeertJohan/go.rice v1.0.0/go.mod h1:eH6gbSOAUv07dQuZVnBmoDP8mgsM1rtixis4Tib9if0= 4 | github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c= 5 | github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= 6 | github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= 7 | github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= 8 | github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= 9 | github.com/daaku/go.zipexe v1.0.0 h1:VSOgZtH418pH9L16hC/JrgSNJbbAL26pj7lmD1+CGdY= 10 | github.com/daaku/go.zipexe v1.0.0/go.mod h1:z8IiR6TsVLEYKwXAoE/I+8ys/sDkgTzSL0CLnGVd57E= 11 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 13 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 14 | github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= 15 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 16 | github.com/gorilla/handlers v1.4.0 h1:XulKRWSQK5uChr4pEgSE4Tc/OcmnU9GJuSwdog/tZsA= 17 | github.com/gorilla/handlers v1.4.0/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= 18 | github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= 19 | github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= 20 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= 21 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= 22 | github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 23 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 24 | github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= 25 | github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= 26 | github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= 27 | github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= 28 | github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229/go.mod h1:0aYXnNPJ8l7uZxf45rWW1a/uME32OF0rhiYGNQ2oF2E= 29 | github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= 30 | github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= 31 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 32 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 33 | github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k= 34 | github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= 35 | github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= 36 | github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= 37 | github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= 38 | github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= 39 | github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= 40 | github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= 41 | github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= 42 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 43 | github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M= 44 | github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= 45 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 46 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 47 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 48 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 49 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 50 | github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= 51 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 52 | github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= 53 | github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= 54 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 55 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 56 | golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A= 57 | golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 58 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 59 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 60 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 61 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 62 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 63 | -------------------------------------------------------------------------------- /k8s/configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: sibyl-config 5 | data: 6 | config.json: | 7 | { 8 | "port": 80, 9 | "debug": true, 10 | "log_level": "DEBUG", 11 | "tls_port": 0, 12 | "tls_private_key": "", 13 | "tls_public_key": "", 14 | "force_tls": false 15 | } 16 | -------------------------------------------------------------------------------- /k8s/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: sibyl 5 | spec: 6 | replicas: 1 7 | selector: 8 | matchLabels: 9 | app: sibyl 10 | template: 11 | metadata: 12 | labels: 13 | app: sibyl 14 | spec: 15 | containers: 16 | - name: sibyl 17 | image: synacor/sibyl 18 | imagePullPolicy: IfNotPresent 19 | volumeMounts: 20 | - name: config 21 | mountPath: /etc/sibyl/config.json 22 | subPath: config.json 23 | readOnly: true 24 | volumes: 25 | - name: config 26 | configMap: 27 | name: sibyl-config 28 | -------------------------------------------------------------------------------- /k8s/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: sibyl 5 | spec: 6 | selector: 7 | app: sibyl 8 | ports: 9 | - port: 80 10 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Package main starts a Sibyl server 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "math" 7 | "net/http" 8 | "os" 9 | "strings" 10 | 11 | rice "github.com/GeertJohan/go.rice" 12 | "github.com/gorilla/handlers" 13 | log "github.com/sirupsen/logrus" 14 | "github.com/spf13/viper" 15 | "github.com/synacor/sibyl/server" 16 | ) 17 | 18 | const defaultPort = 5000 19 | 20 | var maxPort = int(math.Pow(2, 16) - 1) 21 | var s *server.Server 22 | 23 | func main() { 24 | // reminder, that viper will only look at the first config file it sees 25 | viper.SetConfigName("config") 26 | viper.SetConfigType("json") 27 | viper.AddConfigPath(".") 28 | viper.AddConfigPath("/etc/sibyl") 29 | viper.SetEnvPrefix("sib") 30 | viper.BindEnv("port") 31 | viper.BindEnv("tls_port") 32 | viper.BindEnv("log_level") 33 | viper.SetDefault("log_level", "info") 34 | viper.SetDefault("port", defaultPort) 35 | if err := viper.ReadInConfig(); err != nil { 36 | // viper requires a config file to be present for some reason. this will check for that error 37 | // and silently ignore it 38 | if _, isConfigFileNotFoundError := err.(viper.ConfigFileNotFoundError); !isConfigFileNotFoundError { 39 | panic(err) 40 | } 41 | } 42 | configureLogger() 43 | 44 | tbox := rice.MustFindBox("templates") 45 | sbox := rice.MustFindBox("static") 46 | 47 | s = server.New(tbox, sbox) 48 | mux := s.ServeMux() 49 | 50 | done := make(chan bool, 1) 51 | go serve(mux) 52 | go s.ListenForEvents(done) 53 | 54 | <-done 55 | } 56 | 57 | func configureLogger() { 58 | levelStr := viper.GetString("log_level") 59 | level, err := log.ParseLevel(levelStr) 60 | if err != nil { 61 | log.Fatalf("level %s does not exist", level) 62 | } 63 | log.SetLevel(level) 64 | log.SetFormatter(&log.TextFormatter{FullTimestamp: true}) 65 | } 66 | 67 | func serve(mux *http.ServeMux) { 68 | port := viper.GetInt("port") 69 | tlsPort := viper.GetInt("tls_port") 70 | forceTLS := viper.GetBool("force_tls") 71 | tlsPrivateKeyFile := viper.GetString("tls_private_key") 72 | tlsPublicKeyFile := viper.GetString("tls_public_key") 73 | 74 | if port <= 0 || port > maxPort { 75 | log.Fatalf("PORT must be 0 < PORT <= %d", maxPort) 76 | } else if tlsPort > 0 && port == tlsPort { 77 | log.Fatalf("PORT cannot equal TLS_PORT") 78 | } else if tlsPort > maxPort { 79 | log.Fatalf("TLS_PORT must be 0 < TLS_PORT <= %d", maxPort) 80 | } else if tlsPort > 0 && (tlsPublicKeyFile == "" || tlsPrivateKeyFile == "") { 81 | log.Fatal("must supply TLS_PRIVATE_KEY and TLS_PUBLIC_KEY if TLS_PORT specified") 82 | } 83 | 84 | if tlsPort > 0 { 85 | go func() { 86 | pstr := fmt.Sprintf(":%d", tlsPort) 87 | log.WithFields(log.Fields{"pid": os.Getpid()}).Printf("Listening on %s", pstr) 88 | 89 | log.Fatal(http.ListenAndServeTLS(pstr, tlsPublicKeyFile, tlsPrivateKeyFile, handlers.CombinedLoggingHandler(os.Stdout, mux))) 90 | }() 91 | } 92 | 93 | pstr := fmt.Sprintf(":%d", port) 94 | log.WithFields(log.Fields{"pid": os.Getpid()}).Printf("Listening on %s", pstr) 95 | log.Fatal(http.ListenAndServe(pstr, handlers.CombinedLoggingHandler(os.Stdout, maybeRedirectToTLS(tlsPort, forceTLS, mux)))) 96 | } 97 | 98 | // maybeRedirectToTLS is middleware for optionally redirecting the user to the TLS version based on arguments passed to the application. 99 | func maybeRedirectToTLS(tlsPort int, forceTLS bool, h http.Handler) http.Handler { 100 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 101 | if forceTLS && tlsPort > 0 { 102 | hostname := strings.Split(r.Host, ":")[0] 103 | if tlsPort != 443 { 104 | hostname += fmt.Sprintf(":%d", tlsPort) 105 | } 106 | 107 | url := "https://" + hostname + r.URL.String() 108 | http.Redirect(w, r, url, http.StatusMovedPermanently) 109 | return 110 | } 111 | 112 | h.ServeHTTP(w, r) 113 | }) 114 | } 115 | -------------------------------------------------------------------------------- /name/name.go: -------------------------------------------------------------------------------- 1 | // Package name generates random names 2 | package name 3 | 4 | import ( 5 | "math/rand" 6 | "strings" 7 | "time" 8 | ) 9 | 10 | var adjectives = strings.Split("Able|Abundant|Adorable|Agreeable|Ancient|Angry|Bad|Beautiful|Better|Bewildered|Big|Bitter|Black|Blue|Boiling|Brave|Breeze|Brief|Broken|Bumpy|Calm|Careful|Chilly|Clean|Clever|Clumsy|Cold|Cool|Crooked|Cuddly|Curly|Curved|Damaged|Dead|Deafening|Defeated|Delightful|Different|Drab|Early|Elegant|Embarrassed|Empty|Faithful|Famous|Fancy|Fast|Fierce|Filthy|First|Flaky|Flat|Fluffy|Freezing|Fresh|Full|Gentle|Gifted|Gigantic|Glamorous|Good|Gray|Greasy|Great|Green|Grumpy|Happy|Heavy|Helpful|Helpless|High|Hissing|Hollow|Huge|Icy|Important|Jealous|Jolly|Kind|Large|Last|Late|Lazy|Light|Little|Lively|Long|Loud|Low|Magnificent|Mammoth|Many|Massive|Melodic|Melted|Miniature|Modern|Mushy|Mysterious|Narrow|Nervous|New|Next|Nice|Noisy|Numerous|Obedient|Obnoxious|Odd|Old|Orange|Own|Panicky|Plain|Powerful|Prickly|Proud|Puny|Purple|Purring|Quaint|Quick|Quiet|Rainy|Rapid|Raspy|Red|Relieved|Repulsive|Rich|Right|Rotten|Round|Salty|Same|Scary|Scrawny|Screeching|Shallow|Short|Shy|Silly|Slow|Small|Sparkling|Sparse|Square|Steep|Sticky|Strong|Substantial|Sweet|Swift|Tall|Tasteless|Thankful|Thoughtless|Thundering|Tiny|Ugliest|Uneven|Uninterested|Unsightly|Uptight|Vast|Victorious|Voiceless|Weak|Whispering|White|Wide|Witty|Wooden|Worried|Wrong|Yellow|Young|Yummy|Zealous", "|") 11 | 12 | var animals = strings.Split("Albatross|Alligator|Anteater|Antelope|Armadillo|Baboon|Badger|Bandicoot|Barracuda|Bat|Bear|Bird|Bison|Bobcat|Bonobo|Buffalo|Bullfrog|Butterfly|Camel|Capybara|Cat|Caterpillar|Catfish|Chameleon|Cheetah|Chicken|Chimpanzee|Chinchilla|Chipmunk|Cougar|Cow|Coyote|Crab|Crocodile|Deer|Dingo|Dog|Dolphin|Donkey|Duck|Eagle|Elephant|Emu|Falcon|Ferret|Flamingo|Fox|Frog|Gecko|Gerbil|Gharial|Giraffe|Goat|Goose|Gopher|Gorilla|Hamster|Hare|Hedgehog|Horse|Jackal|Jaguar|Kangaroo|Kiwi|Koala|Lemming|Lemur|Leopard|Liger|Lion|Lizard|Llama|Lobster|Mandrill|Meerkat|Mongoose|Mongrel|Monkey|Moose|Mouse|Mule|Ocelot|Octopus|Opossum|Ostrich|Otter|Panther|Parrot|Peacock|Pelican|Penguin|Pig|Platypus|Possum|Rabbit|Raccoon|Rat|Rattlesnake|Reindeer|Rhinoceros|Salamander|Scorpion|Seahorse|Seal|Serval|Sheep|Shrimp|Skunk|Sloth|Snake|Squid|Squirrel|Starfish|Stingray|Tapir|Tiger|Tortoise|Toucan|Turkey|Vulture|Wallaby|Walrus|Warthog|Wasp|Weasel|Wildebeest|Wolf|Wolverine|Wombat|Woodpecker|Yak|Zebra", "|") 13 | 14 | // no need for crypto/rand, so we'll seed with a timestamp so we can easily test 15 | var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) 16 | 17 | // Generate will return a random name 18 | func Generate() string { 19 | return randomWord(adjectives) + " " + randomWord(animals) 20 | } 21 | 22 | func randomWord(list []string) string { 23 | return list[rnd.Intn(len(list))] 24 | } 25 | -------------------------------------------------------------------------------- /name/name_test.go: -------------------------------------------------------------------------------- 1 | package name 2 | 3 | import ( 4 | "math/rand" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestGenerate(t *testing.T) { 11 | // manually set the seed so we get a consistent result 12 | rnd = rand.New(rand.NewSource(3)) 13 | 14 | assert.Equal(t, "Clean Butterfly", Generate()) 15 | assert.Equal(t, "Lively Penguin", Generate()) 16 | } 17 | -------------------------------------------------------------------------------- /resources/sibyl-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synacor/sibyl/5a45d91b6b398d4c559903f451172130322734d6/resources/sibyl-screenshot.png -------------------------------------------------------------------------------- /server/client.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "errors" 5 | "net" 6 | "regexp" 7 | "sync" 8 | "time" 9 | 10 | "github.com/gorilla/websocket" 11 | log "github.com/sirupsen/logrus" 12 | "github.com/synacor/sibyl/game" 13 | "github.com/synacor/sibyl/name" 14 | ) 15 | 16 | const ( 17 | readLimit = 2048 // 2KiB 18 | 19 | // Write timeout 20 | writeWait = 10 * time.Second 21 | 22 | // Ensure a pong is received every 30 seconds 23 | pongWait = 30 * time.Second 24 | 25 | // Send a ping out every 27 seconds. Must be less than pongWait. If pong doesn't happen with pongWait - pingPeriod, the connection will timeout 26 | pingPeriod = (pongWait * 9) / 10 27 | ) 28 | 29 | // ErrInvalidUsername is an error when the username does not match criteria 30 | var ErrInvalidUsername = errors.New("server: invalid username entered") 31 | 32 | // UsernameMaxLength is the maximum number of characters allowed in a username 33 | const UsernameMaxLength = 25 34 | 35 | var validUsernameRx = regexp.MustCompile(`^[\p{L}\p{M}\p{S}\p{N}\p{P} ]{1,25}\z`) 36 | var withLetterRx = regexp.MustCompile(`\p{L}`) 37 | 38 | // WsConn is an interface which implements a subset of the available methods in *websocket.Conn 39 | type WsConn interface { 40 | Close() error 41 | ReadJSON(v interface{}) error 42 | RemoteAddr() net.Addr 43 | SetPongHandler(func(appDate string) error) 44 | SetReadDeadline(t time.Time) error 45 | SetReadLimit(limit int64) 46 | SetWriteDeadline(t time.Time) error 47 | WriteJSON(v interface{}) error 48 | WriteMessage(messageType int, data []byte) error 49 | } 50 | 51 | type safeIdentifier struct { 52 | id int 53 | name string 54 | mu sync.RWMutex 55 | } 56 | 57 | // Client represents a user connected via websocket 58 | type Client struct { 59 | Game *game.Game 60 | send chan interface{} 61 | Conn WsConn 62 | safeIdentifier safeIdentifier 63 | } 64 | 65 | // NewClient instantiates a new client object. 66 | func NewClient(game *game.Game, conn WsConn, id int, uname string) *Client { 67 | if uname == "" { 68 | uname = name.Generate() 69 | } 70 | 71 | return &Client{ 72 | Game: game, 73 | send: make(chan interface{}, 256), 74 | Conn: conn, 75 | safeIdentifier: safeIdentifier{ 76 | id: id, 77 | name: uname, 78 | }, 79 | } 80 | } 81 | 82 | // SetName sets the name of the player 83 | func (c *Client) SetName(n string) error { 84 | if !validUsernameRx.MatchString(n) || !withLetterRx.MatchString(n) { 85 | return ErrInvalidUsername 86 | } 87 | 88 | c.safeIdentifier.mu.Lock() 89 | defer c.safeIdentifier.mu.Unlock() 90 | c.safeIdentifier.name = n 91 | return nil 92 | } 93 | 94 | // ID returns the ID of the client 95 | func (c *Client) ID() int { 96 | // this won't change, no mutex necessary 97 | return c.safeIdentifier.id 98 | } 99 | 100 | // Name returns the display name for the user 101 | func (c *Client) Name() string { 102 | c.safeIdentifier.mu.RLock() 103 | defer c.safeIdentifier.mu.RUnlock() 104 | 105 | return c.safeIdentifier.name 106 | } 107 | 108 | // Send will send an object to the client. 109 | func (c *Client) Send(o interface{}) { 110 | log.Println(o) 111 | c.send <- o 112 | } 113 | 114 | // CloseChannel will close the send channel 115 | func (c *Client) CloseChannel() { 116 | close(c.send) 117 | } 118 | 119 | // RemoteAddr returns the remote address (IP + port) of the client 120 | func (c *Client) RemoteAddr() string { 121 | return c.Conn.RemoteAddr().String() 122 | } 123 | 124 | // WritePump writes messages to the client. 125 | // This method should be called in a separate goroutine. 126 | func (c *Client) WritePump(s *Server) { 127 | ticker := time.NewTicker(pingPeriod) 128 | 129 | defer func() { 130 | ticker.Stop() 131 | c.Conn.Close() 132 | }() 133 | 134 | for { 135 | select { 136 | case msg, ok := <-c.send: 137 | c.Conn.SetWriteDeadline(time.Now().Add(writeWait)) 138 | if !ok { 139 | c.Conn.WriteMessage(websocket.CloseMessage, []byte{}) 140 | return 141 | } 142 | 143 | if err := c.Conn.WriteJSON(msg); err != nil { 144 | log.WithFields(log.Fields{"client": c.Conn.RemoteAddr().String()}).Errorf("could not write JSON: %v", err) 145 | return 146 | } 147 | case <-ticker.C: 148 | c.Conn.SetWriteDeadline(time.Now().Add(writeWait)) 149 | if err := c.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil { 150 | return 151 | } 152 | } 153 | } 154 | } 155 | 156 | // ReadPump reads messages sent from the client. 157 | func (c *Client) ReadPump(s *Server) { 158 | defer func() { 159 | c.Conn.Close() 160 | }() 161 | 162 | c.Conn.SetReadDeadline(time.Now().Add(pongWait)) 163 | c.Conn.SetReadLimit(readLimit) 164 | c.Conn.SetPongHandler(func(string) error { 165 | c.Conn.SetReadDeadline(time.Now().Add(pongWait)) 166 | return nil 167 | }) 168 | 169 | for { 170 | var r WsRequest 171 | if err := c.Conn.ReadJSON(&r); err != nil { 172 | if websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) { 173 | log.WithFields(log.Fields{"client": c.Conn.RemoteAddr().String()}).Errorf("could not read JSON: %v", err) 174 | } 175 | break 176 | } 177 | 178 | s.HandleWsRequest(c, &r) 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /server/client_test.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "net" 5 | "strings" 6 | "testing" 7 | "time" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/synacor/sibyl/game" 11 | ) 12 | 13 | var panicError string 14 | 15 | func TestSendAndClose(t *testing.T) { 16 | g, _ := game.New("Test", "", nil) 17 | c := NewClient(g, nil, 1, "") 18 | c.Send("Test") 19 | a := <-c.send 20 | assert.Equal(t, "Test", a.(string)) 21 | 22 | c.CloseChannel() 23 | capturePanic(func() { 24 | c.send <- true 25 | }) 26 | assert.Equal(t, "send on closed channel", panicError) 27 | } 28 | 29 | func TestID(t *testing.T) { 30 | c := NewClient(&game.Game{}, newWsConn(), 5, "") 31 | assert.Equal(t, 5, c.ID()) 32 | } 33 | 34 | func TestName(t *testing.T) { 35 | c := NewClient(&game.Game{}, newWsConn(), 5, "") 36 | s := strings.Split(c.Name(), " ") 37 | assert.Equal(t, 2, len(s)) 38 | assert.Regexp(t, `^[A-Z][a-z]+\z`, s[0]) 39 | assert.Regexp(t, `^[A-Z][a-z]+\z`, s[1]) 40 | 41 | err := c.SetName("Göod Name!") 42 | assert.NoError(t, err) 43 | assert.Equal(t, "Göod Name!", c.Name()) 44 | 45 | err = c.SetName("!!!") 46 | assert.Equal(t, ErrInvalidUsername, err) 47 | 48 | assert.Equal(t, 25, UsernameMaxLength) 49 | 50 | name := strings.Repeat("a", UsernameMaxLength) 51 | err = c.SetName(name) 52 | assert.NoError(t, err) 53 | assert.Equal(t, name, c.Name()) 54 | 55 | err = c.SetName(strings.Repeat("a", UsernameMaxLength+1)) 56 | assert.Equal(t, ErrInvalidUsername, err) 57 | } 58 | 59 | func TestProvidedName(t *testing.T) { 60 | c := NewClient(&game.Game{}, newWsConn(), 5, "My Test") 61 | assert.Equal(t, "My Test", c.Name()) 62 | } 63 | 64 | func TestRemoteAddr(t *testing.T) { 65 | conn := newWsConn() 66 | conn.addr = &addr{"1.2.3.4"} 67 | g, _ := game.New("Test", "", nil) 68 | 69 | c := NewClient(g, conn, 1, "") 70 | assert.Equal(t, "1.2.3.4", c.RemoteAddr()) 71 | } 72 | 73 | func TestWritePump(t *testing.T) { 74 | g, _ := game.New("Test", "", nil) 75 | conn := newWsConn() 76 | c := NewClient(g, conn, 1, "") 77 | 78 | go func() { 79 | c.send <- "Test" 80 | c.CloseChannel() 81 | }() 82 | 83 | c.WritePump(nil) 84 | 85 | assert.Equal(t, 2, len(conn.writeDeadline)) 86 | assert.True(t, conn.writeDeadline[1].After(conn.writeDeadline[0])) 87 | assert.True(t, conn.writeDeadline[1].After(time.Now())) 88 | assert.Equal(t, "Test", conn.writeJSON.(string)) 89 | } 90 | 91 | type wsConn struct { 92 | addr *addr 93 | closeInvoked int 94 | writeDeadline []time.Time 95 | writeMessageType int 96 | writeMessageData []byte 97 | writeJSON interface{} 98 | } 99 | 100 | func newWsConn() *wsConn { 101 | return &wsConn{ 102 | writeDeadline: make([]time.Time, 0), 103 | } 104 | } 105 | 106 | type addr struct{ ip string } 107 | 108 | func (a *addr) Network() string { 109 | return "" 110 | } 111 | 112 | func (a *addr) String() string { 113 | return a.ip 114 | } 115 | 116 | func (c *wsConn) Close() error { c.closeInvoked++; return nil } 117 | func (c *wsConn) ReadJSON(v interface{}) error { return nil } 118 | func (c *wsConn) RemoteAddr() net.Addr { return c.addr } 119 | func (c *wsConn) SetPongHandler(func(appDate string) error) {} 120 | func (c *wsConn) SetReadDeadline(t time.Time) error { return nil } 121 | func (c *wsConn) SetReadLimit(limit int64) {} 122 | func (c *wsConn) SetWriteDeadline(t time.Time) error { 123 | c.writeDeadline = append(c.writeDeadline, t) 124 | return nil 125 | } 126 | func (c *wsConn) WriteJSON(v interface{}) error { c.writeJSON = v; return nil } 127 | func (c *wsConn) WriteMessage(messageType int, data []byte) error { 128 | c.writeMessageType = messageType 129 | c.writeMessageData = data 130 | return nil 131 | } 132 | 133 | func capturePanic(fn func()) { 134 | panicError = "" 135 | 136 | defer func() { 137 | if r := recover(); r != nil { 138 | panicError = r.(error).Error() 139 | } 140 | }() 141 | 142 | fn() 143 | } 144 | -------------------------------------------------------------------------------- /server/server.go: -------------------------------------------------------------------------------- 1 | // Package server contains controller and client logic 2 | package server 3 | 4 | import ( 5 | "encoding/json" 6 | "fmt" 7 | "html/template" 8 | "net/http" 9 | "net/url" 10 | "os" 11 | "os/signal" 12 | "sort" 13 | "strings" 14 | "sync" 15 | "syscall" 16 | "time" 17 | 18 | rice "github.com/GeertJohan/go.rice" 19 | log "github.com/sirupsen/logrus" 20 | 21 | "github.com/gorilla/websocket" 22 | "github.com/spf13/viper" 23 | "github.com/synacor/sibyl/deck" 24 | "github.com/synacor/sibyl/game" 25 | ) 26 | 27 | // WsRequestAction is a type for representing a web socket action 28 | type WsRequestAction string 29 | 30 | // WsRequestAction constants 31 | const ( 32 | WsRequestActionSelectCard WsRequestAction = "select" 33 | WsRequestActionReveal = "reveal" 34 | WsRequestActionReset = "reset" 35 | WsRequestActionDeck = "deck" 36 | WsRequestActionTopic = "topic" 37 | WsRequestActionUsername = "username" 38 | ) 39 | 40 | // WsRequest is data that was read from a web socket connection 41 | type WsRequest struct { 42 | Action WsRequestAction `json:"action"` 43 | Card int `json:"card"` 44 | Deck string `json:"deck"` 45 | Room string `json:"room"` 46 | Token string `json:"token"` 47 | Value string `json:"value"` 48 | } 49 | 50 | type safeGames struct { 51 | games map[string]*game.Game 52 | mutex *sync.RWMutex 53 | } 54 | 55 | // Server is the main object that can be used to return an *http.ServeMux object. 56 | type Server struct { 57 | staticBox *rice.Box 58 | templates map[string]*template.Template 59 | debug bool 60 | destroyGame chan *game.Game 61 | safeGames *safeGames 62 | } 63 | 64 | var upgrader = websocket.Upgrader{ 65 | ReadBufferSize: 1024, 66 | WriteBufferSize: 1024, 67 | } 68 | 69 | type indexTemplateValues struct { 70 | RoomNameMaxLength int 71 | Error string 72 | NotFoundRoom string 73 | } 74 | 75 | type roomTemplateValues struct { 76 | Token string 77 | Decks []string 78 | DecksJSON template.JS 79 | Room string 80 | URL string 81 | TopicMaxLength int 82 | Username string 83 | UsernameMaxLength int 84 | } 85 | 86 | func init() { 87 | viper.BindEnv("debug") 88 | } 89 | 90 | // New returns a new *Server object 91 | func New(templatesBox, staticBox *rice.Box) *Server { 92 | base := template.Must(template.New("").Parse(templatesBox.MustString("template.html"))) 93 | c := &Server{ 94 | staticBox: staticBox, 95 | safeGames: &safeGames{ 96 | games: make(map[string]*game.Game), 97 | mutex: &sync.RWMutex{}, 98 | }, 99 | destroyGame: make(chan *game.Game), 100 | 101 | debug: viper.GetBool("debug"), 102 | templates: map[string]*template.Template{ 103 | "index": template.Must(template.Must(base.Clone()).Parse(templatesBox.MustString("index.html"))), 104 | "room": template.Must(template.Must(base.Clone()).Parse(templatesBox.MustString("room.html"))), 105 | }, 106 | } 107 | 108 | return c 109 | } 110 | 111 | // ServeMux returns a mux that can be used with the listen and server methods in net/http 112 | func (s *Server) ServeMux() *http.ServeMux { 113 | m := http.NewServeMux() 114 | m.HandleFunc("/", s.indexHandler) 115 | m.HandleFunc("/r/", s.roomHandler) 116 | m.HandleFunc("/ws", s.wsHandler) 117 | m.HandleFunc("/create", s.createRoomHandler) 118 | m.Handle("/static/", http.StripPrefix("/static/", http.FileServer(s.staticBox.HTTPBox()))) 119 | m.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { 120 | file, err := s.staticBox.Open("favicon.ico") 121 | if err != nil { 122 | http.NotFound(w, r) 123 | return 124 | } 125 | defer file.Close() 126 | 127 | var modTime time.Time 128 | if stat, _ := file.Stat(); stat != nil { 129 | modTime = stat.ModTime() 130 | } 131 | 132 | http.ServeContent(w, r, "favicon.ico", modTime, file) 133 | }) 134 | 135 | return m 136 | } 137 | 138 | // createRoomHandler handles requests to POST /create 139 | func (s *Server) createRoomHandler(w http.ResponseWriter, r *http.Request) { 140 | if strings.ToUpper(r.Method) != http.MethodPost { 141 | w.Header().Set("Allow", http.MethodPost) 142 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) 143 | return 144 | } 145 | 146 | room := r.PostFormValue("room") 147 | if !game.RoomNameIsValid(room) { 148 | http.Redirect(w, r, "/?invalid", http.StatusSeeOther) 149 | return 150 | } 151 | 152 | defaultDeck := r.PostFormValue("deck") 153 | if err := s.createGameIfNotExists(room, defaultDeck); err != nil { 154 | if err == game.ErrInvalidRoomName { 155 | http.Redirect(w, r, "/?invalid", http.StatusSeeOther) 156 | return 157 | } 158 | 159 | log.WithFields(log.Fields{"room": room}).Errorf("could not create room: %v", err) 160 | http.Redirect(w, r, "/?error", http.StatusSeeOther) 161 | return 162 | } 163 | 164 | roomURL := "/r/" + room 165 | http.Redirect(w, r, roomURL, http.StatusSeeOther) 166 | return 167 | } 168 | 169 | // indexHandler handles requests to / 170 | func (s *Server) indexHandler(w http.ResponseWriter, r *http.Request) { 171 | if r.URL.Path != "/" { 172 | http.NotFound(w, r) 173 | return 174 | } 175 | 176 | values := indexTemplateValues{ 177 | RoomNameMaxLength: game.RoomNameMaxLength, 178 | } 179 | 180 | r.ParseForm() 181 | if _, hasInvalid := r.Form["invalid"]; hasInvalid { 182 | values.Error = fmt.Sprintf("Invalid room name. %s", game.RoomNameValidDescription) 183 | } else if room := r.FormValue("notfound"); room != "" { 184 | // we'll present a quick create button for the user 185 | values.NotFoundRoom = room 186 | } else if _, hasError := r.Form["error"]; hasError { 187 | values.Error = fmt.Sprintf("We could not complete your request at this time.") 188 | } 189 | 190 | s.templates["index"].Execute(w, &values) 191 | } 192 | 193 | // wsHandler handles requests to /ws 194 | func (s *Server) wsHandler(w http.ResponseWriter, r *http.Request) { 195 | room := r.FormValue("room") 196 | token := r.FormValue("token") 197 | username := r.FormValue("username") 198 | 199 | g := s.getGameByRoom(room) 200 | if g == nil { 201 | log.WithFields(log.Fields{"room": room, "client": r.RemoteAddr}).Warn("could not get game for room") 202 | return 203 | } 204 | 205 | if token != g.Token { 206 | log.WithFields(log.Fields{"room": room, "client": r.RemoteAddr}).Warn("token does not match for room") 207 | return 208 | } 209 | 210 | conn, err := upgrader.Upgrade(w, r, nil) 211 | if err != nil { 212 | log.Errorf("could not upgrade connection: %v", err) 213 | return 214 | } 215 | 216 | client := NewClient(g, conn, g.NextClientID(), username) 217 | g.RegisterClient(client) 218 | defer func() { 219 | g.UnregisterClient(client) 220 | }() 221 | 222 | go client.WritePump(s) 223 | client.ReadPump(s) 224 | } 225 | 226 | // roomHandler handles requests to /r/ 227 | func (s *Server) roomHandler(w http.ResponseWriter, r *http.Request) { 228 | // Path looks like /r/foobar, so we want to strip off "/r/" (first 3 chars) 229 | room := string(r.URL.Path[3:]) 230 | 231 | var token string 232 | g := s.getGameByRoom(room) 233 | if g == nil { 234 | http.Redirect(w, r, "/?notfound="+url.QueryEscape(room), http.StatusSeeOther) 235 | return 236 | } 237 | 238 | token = g.Token 239 | 240 | deckJSON, _ := json.Marshal(deck.AllDecks) 241 | 242 | decks := make([]string, 0, len(deck.AllDecks)) 243 | for d := range deck.AllDecks { 244 | decks = append(decks, d) 245 | } 246 | sort.Strings(decks) 247 | 248 | values := roomTemplateValues{ 249 | Token: token, 250 | Room: g.Room, 251 | URL: r.URL.String(), 252 | Decks: decks, 253 | DecksJSON: template.JS(string(deckJSON)), 254 | TopicMaxLength: game.TopicMaxLength, 255 | UsernameMaxLength: UsernameMaxLength, 256 | } 257 | s.templates["room"].Execute(w, &values) 258 | } 259 | 260 | func (s *Server) getGameByRoom(room string) *game.Game { 261 | s.safeGames.mutex.RLock() 262 | defer s.safeGames.mutex.RUnlock() 263 | 264 | if g, found := s.safeGames.games[s.roomKey(room)]; found { 265 | return g 266 | } 267 | 268 | return nil 269 | } 270 | 271 | func (s *Server) createGameIfNotExists(room, defaultDeck string) error { 272 | if s.getGameByRoom(room) != nil { 273 | return nil 274 | } 275 | 276 | g, err := game.New(room, defaultDeck, s.destroyGame) 277 | if err != nil { 278 | return err 279 | } 280 | 281 | log.WithFields(log.Fields{"room": g.Room, "token": g.Token}).Info("room created") 282 | s.safeGames.mutex.Lock() 283 | s.safeGames.games[s.roomKey(room)] = g 284 | s.safeGames.mutex.Unlock() 285 | 286 | return nil 287 | } 288 | 289 | func (s *Server) roomKey(room string) string { 290 | return strings.ToLower(room) 291 | } 292 | 293 | // HandleWsRequest handles requests that came in from a web socket connection via Client 294 | func (s *Server) HandleWsRequest(c *Client, r *WsRequest) { 295 | if s.debug { 296 | b, err := json.Marshal(r) 297 | if err != nil { 298 | log.Errorf("could not marshal JSON: %v", err) 299 | } else { 300 | log.WithFields(log.Fields{"client": c.Conn.RemoteAddr().String()}).Debugf("received message: %s", string(b)) 301 | } 302 | } 303 | 304 | if c.Game.Room != r.Room || c.Game.Token != r.Token { 305 | log.WithFields(log.Fields{"client": c.Conn.RemoteAddr().String()}).Warnf("token is stale. expected (%s, %s), got (%s, %s)", c.Game.Room, c.Game.Token, r.Room, r.Token) 306 | return 307 | } 308 | 309 | switch r.Action { 310 | case WsRequestActionSelectCard: 311 | c.Game.AddCard(c, r.Card, r.Deck) 312 | case WsRequestActionReveal: 313 | c.Game.Reveal() 314 | case WsRequestActionReset: 315 | c.Game.Reset() 316 | case WsRequestActionDeck: 317 | d, found := deck.AllDecks[r.Deck] 318 | if found { 319 | c.Game.SetDeck(d) 320 | } 321 | case WsRequestActionTopic: 322 | c.Game.SetTopic(r.Value) 323 | case WsRequestActionUsername: 324 | c.SetName(r.Value) 325 | c.Game.SendUpdate() 326 | default: 327 | log.Errorf("unknown action received via ws: %s", r.Action) 328 | } 329 | } 330 | 331 | // ListenForEvents will listen for various events like when to destroy a game, and when to disconnect the server. 332 | func (s *Server) ListenForEvents(done chan bool) { 333 | sig := make(chan os.Signal, 1) 334 | signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1) 335 | 336 | for { 337 | select { 338 | case game := <-s.destroyGame: 339 | roomKey := s.roomKey(game.Room) 340 | s.safeGames.mutex.Lock() 341 | if _, ok := s.safeGames.games[roomKey]; ok { 342 | delete(s.safeGames.games, roomKey) 343 | log.WithFields(log.Fields{"room": game.Room, "token": game.Token}).Info("room destroyed") 344 | } 345 | s.safeGames.mutex.Unlock() 346 | case theSig := <-sig: 347 | if theSig == syscall.SIGUSR1 { 348 | s.safeGames.mutex.RLock() 349 | if len(s.safeGames.games) == 0 { 350 | s.safeGames.mutex.RUnlock() 351 | log.Info("no active rooms") 352 | continue 353 | } 354 | 355 | keys := make([]string, 0, len(s.safeGames.games)) 356 | for key := range s.safeGames.games { 357 | keys = append(keys, key) 358 | } 359 | sort.Strings(keys) 360 | for i, key := range keys { 361 | log.WithFields(log.Fields{"room": key, "clients": s.safeGames.games[key].RegisteredClientsCount()}).Infof("room #%d", i+1) 362 | } 363 | s.safeGames.mutex.RUnlock() 364 | } else { 365 | log.Printf("Shut down.") 366 | done <- true 367 | return 368 | } 369 | } 370 | } 371 | } 372 | -------------------------------------------------------------------------------- /static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synacor/sibyl/5a45d91b6b398d4c559903f451172130322734d6/static/favicon.ico -------------------------------------------------------------------------------- /static/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synacor/sibyl/5a45d91b6b398d4c559903f451172130322734d6/static/images/logo.png -------------------------------------------------------------------------------- /static/images/synacor-bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synacor/sibyl/5a45d91b6b398d4c559903f451172130322734d6/static/images/synacor-bg.png -------------------------------------------------------------------------------- /static/images/synacor-gray.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 9 | 13 | 14 | 16 | 18 | 21 | 24 | 26 | 27 | -------------------------------------------------------------------------------- /static/javascripts/index.js: -------------------------------------------------------------------------------- 1 | window.onload = function() { 2 | var deck, quickCreateLink, quickCreateForm 3 | document.getElementById("room").focus() 4 | 5 | quickCreateForm = document.getElementById("create-room-quick") 6 | 7 | // handle the link on the index page when the user tries to join a non-existent page 8 | if (quickCreateForm) { 9 | quickCreateForm.getElementsByTagName("a")[0].onclick = function(e) { 10 | e.preventDefault && e.preventDefault() 11 | e.stopPropagation && e.stopPropagation() 12 | 13 | quickCreateForm.submit() 14 | 15 | return false 16 | } 17 | } 18 | 19 | if (typeof(localStorage) !== "undefined") { 20 | if ( deck = localStorage.getItem("deck") ) { 21 | document.getElementById("deck").setAttribute("value", deck) 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /static/javascripts/room.js: -------------------------------------------------------------------------------- 1 | var Sibyl = function() { 2 | this.inReveal = false 3 | 4 | if (!window["SibylConfig"] || !SibylConfig.Token) { 5 | this.addToConsole("Could not create room.") 6 | return 7 | } else if (!("WebSocket" in window)) { 8 | this.addToConsole("Your browser does not support Web Sockets.") 9 | return 10 | } 11 | 12 | this.deck = null 13 | this.room = SibylConfig.Room 14 | this.token = SibylConfig.Token 15 | this.topic = null 16 | this.lastConnectAttempt = 0 17 | this.username = this.getItem("username") || "" 18 | this.rememberUsername = !!this.getItem("remember-username") 19 | this.elapsed = 0 20 | this.elapseStarted = new Date() 21 | 22 | // ensure a consistent state (side effect from chrome when opening multiple tabs) 23 | if (!this.rememberUsername) { 24 | this.username = "" 25 | this.removeItem("username") 26 | } 27 | 28 | this.connectToWebSocket() 29 | this.setupBindings() 30 | 31 | setInterval(this.updateElapsed.bind(this), 20) 32 | } 33 | 34 | Sibyl.prototype.updateElapsed = function() { 35 | if (isNaN(this.elapsed)) { 36 | document.querySelector('div.clock').textContent = '' 37 | return 38 | } 39 | 40 | var elapsed = this.elapsed + Math.floor((new Date() - this.elapseStarted)/1000) 41 | var minutes = Math.floor(elapsed / 60) 42 | var seconds = elapsed % 60 43 | if (seconds < 10) { 44 | seconds = '0' + seconds 45 | } 46 | document.querySelector('div.clock').textContent = minutes + ':' + seconds 47 | } 48 | 49 | Sibyl.prototype.setupBindings = function() { 50 | var self = this, 51 | $cards = $("#cards"), 52 | $topic = $("#topic"), 53 | $currentUser = $("#current-username"), 54 | $rememberUser = $("#remember-username") 55 | 56 | $rememberUser.prop("checked", this.rememberUsername) 57 | $rememberUser.click(function(e) { 58 | this.rememberUsername = this.checked 59 | if (this.checked) { 60 | self.storeItem("remember-username", true) 61 | self.storeItem("username", self.username) 62 | } else { 63 | self.removeItem("remember-username") 64 | self.removeItem("username") 65 | } 66 | }) 67 | 68 | $("#room-url").html(document.location.href) 69 | $("#copy-url").click(function(e) { 70 | var x = e.clientX + document.body.scrollLeft, 71 | y = e.clientY + document.body.scrollTop, 72 | ok, msg = "link copied!", 73 | $copydiv, 74 | $input = $("").css({ 75 | position: "absolute", 76 | top: y, 77 | left: x, 78 | opacity: 0 79 | }).appendTo("body").val(document.location.href).focus().select() 80 | 81 | try { 82 | document.execCommand("copy") 83 | } catch(e) { 84 | msg = "browser does not support copy command" 85 | } 86 | 87 | $input.remove() 88 | 89 | $copydiv = $("
").html(msg).addClass("message").css({ top: y, left: x }).appendTo("body") 90 | setTimeout(function() { 91 | $copydiv.fadeTo("slow", 0, function() { 92 | $copydiv.remove() 93 | }) 94 | }, 1000) 95 | 96 | return false; 97 | }) 98 | 99 | $("#reveal").click(function() { 100 | if ($cards.find("span.card-facedown").length > 0) { 101 | self.send("reveal") 102 | } 103 | 104 | return false; 105 | }) 106 | 107 | $("#reset").click(function() { 108 | self.send("reset") 109 | return false; 110 | }) 111 | 112 | $(".decks a").click(function() { 113 | self.send("deck", { deck: $(this).attr("data-name") }) 114 | return false 115 | }) 116 | 117 | var textToInput = function(action, $text, value, inputClassName, maxLength) { 118 | var $form = $("
"), 119 | $input = $("").attr("type", "text").attr("maxlength", maxLength).val(value).addClass(inputClassName), 120 | showText = function() { 121 | $text.show() 122 | $form.remove() 123 | } 124 | 125 | $input.blur(function() { 126 | showText() 127 | }) 128 | 129 | $input.keydown(function(e) { 130 | if (e.keyCode == 27) { // escape key 131 | showText() 132 | } 133 | }) 134 | 135 | $form.append($input) 136 | $text.hide() 137 | $text.parent().prepend($form) 138 | $form.submit(function() { 139 | // JavaScript (ES5) doesn't have support for unicode categories. We'll ensure all characters are 140 | // printable on the server 141 | if ($input.val().match(/\w/)) { 142 | $text.text( $input.val() ) 143 | self.send(action, { value: $input.val() }) 144 | } 145 | 146 | showText() 147 | return false 148 | }) 149 | 150 | $input.focus().select() 151 | return false 152 | } 153 | 154 | $currentUser.click(function() { 155 | textToInput("username", $currentUser, self.username, "current-username-edit", SibylConfig.UsernameMaxLength) 156 | }) 157 | 158 | $topic.click(function() { 159 | textToInput("topic", $topic, self.topic, "topic-edit", SibylConfig.TopicMaxLength) 160 | }) 161 | 162 | $(window).on("beforeunload", function() { 163 | self.disconnect() 164 | }) 165 | } 166 | 167 | Sibyl.prototype.updateBoard = function(data) { 168 | var n, i, 169 | $cards = $("#cards"), 170 | $myHand = $("#my-hand"), 171 | $topic = $("#topic"), 172 | $username = $("#current-username"), 173 | self = this, 174 | $myCard, 175 | $span, 176 | $div, 177 | deck 178 | 179 | this.elapseStarted = new Date() 180 | this.elapsed = data.elapsed 181 | 182 | this.username = data.username 183 | $username.text(this.username) 184 | 185 | if (this.rememberUsername) { 186 | this.storeItem("username", this.username) 187 | } 188 | 189 | this.topic = data.topic 190 | $topic.text(this.topic) 191 | 192 | this.inReveal = data.reveal 193 | 194 | if (data.reset) { 195 | $myHand.find("a").removeClass("chosen") 196 | } 197 | 198 | if ( !this.deck || this.deck != data.deck ) { 199 | this.deck = data.deck 200 | this.storeItem("deck", this.deck) 201 | deck = SibylConfig.Decks[this.deck] 202 | 203 | $myHand.html("") 204 | n = deck.cards.length 205 | for (i = 0; i < n; i++) { 206 | $myCard = $("").attr("href", "#").attr("data-index", i) 207 | $myCard.append($("").addClass("card").addClass("card-flipped").html(deck.cards[i])) 208 | $myHand.append($myCard) 209 | } 210 | 211 | $myHand.find("a").click(function() { 212 | var card = parseInt($(this).attr("data-index"), 10) 213 | if (!self.inReveal) { 214 | $myHand.find("a").removeClass("chosen") 215 | $(this).addClass("chosen") 216 | 217 | self.send("select", { card: card, deck: self.deck }) 218 | } 219 | 220 | return false 221 | }) 222 | } 223 | 224 | $cards.html("") 225 | 226 | var playerIDsToCards = {} 227 | n = data.cards.length 228 | for (i = 0; i < n; i++) { 229 | playerIDsToCards[data.cards[i].playerID] = data.cards[i].card 230 | } 231 | 232 | var playerIDs = [] 233 | for (i in data.players) { 234 | if (data.players.hasOwnProperty(i)) { 235 | playerIDs.push(i) 236 | } 237 | } 238 | 239 | playerIDs.sort(function(a,b) { 240 | return data.players[a].localeCompare(data.players[b]) 241 | }) 242 | 243 | n = playerIDs.length 244 | for (i = 0; i < n; i++) { 245 | var playerID = playerIDs[i] 246 | 247 | $div = $("
").addClass("card") 248 | 249 | if ( playerID in playerIDsToCards ) { 250 | $span = $("") 251 | $span.html(SibylConfig.Decks[this.deck].cards[ playerIDsToCards[playerID] ]) 252 | $span.addClass("card") 253 | 254 | if (this.inReveal) { 255 | $span.addClass("card-flipped") 256 | } else { 257 | $span.addClass("card-facedown") 258 | } 259 | 260 | $div.append($span) 261 | 262 | $span = $("").addClass("player-name").text(data.players[playerID]) 263 | $div.append($span) 264 | } else { 265 | $div = $("
").addClass("card") 266 | $div.append($("").addClass("card").addClass("card-blank").html("?")) 267 | $div.append($("").addClass("player-name").text(data.players[playerID])) 268 | } 269 | 270 | $cards.append($div) 271 | } 272 | } 273 | 274 | Sibyl.prototype.connectToWebSocket = function(isRetry) { 275 | var self = this, 276 | url = (window.location.protocol == "https:" ? "wss://" : "ws://") + window.location.host + "/ws?room=" + encodeURIComponent(this.room) + "&token=" + encodeURIComponent(this.token) + "&username=" + encodeURIComponent(this.username), 277 | conn = new WebSocket(url), 278 | isOpen = false 279 | 280 | conn.onopen = function(evt) { 281 | isOpen = true 282 | isRetry = false 283 | self.addToConsole("Connected.") 284 | setTimeout(function() { 285 | if (isOpen) { 286 | self.showGame() 287 | } 288 | }, 250); 289 | } 290 | conn.onerror = function(evt) { 291 | self.addToConsole("Error. Lost connection.") 292 | self.showConsole() 293 | } 294 | conn.onclose = function(evt) { 295 | var now 296 | 297 | isOpen = false 298 | if (isRetry) { 299 | self.addToConsole("Server may be offline.") 300 | } else { 301 | self.addToConsole("Server disconnected.") 302 | } 303 | 304 | self.showConsole() 305 | 306 | if (!isRetry) { 307 | now = new Date().getTime() / 1000 308 | if ( now - self.lastConnectAttempt < 10 ) { 309 | self.addToConsole('Having an issue? Try using https: https://' + window.location.host + window.location.pathname + '') 310 | return 311 | } 312 | self.lastConnectAttempt = now 313 | 314 | setTimeout(function() { 315 | self.addToConsole("Attempting to reconnect...") 316 | 317 | setTimeout(function() { 318 | self.connectToWebSocket(true) 319 | }, 2500) 320 | }, 250) 321 | } 322 | } 323 | conn.onmessage = function(evt) { 324 | var data = JSON.parse(evt.data) 325 | if (data.error) { 326 | self.disconnect() 327 | self.addToConsole(data.error) 328 | self.showConsole() 329 | } else { 330 | self.updateBoard(data) 331 | } 332 | } 333 | 334 | this.conn = conn 335 | } 336 | 337 | Sibyl.prototype.disconnect = function() { 338 | this.addToConsole("Disconnected.") 339 | this.conn.onclose = function() { } 340 | this.conn.close(1000, "closing ok") 341 | } 342 | 343 | Sibyl.prototype.addToConsole = function(msg) { 344 | $("section.console div.block").append("
" + msg) 345 | } 346 | 347 | Sibyl.prototype.showGame = function() { 348 | $("section.console").hide() 349 | $("section.game").fadeIn("slow") 350 | } 351 | 352 | Sibyl.prototype.showConsole = function() { 353 | $("section.game").hide() 354 | $("section.console").show() 355 | } 356 | 357 | Sibyl.prototype.send = function(action, opts) { 358 | opts = opts ? opts : {} 359 | this.conn.send(JSON.stringify({ 360 | action: action, 361 | card: opts.card || null, 362 | deck: opts.deck || null, 363 | room: this.room, 364 | token: this.token, 365 | value: opts.value || null 366 | })) 367 | } 368 | 369 | Sibyl.prototype.getItem = function(key) { 370 | var value = null 371 | 372 | if (typeof(localStorage) !== "undefined") { 373 | try { value = localStorage.getItem(key) } 374 | catch (e) { } 375 | } 376 | 377 | return value 378 | } 379 | 380 | Sibyl.prototype.storeItem = function(key, value) { 381 | if (typeof(localStorage) !== "undefined") { 382 | try { localStorage.setItem(key, value) } 383 | catch (e) { } 384 | } 385 | } 386 | 387 | Sibyl.prototype.removeItem = function(key) { 388 | if (typeof(localStorage) !== "undefined") { 389 | try { localStorage.removeItem(key) } 390 | catch (e) { } 391 | } 392 | } 393 | 394 | $(function() { 395 | var p = new Sibyl() 396 | }) 397 | -------------------------------------------------------------------------------- /static/stylesheets/styles.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | outline: none; 4 | } 5 | :root { 6 | --light-gray: #aaa; 7 | --spacing: 15px; 8 | } 9 | html { 10 | font: 1em 'Lato', sans-serif; 11 | } 12 | form { 13 | display: inline; 14 | } 15 | 16 | body { 17 | background-color: #f3f3f3; 18 | margin: 0; 19 | padding: 0; 20 | } 21 | 22 | a { 23 | color: #09c; 24 | } 25 | a:hover { 26 | color: #2ecc71; 27 | } 28 | 29 | header { 30 | background-color: #272727; 31 | height: 118px; 32 | } 33 | 34 | main { 35 | background-color: #fff; 36 | padding: var(--spacing) 0 100px 0; 37 | } 38 | 39 | footer { 40 | color: #888; 41 | font-size: 0.8em; 42 | padding: 25px 0; 43 | } 44 | footer div.block { 45 | margin: 0 auto; 46 | padding: 0; 47 | text-align: center; 48 | } 49 | footer p { 50 | display: inline-block; 51 | height: 18px; 52 | line-height: 18px; 53 | margin: 0; 54 | padding: 0; 55 | text-align: center; 56 | vertical-align: middle; 57 | } 58 | footer p.built-by img { 59 | display: inline-block; 60 | height: 18px; 61 | padding-left: 5px; 62 | position: relative; 63 | top: -1px; 64 | vertical-align: middle; 65 | } 66 | footer p.version { 67 | padding-right: 8px; 68 | margin-right: 8px; 69 | border-right: 1px solid #888; 70 | } 71 | footer a { 72 | color: #888; 73 | text-decoration: none; 74 | } 75 | footer a:hover { 76 | color: #2ecc71; 77 | } 78 | 79 | div.block { 80 | padding: 0 var(--spacing); 81 | } 82 | 83 | header p { 84 | margin: 0; 85 | padding-top: 18px; 86 | } 87 | 88 | p, h1, h2, h3, h4, h5 { 89 | margin: 0 0 var(--spacing) 0; 90 | } 91 | 92 | .topic h2 { 93 | border: 2px solid transparent; 94 | border-style: inset; 95 | border-bottom: 2px dotted var(--light-gray); 96 | float: left; 97 | font-size: 1.5em; 98 | margin: 0; 99 | } 100 | .topic h2:hover { 101 | background-color: white; 102 | user-select: text; 103 | cursor: auto; 104 | border: 1px solid #ccc; 105 | padding: 1px; 106 | } 107 | header h1 { 108 | display: none; 109 | margin: 0; 110 | } 111 | 112 | .game { 113 | display: none; 114 | } 115 | section.community { 116 | margin-top: var(--spacing); 117 | } 118 | section.community div.block { 119 | position: relative; 120 | } 121 | .clock { 122 | color: rgba(0, 0, 0, 0.1); 123 | font-size: 3em; 124 | font-weight: bold; 125 | position: absolute; 126 | right: var(--spacing); 127 | top: 0; 128 | } 129 | section.community div.block::after { 130 | clear: both; 131 | content: ''; 132 | display: block; 133 | } 134 | .community { 135 | background-color: #2ecc71; 136 | color: #fff; 137 | padding: 10px 0 5px; /* using 5px on bottom; card has bottom margin */ 138 | } 139 | .community p { 140 | margin: 0; 141 | } 142 | 143 | #cards { 144 | min-height: 160px; 145 | } 146 | #cards::after { 147 | clear: both; 148 | content: ''; 149 | display: block; 150 | } 151 | div.card { 152 | display: inline-block; 153 | text-align: center; 154 | margin-bottom: 5px; 155 | margin-right: 5px; 156 | width: 100px; 157 | } 158 | span.player-name { 159 | color: #000; 160 | display: inline-block; 161 | font-size: 0.8em; 162 | opacity: 0.6; 163 | overflow: hidden; 164 | vertical-align: top; 165 | width: 100px; 166 | } 167 | span.card { 168 | background-color: #c10; 169 | background: url(/static/images/synacor-bg.png), linear-gradient(#c10, #910); 170 | border-radius: 5px; 171 | color: #333; 172 | display: block; 173 | font-size: 3em; 174 | font-weight: bold; 175 | height: 155px; 176 | line-height: 155px; 177 | text-align: center; 178 | text-indent: -10000px; 179 | width: 100px; 180 | } 181 | span.card:last-child { 182 | margin-right: 0px; 183 | } 184 | 185 | span.card-flipped { 186 | background-color: #eee; 187 | background: linear-gradient(rgb(233,235,234), rgb(222,225,224)); 188 | text-indent: 0; 189 | } 190 | 191 | span.card-blank { 192 | background: rgb(53, 176, 102); 193 | font-size: 8em; 194 | color: rgba(0,0,0,0.05); 195 | text-indent: 0; 196 | text-shadow: none; 197 | } 198 | 199 | .my-hand { 200 | margin-top: var(--spacing); 201 | } 202 | #my-hand span.card { 203 | font-size: 1.5em; 204 | height: 77px; 205 | line-height: 77px; 206 | width: 50px; 207 | } 208 | #my-hand a{ 209 | color: #000; 210 | float: left; 211 | display: inline-block; 212 | height: 77px; 213 | width: 50px; 214 | margin-right: 5px; 215 | margin-bottom: 5px; 216 | text-decoration: none; 217 | } 218 | #my-hand a:last-child { 219 | margin-right: 0; 220 | } 221 | 222 | #my-hand:after { 223 | content: ''; 224 | display: block; 225 | clear: both; 226 | } 227 | 228 | #my-hand a span { 229 | position: relative; 230 | top: 0; 231 | transition: top 0.1s; 232 | } 233 | #my-hand a:hover span { 234 | top: -8px; 235 | } 236 | #my-hand a.chosen:hover span { 237 | box-shadow: 0px 0px 3px 3px rgba(46, 204, 133, 1); 238 | cursor: default; 239 | top: 0; 240 | } 241 | #my-hand a.chosen span { 242 | box-shadow: 0px 0px 3px 3px rgba(46, 204, 133, 1); 243 | } 244 | .commands { 245 | float: right; 246 | } 247 | .commands div.controls { 248 | float: left; 249 | } 250 | .commands span { 251 | color: #888; 252 | float: left; 253 | } 254 | .commands a { 255 | text-decoration: none; 256 | margin-left: 10px; 257 | float: left; 258 | } 259 | 260 | #reveal, #reset { 261 | font-size: 1.2em; 262 | } 263 | #reveal:before { 264 | font-size: 0.85em; 265 | content: '✓ '; 266 | } 267 | #reset:before { 268 | font-size: 0.85em; 269 | content: '↻ '; 270 | } 271 | .decks { 272 | margin-top: var(--spacing); 273 | } 274 | .console { 275 | background-color: #2ecc71; 276 | color: #272727; 277 | font: 1em 'Roboto Mono', monospace; 278 | padding: 10px; 279 | } 280 | .console a { 281 | color: #000; 282 | } 283 | .console a:hover { 284 | color: #09c; 285 | } 286 | strong.room { 287 | background-color: #ddd; 288 | border: 1px solid var(--light-gray); 289 | border-radius: 2px; 290 | padding: 1px 2px; 291 | margin: -1px 0; 292 | display: inline-block; 293 | color: #000; 294 | } 295 | 296 | fieldset { 297 | background-color: #2ecc71; 298 | border: 0; 299 | padding: 25px 10px; 300 | text-align: center; 301 | } 302 | 303 | section.index input { 304 | font: 2em 'Lato', sans-serif; 305 | } 306 | 307 | div.message { 308 | background-color: #09c; 309 | border-radius: 5px; 310 | color: #fff; 311 | padding: 3px; 312 | float: left; 313 | position: absolute; 314 | transform: translate(-50%, -50%); 315 | } 316 | 317 | p.invalid { 318 | color: #c10; 319 | text-align: center; 320 | } 321 | 322 | section.welcome { 323 | margin: 30px 0 50px; 324 | } 325 | p.hero { 326 | font-size: 1.6em; 327 | margin: 0 0 5px 0; 328 | } 329 | p.about { 330 | margin: 0; 331 | line-height: 1.3em; 332 | } 333 | p.hero span.rapid { 334 | color: #2ecc71; 335 | font-style: italic; 336 | } 337 | section.topic div.block:after { 338 | display: block; 339 | content: ''; 340 | clear: both; 341 | } 342 | input.topic-edit, input.current-username-edit { 343 | background-color: white; 344 | border: 1px solid #ccc; 345 | cursor: auto; 346 | font: bold 1.5em 'Lato', sans-serif; 347 | margin: 0; 348 | padding: 0; 349 | padding: 1px; 350 | user-select: text; 351 | width: 100%; 352 | } 353 | 354 | input.current-username-edit { 355 | font-size: 1em; 356 | width: auto; 357 | } 358 | #current-username { 359 | display: inline-block; 360 | border: 2px solid transparent; 361 | border-style: inset; 362 | border-bottom: 2px dotted var(--light-gray); 363 | font-weight: bold; 364 | margin: 0; 365 | } 366 | #current-username:hover { 367 | background-color: white; 368 | user-select: text; 369 | cursor: auto; 370 | border: 1px solid #ccc; 371 | padding: 1px; 372 | } 373 | .topic h2:hover, 374 | #current-username:hover { 375 | position: relative; 376 | } 377 | .topic h2:hover:after, 378 | #current-username:hover:after { 379 | background-color: #eee; 380 | border: 1px solid #ccc; 381 | content: '✎'; 382 | font-size: 0.8em; 383 | height: 0.8em; 384 | line-height: 0.8em; 385 | padding: 2px; 386 | position: absolute; 387 | right: 0; 388 | text-align: center; 389 | top: 0; 390 | width: 0.8em; 391 | 392 | border-right-width: 0; 393 | border-top-width: 0; 394 | } 395 | 396 | @media only screen and (max-width: 799px) { 397 | section.index input { 398 | width: 100%; 399 | } 400 | } 401 | 402 | @media only screen and (min-width: 800px) { 403 | p.hero { 404 | font-size: 3em; 405 | margin: 0 0 var(--spacing) 0; 406 | } 407 | p.about { 408 | margin: 0; 409 | line-height: 1.3em; 410 | } 411 | p.hero span.rapid { 412 | color: #2ecc71; 413 | font-style: italic; 414 | } 415 | div.block { 416 | padding: 0 25px; 417 | } 418 | section.welcome { 419 | margin: 90px 0 110px; 420 | } 421 | fieldset { 422 | margin: 0 -25px; 423 | } 424 | } 425 | 426 | @media only screen and (min-width: 1200px) { 427 | div.block { 428 | margin: 0 auto; 429 | width: 1200px; 430 | } 431 | } 432 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | {{ define "content" }} 2 |
3 |
4 |
5 |

Rapid Agile Estimations

6 | 7 |

Your user stories already exist in a backlog, so why enter them yet again into another tool? Sibyl is different. No sign-ups, no long forms asking for user stories, just create a room and start estimating!

8 |
9 |
10 | 11 | {{ if .Error }} 12 |
13 |
14 |

{{ .Error }}

15 |
16 |
17 | {{ end }} 18 | 19 | {{ if .NotFoundRoom }} 20 |
21 |
22 | 23 | 24 |

A room with the name "{{ .NotFoundRoom }}" was not found. You can create the room or create your own by using the form below. 25 |

26 |
27 |
28 | {{ end }} 29 | 30 |
31 |
32 |
33 | 34 | 35 |
36 |
37 |
38 |
39 | {{ end }} 40 | 41 | {{ define "javascript" }} 42 | 43 | {{ end }} 44 | -------------------------------------------------------------------------------- /templates/room.html: -------------------------------------------------------------------------------- 1 | {{ define "content" }} 2 |
3 |
4 |
5 |

You are in the room {{ .Room }}. You can copy the link by clicking here. Your name is . Remember your name.

6 |
7 |
8 | 9 |
10 |
11 |
12 |

The Topic

13 |
14 |
15 |
16 |
17 |

Community Cards

18 | 19 |
20 | 00:00 21 |
22 | 23 |
24 |
25 |
26 | 27 |
28 |
29 |
30 | Reveal 31 | Reset 32 |
33 |
34 |
35 | 36 |
37 |
38 |

My Hand

39 | 40 |
41 |
42 | 43 |
44 | Choose Deck: 45 | 46 |
    47 | {{ range .Decks }} 48 |
  • {{ . }}
  • 49 | {{ end }} 50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | Connecting to server... 58 |
59 |
60 |
61 | {{ end }} 62 | 63 | 64 | {{ define "javascript" }} 65 | 74 | 75 | 76 | {{ end }} 77 | -------------------------------------------------------------------------------- /templates/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Sibyl - Rapid Agile Estimations 7 | 8 | 9 | 10 | 11 |
12 |
13 |

14 | 15 |

Sibyl

16 |
17 |
18 |
19 | {{ template "content" . }} 20 |
21 | 26 | 27 | {{ template "javascript" . }} 28 | 29 | 30 | --------------------------------------------------------------------------------