├── .gitattributes ├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.nix ├── Cargo.toml ├── LICENSE ├── README.org ├── build.rs ├── default.nix ├── envrc.example ├── migrations ├── .gitkeep ├── 00000000000000_diesel_initial_setup │ ├── down.sql │ └── up.sql ├── 2018-04-08-133240_create_posts │ ├── down.sql │ └── up.sql ├── 2018-04-08-161017_joinable_posts │ ├── down.sql │ └── up.sql ├── 2018-04-08-172739_default_posted │ ├── down.sql │ └── up.sql ├── 2018-04-08-182319_add_authors │ ├── down.sql │ └── up.sql ├── 2018-04-14-140818_posts_only_in_posts │ ├── down.sql │ └── up.sql ├── 2018-04-14-153202_add_stickies_improve_index │ ├── down.sql │ └── up.sql ├── 2018-04-14-170750_search-index │ ├── down.sql │ └── up.sql ├── 2018-05-01-141548_add-users │ ├── down.sql │ └── up.sql ├── 2018-05-01-183232_simplified-post-view │ ├── down.sql │ └── up.sql ├── 2018-05-25-160648_add_closed_column │ ├── down.sql │ └── up.sql └── 2018-05-25-161939_add_closed_to_index │ ├── down.sql │ └── up.sql ├── src ├── db.rs ├── errors.rs ├── handlers.rs ├── main.rs ├── models.rs ├── oidc.rs ├── render.rs └── schema.rs ├── static ├── highlight.css ├── highlight.js └── styles.css ├── templates ├── index.html ├── post.html ├── search.html └── thread.html └── todo.org /.gitattributes: -------------------------------------------------------------------------------- 1 | Cargo.nix linguist-generated=true 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .envrc 2 | /target/ 3 | **/*.rs.bk 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: nix 2 | sudo: true 3 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | A SERMON ON ETHICS AND LOVE 2 | =========================== 3 | 4 | One day Mal-2 asked the messenger spirit Saint Gulik to approach the 5 | Goddess and request Her presence for some desperate advice. Shortly 6 | afterwards the radio came on by itself, and an ethereal female Voice 7 | said **YES?** 8 | 9 | "O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord! 10 | Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a 11 | heavy burden from my heart!" 12 | 13 | **WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.** 14 | 15 | "I am filled with fear and tormented with terrible visions of pain. 16 | Everywhere people are hurting one another, the planet is rampant with 17 | injustices, whole societies plunder groups of their own people, 18 | mothers imprison sons, children perish while brothers war. O, woe." 19 | 20 | **WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?** 21 | 22 | "But nobody Wants it! Everybody hates it." 23 | 24 | **OH. WELL, THEN *STOP*.** 25 | 26 | At which moment She turned herself into an aspirin commercial and left 27 | The Polyfather stranded alone with his species. 28 | 29 | SINISTER DEXTER HAS A BROKEN SPIROMETER. 30 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contribution Guidelines 2 | ======================= 3 | 4 | 5 | **Table of Contents** 6 | 7 | - [Contribution Guidelines](#contribution-guidelines) 8 | - [Before making a change](#before-making-a-change) 9 | - [Commit messages](#commit-messages) 10 | - [Commit content](#commit-content) 11 | - [Code quality](#code-quality) 12 | - [Builds & tests](#builds--tests) 13 | 14 | 15 | 16 | This is a loose set of "guidelines" for contributing to my projects. 17 | Please note that I will not accept any pull requests that don't follow 18 | these guidelines. 19 | 20 | Also consider the [code of conduct](CODE_OF_CONDUCT.md). No really, 21 | you should. 22 | 23 | ## Before making a change 24 | 25 | Before making a change, consider your motivation for making the 26 | change. Documentation updates, bug fixes and the like are *always* 27 | welcome. 28 | 29 | When adding a feature you should consider whether it is only useful 30 | for your particular use-case or whether it is generally applicable for 31 | other users of the project. 32 | 33 | When in doubt - just ask me! 34 | 35 | ## Commit messages 36 | 37 | All commit messages should follow the style-guide used by the [Angular 38 | project][]. This means for the most part that your commit message 39 | should be structured like this: 40 | 41 | ``` 42 | type(scope): Subject line with at most 68 a character length 43 | 44 | Body of the commit message with an empty line between subject and 45 | body. This text should explain what the change does and why it has 46 | been made, *especially* if it introduces a new feature. 47 | 48 | Relevant issues should be mentioned if they exist. 49 | ``` 50 | 51 | Where `type` can be one of: 52 | 53 | * `feat`: A new feature has been introduced 54 | * `fix`: An issue of some kind has been fixed 55 | * `docs`: Documentation or comments have been updated 56 | * `style`: Formatting changes only 57 | * `refactor`: Hopefully self-explanatory! 58 | * `test`: Added missing tests / fixed tests 59 | * `chore`: Maintenance work 60 | 61 | And `scope` should refer to some kind of logical grouping inside of 62 | the project. 63 | 64 | Please take a look at the existing commit log for examples. 65 | 66 | ## Commit content 67 | 68 | Multiple changes should be divided into multiple git commits whenever 69 | possible. Common sense applies. 70 | 71 | The fix for a single-line whitespace issue is fine to include in a 72 | different commit. Introducing a new feature and refactoring 73 | (unrelated) code in the same commit is not fine. 74 | 75 | `git commit -a` is generally **taboo**. 76 | 77 | In my experience making "sane" commits becomes *significantly* easier 78 | as developer tooling is improved. The interface to `git` that I 79 | recommend is [magit][]. Even if you are not yet an Emacs user, it 80 | makes sense to install Emacs just to be able to use magit - it is 81 | really that good. 82 | 83 | For staging sane chunks on the command line with only git, consider 84 | `git add -p`. 85 | 86 | ## Code quality 87 | 88 | This one should go without saying - but please ensure that your code 89 | quality does not fall below the rest of the project. This is of course 90 | very subjective, but as an example if you place code that throws away 91 | errors into a block in which errors are handled properly your change 92 | will be rejected. 93 | 94 | In my experience there is a strong correlation between the visual 95 | appearance of a code block and its quality. This is a simple way to 96 | sanity-check your work while squinting and keeping some distance from 97 | your screen ;-) 98 | 99 | ## Builds & tests 100 | 101 | Most of my projects are built using [Nix][] to avoid "build pollution" 102 | via the user's environment. If you have Nix installed and are 103 | contributing to a project that has a `default.nix`, consider using 104 | `nix-build` to verify that builds work correctly. 105 | 106 | If the project has tests, check that they still work before submitting 107 | your change. 108 | 109 | Both of these will usually be covered by Travis CI. 110 | 111 | 112 | [Angular project]: https://gist.github.com/stephenparish/9941e89d80e2bc58a153#format-of-the-commit-message 113 | [magit]: https://magit.vc/ 114 | [Nix]: https://nixos.org/nix/ 115 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "converse" 3 | version = "0.1.0" 4 | authors = ["Vincent Ambo "] 5 | license = "AGPL-3.0-or-later" 6 | 7 | [dependencies] 8 | actix = "0.5" 9 | actix-web = "0.6" 10 | askama = "0.6" 11 | chrono = { version = "0.4", features = ["serde"] } 12 | comrak = "0.2" 13 | diesel = { version = "1.2", features = ["postgres", "chrono", "r2d2"]} 14 | env_logger = "0.5" 15 | failure = "0.1" 16 | futures = "0.1" 17 | hyper = "0.11" 18 | log = "0.4" 19 | md5 = "0.3.7" 20 | mime_guess = "2.0.0-alpha" 21 | pq-sys = "=0.4.4" 22 | r2d2 = "0.8" 23 | rand = "0.4" 24 | reqwest = "0.8" 25 | serde = "1.0" 26 | serde_derive = "1.0" 27 | serde_json = "1.0" 28 | tokio = "0.1" 29 | tokio-timer = "0.2" 30 | url = "1.7" 31 | url_serde = "0.2" 32 | 33 | [build-dependencies] 34 | pulldown-cmark = "0.1" 35 | askama = "0.6" 36 | -------------------------------------------------------------------------------- /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 by 637 | 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 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | #+TITLE: Converse 2 | #+AUTHOR: Vincent Ambo 3 | 4 | Welcome to Converse, a work-in-progress forum software written in 5 | Rust. The intention behind Converse is to provide a simple forum-like 6 | experience. 7 | 8 | There is not a lot of documentation about Converse yet and it has 9 | several known issues. Also note that Converse is being developed for a 10 | specific use-case and is not going to be a forum feature kitchen-sink 11 | like most classical forum softwares. 12 | 13 | Better documentation is forthcoming once the remaining basics have 14 | been taken care of. 15 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | extern crate askama; 2 | 3 | fn main() { 4 | askama::rerun_if_templates_changed(); 5 | } 6 | -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | # This Nix derivation imports the generated Carnix sources and builds 2 | # Converse. 3 | # 4 | # To work around an issue in Carnix ([1] & [2]) the attributes of the 5 | # comrak crate have been overridden with a dummy environment variable 6 | # to simulate a Cargo-based build. This requires a manual change to 7 | # `Cargo.nix` when updating dependencies. 8 | # 9 | # [1]: https://nest.pijul.com/pmeunier/carnix/discussions/2 10 | # [2]: https://nest.pijul.com/pmeunier/carnix/discussions/3 11 | 12 | { pkgs ? import {}}: 13 | 14 | let cargo = pkgs.callPackage ./Cargo.nix {}; 15 | in cargo.converse {} 16 | -------------------------------------------------------------------------------- /envrc.example: -------------------------------------------------------------------------------- 1 | # This is an example configuration for running converse during 2 | # development using direnv: 3 | # https://github.com/direnv/direnv 4 | # 5 | # The OIDC actor is configured with bogus values as disabling logins 6 | # never causes it to run anyways. 7 | 8 | export DATABASE_URL=postgres://converse:converse@localhost/converse 9 | export RUST_LOG=info 10 | export OIDC_DISCOVERY_URL=https://does.not.matter.com/ 11 | export OIDC_CLIENT_ID=some-client-id 12 | export OIDC_CLIENT_SECRET='some-client-secret' 13 | export BASE_URL=http://localhost:4567 14 | export REQUIRE_LOGIN=false 15 | -------------------------------------------------------------------------------- /migrations/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tazjin/converse/8901d5d73a50ce2d426aece1f8ab0ff0216278ef/migrations/.gitkeep -------------------------------------------------------------------------------- /migrations/00000000000000_diesel_initial_setup/down.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass); 6 | DROP FUNCTION IF EXISTS diesel_set_updated_at(); 7 | -------------------------------------------------------------------------------- /migrations/00000000000000_diesel_initial_setup/up.sql: -------------------------------------------------------------------------------- 1 | -- This file was automatically created by Diesel to setup helper functions 2 | -- and other internal bookkeeping. This file is safe to edit, any future 3 | -- changes will be added to existing projects as new migrations. 4 | 5 | 6 | 7 | 8 | -- Sets up a trigger for the given table to automatically set a column called 9 | -- `updated_at` whenever the row is modified (unless `updated_at` was included 10 | -- in the modified columns) 11 | -- 12 | -- # Example 13 | -- 14 | -- ```sql 15 | -- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW()); 16 | -- 17 | -- SELECT diesel_manage_updated_at('users'); 18 | -- ``` 19 | CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$ 20 | BEGIN 21 | EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s 22 | FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl); 23 | END; 24 | $$ LANGUAGE plpgsql; 25 | 26 | CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$ 27 | BEGIN 28 | IF ( 29 | NEW IS DISTINCT FROM OLD AND 30 | NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at 31 | ) THEN 32 | NEW.updated_at := current_timestamp; 33 | END IF; 34 | RETURN NEW; 35 | END; 36 | $$ LANGUAGE plpgsql; 37 | -------------------------------------------------------------------------------- /migrations/2018-04-08-133240_create_posts/down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE posts; 2 | DROP TABLE threads; 3 | -------------------------------------------------------------------------------- /migrations/2018-04-08-133240_create_posts/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE threads ( 2 | id SERIAL PRIMARY KEY, 3 | title VARCHAR NOT NULL, 4 | body TEXT NOT NULL, 5 | posted TIMESTAMPTZ NOT NULL 6 | ); 7 | 8 | CREATE TABLE posts ( 9 | id SERIAL PRIMARY KEY, 10 | thread SERIAL REFERENCES threads (id), 11 | body TEXT NOT NULL, 12 | posted TIMESTAMPTZ NOT NULL 13 | ); 14 | -------------------------------------------------------------------------------- /migrations/2018-04-08-161017_joinable_posts/down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE posts RENAME COLUMN thread_id TO thread; 2 | -------------------------------------------------------------------------------- /migrations/2018-04-08-161017_joinable_posts/up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE posts RENAME COLUMN thread TO thread_id; 2 | -------------------------------------------------------------------------------- /migrations/2018-04-08-172739_default_posted/down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE threads ALTER COLUMN posted DROP DEFAULT; 2 | ALTER TABLE posts ALTER COLUMN posted DROP DEFAULT; 3 | -------------------------------------------------------------------------------- /migrations/2018-04-08-172739_default_posted/up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE threads ALTER COLUMN posted SET DEFAULT (NOW() AT TIME ZONE 'UTC'); 2 | ALTER TABLE posts ALTER COLUMN posted SET DEFAULT (NOW() AT TIME ZONE 'UTC'); 3 | -------------------------------------------------------------------------------- /migrations/2018-04-08-182319_add_authors/down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE threads DROP COLUMN author_name; 2 | ALTER TABLE threads DROP COLUMN author_email; 3 | 4 | ALTER TABLE posts DROP COLUMN author_name; 5 | ALTER TABLE posts DROP COLUMN author_email; 6 | -------------------------------------------------------------------------------- /migrations/2018-04-08-182319_add_authors/up.sql: -------------------------------------------------------------------------------- 1 | -- This migration adds an 'author' column to the thread & post table. 2 | -- Authors don't currently exist as independent objects in the 3 | -- database as most user management is simply delegated to the OIDC 4 | -- provider. 5 | 6 | ALTER TABLE threads ADD COLUMN author_name VARCHAR NOT NULL DEFAULT 'anonymous'; 7 | ALTER TABLE threads ADD COLUMN author_email VARCHAR NOT NULL DEFAULT 'unknown@example.org'; 8 | 9 | ALTER TABLE posts ADD COLUMN author_name VARCHAR NOT NULL DEFAULT 'anonymous'; 10 | ALTER TABLE posts ADD COLUMN author_email VARCHAR NOT NULL DEFAULT 'unknown@example.org'; 11 | -------------------------------------------------------------------------------- /migrations/2018-04-14-140818_posts_only_in_posts/down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE threads ADD COLUMN body TEXT NOT NULL DEFAULT ''; 2 | -------------------------------------------------------------------------------- /migrations/2018-04-14-140818_posts_only_in_posts/up.sql: -------------------------------------------------------------------------------- 1 | -- Instead of storing the thread OP in the thread table, this will 2 | -- make it a post as well. 3 | -- At the time at which this migration was created no important data 4 | -- existed in any converse instances, so data is not moved. 5 | 6 | ALTER TABLE threads DROP COLUMN body; 7 | -------------------------------------------------------------------------------- /migrations/2018-04-14-153202_add_stickies_improve_index/down.sql: -------------------------------------------------------------------------------- 1 | DROP VIEW thread_index; 2 | ALTER TABLE threads DROP COLUMN sticky; 3 | -------------------------------------------------------------------------------- /migrations/2018-04-14-153202_add_stickies_improve_index/up.sql: -------------------------------------------------------------------------------- 1 | -- Add support for stickies in threads 2 | ALTER TABLE threads ADD COLUMN sticky BOOLEAN NOT NULL DEFAULT FALSE; 3 | 4 | -- CREATE a simple view that returns the list of threads ordered by 5 | -- the last post that occured in the thread. 6 | CREATE VIEW thread_index AS 7 | SELECT t.id AS thread_id, 8 | t.title AS title, 9 | t.author_name AS thread_author, 10 | t.posted AS created, 11 | t.sticky AS sticky, 12 | p.id AS post_id, 13 | p.author_name AS post_author, 14 | p.posted AS posted 15 | FROM threads t 16 | JOIN (SELECT DISTINCT ON (thread_id) 17 | id, thread_id, author_name, posted 18 | FROM posts 19 | ORDER BY thread_id, id DESC) AS p 20 | ON t.id = p.thread_id 21 | ORDER BY t.sticky DESC, p.id DESC; 22 | -------------------------------------------------------------------------------- /migrations/2018-04-14-170750_search-index/down.sql: -------------------------------------------------------------------------------- 1 | DROP INDEX idx_fts_search; 2 | DROP MATERIALIZED VIEW search_index; 3 | -------------------------------------------------------------------------------- /migrations/2018-04-14-170750_search-index/up.sql: -------------------------------------------------------------------------------- 1 | -- Prepare a materialised view containing the tsvector data for all 2 | -- threads and posts. This view is indexed using a GIN-index to enable 3 | -- performant full-text searches. 4 | -- 5 | -- For now the query language is hardcoded to be English. 6 | 7 | CREATE MATERIALIZED VIEW search_index AS 8 | SELECT p.id AS post_id, 9 | p.author_name AS author, 10 | t.id AS thread_id, 11 | t.title AS title, 12 | p.body AS body, 13 | setweight(to_tsvector('english', t.title), 'B') || 14 | setweight(to_tsvector('english', p.body), 'A') || 15 | setweight(to_tsvector('simple', t.author_name), 'C') || 16 | setweight(to_tsvector('simple', p.author_name), 'C') AS document 17 | FROM posts p 18 | JOIN threads t 19 | ON t.id = p.thread_id; 20 | 21 | CREATE INDEX idx_fts_search ON search_index USING gin(document); 22 | -------------------------------------------------------------------------------- /migrations/2018-05-01-141548_add-users/down.sql: -------------------------------------------------------------------------------- 1 | -- First restore the old columns: 2 | ALTER TABLE threads ADD COLUMN author_name VARCHAR; 3 | ALTER TABLE threads ADD COLUMN author_email VARCHAR; 4 | ALTER TABLE posts ADD COLUMN author_name VARCHAR; 5 | ALTER TABLE posts ADD COLUMN author_email VARCHAR; 6 | 7 | -- Then select the data back into them: 8 | UPDATE threads SET author_name = users.name, 9 | author_email = users.email 10 | FROM users 11 | WHERE threads.user_id = users.id; 12 | 13 | UPDATE posts SET author_name = users.name, 14 | author_email = users.email 15 | FROM users 16 | WHERE posts.user_id = users.id; 17 | 18 | -- add the constraints back: 19 | ALTER TABLE threads ALTER COLUMN author_name SET NOT NULL; 20 | ALTER TABLE threads ALTER COLUMN author_email SET NOT NULL; 21 | ALTER TABLE posts ALTER COLUMN author_name SET NOT NULL; 22 | ALTER TABLE posts ALTER COLUMN author_email SET NOT NULL; 23 | 24 | -- reset the index view: 25 | CREATE OR REPLACE VIEW thread_index AS 26 | SELECT t.id AS thread_id, 27 | t.title AS title, 28 | t.author_name AS thread_author, 29 | t.posted AS created, 30 | t.sticky AS sticky, 31 | p.id AS post_id, 32 | p.author_name AS post_author, 33 | p.posted AS posted 34 | FROM threads t 35 | JOIN (SELECT DISTINCT ON (thread_id) 36 | id, thread_id, author_name, posted 37 | FROM posts 38 | ORDER BY thread_id, id DESC) AS p 39 | ON t.id = p.thread_id 40 | ORDER BY t.sticky DESC, p.id DESC; 41 | 42 | -- reset the search view: 43 | DROP MATERIALIZED VIEW search_index; 44 | CREATE MATERIALIZED VIEW search_index AS 45 | SELECT p.id AS post_id, 46 | p.author_name AS author, 47 | t.id AS thread_id, 48 | t.title AS title, 49 | p.body AS body, 50 | setweight(to_tsvector('english', t.title), 'B') || 51 | setweight(to_tsvector('english', p.body), 'A') || 52 | setweight(to_tsvector('simple', t.author_name), 'C') || 53 | setweight(to_tsvector('simple', p.author_name), 'C') AS document 54 | FROM posts p 55 | JOIN threads t 56 | ON t.id = p.thread_id; 57 | 58 | CREATE INDEX idx_fts_search ON search_index USING gin(document); 59 | 60 | -- and drop the users table and columns: 61 | ALTER TABLE posts DROP COLUMN user_id; 62 | ALTER TABLE threads DROP COLUMN user_id; 63 | DROP TABLE users; 64 | -------------------------------------------------------------------------------- /migrations/2018-05-01-141548_add-users/up.sql: -------------------------------------------------------------------------------- 1 | -- This query creates a users table and migrates the existing user 2 | -- information (from the posts table) into it. 3 | 4 | CREATE TABLE users ( 5 | id SERIAL PRIMARY KEY, 6 | email VARCHAR NOT NULL UNIQUE, 7 | name VARCHAR NOT NULL, 8 | admin BOOLEAN NOT NULL DEFAULT false 9 | ); 10 | 11 | -- Insert the 'anonymous' user explicitly: 12 | INSERT INTO users (name, email) 13 | VALUES ('Anonymous', 'anonymous@nothing.org'); 14 | 15 | INSERT INTO users (id, email, name) 16 | SELECT nextval('users_id_seq'), 17 | author_email AS email, 18 | author_name AS name 19 | FROM posts 20 | WHERE author_email != 'anonymous@nothing.org' 21 | GROUP BY name, email; 22 | 23 | -- Create the 'user_id' column in the relevant tables (initially 24 | -- without a not-null constraint) and populate it with the data 25 | -- selected above: 26 | ALTER TABLE posts ADD COLUMN user_id INTEGER REFERENCES users (id); 27 | UPDATE posts SET user_id = users.id 28 | FROM users 29 | WHERE users.email = posts.author_email; 30 | 31 | ALTER TABLE threads ADD COLUMN user_id INTEGER REFERENCES users (id); 32 | UPDATE threads SET user_id = users.id 33 | FROM users 34 | WHERE users.email = threads.author_email; 35 | 36 | -- Add the constraints: 37 | ALTER TABLE posts ALTER COLUMN user_id SET NOT NULL; 38 | ALTER TABLE threads ALTER COLUMN user_id SET NOT NULL; 39 | 40 | -- Update the index view: 41 | CREATE OR REPLACE VIEW thread_index AS 42 | SELECT t.id AS thread_id, 43 | t.title AS title, 44 | ta.name AS thread_author, 45 | t.posted AS created, 46 | t.sticky AS sticky, 47 | p.id AS post_id, 48 | pa.name AS post_author, 49 | p.posted AS posted 50 | FROM threads t 51 | JOIN (SELECT DISTINCT ON (thread_id) 52 | id, thread_id, user_id, posted 53 | FROM posts 54 | ORDER BY thread_id, id DESC) AS p 55 | ON t.id = p.thread_id 56 | JOIN users ta ON ta.id = t.user_id 57 | JOIN users pa ON pa.id = p.user_id 58 | ORDER BY t.sticky DESC, p.id DESC; 59 | 60 | -- Update the search view: 61 | DROP MATERIALIZED VIEW search_index; 62 | CREATE MATERIALIZED VIEW search_index AS 63 | SELECT p.id AS post_id, 64 | pa.name AS author, 65 | t.id AS thread_id, 66 | t.title AS title, 67 | p.body AS body, 68 | setweight(to_tsvector('english', t.title), 'B') || 69 | setweight(to_tsvector('english', p.body), 'A') || 70 | setweight(to_tsvector('simple', ta.name), 'C') || 71 | setweight(to_tsvector('simple', pa.name), 'C') AS document 72 | FROM posts p 73 | JOIN threads t ON t.id = p.thread_id 74 | JOIN users ta ON ta.id = t.user_id 75 | JOIN users pa ON pa.id = p.user_id; 76 | 77 | CREATE INDEX idx_fts_search ON search_index USING gin(document); 78 | 79 | -- And drop the old fields: 80 | ALTER TABLE posts DROP COLUMN author_name; 81 | ALTER TABLE posts DROP COLUMN author_email; 82 | ALTER TABLE threads DROP COLUMN author_name; 83 | ALTER TABLE threads DROP COLUMN author_email; 84 | -------------------------------------------------------------------------------- /migrations/2018-05-01-183232_simplified-post-view/down.sql: -------------------------------------------------------------------------------- 1 | DROP VIEW simple_posts; 2 | -------------------------------------------------------------------------------- /migrations/2018-05-01-183232_simplified-post-view/up.sql: -------------------------------------------------------------------------------- 1 | -- Creates a view for listing posts akin to the post table before 2 | -- splitting out users. This exists to avoid having to do joining 3 | -- logic and such inside of the application. 4 | 5 | CREATE VIEW simple_posts AS 6 | SELECT p.id AS id, 7 | thread_id, body, posted, user_id, 8 | users.name AS author_name, 9 | users.email AS author_email 10 | FROM posts p 11 | JOIN users ON users.id = p.user_id; 12 | -------------------------------------------------------------------------------- /migrations/2018-05-25-160648_add_closed_column/down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE threads DROP COLUMN closed; 2 | -------------------------------------------------------------------------------- /migrations/2018-05-25-160648_add_closed_column/up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE threads ADD COLUMN closed BOOLEAN NOT NULL DEFAULT false; 2 | -------------------------------------------------------------------------------- /migrations/2018-05-25-161939_add_closed_to_index/down.sql: -------------------------------------------------------------------------------- 1 | -- Update the index view: 2 | DROP VIEW thread_index; 3 | CREATE VIEW thread_index AS 4 | SELECT t.id AS thread_id, 5 | t.title AS title, 6 | ta.name AS thread_author, 7 | t.posted AS created, 8 | t.sticky AS sticky, 9 | p.id AS post_id, 10 | pa.name AS post_author, 11 | p.posted AS posted 12 | FROM threads t 13 | JOIN (SELECT DISTINCT ON (thread_id) 14 | id, thread_id, user_id, posted 15 | FROM posts 16 | ORDER BY thread_id, id DESC) AS p 17 | ON t.id = p.thread_id 18 | JOIN users ta ON ta.id = t.user_id 19 | JOIN users pa ON pa.id = p.user_id 20 | ORDER BY t.sticky DESC, p.id DESC; 21 | 22 | -- Update the post view: 23 | DROP VIEW simple_posts; 24 | CREATE VIEW simple_posts AS 25 | SELECT p.id AS id, 26 | thread_id, body, posted, user_id, 27 | users.name AS author_name, 28 | users.email AS author_email 29 | FROM posts p 30 | JOIN users ON users.id = p.user_id; 31 | -------------------------------------------------------------------------------- /migrations/2018-05-25-161939_add_closed_to_index/up.sql: -------------------------------------------------------------------------------- 1 | -- Update the index view: 2 | DROP VIEW thread_index; 3 | CREATE VIEW thread_index AS 4 | SELECT t.id AS thread_id, 5 | t.title AS title, 6 | ta.name AS thread_author, 7 | t.posted AS created, 8 | t.sticky AS sticky, 9 | t.closed AS closed, 10 | p.id AS post_id, 11 | pa.name AS post_author, 12 | p.posted AS posted 13 | FROM threads t 14 | JOIN (SELECT DISTINCT ON (thread_id) 15 | id, thread_id, user_id, posted 16 | FROM posts 17 | ORDER BY thread_id, id DESC) AS p 18 | ON t.id = p.thread_id 19 | JOIN users ta ON ta.id = t.user_id 20 | JOIN users pa ON pa.id = p.user_id 21 | ORDER BY t.sticky DESC, p.id DESC; 22 | 23 | -- Update post view: 24 | DROP VIEW simple_posts; 25 | CREATE VIEW simple_posts AS 26 | SELECT p.id AS id, 27 | thread_id, body, 28 | p.posted AS posted, 29 | p.user_id AS user_id, 30 | threads.closed AS closed, 31 | users.name AS author_name, 32 | users.email AS author_email 33 | FROM posts p 34 | JOIN users ON users.id = p.user_id 35 | JOIN threads ON threads.id = p.thread_id; 36 | -------------------------------------------------------------------------------- /src/db.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | //! This module implements the database connection actor. 20 | 21 | use actix::prelude::*; 22 | use diesel::{self, sql_query}; 23 | use diesel::sql_types::Text; 24 | use diesel::prelude::*; 25 | use diesel::r2d2::{Pool, ConnectionManager}; 26 | use models::*; 27 | use errors::{ConverseError, Result}; 28 | 29 | /// The DB actor itself. Several of these will be run in parallel by 30 | /// `SyncArbiter`. 31 | pub struct DbExecutor(pub Pool>); 32 | 33 | impl Actor for DbExecutor { 34 | type Context = SyncContext; 35 | } 36 | 37 | /// Message used to request a list of threads. 38 | /// TODO: This should support page numbers. 39 | pub struct ListThreads; 40 | message!(ListThreads, Result>); 41 | 42 | impl Handler for DbExecutor { 43 | type Result = ::Result; 44 | 45 | fn handle(&mut self, _: ListThreads, _: &mut Self::Context) -> Self::Result { 46 | use schema::thread_index::dsl::*; 47 | 48 | let conn = self.0.get()?; 49 | let results = thread_index 50 | .load::(&conn)?; 51 | Ok(results) 52 | } 53 | } 54 | 55 | /// Message used to look up a user based on their email-address. If 56 | /// the user does not exist, it is created. 57 | pub struct LookupOrCreateUser { 58 | pub email: String, 59 | pub name: String, 60 | } 61 | 62 | message!(LookupOrCreateUser, Result); 63 | 64 | impl Handler for DbExecutor { 65 | type Result = ::Result; 66 | 67 | fn handle(&mut self, 68 | msg: LookupOrCreateUser, 69 | _: &mut Self::Context) -> Self::Result { 70 | use schema::users; 71 | use schema::users::dsl::*; 72 | 73 | let conn = self.0.get()?; 74 | 75 | let opt_user = users 76 | .filter(email.eq(&msg.email)) 77 | .first(&conn).optional()?; 78 | 79 | if let Some(user) = opt_user { 80 | Ok(user) 81 | } else { 82 | let new_user = NewUser { 83 | email: msg.email, 84 | name: msg.name, 85 | }; 86 | 87 | let user: User = diesel::insert_into(users::table) 88 | .values(&new_user) 89 | .get_result(&conn)?; 90 | 91 | info!("Created new user {} with ID {}", new_user.email, user.id); 92 | 93 | Ok(user) 94 | } 95 | } 96 | } 97 | 98 | /// Message used to fetch a specific thread. Returns the thread and 99 | /// its posts. 100 | pub struct GetThread(pub i32); 101 | message!(GetThread, Result<(Thread, Vec)>); 102 | 103 | impl Handler for DbExecutor { 104 | type Result = ::Result; 105 | 106 | fn handle(&mut self, msg: GetThread, _: &mut Self::Context) -> Self::Result { 107 | use schema::threads::dsl::*; 108 | use schema::simple_posts::dsl::id; 109 | 110 | let conn = self.0.get()?; 111 | let thread_result: Thread = threads 112 | .find(msg.0).first(&conn)?; 113 | 114 | let post_list = SimplePost::belonging_to(&thread_result) 115 | .order_by(id.asc()) 116 | .load::(&conn)?; 117 | 118 | Ok((thread_result, post_list)) 119 | } 120 | } 121 | 122 | /// Message used to fetch a specific post. 123 | #[derive(Deserialize, Debug)] 124 | pub struct GetPost { pub id: i32 } 125 | 126 | message!(GetPost, Result); 127 | 128 | impl Handler for DbExecutor { 129 | type Result = ::Result; 130 | 131 | fn handle(&mut self, msg: GetPost, _: &mut Self::Context) -> Self::Result { 132 | use schema::simple_posts::dsl::*; 133 | let conn = self.0.get()?; 134 | Ok(simple_posts.find(msg.id).first(&conn)?) 135 | } 136 | } 137 | 138 | /// Message used to update the content of a post. 139 | #[derive(Deserialize)] 140 | pub struct UpdatePost { 141 | pub post_id: i32, 142 | pub post: String, 143 | } 144 | 145 | message!(UpdatePost, Result); 146 | 147 | impl Handler for DbExecutor { 148 | type Result = Result; 149 | 150 | fn handle(&mut self, msg: UpdatePost, _: &mut Self::Context) -> Self::Result { 151 | use schema::posts::dsl::*; 152 | let conn = self.0.get()?; 153 | let updated = diesel::update(posts.find(msg.post_id)) 154 | .set(body.eq(msg.post)) 155 | .get_result(&conn)?; 156 | 157 | Ok(updated) 158 | } 159 | } 160 | 161 | /// Message used to create a new thread 162 | pub struct CreateThread { 163 | pub new_thread: NewThread, 164 | pub post: String, 165 | } 166 | message!(CreateThread, Result); 167 | 168 | impl Handler for DbExecutor { 169 | type Result = ::Result; 170 | 171 | fn handle(&mut self, msg: CreateThread, _: &mut Self::Context) -> Self::Result { 172 | use schema::threads; 173 | use schema::posts; 174 | 175 | let conn = self.0.get()?; 176 | 177 | conn.transaction::(|| { 178 | // First insert the thread structure itself 179 | let thread: Thread = diesel::insert_into(threads::table) 180 | .values(&msg.new_thread) 181 | .get_result(&conn)?; 182 | 183 | // ... then create the first post in the thread. 184 | let new_post = NewPost { 185 | thread_id: thread.id, 186 | body: msg.post, 187 | user_id: msg.new_thread.user_id, 188 | }; 189 | 190 | diesel::insert_into(posts::table) 191 | .values(&new_post) 192 | .execute(&conn)?; 193 | 194 | Ok(thread) 195 | }) 196 | } 197 | } 198 | 199 | /// Message used to create a new reply 200 | pub struct CreatePost(pub NewPost); 201 | message!(CreatePost, Result); 202 | 203 | impl Handler for DbExecutor { 204 | type Result = ::Result; 205 | 206 | fn handle(&mut self, msg: CreatePost, _: &mut Self::Context) -> Self::Result { 207 | use schema::posts; 208 | 209 | let conn = self.0.get()?; 210 | 211 | let closed: bool = { 212 | use schema::threads::dsl::*; 213 | threads.select(closed) 214 | .find(msg.0.thread_id) 215 | .first(&conn)? 216 | }; 217 | 218 | if closed { 219 | return Err(ConverseError::ThreadClosed { 220 | id: msg.0.thread_id 221 | }) 222 | } 223 | 224 | Ok(diesel::insert_into(posts::table) 225 | .values(&msg.0) 226 | .get_result(&conn)?) 227 | } 228 | } 229 | 230 | /// Message used to search for posts 231 | #[derive(Deserialize)] 232 | pub struct SearchPosts { pub query: String } 233 | message!(SearchPosts, Result>); 234 | 235 | /// Raw PostgreSQL query used to perform full-text search on posts 236 | /// with a supplied phrase. For now, the query language is hardcoded 237 | /// to English and only "plain" queries (i.e. no searches for exact 238 | /// matches or more advanced query syntax) are supported. 239 | const SEARCH_QUERY: &'static str = r#" 240 | WITH search_query (query) AS (VALUES (plainto_tsquery('english', $1))) 241 | SELECT post_id, 242 | thread_id, 243 | author, 244 | title, 245 | ts_headline('english', body, query) AS headline 246 | FROM search_index, search_query 247 | WHERE document @@ query 248 | ORDER BY ts_rank(document, query) DESC 249 | LIMIT 50 250 | "#; 251 | 252 | impl Handler for DbExecutor { 253 | type Result = ::Result; 254 | 255 | fn handle(&mut self, msg: SearchPosts, _: &mut Self::Context) -> Self::Result { 256 | let conn = self.0.get()?; 257 | 258 | let search_results = sql_query(SEARCH_QUERY) 259 | .bind::(msg.query) 260 | .get_results::(&conn)?; 261 | 262 | Ok(search_results) 263 | } 264 | } 265 | 266 | /// Message that triggers a refresh of the view used for full-text 267 | /// searching. 268 | pub struct RefreshSearchView; 269 | message!(RefreshSearchView, Result<()>); 270 | 271 | const REFRESH_QUERY: &'static str = "REFRESH MATERIALIZED VIEW search_index"; 272 | 273 | impl Handler for DbExecutor { 274 | type Result = Result<()>; 275 | 276 | fn handle(&mut self, _: RefreshSearchView, _: &mut Self::Context) -> Self::Result { 277 | let conn = self.0.get()?; 278 | debug!("Refreshing search_index view in DB"); 279 | sql_query(REFRESH_QUERY).execute(&conn)?; 280 | Ok(()) 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | //! This module defines custom error types using the `failure`-crate. 20 | //! Links to foreign error types (such as database connection errors) 21 | //! are established in a similar way as was tradition in 22 | //! `error_chain`, albeit manually. 23 | 24 | use std::result; 25 | use actix_web::{ResponseError, HttpResponse}; 26 | use actix_web::http::StatusCode; 27 | 28 | // Modules with foreign errors: 29 | use actix; 30 | use actix_web; 31 | use askama; 32 | use diesel; 33 | use r2d2; 34 | use reqwest; 35 | use tokio_timer; 36 | 37 | pub type Result = result::Result; 38 | 39 | #[derive(Debug, Fail)] 40 | pub enum ConverseError { 41 | #[fail(display = "an internal Converse error occured: {}", reason)] 42 | InternalError { reason: String }, 43 | 44 | #[fail(display = "a database error occured: {}", error)] 45 | Database { error: diesel::result::Error }, 46 | 47 | #[fail(display = "a database connection pool error occured: {}", error)] 48 | ConnectionPool { error: r2d2::Error }, 49 | 50 | #[fail(display = "a template rendering error occured: {}", reason)] 51 | Template { reason: String }, 52 | 53 | #[fail(display = "error occured during request handling: {}", error)] 54 | ActixWeb { error: actix_web::Error }, 55 | 56 | #[fail(display = "error occured running timer: {}", error)] 57 | Timer { error: tokio_timer::Error }, 58 | 59 | #[fail(display = "user {} does not have permission to edit post {}", user, id)] 60 | PostEditForbidden { user: i32, id: i32 }, 61 | 62 | #[fail(display = "thread {} is closed and can not be responded to", id)] 63 | ThreadClosed { id: i32 }, 64 | 65 | // This variant is used as a catch-all for wrapping 66 | // actix-web-compatible response errors, such as the errors it 67 | // throws itself. 68 | #[fail(display = "Actix response error: {}", error)] 69 | Actix { error: Box }, 70 | } 71 | 72 | // Establish conversion links to foreign errors: 73 | 74 | impl From for ConverseError { 75 | fn from(error: diesel::result::Error) -> ConverseError { 76 | ConverseError::Database { error } 77 | } 78 | } 79 | 80 | impl From for ConverseError { 81 | fn from(error: r2d2::Error) -> ConverseError { 82 | ConverseError::ConnectionPool { error } 83 | } 84 | } 85 | 86 | impl From for ConverseError { 87 | fn from(error: askama::Error) -> ConverseError { 88 | ConverseError::Template { 89 | reason: format!("{}", error), 90 | } 91 | } 92 | } 93 | 94 | impl From for ConverseError { 95 | fn from(error: actix::MailboxError) -> ConverseError { 96 | ConverseError::Actix { error: Box::new(error) } 97 | } 98 | } 99 | 100 | impl From for ConverseError { 101 | fn from(error: actix_web::Error) -> ConverseError { 102 | ConverseError::ActixWeb { error } 103 | } 104 | } 105 | 106 | impl From for ConverseError { 107 | fn from(error: reqwest::Error) -> ConverseError { 108 | ConverseError::InternalError { 109 | reason: format!("Failed to make HTTP request: {}", error), 110 | } 111 | } 112 | } 113 | 114 | impl From for ConverseError { 115 | fn from(error: tokio_timer::Error) -> ConverseError { 116 | ConverseError::Timer { error } 117 | } 118 | } 119 | 120 | // Support conversion of error type into HTTP error responses: 121 | 122 | impl ResponseError for ConverseError { 123 | fn error_response(&self) -> HttpResponse { 124 | // Everything is mapped to internal server errors for now. 125 | match *self { 126 | ConverseError::ThreadClosed { id } => HttpResponse::SeeOther() 127 | .header("Location", format!("/thread/{}#post-reply", id)) 128 | .finish(), 129 | _ => HttpResponse::build(StatusCode::INTERNAL_SERVER_ERROR) 130 | .body(format!("An error occured: {}", self)) 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/handlers.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | //! This module contains the implementation of converse's actix-web 20 | //! HTTP handlers. 21 | //! 22 | //! Most handlers have an associated rendering function using one of 23 | //! the tera templates stored in the `/templates` directory in the 24 | //! project root. 25 | 26 | use actix::prelude::*; 27 | use actix_web::*; 28 | use actix_web::http::Method; 29 | use actix_web::middleware::identity::RequestIdentity; 30 | use actix_web::middleware::{Started, Middleware}; 31 | use actix_web; 32 | use db::*; 33 | use errors::ConverseError; 34 | use futures::Future; 35 | use mime_guess::guess_mime_type; 36 | use models::*; 37 | use oidc::*; 38 | use render::*; 39 | 40 | type ConverseResponse = Box>; 41 | 42 | const HTML: &'static str = "text/html"; 43 | const ANONYMOUS: i32 = 1; 44 | const NEW_THREAD_LENGTH_ERR: &'static str = "Title and body can not be empty!"; 45 | 46 | /// Represents the state carried by the web server actors. 47 | pub struct AppState { 48 | /// Address of the database actor 49 | pub db: Addr, 50 | 51 | /// Address of the OIDC actor 52 | pub oidc: Addr, 53 | 54 | /// Address of the rendering actor 55 | pub renderer: Addr, 56 | } 57 | 58 | pub fn forum_index(state: State) -> ConverseResponse { 59 | state.db.send(ListThreads) 60 | .flatten() 61 | .and_then(move |res| state.renderer.send(IndexPage { 62 | threads: res 63 | }).from_err()) 64 | .flatten() 65 | .map(|res| HttpResponse::Ok().content_type(HTML).body(res)) 66 | .responder() 67 | } 68 | 69 | /// Returns the ID of the currently logged in user. If there is no ID 70 | /// present, the ID of the anonymous user will be returned. 71 | pub fn get_user_id(req: &HttpRequest) -> i32 { 72 | if let Some(id) = req.identity() { 73 | // If this .expect() call is triggered, someone is likely 74 | // attempting to mess with their cookies. These requests can 75 | // be allowed to fail without further ado. 76 | id.parse().expect("Session cookie contained invalid data!") 77 | } else { 78 | ANONYMOUS 79 | } 80 | } 81 | 82 | /// This handler retrieves and displays a single forum thread. 83 | pub fn forum_thread(state: State, 84 | req: HttpRequest, 85 | thread_id: Path) -> ConverseResponse { 86 | let id = thread_id.into_inner(); 87 | let user = get_user_id(&req); 88 | 89 | state.db.send(GetThread(id)) 90 | .flatten() 91 | .and_then(move |res| state.renderer.send(ThreadPage { 92 | current_user: user, 93 | thread: res.0, 94 | posts: res.1, 95 | }).from_err()) 96 | .flatten() 97 | .map(|res| HttpResponse::Ok().content_type(HTML).body(res)) 98 | .responder() 99 | } 100 | 101 | /// This handler presents the user with the "New Thread" form. 102 | pub fn new_thread(state: State) -> ConverseResponse { 103 | state.renderer.send(NewThreadPage::default()).flatten() 104 | .map(|res| HttpResponse::Ok().content_type(HTML).body(res)) 105 | .responder() 106 | } 107 | 108 | #[derive(Deserialize)] 109 | pub struct NewThreadForm { 110 | pub title: String, 111 | pub post: String, 112 | } 113 | 114 | /// This handler receives a "New thread"-form and redirects the user 115 | /// to the new thread after creation. 116 | pub fn submit_thread(state: State, 117 | input: Form, 118 | req: HttpRequest) -> ConverseResponse { 119 | // Trim whitespace out of inputs: 120 | let input = NewThreadForm { 121 | title: input.title.trim().into(), 122 | post: input.post.trim().into(), 123 | }; 124 | 125 | // Perform simple validation and abort here if it fails: 126 | if input.title.is_empty() || input.post.is_empty() { 127 | return state.renderer 128 | .send(NewThreadPage { 129 | alerts: vec![NEW_THREAD_LENGTH_ERR], 130 | title: Some(input.title), 131 | post: Some(input.post), 132 | }) 133 | .flatten() 134 | .map(|res| HttpResponse::Ok().content_type(HTML).body(res)) 135 | .responder(); 136 | } 137 | 138 | let user_id = get_user_id(&req); 139 | 140 | let new_thread = NewThread { 141 | user_id, 142 | title: input.title, 143 | }; 144 | 145 | let msg = CreateThread { 146 | new_thread, 147 | post: input.post, 148 | }; 149 | 150 | state.db.send(msg) 151 | .from_err() 152 | .and_then(move |res| { 153 | let thread = res?; 154 | info!("Created new thread \"{}\" with ID {}", thread.title, thread.id); 155 | Ok(HttpResponse::SeeOther() 156 | .header("Location", format!("/thread/{}", thread.id)) 157 | .finish()) 158 | }) 159 | .responder() 160 | } 161 | 162 | #[derive(Deserialize)] 163 | pub struct NewPostForm { 164 | pub thread_id: i32, 165 | pub post: String, 166 | } 167 | 168 | /// This handler receives a "Reply"-form and redirects the user to the 169 | /// new post after creation. 170 | pub fn reply_thread(state: State, 171 | input: Form, 172 | req: HttpRequest) -> ConverseResponse { 173 | let user_id = get_user_id(&req); 174 | 175 | let new_post = NewPost { 176 | user_id, 177 | thread_id: input.thread_id, 178 | body: input.post.trim().into(), 179 | }; 180 | 181 | state.db.send(CreatePost(new_post)) 182 | .flatten() 183 | .from_err() 184 | .and_then(move |post| { 185 | info!("Posted reply {} to thread {}", post.id, post.thread_id); 186 | Ok(HttpResponse::SeeOther() 187 | .header("Location", format!("/thread/{}#post-{}", post.thread_id, post.id)) 188 | .finish()) 189 | }) 190 | .responder() 191 | } 192 | 193 | /// This handler presents the user with the form to edit a post. If 194 | /// the user attempts to edit a post that they do not have access to, 195 | /// they are currently ungracefully redirected back to the post 196 | /// itself. 197 | pub fn edit_form(state: State, 198 | req: HttpRequest, 199 | query: Path) -> ConverseResponse { 200 | let user_id = get_user_id(&req); 201 | 202 | state.db.send(query.into_inner()) 203 | .flatten() 204 | .from_err() 205 | .and_then(move |post| { 206 | if user_id != 1 && post.user_id == user_id { 207 | return Ok(post); 208 | } 209 | 210 | Err(ConverseError::PostEditForbidden { 211 | user: user_id, 212 | id: post.id, 213 | }) 214 | }) 215 | .and_then(move |post| { 216 | let edit_msg = EditPostPage { 217 | id: post.id, 218 | post: post.body, 219 | }; 220 | 221 | state.renderer.send(edit_msg).from_err() 222 | }) 223 | .flatten() 224 | .map(|page| HttpResponse::Ok().content_type(HTML).body(page)) 225 | .responder() 226 | } 227 | 228 | /// This handler "executes" an edit to a post if the current user owns 229 | /// the edited post. 230 | pub fn edit_post(state: State, 231 | req: HttpRequest, 232 | update: Form) -> ConverseResponse { 233 | let user_id = get_user_id(&req); 234 | 235 | state.db.send(GetPost { id: update.post_id }) 236 | .flatten() 237 | .from_err() 238 | .and_then(move |post| { 239 | if user_id != 1 && post.user_id == user_id { 240 | Ok(()) 241 | } else { 242 | Err(ConverseError::PostEditForbidden { 243 | user: user_id, 244 | id: post.id, 245 | }) 246 | } 247 | }) 248 | .and_then(move |_| state.db.send(update.0).from_err()) 249 | .flatten() 250 | .map(|updated| HttpResponse::SeeOther() 251 | .header("Location", format!("/thread/{}#post-{}", 252 | updated.thread_id, updated.id)) 253 | .finish()) 254 | .responder() 255 | } 256 | 257 | /// This handler executes a full-text search on the forum database and 258 | /// displays the results to the user. 259 | pub fn search_forum(state: State, 260 | query: Query) -> ConverseResponse { 261 | let query_string = query.query.clone(); 262 | state.db.send(query.into_inner()) 263 | .flatten() 264 | .and_then(move |results| state.renderer.send(SearchResultPage { 265 | results, 266 | query: query_string, 267 | }).from_err()) 268 | .flatten() 269 | .map(|res| HttpResponse::Ok().content_type(HTML).body(res)) 270 | .responder() 271 | } 272 | 273 | /// This handler initiates an OIDC login. 274 | pub fn login(state: State) -> ConverseResponse { 275 | state.oidc.send(GetLoginUrl) 276 | .from_err() 277 | .and_then(|url| Ok(HttpResponse::TemporaryRedirect() 278 | .header("Location", url) 279 | .finish())) 280 | .responder() 281 | } 282 | 283 | /// This handler handles an OIDC callback (i.e. completed login). 284 | /// 285 | /// Upon receiving the callback, a token is retrieved from the OIDC 286 | /// provider and a user lookup is performed. If a user with a matching 287 | /// email-address is found in the database, it is logged in - 288 | /// otherwise a new user is created. 289 | pub fn callback(state: State, 290 | data: Form, 291 | mut req: HttpRequest) -> ConverseResponse { 292 | state.oidc.send(RetrieveToken(data.0)).flatten() 293 | .map(|author| LookupOrCreateUser { 294 | email: author.email, 295 | name: author.name, 296 | }) 297 | .and_then(move |msg| state.db.send(msg).from_err()).flatten() 298 | .and_then(move |user| { 299 | info!("Completed login for user {} ({})", user.email, user.id); 300 | req.remember(user.id.to_string()); 301 | Ok(HttpResponse::SeeOther() 302 | .header("Location", "/") 303 | .finish())}) 304 | .responder() 305 | } 306 | 307 | /// This is an extension trait to enable easy serving of embedded 308 | /// static content. 309 | /// 310 | /// It is intended to be called with `include_bytes!()` when setting 311 | /// up the actix-web application. 312 | pub trait EmbeddedFile { 313 | fn static_file(self, path: &'static str, content: &'static [u8]) -> Self; 314 | } 315 | 316 | impl EmbeddedFile for App { 317 | fn static_file(self, path: &'static str, content: &'static [u8]) -> Self { 318 | self.route(path, Method::GET, move |_: HttpRequest<_>| { 319 | let mime = format!("{}", guess_mime_type(path)); 320 | HttpResponse::Ok() 321 | .content_type(mime.as_str()) 322 | .body(content) 323 | }) 324 | } 325 | } 326 | 327 | /// Middleware used to enforce logins unceremoniously. 328 | pub struct RequireLogin; 329 | 330 | impl Middleware for RequireLogin { 331 | fn start(&self, req: &mut HttpRequest) -> actix_web::Result { 332 | let logged_in = req.identity().is_some(); 333 | let is_oidc_req = req.path().starts_with("/oidc"); 334 | 335 | if !is_oidc_req && !logged_in { 336 | Ok(Started::Response( 337 | HttpResponse::SeeOther() 338 | .header("Location", "/oidc/login") 339 | .finish() 340 | )) 341 | } else { 342 | Ok(Started::Done) 343 | } 344 | } 345 | } 346 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | #[macro_use] 20 | extern crate askama; 21 | 22 | #[macro_use] 23 | extern crate diesel; 24 | 25 | #[macro_use] 26 | extern crate failure; 27 | 28 | #[macro_use] 29 | extern crate log; 30 | 31 | #[macro_use] 32 | extern crate serde_derive; 33 | 34 | extern crate actix; 35 | extern crate actix_web; 36 | extern crate chrono; 37 | extern crate comrak; 38 | extern crate env_logger; 39 | extern crate futures; 40 | extern crate hyper; 41 | extern crate md5; 42 | extern crate mime_guess; 43 | extern crate r2d2; 44 | extern crate rand; 45 | extern crate reqwest; 46 | extern crate serde; 47 | extern crate serde_json; 48 | extern crate tokio; 49 | extern crate tokio_timer; 50 | extern crate url; 51 | extern crate url_serde; 52 | 53 | /// Simple macro used to reduce boilerplate when defining actor 54 | /// message types. 55 | macro_rules! message { 56 | ( $t:ty, $r:ty ) => { 57 | impl Message for $t { 58 | type Result = $r; 59 | } 60 | } 61 | } 62 | 63 | pub mod db; 64 | pub mod errors; 65 | pub mod handlers; 66 | pub mod models; 67 | pub mod oidc; 68 | pub mod render; 69 | pub mod schema; 70 | 71 | use actix::prelude::*; 72 | use actix_web::*; 73 | use actix_web::http::Method; 74 | use actix_web::middleware::Logger; 75 | use actix_web::middleware::identity::{IdentityService, CookieIdentityPolicy}; 76 | use db::*; 77 | use diesel::pg::PgConnection; 78 | use diesel::r2d2::{ConnectionManager, Pool}; 79 | use handlers::*; 80 | use oidc::OidcExecutor; 81 | use rand::{OsRng, Rng}; 82 | use render::Renderer; 83 | use std::env; 84 | 85 | fn config(name: &str) -> String { 86 | env::var(name).expect(&format!("{} must be set", name)) 87 | } 88 | 89 | fn config_default(name: &str, default: &str) -> String { 90 | env::var(name).unwrap_or(default.into()) 91 | } 92 | 93 | fn start_db_executor() -> Addr { 94 | info!("Initialising database connection pool ..."); 95 | let db_url = config("DATABASE_URL"); 96 | 97 | let manager = ConnectionManager::::new(db_url); 98 | let pool = Pool::builder().build(manager).expect("Failed to initialise DB pool"); 99 | 100 | SyncArbiter::start(2, move || DbExecutor(pool.clone())) 101 | } 102 | 103 | fn schedule_search_refresh(db: Addr) { 104 | use tokio::prelude::*; 105 | use tokio::timer::Interval; 106 | use std::time::{Duration, Instant}; 107 | use std::thread; 108 | 109 | let task = Interval::new(Instant::now(), Duration::from_secs(60)) 110 | .from_err() 111 | .for_each(move |_| db.send(db::RefreshSearchView).flatten()) 112 | .map_err(|err| error!("Error while updating search view: {}", err)); 113 | 114 | thread::spawn(|| tokio::run(task)); 115 | } 116 | 117 | fn start_oidc_executor(base_url: &str) -> Addr { 118 | info!("Initialising OIDC integration ..."); 119 | let oidc_url = config("OIDC_DISCOVERY_URL"); 120 | let oidc_config = oidc::load_oidc(&oidc_url) 121 | .expect("Failed to retrieve OIDC discovery document"); 122 | 123 | let oidc = oidc::OidcExecutor { 124 | oidc_config, 125 | client_id: config("OIDC_CLIENT_ID"), 126 | client_secret: config("OIDC_CLIENT_SECRET"), 127 | redirect_uri: format!("{}/oidc/callback", base_url), 128 | }; 129 | 130 | oidc.start() 131 | } 132 | 133 | fn start_renderer() -> Addr { 134 | let comrak = comrak::ComrakOptions{ 135 | github_pre_lang: true, 136 | ext_strikethrough: true, 137 | ext_table: true, 138 | ext_autolink: true, 139 | ext_tasklist: true, 140 | ext_footnotes: true, 141 | ext_tagfilter: true, 142 | ..Default::default() 143 | }; 144 | 145 | Renderer{ comrak }.start() 146 | } 147 | 148 | fn gen_session_key() -> [u8; 64] { 149 | let mut key_bytes = [0; 64]; 150 | let mut rng = OsRng::new() 151 | .expect("Failed to retrieve RNG for key generation"); 152 | rng.fill_bytes(&mut key_bytes); 153 | 154 | key_bytes 155 | } 156 | 157 | fn start_http_server(base_url: String, 158 | db_addr: Addr, 159 | oidc_addr: Addr, 160 | renderer_addr: Addr) { 161 | info!("Initialising HTTP server ..."); 162 | let bind_host = config_default("CONVERSE_BIND_HOST", "127.0.0.1:4567"); 163 | let key = gen_session_key(); 164 | let require_login = config_default("REQUIRE_LOGIN", "true".into()) == "true"; 165 | 166 | server::new(move || { 167 | let state = AppState { 168 | db: db_addr.clone(), 169 | oidc: oidc_addr.clone(), 170 | renderer: renderer_addr.clone(), 171 | }; 172 | 173 | let identity = IdentityService::new( 174 | CookieIdentityPolicy::new(&key) 175 | .name("converse_auth") 176 | .path("/") 177 | .secure(base_url.starts_with("https")) 178 | ); 179 | 180 | let app = App::with_state(state) 181 | .middleware(Logger::default()) 182 | .middleware(identity) 183 | .resource("/", |r| r.method(Method::GET).with(forum_index)) 184 | .resource("/thread/new", |r| r.method(Method::GET).with(new_thread)) 185 | .resource("/thread/submit", |r| r.method(Method::POST).with3(submit_thread)) 186 | .resource("/thread/reply", |r| r.method(Method::POST).with3(reply_thread)) 187 | .resource("/thread/{id}", |r| r.method(Method::GET).with3(forum_thread)) 188 | .resource("/post/{id}/edit", |r| r.method(Method::GET).with3(edit_form)) 189 | .resource("/post/edit", |r| r.method(Method::POST).with3(edit_post)) 190 | .resource("/search", |r| r.method(Method::GET).with2(search_forum)) 191 | .resource("/oidc/login", |r| r.method(Method::GET).with(login)) 192 | .resource("/oidc/callback", |r| r.method(Method::POST).with3(callback)) 193 | .static_file("/static/highlight.css", include_bytes!("../static/highlight.css")) 194 | .static_file("/static/highlight.js", include_bytes!("../static/highlight.js")) 195 | .static_file("/static/styles.css", include_bytes!("../static/styles.css")); 196 | 197 | if require_login { 198 | app.middleware(RequireLogin) 199 | } else { 200 | app 201 | }}) 202 | .bind(&bind_host).expect(&format!("Could not bind on '{}'", bind_host)) 203 | .start(); 204 | } 205 | 206 | fn main() { 207 | env_logger::init(); 208 | 209 | info!("Welcome to Converse! Hold on tight while we're getting ready."); 210 | let sys = actix::System::new("converse"); 211 | 212 | let base_url = config("BASE_URL"); 213 | 214 | let db_addr = start_db_executor(); 215 | let oidc_addr = start_oidc_executor(&base_url); 216 | let renderer_addr = start_renderer(); 217 | 218 | schedule_search_refresh(db_addr.clone()); 219 | 220 | start_http_server(base_url, db_addr, oidc_addr, renderer_addr); 221 | 222 | sys.run(); 223 | } 224 | -------------------------------------------------------------------------------- /src/models.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | use chrono::prelude::{DateTime, Utc}; 20 | use schema::{users, threads, posts, simple_posts}; 21 | use diesel::sql_types::{Text, Integer}; 22 | 23 | /// Represents a single user in the Converse database. Converse does 24 | /// not handle logins itself, but rather looks them up based on the 25 | /// email address received from an OIDC provider. 26 | #[derive(Identifiable, Queryable, Serialize)] 27 | pub struct User { 28 | pub id: i32, 29 | pub name: String, 30 | pub email: String, 31 | pub admin: bool, 32 | } 33 | 34 | #[derive(Identifiable, Queryable, Serialize, Associations)] 35 | #[belongs_to(User)] 36 | pub struct Thread { 37 | pub id: i32, 38 | pub title: String, 39 | pub posted: DateTime, 40 | pub sticky: bool, 41 | pub user_id: i32, 42 | pub closed: bool, 43 | } 44 | 45 | #[derive(Identifiable, Queryable, Serialize, Associations)] 46 | #[belongs_to(Thread)] 47 | #[belongs_to(User)] 48 | pub struct Post { 49 | pub id: i32, 50 | pub thread_id: i32, 51 | pub body: String, 52 | pub posted: DateTime, 53 | pub user_id: i32, 54 | } 55 | 56 | /// This struct is used as the query result type for the simplified 57 | /// post view, which already joins user information in the database. 58 | #[derive(Identifiable, Queryable, Serialize, Associations)] 59 | #[belongs_to(Thread)] 60 | pub struct SimplePost { 61 | pub id: i32, 62 | pub thread_id: i32, 63 | pub body: String, 64 | pub posted: DateTime, 65 | pub user_id: i32, 66 | pub closed: bool, 67 | pub author_name: String, 68 | pub author_email: String, 69 | } 70 | 71 | /// This struct is used as the query result type for the thread index 72 | /// view, which lists the index of threads ordered by the last post in 73 | /// each thread. 74 | #[derive(Queryable, Serialize)] 75 | pub struct ThreadIndex { 76 | pub thread_id: i32, 77 | pub title: String, 78 | pub thread_author: String, 79 | pub created: DateTime, 80 | pub sticky: bool, 81 | pub closed: bool, 82 | pub post_id: i32, 83 | pub post_author: String, 84 | pub posted: DateTime, 85 | } 86 | 87 | #[derive(Deserialize, Insertable)] 88 | #[table_name="threads"] 89 | pub struct NewThread { 90 | pub title: String, 91 | pub user_id: i32, 92 | } 93 | 94 | #[derive(Deserialize, Insertable)] 95 | #[table_name="users"] 96 | pub struct NewUser { 97 | pub email: String, 98 | pub name: String, 99 | } 100 | 101 | #[derive(Deserialize, Insertable)] 102 | #[table_name="posts"] 103 | pub struct NewPost { 104 | pub thread_id: i32, 105 | pub body: String, 106 | pub user_id: i32, 107 | } 108 | 109 | /// This struct models the response of a full-text search query. It 110 | /// does not use a table/schema definition struct like the other 111 | /// tables, as no table of this type actually exists. 112 | #[derive(QueryableByName, Debug, Serialize)] 113 | pub struct SearchResult { 114 | #[sql_type = "Integer"] 115 | pub post_id: i32, 116 | #[sql_type = "Integer"] 117 | pub thread_id: i32, 118 | #[sql_type = "Text"] 119 | pub author: String, 120 | #[sql_type = "Text"] 121 | pub title: String, 122 | 123 | /// Headline represents the result of Postgres' ts_headline() 124 | /// function, which highlights search terms in the search results. 125 | #[sql_type = "Text"] 126 | pub headline: String, 127 | } 128 | -------------------------------------------------------------------------------- /src/oidc.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | //! This module provides authentication via OIDC compliant 20 | //! authentication sources. 21 | //! 22 | //! Currently Converse only supports a single OIDC provider. Note that 23 | //! this has so far only been tested with Office365. 24 | 25 | use actix::prelude::*; 26 | use reqwest; 27 | use url::Url; 28 | use url_serde; 29 | use errors::*; 30 | use reqwest::header::Authorization; 31 | use hyper::header::Bearer; 32 | 33 | /// This structure represents the contents of an OIDC discovery 34 | /// document. 35 | #[derive(Deserialize, Debug, Clone)] 36 | pub struct OidcConfig { 37 | #[serde(with = "url_serde")] 38 | authorization_endpoint: Url, 39 | token_endpoint: String, 40 | userinfo_endpoint: String, 41 | 42 | scopes_supported: Vec, 43 | issuer: String, 44 | } 45 | 46 | #[derive(Clone, Debug)] 47 | pub struct OidcExecutor { 48 | pub client_id: String, 49 | pub client_secret: String, 50 | pub redirect_uri: String, 51 | pub oidc_config: OidcConfig, 52 | } 53 | 54 | /// This struct represents the form response returned by an OIDC 55 | /// provider with the `code`. 56 | #[derive(Debug, Deserialize)] 57 | pub struct CodeResponse { 58 | pub code: String, 59 | } 60 | 61 | /// This struct represents the data extracted from the ID token and 62 | /// stored in the user's session. 63 | #[derive(Debug, Serialize, Deserialize)] 64 | pub struct Author { 65 | pub name: String, 66 | pub email: String, 67 | } 68 | 69 | impl Actor for OidcExecutor { 70 | type Context = Context; 71 | } 72 | 73 | /// Message used to request the login URL: 74 | pub struct GetLoginUrl; // TODO: Add a nonce parameter stored in session. 75 | message!(GetLoginUrl, String); 76 | 77 | impl Handler for OidcExecutor { 78 | type Result = String; 79 | 80 | fn handle(&mut self, _: GetLoginUrl, _: &mut Self::Context) -> Self::Result { 81 | let mut url: Url = self.oidc_config.authorization_endpoint.clone(); 82 | { 83 | let mut params = url.query_pairs_mut(); 84 | params.append_pair("client_id", &self.client_id); 85 | params.append_pair("response_type", "code"); 86 | params.append_pair("scope", "openid"); 87 | params.append_pair("redirect_uri", &self.redirect_uri); 88 | params.append_pair("response_mode", "form_post"); 89 | } 90 | return url.into_string(); 91 | } 92 | } 93 | 94 | /// Message used to request the token from the returned code and 95 | /// retrieve userinfo from the appropriate endpoint. 96 | pub struct RetrieveToken(pub CodeResponse); 97 | message!(RetrieveToken, Result); 98 | 99 | #[derive(Debug, Deserialize)] 100 | struct TokenResponse { 101 | access_token: String, 102 | } 103 | 104 | // TODO: This is currently hardcoded to Office365 fields. 105 | #[derive(Debug, Deserialize)] 106 | struct Userinfo { 107 | name: String, 108 | unique_name: String, // email in office365 109 | } 110 | 111 | impl Handler for OidcExecutor { 112 | type Result = Result; 113 | 114 | fn handle(&mut self, msg: RetrieveToken, _: &mut Self::Context) -> Self::Result { 115 | debug!("Received OAuth2 code, requesting access_token"); 116 | let client = reqwest::Client::new(); 117 | let params: [(&str, &str); 5] = [ 118 | ("client_id", &self.client_id), 119 | ("client_secret", &self.client_secret), 120 | ("grant_type", "authorization_code"), 121 | ("code", &msg.0.code), 122 | ("redirect_uri", &self.redirect_uri), 123 | ]; 124 | 125 | let mut response = client.post(&self.oidc_config.token_endpoint) 126 | .form(¶ms) 127 | .send()?; 128 | 129 | debug!("Received token response: {:?}", response); 130 | let token: TokenResponse = response.json()?; 131 | 132 | let user: Userinfo = client.get(&self.oidc_config.userinfo_endpoint) 133 | .header(Authorization(Bearer { token: token.access_token })) 134 | .send()? 135 | .json()?; 136 | 137 | Ok(Author { 138 | name: user.name, 139 | email: user.unique_name, 140 | }) 141 | } 142 | } 143 | 144 | /// Convenience function to attempt loading an OIDC discovery document 145 | /// from a specified URL: 146 | pub fn load_oidc(url: &str) -> Result { 147 | let config: OidcConfig = reqwest::get(url)?.json()?; 148 | Ok(config) 149 | } 150 | -------------------------------------------------------------------------------- /src/render.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | //! This module defines a rendering actor used for processing Converse 20 | //! data into whatever format is needed by the templates and rendering 21 | //! them. 22 | 23 | use actix::prelude::*; 24 | use askama::Template; 25 | use errors::*; 26 | use std::fmt; 27 | use md5; 28 | use models::*; 29 | use chrono::prelude::{DateTime, Utc}; 30 | use comrak::{ComrakOptions, markdown_to_html}; 31 | 32 | pub struct Renderer { 33 | pub comrak: ComrakOptions, 34 | } 35 | 36 | impl Actor for Renderer { 37 | type Context = actix::Context; 38 | } 39 | 40 | /// Represents a data formatted for human consumption 41 | #[derive(Debug)] 42 | struct FormattedDate(DateTime); 43 | 44 | impl fmt::Display for FormattedDate { 45 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 46 | write!(f, "{}", self.0.format("%a %d %B %Y, %R")) 47 | } 48 | } 49 | 50 | /// Message used to render the index page. 51 | pub struct IndexPage { 52 | pub threads: Vec, 53 | } 54 | message!(IndexPage, Result); 55 | 56 | #[derive(Debug)] 57 | struct IndexThread { 58 | id: i32, 59 | title: String, 60 | sticky: bool, 61 | closed: bool, 62 | posted: FormattedDate, 63 | author_name: String, 64 | post_author: String, 65 | } 66 | 67 | #[derive(Template)] 68 | #[template(path = "index.html")] 69 | struct IndexPageTemplate { 70 | threads: Vec, 71 | } 72 | 73 | impl Handler for Renderer { 74 | type Result = Result; 75 | 76 | fn handle(&mut self, msg: IndexPage, _: &mut Self::Context) -> Self::Result { 77 | let threads: Vec = msg.threads 78 | .into_iter() 79 | .map(|thread| IndexThread { 80 | id: thread.thread_id, 81 | title: thread.title, // escape_html(&thread.title), 82 | sticky: thread.sticky, 83 | closed: thread.closed, 84 | posted: FormattedDate(thread.posted), 85 | author_name: thread.thread_author, 86 | post_author: thread.post_author, 87 | }) 88 | .collect(); 89 | 90 | let tpl = IndexPageTemplate { 91 | threads 92 | }; 93 | 94 | tpl.render().map_err(|e| e.into()) 95 | } 96 | } 97 | 98 | /// Message used to render a thread. 99 | pub struct ThreadPage { 100 | pub current_user: i32, 101 | pub thread: Thread, 102 | pub posts: Vec, 103 | } 104 | message!(ThreadPage, Result); 105 | 106 | // "Renderable" structures with data transformations applied. 107 | #[derive(Debug)] 108 | struct RenderablePost { 109 | id: i32, 110 | body: String, 111 | posted: FormattedDate, 112 | author_name: String, 113 | author_gravatar: String, 114 | editable: bool, 115 | } 116 | 117 | /// This structure represents the transformed thread data with 118 | /// Markdown rendering and other changes applied. 119 | #[derive(Template)] 120 | #[template(path = "thread.html")] 121 | struct RenderableThreadPage { 122 | id: i32, 123 | title: String, 124 | closed: bool, 125 | posts: Vec, 126 | } 127 | 128 | /// Helper function for computing Gravatar links. 129 | fn md5_hex(input: &[u8]) -> String { 130 | format!("{:x}", md5::compute(input)) 131 | } 132 | 133 | fn prepare_thread(comrak: &ComrakOptions, page: ThreadPage) -> RenderableThreadPage { 134 | let user = page.current_user; 135 | 136 | let posts = page.posts.into_iter().map(|post| { 137 | let editable = user != 1 && post.user_id == user; 138 | 139 | RenderablePost { 140 | id: post.id, 141 | body: markdown_to_html(&post.body, comrak), 142 | posted: FormattedDate(post.posted), 143 | author_name: post.author_name.clone(), 144 | author_gravatar: md5_hex(post.author_email.as_bytes()), 145 | editable, 146 | } 147 | }).collect(); 148 | 149 | RenderableThreadPage { 150 | posts, 151 | closed: page.thread.closed, 152 | id: page.thread.id, 153 | title: page.thread.title, 154 | } 155 | } 156 | 157 | impl Handler for Renderer { 158 | type Result = Result; 159 | 160 | fn handle(&mut self, msg: ThreadPage, _: &mut Self::Context) -> Self::Result { 161 | let renderable = prepare_thread(&self.comrak, msg); 162 | renderable.render().map_err(|e| e.into()) 163 | } 164 | } 165 | 166 | /// The different types of editing modes supported by the editing 167 | /// template: 168 | #[derive(Debug, PartialEq)] 169 | pub enum EditingMode { 170 | NewThread, 171 | PostReply, 172 | EditPost, 173 | } 174 | 175 | impl Default for EditingMode { 176 | fn default() -> EditingMode { EditingMode::NewThread } 177 | } 178 | 179 | /// This is the template used for rendering the new thread, edit post 180 | /// and reply to thread forms. 181 | #[derive(Template, Default)] 182 | #[template(path = "post.html")] 183 | pub struct FormTemplate { 184 | /// Which editing mode is to be used by the template? 185 | pub mode: EditingMode, 186 | 187 | /// Potential alerts to display to the user (e.g. input validation 188 | /// results) 189 | pub alerts: Vec<&'static str>, 190 | 191 | /// Either the title to be used in the subject field or the title 192 | /// of the thread the user is responding to. 193 | pub title: Option, 194 | 195 | /// Body of the post being edited, if present. 196 | pub post: Option, 197 | 198 | /// ID of the thread being replied to or the post being edited. 199 | pub id: Option, 200 | } 201 | 202 | /// Message used to render new thread page. 203 | /// 204 | /// It can optionally contain a vector of warnings to display to the 205 | /// user in alert boxes, such as input validation errors. 206 | #[derive(Default)] 207 | pub struct NewThreadPage { 208 | pub alerts: Vec<&'static str>, 209 | pub title: Option, 210 | pub post: Option, 211 | } 212 | message!(NewThreadPage, Result); 213 | 214 | impl Handler for Renderer { 215 | type Result = Result; 216 | 217 | fn handle(&mut self, msg: NewThreadPage, _: &mut Self::Context) -> Self::Result { 218 | let ctx = FormTemplate { 219 | alerts: msg.alerts, 220 | title: msg.title, 221 | post: msg.post, 222 | ..Default::default() 223 | }; 224 | ctx.render().map_err(|e| e.into()) 225 | } 226 | } 227 | 228 | /// Message used to render post editing page. 229 | pub struct EditPostPage { 230 | pub id: i32, 231 | pub post: String, 232 | } 233 | message!(EditPostPage, Result); 234 | 235 | impl Handler for Renderer { 236 | type Result = Result; 237 | 238 | fn handle(&mut self, msg: EditPostPage, _: &mut Self::Context) -> Self::Result { 239 | let ctx = FormTemplate { 240 | mode: EditingMode::EditPost, 241 | id: Some(msg.id), 242 | post: Some(msg.post), 243 | ..Default::default() 244 | }; 245 | 246 | ctx.render().map_err(|e| e.into()) 247 | } 248 | } 249 | 250 | /// Message used to render search results 251 | #[derive(Template)] 252 | #[template(path = "search.html")] 253 | pub struct SearchResultPage { 254 | pub query: String, 255 | pub results: Vec, 256 | } 257 | message!(SearchResultPage, Result); 258 | 259 | impl Handler for Renderer { 260 | type Result = Result; 261 | 262 | fn handle(&mut self, msg: SearchResultPage, _: &mut Self::Context) -> Self::Result { 263 | msg.render().map_err(|e| e.into()) 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /src/schema.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Vincent Ambo 2 | // 3 | // This file is part of Converse. 4 | // 5 | // Converse is free software: you can redistribute it and/or modify it 6 | // under the terms of the GNU Affero General Public License as 7 | // published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, but 11 | // WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | // Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public 16 | // License along with this program. If not, see 17 | // . 18 | 19 | table! { 20 | posts (id) { 21 | id -> Int4, 22 | thread_id -> Int4, 23 | body -> Text, 24 | posted -> Timestamptz, 25 | user_id -> Int4, 26 | } 27 | } 28 | 29 | table! { 30 | threads (id) { 31 | id -> Int4, 32 | title -> Varchar, 33 | posted -> Timestamptz, 34 | sticky -> Bool, 35 | user_id -> Int4, 36 | closed -> Bool, 37 | } 38 | } 39 | 40 | table! { 41 | users (id) { 42 | id -> Int4, 43 | email -> Varchar, 44 | name -> Varchar, 45 | admin -> Bool, 46 | } 47 | } 48 | 49 | // Note: Manually inserted as print-schema does not add views. 50 | table! { 51 | simple_posts (id) { 52 | id -> Int4, 53 | thread_id -> Int4, 54 | body -> Text, 55 | posted -> Timestamptz, 56 | user_id -> Int4, 57 | closed -> Bool, 58 | author_name -> Text, 59 | author_email -> Text, 60 | } 61 | } 62 | 63 | // Note: Manually inserted as print-schema does not add views. 64 | table! { 65 | thread_index (thread_id) { 66 | thread_id -> Int4, 67 | title -> Text, 68 | thread_author -> Text, 69 | created -> Timestamptz, 70 | sticky -> Bool, 71 | closed -> Bool, 72 | post_id -> Int4, 73 | post_author -> Text, 74 | posted -> Timestamptz, 75 | } 76 | } 77 | 78 | joinable!(posts -> threads (thread_id)); 79 | joinable!(posts -> users (user_id)); 80 | joinable!(threads -> users (user_id)); 81 | joinable!(simple_posts -> threads (thread_id)); 82 | 83 | allow_tables_to_appear_in_same_query!( 84 | posts, 85 | threads, 86 | users, 87 | simple_posts, 88 | ); 89 | -------------------------------------------------------------------------------- /static/highlight.css: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | github.com style (c) Vasily Polovnyov 4 | 5 | */ 6 | 7 | .hljs { 8 | display: block; 9 | overflow-x: auto; 10 | padding: 0.5em; 11 | color: #333; 12 | background: #f8f8f8; 13 | } 14 | 15 | .hljs-comment, 16 | .hljs-quote { 17 | color: #998; 18 | font-style: italic; 19 | } 20 | 21 | .hljs-keyword, 22 | .hljs-selector-tag, 23 | .hljs-subst { 24 | color: #333; 25 | font-weight: bold; 26 | } 27 | 28 | .hljs-number, 29 | .hljs-literal, 30 | .hljs-variable, 31 | .hljs-template-variable, 32 | .hljs-tag .hljs-attr { 33 | color: #008080; 34 | } 35 | 36 | .hljs-string, 37 | .hljs-doctag { 38 | color: #d14; 39 | } 40 | 41 | .hljs-title, 42 | .hljs-section, 43 | .hljs-selector-id { 44 | color: #900; 45 | font-weight: bold; 46 | } 47 | 48 | .hljs-subst { 49 | font-weight: normal; 50 | } 51 | 52 | .hljs-type, 53 | .hljs-class .hljs-title { 54 | color: #458; 55 | font-weight: bold; 56 | } 57 | 58 | .hljs-tag, 59 | .hljs-name, 60 | .hljs-attribute { 61 | color: #000080; 62 | font-weight: normal; 63 | } 64 | 65 | .hljs-regexp, 66 | .hljs-link { 67 | color: #009926; 68 | } 69 | 70 | .hljs-symbol, 71 | .hljs-bullet { 72 | color: #990073; 73 | } 74 | 75 | .hljs-built_in, 76 | .hljs-builtin-name { 77 | color: #0086b3; 78 | } 79 | 80 | .hljs-meta { 81 | color: #999; 82 | font-weight: bold; 83 | } 84 | 85 | .hljs-deletion { 86 | background: #fdd; 87 | } 88 | 89 | .hljs-addition { 90 | background: #dfd; 91 | } 92 | 93 | .hljs-emphasis { 94 | font-style: italic; 95 | } 96 | 97 | .hljs-strong { 98 | font-weight: bold; 99 | } 100 | -------------------------------------------------------------------------------- /static/highlight.js: -------------------------------------------------------------------------------- 1 | /*! highlight.js v9.12.0 | BSD3 License | git.io/hljslicense */ 2 | !function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/g,"&").replace(//g,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=B.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset"}function u(e){s+=""}function c(e){("start"===e.event?o:u)(e.node)}for(var l=0,s="",f=[];e.length||r.length;){var g=i();if(s+=n(a.substring(l,g[0].offset)),l=g[0].offset,g===e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===l);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return s+n(a.substr(l))}function l(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW&&[o(e)]||[e]}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},u=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?u("keyword",a.k):x(a.k).forEach(function(e){u(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return l("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var c=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=c.length?t(c.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function l(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function p(e,n,t,r){var a=r?"":I.classPrefix,i='',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=l(E,r),e?(B+=e[1],a+=p(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function d(){var e="string"==typeof E.sL;if(e&&!y[E.sL])return n(k);var t=e?f(E.sL,k,!0,x[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0&&(B+=t.r),e&&(x[E.sL]=t.top),p(t.language,t.value,!1,!0)}function b(){L+=null!=E.sL?d():h(),k=""}function v(e){L+=e.cN?p(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function m(e,n){if(k+=e,null==n)return b(),0;var t=o(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),b(),t.rB||t.eB||(k=n)),v(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),b(),a.eE&&(k=n));do E.cN&&(L+=C),E.skip||(B+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"")+'"');return k+=n,n.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,E=i||N,x={},L="";for(R=E;R!==N;R=R.parent)R.cN&&(L=p(R.cN,"",!0)+L);var k="",B=0;try{for(var M,j,O=0;;){if(E.t.lastIndex=O,M=E.t.exec(t),!M)break;j=m(t.substring(O,M.index),M[0]),O=M.index+j}for(m(t.substr(O)),R=E;R.parent;R=R.parent)R.cN&&(L+=C);return{r:B,value:L,language:e,top:E}}catch(T){if(T.message&&-1!==T.message.indexOf("Illegal"))return{r:0,value:n(t)};throw T}}function g(e,t){t=t||I.languages||x(y);var r={r:0,value:n(e)},a=r;return t.filter(w).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function p(e){return I.tabReplace||I.useBR?e.replace(M,function(e,n){return I.useBR&&"\n"===e?"
":I.tabReplace?n.replace(/\t/g,I.tabReplace):""}):e}function h(e,n,t){var r=n?L[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function d(e){var n,t,r,o,l,s=i(e);a(s)||(I.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):n=e,l=n.textContent,r=s?f(s,l,!0):g(l),t=u(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=c(t,u(o),l)),r.value=p(r.value),e.innerHTML=r.value,e.className=h(e.className,s,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function b(e){I=o(I,e)}function v(){if(!v.called){v.called=!0;var e=document.querySelectorAll("pre code");E.forEach.call(e,d)}}function m(){addEventListener("DOMContentLoaded",v,!1),addEventListener("load",v,!1)}function N(n,t){var r=y[n]=t(e);r.aliases&&r.aliases.forEach(function(e){L[e]=n})}function R(){return x(y)}function w(e){return e=(e||"").toLowerCase(),y[e]||y[L[e]]}var E=[],x=Object.keys,y={},L={},k=/^(no-?highlight|plain|text)$/i,B=/\blang(?:uage)?-([\w-]+)\b/i,M=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,C="
",I={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=f,e.highlightAuto=g,e.fixMarkup=p,e.highlightBlock=d,e.configure=b,e.initHighlighting=v,e.initHighlightingOnLoad=m,e.registerLanguage=N,e.listLanguages=R,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("erlang",function(e){var r="[a-z'][a-zA-Z0-9_']*",c="("+r+":"+r+"|"+r+")",b={keyword:"after and andalso|10 band begin bnot bor bsl bzr bxor case catch cond div end fun if let not of orelse|10 query receive rem try when xor",literal:"false true"},i=e.C("%","$"),n={cN:"number",b:"\\b(\\d+#[a-fA-F0-9]+|\\d+(\\.\\d+)?([eE][-+]?\\d+)?)",r:0},a={b:"fun\\s+"+r+"/\\d+"},d={b:c+"\\(",e:"\\)",rB:!0,r:0,c:[{b:c,r:0},{b:"\\(",e:"\\)",eW:!0,rE:!0,r:0}]},o={b:"{",e:"}",r:0},t={b:"\\b_([A-Z][A-Za-z0-9_]*)?",r:0},f={b:"[A-Z][a-zA-Z0-9_]*",r:0},l={b:"#"+e.UIR,r:0,rB:!0,c:[{b:"#"+e.UIR,r:0},{b:"{",e:"}",r:0}]},s={bK:"fun receive if try case",e:"end",k:b};s.c=[i,a,e.inherit(e.ASM,{cN:""}),s,d,e.QSM,n,o,t,f,l];var u=[i,a,s,d,e.QSM,n,o,t,f,l];d.c[1].c=u,o.c=u,l.c[1].c=u;var h={cN:"params",b:"\\(",e:"\\)",c:u};return{aliases:["erl"],k:b,i:"(",rB:!0,i:"\\(|#|//|/\\*|\\\\|:|;",c:[h,e.inherit(e.TM,{b:r})],starts:{e:";|\\.",k:b,c:u}},i,{b:"^-",e:"\\.",r:0,eE:!0,rB:!0,l:"-"+e.IR,k:"-module -record -undef -export -ifdef -ifndef -author -copyright -doc -vsn -import -include -include_lib -compile -define -else -endif -file -behaviour -behavior -spec",c:[h]},n,e.QSM,l,t,f,o,{b:/\.$/}]}});hljs.registerLanguage("cs",function(e){var i={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},t={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},r=e.inherit(t,{i:/\n/}),a={cN:"subst",b:"{",e:"}",k:i},c=e.inherit(a,{i:/\n/}),n={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,c]},s={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},a]},o=e.inherit(s,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},c]});a.c=[s,n,t,e.ASM,e.QSM,e.CNM,e.CBCM],c.c=[o,n,r,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[s,n,t,e.ASM,e.QSM]},b=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp"],k:i,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:""},{b:""}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",r:0},{cN:"function",b:"("+b+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:i,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:i,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("swift",function(e){var i={keyword:"__COLUMN__ __FILE__ __FUNCTION__ __LINE__ as as! as? associativity break case catch class continue convenience default defer deinit didSet do dynamic dynamicType else enum extension fallthrough false fileprivate final for func get guard if import in indirect infix init inout internal is lazy left let mutating nil none nonmutating open operator optional override postfix precedence prefix private protocol Protocol public repeat required rethrows return right self Self set static struct subscript super switch throw throws true try try! try? Type typealias unowned var weak where while willSet",literal:"true false nil",built_in:"abs advance alignof alignofValue anyGenerator assert assertionFailure bridgeFromObjectiveC bridgeFromObjectiveCUnconditional bridgeToObjectiveC bridgeToObjectiveCUnconditional c contains count countElements countLeadingZeros debugPrint debugPrintln distance dropFirst dropLast dump encodeBitsAsWords enumerate equal fatalError filter find getBridgedObjectiveCType getVaList indices insertionSort isBridgedToObjectiveC isBridgedVerbatimToObjectiveC isUniquelyReferenced isUniquelyReferencedNonObjC join lazy lexicographicalCompare map max maxElement min minElement numericCast overlaps partition posix precondition preconditionFailure print println quickSort readLine reduce reflect reinterpretCast reverse roundUpToAlignment sizeof sizeofValue sort split startsWith stride strideof strideofValue swap toString transcode underestimateCount unsafeAddressOf unsafeBitCast unsafeDowncast unsafeUnwrap unsafeReflect withExtendedLifetime withObjectAtPlusZero withUnsafePointer withUnsafePointerToObject withUnsafeMutablePointer withUnsafeMutablePointers withUnsafePointer withUnsafePointers withVaList zip"},t={cN:"type",b:"\\b[A-Z][\\wÀ-ʸ']*",r:0},n=e.C("/\\*","\\*/",{c:["self"]}),r={cN:"subst",b:/\\\(/,e:"\\)",k:i,c:[]},a={cN:"number",b:"\\b([\\d_]+(\\.[\\deE_]+)?|0x[a-fA-F0-9_]+(\\.[a-fA-F0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b",r:0},o=e.inherit(e.QSM,{c:[r,e.BE]});return r.c=[a],{k:i,c:[o,e.CLCM,n,t,a,{cN:"function",bK:"func",e:"{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{b://},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:i,c:["self",a,o,e.CBCM,{b:":"}],i:/["']/}],i:/\[|%/},{cN:"class",bK:"struct protocol class extension enum",k:i,e:"\\{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/})]},{cN:"meta",b:"(@warn_unused_result|@exported|@lazy|@noescape|@NSCopying|@NSManaged|@objc|@convention|@required|@noreturn|@IBAction|@IBDesignable|@IBInspectable|@IBOutlet|@infix|@prefix|@postfix|@autoclosure|@testable|@available|@nonobjc|@NSApplicationMain|@UIApplicationMain)"},{bK:"import",e:/$/,c:[e.CLCM,n]}]}});hljs.registerLanguage("elixir",function(e){var r="[a-zA-Z_][a-zA-Z0-9_]*(\\!|\\?)?",n="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",b="and false then defined module in return redo retry end for true self when next until do begin unless nil break not case cond alias while ensure or include use alias fn quote",c={cN:"subst",b:"#\\{",e:"}",l:r,k:b},a={cN:"string",c:[e.BE,c],v:[{b:/'/,e:/'/},{b:/"/,e:/"/}]},i={cN:"function",bK:"def defp defmacro",e:/\B\b/,c:[e.inherit(e.TM,{b:r,endsParent:!0})]},l=e.inherit(i,{cN:"class",bK:"defimpl defmodule defprotocol defrecord",e:/\bdo\b|$|;/}),s=[a,e.HCM,l,i,{cN:"symbol",b:":(?!\\s)",c:[a,{b:n}],r:0},{cN:"symbol",b:r+":",r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{cN:"variable",b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{b:"->"},{b:"("+e.RSR+")\\s*",c:[e.HCM,{cN:"regexp",i:"\\n",c:[e.BE,c],v:[{b:"/",e:"/[a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}],r:0}];return c.c=s,{l:r,k:b,c:s}});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,a,t]}});hljs.registerLanguage("erlang-repl",function(e){return{k:{built_in:"spawn spawn_link self",keyword:"after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if let not of or orelse|10 query receive rem try when xor"},c:[{cN:"meta",b:"^[0-9]+> ",r:10},e.C("%","$"),{cN:"number",b:"\\b(\\d+#[a-fA-F0-9]+|\\d+(\\.\\d+)?([eE][-+]?\\d+)?)",r:0},e.ASM,e.QSM,{b:"\\?(::)?([A-Z]\\w*(::)?)+"},{b:"->"},{b:"ok"},{b:"!"},{b:"(\\b[a-z'][a-zA-Z0-9_']*:[a-z'][a-zA-Z0-9_']*)|(\\b[a-z'][a-zA-Z0-9_']*)",r:0},{b:"[A-Z][a-zA-Z0-9_']*",r:0}]}});hljs.registerLanguage("elm",function(e){var i={v:[e.C("--","$"),e.C("{-","-}",{c:["self"]})]},t={cN:"type",b:"\\b[A-Z][\\w']*",r:0},c={b:"\\(",e:"\\)",i:'"',c:[{cN:"type",b:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},i]},n={b:"{",e:"}",c:c.c};return{k:"let in if then else case of where module import exposing type alias as infix infixl infixr port effect command subscription",c:[{bK:"port effect module",e:"exposing",k:"port effect module where command subscription exposing",c:[c,i],i:"\\W\\.|;"},{b:"import",e:"$",k:"import as exposing",c:[c,i],i:"\\W\\.|;"},{b:"type",e:"$",k:"type alias",c:[t,c,n,i]},{bK:"infix infixl infixr",e:"$",c:[e.CNM,i]},{b:"port",e:"$",k:"port",c:[i]},e.QSM,e.CNM,t,e.inherit(e.TM,{b:"^[_a-z][\\w']*"}),i,{b:"->|<-"}],i:/;/}});hljs.registerLanguage("clojure",function(e){var t={"builtin-name":"def defonce cond apply if-not if-let if not not= = < > <= >= == + / * - rem quot neg? pos? delay? symbol? keyword? true? false? integer? empty? coll? list? set? ifn? fn? associative? sequential? sorted? counted? reversible? number? decimal? class? distinct? isa? float? rational? reduced? ratio? odd? even? char? seq? vector? string? map? nil? contains? zero? instance? not-every? not-any? libspec? -> ->> .. . inc compare do dotimes mapcat take remove take-while drop letfn drop-last take-last drop-while while intern condp case reduced cycle split-at split-with repeat replicate iterate range merge zipmap declare line-seq sort comparator sort-by dorun doall nthnext nthrest partition eval doseq await await-for let agent atom send send-off release-pending-sends add-watch mapv filterv remove-watch agent-error restart-agent set-error-handler error-handler set-error-mode! error-mode shutdown-agents quote var fn loop recur throw try monitor-enter monitor-exit defmacro defn defn- macroexpand macroexpand-1 for dosync and or when when-not when-let comp juxt partial sequence memoize constantly complement identity assert peek pop doto proxy defstruct first rest cons defprotocol cast coll deftype defrecord last butlast sigs reify second ffirst fnext nfirst nnext defmulti defmethod meta with-meta ns in-ns create-ns import refer keys select-keys vals key val rseq name namespace promise into transient persistent! conj! assoc! dissoc! pop! disj! use class type num float double short byte boolean bigint biginteger bigdec print-method print-dup throw-if printf format load compile get-in update-in pr pr-on newline flush read slurp read-line subvec with-open memfn time re-find re-groups rand-int rand mod locking assert-valid-fdecl alias resolve ref deref refset swap! reset! set-validator! compare-and-set! alter-meta! reset-meta! commute get-validator alter ref-set ref-history-count ref-min-history ref-max-history ensure sync io! new next conj set! to-array future future-call into-array aset gen-class reduce map filter find empty hash-map hash-set sorted-map sorted-map-by sorted-set sorted-set-by vec vector seq flatten reverse assoc dissoc list disj get union difference intersection extend extend-type extend-protocol int nth delay count concat chunk chunk-buffer chunk-append chunk-first chunk-rest max min dec unchecked-inc-int unchecked-inc unchecked-dec-inc unchecked-dec unchecked-negate unchecked-add-int unchecked-add unchecked-subtract-int unchecked-subtract chunk-next chunk-cons chunked-seq? prn vary-meta lazy-seq spread list* str find-keyword keyword symbol gensym force rationalize"},r="a-zA-Z_\\-!.?+*=<>&#'",n="["+r+"]["+r+"0-9/;:]*",a="[-+]?\\d+(\\.\\d+)?",o={b:n,r:0},s={cN:"number",b:a,r:0},c=e.inherit(e.QSM,{i:null}),i=e.C(";","$",{r:0}),d={cN:"literal",b:/\b(true|false|nil)\b/},l={b:"[\\[\\{]",e:"[\\]\\}]"},m={cN:"comment",b:"\\^"+n},p=e.C("\\^\\{","\\}"),u={cN:"symbol",b:"[:]{1,2}"+n},f={b:"\\(",e:"\\)"},h={eW:!0,r:0},y={k:t,l:n,cN:"name",b:n,starts:h},b=[f,c,m,p,i,u,l,s,d,o];return f.c=[e.C("comment",""),y,h],h.c=b,l.c=b,p.c=[l],{aliases:["clj"],i:/\S/,c:[f,c,m,p,i,u,l,s,d]}});hljs.registerLanguage("dns",function(d){return{aliases:["bind","zone"],k:{keyword:"IN A AAAA AFSDB APL CAA CDNSKEY CDS CERT CNAME DHCID DLV DNAME DNSKEY DS HIP IPSECKEY KEY KX LOC MX NAPTR NS NSEC NSEC3 NSEC3PARAM PTR RRSIG RP SIG SOA SRV SSHFP TA TKEY TLSA TSIG TXT"},c:[d.C(";","$",{r:0}),{cN:"meta",b:/^\$(TTL|GENERATE|INCLUDE|ORIGIN)\b/},{cN:"number",b:"((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))\\b"},{cN:"number",b:"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\b"},d.inherit(d.NM,{b:/\b\d+[dhwm]?/})]}});hljs.registerLanguage("dockerfile",function(e){return{aliases:["docker"],cI:!0,k:"from maintainer expose env arg user onbuild stopsignal",c:[e.HCM,e.ASM,e.QSM,e.NM,{bK:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{e:/[^\\]\n/,sL:"bash"}}],i:"`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[t],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[t],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("nginx",function(e){var r={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},b={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,r],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[r]},{cN:"regexp",c:[e.BE,r],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},r]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:b}],r:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("ruby",function(e){var b="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:r},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:b}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:b}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d,i.c=d;var l="[>?]>",o="[\\w#]+\\(\\w+\\):\\d+:\\d+>",u="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",w=[{b:/^\s*=>/,starts:{e:"$",c:d}},{cN:"meta",b:"^("+l+"|"+o+"|"+u+")",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:s.concat(w).concat(d)}});hljs.registerLanguage("lua",function(e){var t="\\[=*\\[",a="\\]=*\\]",r={b:t,e:a,c:["self"]},n=[e.C("--(?!"+t+")","$"),e.C("--"+t,a,{c:[r],r:10})];return{l:e.UIR,k:{literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstringmodule next pairs pcall print rawequal rawget rawset require select setfenvsetmetatable tonumber tostring type unpack xpcall arg selfcoroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},c:n.concat([{cN:"function",bK:"function",e:"\\)",c:[e.inherit(e.TM,{b:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{cN:"params",b:"\\(",eW:!0,c:n}].concat(n)},e.CNM,e.ASM,e.QSM,{cN:"string",b:t,e:a,c:[r],r:5}])}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("scheme",function(e){var t="[^\\(\\)\\[\\]\\{\\}\",'`;#|\\\\\\s]+",r="(\\-|\\+)?\\d+([./]\\d+)?",a=r+"[+\\-]"+r+"i",i={"builtin-name":"case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules ' * + , ,@ - ... / ; < <= = => > >= ` abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string=? string>? string? substring symbol->string symbol? tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?"},n={cN:"meta",b:"^#!",e:"$"},c={cN:"literal",b:"(#t|#f|#\\\\"+t+"|#\\\\.)"},l={cN:"number",v:[{b:r,r:0},{b:a,r:0},{b:"#b[0-1]+(/[0-1]+)?"},{b:"#o[0-7]+(/[0-7]+)?"},{b:"#x[0-9a-f]+(/[0-9a-f]+)?"}]},s=e.QSM,o=[e.C(";","$",{r:0}),e.C("#\\|","\\|#")],u={b:t,r:0},p={cN:"symbol",b:"'"+t},d={eW:!0,r:0},m={v:[{b:/'/},{b:"`"}],c:[{b:"\\(",e:"\\)",c:["self",c,s,l,u,p]}]},g={cN:"name",b:t,l:t,k:i},h={b:/lambda/,eW:!0,rB:!0,c:[g,{b:/\(/,e:/\)/,endsParent:!0,c:[u]}]},b={v:[{b:"\\(",e:"\\)"},{b:"\\[",e:"\\]"}],c:[h,g,d]};return d.c=[c,l,s,u,p,m,b].concat(o),{i:/\S/,c:[n,l,s,p,m,b].concat(o)}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});hljs.registerLanguage("typescript",function(e){var r={keyword:"in if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const class public private protected get set super static implements enum export import declare type namespace abstract as from extends async await",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document any number boolean string void Promise"};return{aliases:["ts"],k:r,c:[{cN:"meta",b:/^\s*['"]use strict['"]/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+e.IR+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:e.IR},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,c:["self",e.CLCM,e.CBCM]}]}]}],r:0},{cN:"function",b:"function",e:/[\{;]/,eE:!0,k:r,c:["self",e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,c:[e.CLCM,e.CBCM],i:/["'\(]/}],i:/%/,r:0},{bK:"constructor",e:/\{/,eE:!0,c:["self",{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,c:[e.CLCM,e.CBCM],i:/["'\(]/}]},{b:/module\./,k:{built_in:"module"},r:0},{bK:"module",e:/\{/,eE:!0},{bK:"interface",e:/\{/,eE:!0,k:"interface extends"},{b:/\$[(.]/},{b:"\\."+e.IR,r:0},{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("lisp",function(b){var e="[a-zA-Z_\\-\\+\\*\\/\\<\\=\\>\\&\\#][a-zA-Z0-9_\\-\\+\\*\\/\\<\\=\\>\\&\\#!]*",c="\\|[^]*?\\|",r="(\\-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|\\-)?\\d+)?",a={cN:"meta",b:"^#!",e:"$"},l={cN:"literal",b:"\\b(t{1}|nil)\\b"},n={cN:"number",v:[{b:r,r:0},{b:"#(b|B)[0-1]+(/[0-1]+)?"},{b:"#(o|O)[0-7]+(/[0-7]+)?"},{b:"#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?"},{b:"#(c|C)\\("+r+" +"+r,e:"\\)"}]},i=b.inherit(b.QSM,{i:null}),t=b.C(";","$",{r:0}),s={b:"\\*",e:"\\*"},u={cN:"symbol",b:"[:&]"+e},d={b:e,r:0},f={b:c},m={b:"\\(",e:"\\)",c:["self",l,i,n,d]},o={c:[n,i,s,u,m,d],v:[{b:"['`]\\(",e:"\\)"},{b:"\\(quote ",e:"\\)",k:{name:"quote"}},{b:"'"+c}]},v={v:[{b:"'"+e},{b:"#'"+e+"(::"+e+")*"}]},N={b:"\\(\\s*",e:"\\)"},A={eW:!0,r:0};return N.c=[{cN:"name",v:[{b:e},{b:c}]},A],A.c=[o,v,N,l,n,i,t,s,u,f,d],{i:/\S/,c:[n,a,l,i,t,o,v,N,d]}});hljs.registerLanguage("javascript",function(e){var r="[A-Za-z$_][0-9A-Za-z$_]*",t={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},a={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:t,c:[]},c={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,c,a,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:t,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,c,e.CLCM,e.CBCM,a,{b:/[{,]\s*/,r:0,c:[{b:r+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:r,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+r+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:r},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:r}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}});hljs.registerLanguage("java",function(e){var a="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",t=a+"(<"+a+"(\\s*,\\s*"+a+")*>)?",r="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",s="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",c={cN:"number",b:s,r:0};return{aliases:["jsp"],k:r,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:r,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:r,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},c,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("clojure-repl",function(e){return{c:[{cN:"meta",b:/^([\w.-]+|\s*#_)=>/,starts:{e:/$/,sL:"clojure"}}]}});hljs.registerLanguage("cpp",function(t){var e={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[t.BE]},{b:'(u8?|U)?R"',e:'"',c:[t.BE]},{b:"'\\\\?.",e:"'",i:"."}]},s={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},i={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},t.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:/<[^\n>]*>/,e:/$/,i:"\\n"},t.CLCM,t.CBCM]},a=t.IR+"\\s*\\(",c={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},n=[e,t.CLCM,t.CBCM,s,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:c,i:"",k:c,c:["self",e]},{b:t.IR+"::",k:c},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:c,c:n.concat([{b:/\(/,e:/\)/,k:c,c:n.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+t.IR+"[\\*&\\s]+)+"+a,rB:!0,e:/[{;=]/,eE:!0,k:c,i:/[^\w\s\*&]/,c:[{b:a,rB:!0,c:[t.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:c,r:0,c:[t.CLCM,t.CBCM,r,s,e]},t.CLCM,t.CBCM,i]},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b://,c:["self"]},t.TM]}]),exports:{preprocessor:i,strings:r,k:c}}});hljs.registerLanguage("kotlin",function(e){var t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit initinterface annotation data sealed internal infix operator out by constructor super trait volatile transient native default",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},r={cN:"keyword",b:/\b(break|continue|return|this)\b/,starts:{c:[{cN:"symbol",b:/@\w+/}]}},i={cN:"symbol",b:e.UIR+"@"},n={cN:"subst",b:"\\${",e:"}",c:[e.ASM,e.CNM]},a={cN:"variable",b:"\\$"+e.UIR},c={cN:"string",v:[{b:'"""',e:'"""',c:[a,n]},{b:"'",e:"'",i:/\n/,c:[e.BE]},{b:'"',e:'"',i:/\n/,c:[e.BE,a,n]}]},s={cN:"meta",b:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UIR+")?"},o={cN:"meta",b:"@"+e.UIR,c:[{b:/\(/,e:/\)/,c:[e.inherit(c,{cN:"meta-string"})]}]};return{k:t,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,r,i,s,o,{cN:"function",bK:"fun",e:"[(]|$",rB:!0,eE:!0,k:t,i:/fun\s+(<.*>)?[^\s\(]+(\s+[^\s\(]+)\s*=/,r:5,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"type",b://,k:"reified",r:0},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:t,r:0,c:[{b:/:/,e:/[=,\/]/,eW:!0,c:[{cN:"type",b:e.UIR},e.CLCM,e.CBCM],r:0},e.CLCM,e.CBCM,s,o,c,e.CNM]},e.CBCM]},{cN:"class",bK:"class interface trait",e:/[:\{(]|$/,eE:!0,i:"extends implements",c:[{bK:"public protected internal private constructor"},e.UTM,{cN:"type",b://,eB:!0,eE:!0,r:0},{cN:"type",b:/[,:]\s*/,e:/[<\(,]|$/,eB:!0,rE:!0},s,o]},c,{cN:"meta",b:"^#!/usr/bin/env",e:"$",i:"\n"},e.CNM]}});hljs.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}});hljs.registerLanguage("makefile",function(e){var i={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@%"}]}});hljs.registerLanguage("haskell",function(e){var i={v:[e.C("--","$"),e.C("{-","-}",{c:["self"]})]},a={cN:"meta",b:"{-#",e:"#-}"},l={cN:"meta",b:"^#",e:"$"},c={cN:"type",b:"\\b[A-Z][\\w']*",r:0},n={b:"\\(",e:"\\)",i:'"',c:[a,l,{cN:"type",b:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TM,{b:"[_a-z][\\w']*"}),i]},s={b:"{",e:"}",c:n.c};return{aliases:["hs"],k:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",c:[{bK:"module",e:"where",k:"module where",c:[n,i],i:"\\W\\.|;"},{b:"\\bimport\\b",e:"$",k:"import qualified as hiding",c:[n,i],i:"\\W\\.|;"},{cN:"class",b:"^(\\s*)?(class|instance)\\b",e:"where",k:"class family instance where",c:[c,n,i]},{cN:"class",b:"\\b(data|(new)?type)\\b",e:"$",k:"data family type newtype deriving",c:[a,c,n,s,i]},{bK:"default",e:"$",c:[c,n,i]},{bK:"infix infixl infixr",e:"$",c:[e.CNM,i]},{b:"\\bforeign\\b",e:"$",k:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",c:[c,e.QSM,i]},{cN:"meta",b:"#!\\/usr\\/bin\\/env runhaskell",e:"$"},a,l,e.QSM,e.CNM,c,e.inherit(e.TM,{b:"^[_a-z][\\w']*"}),i,{b:"->|<-"}]}});hljs.registerLanguage("nix",function(e){var r={keyword:"rec with let in inherit assert if else then",literal:"true false or and null",built_in:"import abort baseNameOf dirOf isNull builtins map removeAttrs throw toString derivation"},t={cN:"subst",b:/\$\{/,e:/}/,k:r},i={b:/[a-zA-Z0-9-_]+(\s*=)/,rB:!0,r:0,c:[{cN:"attr",b:/\S+/}]},s={cN:"string",c:[t],v:[{b:"''",e:"''"},{b:'"',e:'"'}]},a=[e.NM,e.HCM,e.CBCM,s,i];return t.c=a,{aliases:["nixos"],k:r,c:a}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("go",function(e){var t={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",literal:"true false iota nil",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{aliases:["golang"],k:t,i:"",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}});hljs.initHighlightingOnLoad(); 3 | -------------------------------------------------------------------------------- /static/styles.css: -------------------------------------------------------------------------------- 1 | * :not(.material-icons) { 2 | font-family: 'Ubuntu', sans-serif; 3 | } 4 | 5 | code, pre, code * { 6 | font-family: 'Ubuntu Mono', monospace !important; 7 | } 8 | 9 | .cvs-title, .thread-link { 10 | text-decoration: none; 11 | } 12 | 13 | .thread-list-item:hover { 14 | background-color: #f5f5f5; 15 | } 16 | 17 | .thread-link { 18 | padding: 5px; 19 | padding-top: 10px; 20 | } 21 | 22 | .thread-title { 23 | padding-right: 15vw; 24 | } 25 | 26 | .search-field { 27 | margin-right: 15px; 28 | max-width: 200px; 29 | } 30 | 31 | .thread-author { 32 | font-style: italic; 33 | font-size: 85%; 34 | } 35 | 36 | @media only screen and (min-width: 768px) { 37 | .converse main { 38 | padding-top: 10px; 39 | padding-bottom: 10px; 40 | } 41 | } 42 | 43 | .mdl-list__item-text-body { 44 | max-height: 40px; 45 | } 46 | 47 | .thread-divider:after { 48 | border-bottom: 1px solid rgba(0,0,0,.13); 49 | content:""; 50 | position: absolute; 51 | width: 80%; 52 | } 53 | 54 | html, body { 55 | margin: 0; 56 | padding: 0; 57 | } 58 | .converse .mdl-layout__header-row { 59 | padding-left: 40px; 60 | } 61 | .converse .mdl-layout.is-small-screen .mdl-layout__header-row h3 { 62 | font-size: inherit; 63 | } 64 | .converse .mdl-card { 65 | height: auto; 66 | display: -webkit-flex; 67 | display: -ms-flexbox; 68 | display: flex; 69 | -webkit-flex-direction: column; 70 | -ms-flex-direction: column; 71 | flex-direction: column; 72 | } 73 | .converse .mdl-card > * { 74 | height: auto; 75 | } 76 | .converse .mdl-card .mdl-card__supporting-text { 77 | margin: 40px; 78 | -webkit-flex-grow: 1; 79 | -ms-flex-positive: 1; 80 | flex-grow: 1; 81 | padding: 0; 82 | color: inherit; 83 | width: calc(100% - 80px); 84 | } 85 | .mdl-demo.converse .mdl-card__supporting-text h4 { 86 | margin-top: 0; 87 | margin-bottom: 20px; 88 | } 89 | .converse .mdl-card__actions { 90 | margin: 0; 91 | padding: 4px 40px; 92 | color: inherit; 93 | } 94 | .converse section.section--center { 95 | max-width: 860px; 96 | } 97 | .converse .mdl-card .avatar-card { 98 | display: flex; 99 | flex-direction: column; 100 | text-align: center; 101 | margin-top: 30px; 102 | } 103 | .desktop-avatar { 104 | width: 80px; 105 | margin-right: auto; 106 | margin-left: auto; 107 | } 108 | .mobile-avatar { 109 | width: 30px; 110 | border-radius: 8px; 111 | margin-bottom: 5px; 112 | } 113 | .mobile-date { 114 | text-decoration: none; 115 | } 116 | .converse .mdl-card .post-box { 117 | margin: 20px; 118 | } 119 | .converse .mdl-card .post-actions { 120 | display: flex; 121 | padding-right: 5px; 122 | } 123 | .post-action { 124 | margin: 5px; 125 | margin-bottom: 10px; 126 | } 127 | .converse section.post-section { 128 | padding: 5px; 129 | } 130 | .post-date { 131 | text-decoration: none; 132 | font-size: 80%; 133 | } 134 | .mdl-layout__content { 135 | flex: 1 0 auto; 136 | } 137 | .converse .reply-box { 138 | padding-top: 10px; 139 | } 140 | .search-result { 141 | margin: 8px; 142 | } 143 | .search-result .mdl-button { 144 | margin: 3px; 145 | } 146 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Converse: Index 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 | Converse 22 |
23 |
24 |
25 | 26 | 27 | 28 |
29 |
30 |   31 | 32 | 35 | 36 |
37 |
38 |
39 |
40 | 70 |
71 |
72 |
73 | 76 |
77 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /templates/post.html: -------------------------------------------------------------------------------- 1 | {# 2 | This template is shared by the new thread, reply and post-editing pages. 3 | 4 | The main display differences between the different editing styles are the 5 | headline of the page ("Submit new thread", "Reply to thread", "Edit post") 6 | and whether or not the subject line field is displayed in the input form. 7 | 8 | Every one of these pages can have a variable length list of alerts submitted 9 | into the template, which will be rendered as Boostrap alert boxes above the 10 | user input form. 11 | #} 12 | 13 | 14 | 15 | 16 | 17 | 18 | Converse: Post 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 | 49 |
50 |
51 |
52 | {% match mode %} 53 | {% when EditingMode::NewThread %} 54 |
55 | {% when EditingMode::PostReply %} 56 | 57 | {% when EditingMode::EditPost %} 58 | 59 | {% endmatch %} 60 | {% match mode %} 61 | {% when EditingMode::PostReply %} 62 | 63 | {% when EditingMode::EditPost %} 64 | 65 | {% else %} 66 | {# no post ID when making a new thread #} 67 | {% endmatch %} 68 |
69 | {% for alert in alerts %} 70 | 71 | {{ alert }}  72 | 73 | {% endfor %} 74 | {% if mode == EditingMode::NewThread %} 75 |
76 | 77 | 78 |
79 | {% endif %} 80 |
81 | 89 | 90 |
91 |
92 |
93 | 94 |
95 |
96 |
97 |
98 |
99 | Quick Markdown primer: 100 |
101 |
102 |

103 | Remember that you can use Markdown when 104 | writing your posts: 105 |

106 |

*italic text*

107 |

**bold text**

108 |

~strikethrough text~

109 |

[link text](https://some.link.com/)

110 |

![image text](https://foo.com/thing.jpg)

111 |

Use * or - to enumerate lists.

112 |

See Markdown documentation for more information!

113 |
114 |
115 |
116 |
117 | 120 |
121 |
122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /templates/search.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Converse: Search results 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 | Converse 22 |
23 |
24 |
25 | 26 | 27 | 28 |
29 |
30 |   31 | 32 | 35 | 36 |
37 |
38 |
39 |
40 |
41 |

Search results for '{{ query }}':

42 |
43 | {% for result in results %} 44 |
45 |
46 |

Posted in '{{ result.title }}' by {{ result.author }}:

47 |

{{ result.headline|safe }}

48 |
49 |
50 |
51 | 52 | arrow_forward 53 | 54 |
55 |
56 | {% endfor %} 57 |
58 |
59 |
60 | 63 |
64 |
65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /templates/thread.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Converse: {{ title }} 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 |
25 | 34 |
35 |
36 | {% for post in posts -%} 37 |
38 | 39 |
40 |
41 | 42 |

{{ post.author_name }}

43 |
44 |
45 | 46 |
47 | 48 |
49 | 50 |  {{ post.author_name }} posted on 51 | {{ post.posted }} 52 |
53 | 54 |
55 | 56 |
57 | 58 |
{{ post.body|safe }}
59 | 60 |
61 |
62 | 63 | {% if post.editable %} 64 | 65 | edit 66 | Edit post 67 | 68 | {% endif %} 69 | 73 |
74 |
75 |
76 | {% endfor %} 77 | 78 | 79 |
80 |
81 | {% if closed %} 82 |
83 | This thread is closed and can no longer be responded to. 84 |
85 | {% else %} 86 |
87 | 88 | 89 |
90 |
91 | 92 | 93 |
94 | 97 |
98 |
99 | {% endif %} 100 |
101 |
102 |
103 |
104 | 107 |
108 |
109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /todo.org: -------------------------------------------------------------------------------- 1 | * DONE Pin *-versions in cargo.toml 2 | * DONE Markdown support 3 | * DONE Post ordering as expected 4 | * DONE Stickies! 5 | * DONE Search 6 | * DONE Post editing 7 | * TODO Configurable number of DB workers 8 | * TODO Match certain types of Diesel errors (esp. for "not found") 9 | * TODO Sketch out categories vs. tags system 10 | * TODO Quote button 11 | * TODO Multiquote buttons 12 | * TODO Pagination 13 | * TODO Multi-thread guest accounts 14 | --------------------------------------------------------------------------------