├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── app ├── blacklist.json ├── config.sample.json ├── functions.py ├── pages │ ├── bot │ │ ├── accounts_add.py │ │ ├── create.py │ │ └── edit.py │ ├── home.py │ └── settings.py ├── scrape.py ├── service.py ├── setup.py ├── static │ ├── bot_generic.png │ ├── favicon.ico │ ├── script.js │ └── style.css ├── templates │ ├── about.html │ ├── ap │ │ ├── actor.json │ │ └── webfinger.json │ ├── bot │ │ ├── accounts.html │ │ ├── accounts_add.html │ │ ├── accounts_delete.html │ │ ├── chat.html │ │ ├── create.html │ │ ├── delete.html │ │ └── edit.html │ ├── close_account.html │ ├── coming_soon.html │ ├── error.html │ ├── footer.html │ ├── front_page.html │ ├── help │ │ └── settings.html │ ├── home.html │ ├── imports.html │ ├── login.html │ ├── report_bug.html │ ├── settings.html │ ├── success.html │ └── welcome.html ├── webui.py └── wsgi.py ├── db └── setup.sql ├── logo.png ├── requirements.txt └── run.sh /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | ko_fi: Lynnesbian 2 | custom: https://www.paypal.me/Lynnesbian 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report a bug with FediBooks 4 | title: '' 5 | labels: bug 6 | assignees: Lynnesbian 7 | 8 | --- 9 | 10 | **What happened?** 11 | A clear and concise description of what the bug is. 12 | 13 | **How did it happen?** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Where did it happen?** 21 | Please copy and paste the URL here. 22 | 23 | **Expected behavior** 24 | A clear and concise description of what you expected to happen. 25 | 26 | **Error message** 27 | Did FediBooks give you an error message? If so, paste the message here. 28 | 29 | **Further comments** 30 | You can add more info here if you'd like. 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: Lynnesbian 7 | 8 | --- 9 | 10 | **What would you like FediBooks to do?** 11 | Type in your feature idea here. Please do not suggest any of the following features: 12 | - Different bot types (for example, bots that post images) 13 | - Donation bonuses 14 | 15 | Please ensure that your idea is: 16 | - Easy to understand for the end user - Don't overwhelm the user with too many options or settings, or complex terminology. 17 | - Relatively achievable - FediBooks is a passion project developed by one person. Something like a mobile app for accessing FediBooks is beyond my skillset and would take too much time. 18 | - Not too heavy on the server - The main FediBooks instance (https://fedibooks.com) is running on a moderately powerful server capable of relatively complex tasks, but some things such as machine learning or automated video generation are beyond its capabilities. 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | config.json 3 | planning.txt 4 | *.pyc 5 | /debug 6 | lynnesbian.json 7 | test.py 8 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.tabSize": 2, 3 | "editor.wordWrap": "on", 4 | "editor.insertSpaces": false 5 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FediBooks 2 | 3 | A web UI for creating your very own ebooks bots. 4 | 5 | # Selfhosting 6 | 7 | FediBooks is currently unfinished - many functions don't work yet, and future updates may make major, breaking changes. I don't recommend self-hosting it yet unless you're willing to work through the potential growing pains. 8 | 9 | 1. Install ``python3`` and ``mariadb`` or ``mysql``. If you're installing on Windows, make sure to check "Add Python to PATH" during Python installation. 10 | 11 | 2. Install the requirements, using ``pip``: 12 | 13 | ``` 14 | # pip3 install -r ./requirements.txt 15 | ``` 16 | 17 | If this doesn't work, try using ``pip`` instead. If it still doesn't work, you might have to install an additional package (for example, ``python-pip`` on Arch Linux). 18 | 19 | 3. Copy the ``app/config.sample.json`` file to ``app/config.json``. 20 | 21 | 4. Fill in the ``app/config.json`` file. 22 | 23 | 5. Run ``python3 app/setup.py`` and follow the on-screen prompts. 24 | 25 | 6. Open the MySQL prompt (using the ``mysql`` command) and type in the following commands: 26 | 27 | ``` 28 | CREATE DATABASE `fedibooks`; 29 | CREATE USER 'myuser' IDENTIFIED BY 'mypassword'; 30 | GRANT ALL PRIVILEGES ON `fedibooks`.* TO 'myuser'; 31 | FLUSH PRIVILEGES; 32 | exit 33 | ``` 34 | 35 | where ``fedibooks`` is your database name, ``myuser`` is your database username and ``mypassword`` is your database user's password. 36 | 37 | 7. Run 38 | 39 | ``` 40 | # mysql -u USERNAME -p DATABASE < db/setup.sql 41 | ``` 42 | 43 | where USERNAME is your database username and DATABASE is your database name. 44 | 45 | 8. Run ``./run.sh`` to start FediBooks. 46 | -------------------------------------------------------------------------------- /app/blacklist.json: -------------------------------------------------------------------------------- 1 | [ 2 | "freespeechextremist.com", 3 | "kiwifarms.cc", 4 | "neckbeard.xyz", 5 | "gameliberty.club", 6 | "freespeech.firedragonstudios.com", 7 | "shitposter.club", 8 | "pawoo.net", 9 | "the.hedgehoghunter.club", 10 | "honey.church", 11 | "anime.website", 12 | "aria.company", 13 | "pl.765racing.com", 14 | "yorishiro.space", 15 | "pl.smuglo.li", 16 | "albin.social", 17 | "social.sunshinegardens.org" 18 | ] 19 | -------------------------------------------------------------------------------- /app/config.sample.json: -------------------------------------------------------------------------------- 1 | { 2 | "secret_key": "enter a random string here", 3 | "db_name": "fedibooks", 4 | "db_user": "fedibooks", 5 | "db_pass": "enter your database password here", 6 | "db_host": "localhost", 7 | "base_uri": "enter your base URI here, e.g. https://example.com", 8 | "service_threads": 8 9 | } 10 | -------------------------------------------------------------------------------- /app/functions.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup 2 | import MySQLdb 3 | from pebble import ProcessPool 4 | from concurrent.futures import TimeoutError 5 | import markovify 6 | import requests 7 | from Crypto.PublicKey import RSA 8 | from Crypto.Hash import SHA256 9 | from Crypto.Signature import PKCS1_v1_5 10 | from base64 import b64decode, b64encode 11 | from mastodon import Mastodon, MastodonUnauthorizedError 12 | import html, re, json 13 | 14 | cfg = json.load(open('config.json')) 15 | 16 | class nlt_fixed(markovify.NewlineText): # modified version of NewlineText that never rejects sentences 17 | def test_sentence_input(self, sentence): 18 | return True # all sentences are valid <3 19 | 20 | def extract_post(post): 21 | post = html.unescape(post) # convert HTML escape codes to text 22 | soup = BeautifulSoup(post, "html.parser") 23 | for lb in soup.select("br"): # replace
with linebreak 24 | lb.replace_with("\n") 25 | 26 | for p in soup.select("p"): # ditto for

27 | p.replace_with("\n") 28 | 29 | for ht in soup.select("a.hashtag"): # convert hashtags from links to text 30 | ht.unwrap() 31 | 32 | for link in soup.select("a"): #ocnvert 1: 134 | id = args[1] 135 | acct = args[3] 136 | handle = args[0] 137 | 138 | # print("Generating post for {}".format(handle)) 139 | 140 | bot, post = generate_output(handle) 141 | 142 | # post will be None if there's no posts for the bot to learn from. 143 | # in such a case, we should just exit without doing anything. 144 | if post == None: return 145 | 146 | client = Mastodon( 147 | client_id = bot['client_id'], 148 | client_secret = bot['client_secret'], 149 | access_token = bot['secret'], 150 | api_base_url = "https://{}".format(handle.split("@")[2]) 151 | ) 152 | 153 | db = MySQLdb.connect( 154 | host = cfg['db_host'], 155 | user=cfg['db_user'], 156 | passwd=cfg['db_pass'], 157 | db=cfg['db_name'], 158 | use_unicode=True, 159 | charset="utf8mb4" 160 | ) 161 | c = db.cursor() 162 | 163 | # print(post) 164 | visibility = bot['post_privacy'] if len(args) == 1 else args[2] 165 | visibilities = ['public', 'unlisted', 'private'] 166 | if visibilities.index(visibility) < visibilities.index(bot['post_privacy']): 167 | # if post_privacy is set to a more restricted level than the visibility of the post we're replying to, use the user's setting 168 | visibility = bot['post_privacy'] 169 | if acct is not None: 170 | post = "{} {}".format(acct, post) 171 | 172 | # ensure post isn't longer than bot['length'] 173 | # TODO: ehhhhhhhhh 174 | post = post[:bot['length']] 175 | # send toot!! 176 | try: 177 | client.status_post(post, id, visibility = visibility, spoiler_text = bot['content_warning']) 178 | except MastodonUnauthorizedError: 179 | # user has revoked the token given to the bot 180 | # this needs to be dealt with properly later on, but for now, we'll just disable the bot 181 | c.execute("UPDATE bots SET enabled = FALSE WHERE handle = %s", (handle,)) 182 | except: 183 | print("Failed to submit post for {}".format(handle)) 184 | 185 | if id == None: 186 | # this wasn't a reply, it was a regular post, so update the last post date 187 | c.execute("UPDATE bots SET last_post = CURRENT_TIMESTAMP() WHERE handle = %s", (handle,)) 188 | db.commit() 189 | c.close() 190 | 191 | def task_done(future): 192 | try: 193 | result = future.result() # blocks until results are ready 194 | except TimeoutError as error: 195 | if not future.silent: print("Timed out on {}.".format(future.function_data)) 196 | 197 | def do_in_pool(function, data, timeout=30, silent=False): 198 | with ProcessPool(max_workers=5, max_tasks=10) as pool: 199 | for i in data: 200 | future = pool.schedule(function, args=[i], timeout=timeout) 201 | future.silent = silent 202 | future.function_data = i 203 | future.add_done_callback(task_done) 204 | 205 | def get_key(): 206 | db = MySQLdb.connect( 207 | host = cfg['db_host'], 208 | user=cfg['db_user'], 209 | passwd=cfg['db_pass'], 210 | db=cfg['db_name'], 211 | use_unicode=True, 212 | charset="utf8mb4" 213 | ) 214 | 215 | dc = db.cursor(MySQLdb.cursors.DictCursor) 216 | dc.execute("SELECT * FROM http_auth_key") 217 | key = dc.fetchone() 218 | if key == None: 219 | # generate new key 220 | key = {} 221 | privkey = RSA.generate(4096) 222 | 223 | key['private'] = privkey.exportKey('PEM').decode('utf-8') 224 | key['public'] = privkey.publickey().exportKey('PEM').decode('utf-8') 225 | 226 | dc.execute("INSERT INTO http_auth_key (private, public) VALUES (%s, %s)", (key['private'], key['public'])) 227 | 228 | dc.close() 229 | db.commit() 230 | 231 | return key 232 | 233 | def signed_get(url, timeout = 10, additional_headers = {}, request_json = True): 234 | headers = {} 235 | if request_json: 236 | headers = { 237 | "Accept": "application/json", 238 | "Content-Type": "application/json" 239 | } 240 | 241 | headers = {**headers, **additional_headers} 242 | 243 | # sign request headers 244 | key = RSA.importKey(get_key()['private']) 245 | sigstring = '' 246 | for header, value in headers.items(): 247 | sigstring += '{}: {}\n'.format(header.lower(), value) 248 | 249 | sigstring.rstrip("\n") 250 | 251 | pkcs = PKCS1_v1_5.new(key) 252 | h = SHA256.new() 253 | h.update(sigstring.encode('ascii')) 254 | 255 | signed_sigstring = b64encode(pkcs.sign(h)).decode('ascii') 256 | 257 | sig = { 258 | 'keyId': "{}/actor".format(cfg['base_uri']), 259 | 'algorithm': 'rsa-sha256', 260 | 'headers': ' '.join(headers.keys()), 261 | 'signature': signed_sigstring 262 | } 263 | 264 | sig_header = ['{}="{}"'.format(k, v) for k, v in sig.items()] 265 | headers['signature'] = ','.join(sig_header) 266 | 267 | r = requests.Request('GET', url, headers) 268 | return r.headers 269 | # return requests.get(url, timeout = timeout) 270 | -------------------------------------------------------------------------------- /app/pages/bot/accounts_add.py: -------------------------------------------------------------------------------- 1 | from flask import session, render_template, request, redirect, url_for 2 | import requests 3 | from mastodon import Mastodon 4 | import re, json 5 | 6 | def bot_accounts_add(mysql, cfg): 7 | if request.method == 'POST': 8 | # remove leading/trailing whitespace 9 | if 'account' in request.form: 10 | session['handle'] = request.form['account'].rstrip().lstrip() 11 | if session['step'] == 1: 12 | if session['handle'] == session['bot']: 13 | error = "Bots cannot learn from themselves." 14 | return render_template("bot/accounts_add.html", error = error) 15 | 16 | # look up user 17 | handle_list = session['handle'].split('@') 18 | if len(handle_list) != 3: 19 | # not formatted correctly 20 | error = "Incorrectly formatted handle." 21 | return render_template("bot/accounts_add.html", error = error) 22 | 23 | session['username'] = handle_list[1] 24 | session['instance'] = handle_list[2] 25 | 26 | if session['instance'] in json.load(open("blacklist.json")): 27 | session['error'] = "Learning from accounts on this instance is not allowed." 28 | return redirect(url_for("render_bot_accounts_add")) 29 | 30 | try: 31 | r = requests.get("https://{}/api/v1/instance".format(session['instance']), timeout=10) 32 | except requests.exceptions.ConnectionError: 33 | error = "Couldn't connect to {}.".format(session['instance']) 34 | return render_template("bot/accounts_add.html", error = error) 35 | except: 36 | error = "An unknown error occurred." 37 | return render_template("bot/accounts_add.html", error = error) 38 | 39 | if r.status_code == 200: 40 | j = r.json() 41 | if "Pleroma" in j['version']: 42 | session['instance_type'] = "Pleroma" 43 | session['step'] += 1 44 | else: 45 | if 'contact_account' in j and 'is_pro' in j['contact_account']: 46 | # gab instance 47 | session['error'] = "Gab instances are not supported." 48 | return render_template("bot/accounts_add.html", error = error) 49 | else: 50 | session['instance_type'] = "Mastodon" 51 | session['step'] += 1 52 | 53 | else: 54 | error = "Unsupported instance type. Misskey support is planned." 55 | return render_template("bot/accounts_add.html", error = error) 56 | 57 | session['client_id'], session['client_secret'] = Mastodon.create_app( 58 | "FediBooks User Authenticator", 59 | api_base_url="https://{}".format(session['instance']), 60 | scopes=["read:statuses", "read:accounts"] if session['instance_type'] == 'Mastodon' else ["read"], 61 | website=cfg['base_uri'] 62 | ) 63 | 64 | client = Mastodon( 65 | client_id=session['client_id'], 66 | client_secret=session['client_secret'], 67 | api_base_url="https://{}".format(session['instance']) 68 | ) 69 | 70 | session['url'] = client.auth_request_url( 71 | client_id=session['client_id'], 72 | scopes=["read:statuses", "read:accounts"] if session['instance_type'] == 'Mastodon' else ["read"] 73 | ) 74 | 75 | elif session['step'] == 2: 76 | # test authentication 77 | try: 78 | client = Mastodon(client_id=session['client_id'], client_secret=session['client_secret'], api_base_url=session['instance']) 79 | session['secret'] = client.log_in( 80 | code = request.form['code'], 81 | scopes=["read:statuses", "read:accounts"] if session['instance_type'] == 'Mastodon' else ["read"], 82 | ) 83 | username = client.account_verify_credentials()['username'] 84 | if username != session['username']: 85 | error = "Please authenticate as {}.".format(session['username']) 86 | if username.lower() == session['username'].lower(): 87 | error += " Make sure you capitalised the name properly - @user and @USER are different." 88 | return render_template("bot/accounts_add.html", error = error) 89 | except: 90 | session['step'] = 1 91 | error = "Authentication failed." 92 | return render_template("bot/accounts_add.html", error = error) 93 | 94 | # 1. download host-meta to find webfinger URL 95 | r = requests.get("https://{}/.well-known/host-meta".format(session['instance']), timeout=10) 96 | if r.status_code != 200: 97 | error = "Couldn't get host-meta." 98 | return render_template("bot/accounts_add.html", error = error) 99 | 100 | # 2. use webfinger to find user's info page 101 | # TODO: use more reliable method 102 | try: 103 | uri = re.search(r'template="([^"]+)"', r.text).group(1) 104 | uri = uri.format(uri = "{}@{}".format(session['username'], session['instance'])) 105 | except: 106 | error = "Couldn't find WebFinger URL." 107 | return render_template("bot/accounts_add.html", error = error) 108 | 109 | r = requests.get(uri, headers={"Accept": "application/json"}, timeout=10) 110 | try: 111 | j = r.json() 112 | except: 113 | error = "Invalid WebFinger response." 114 | return render_template("bot/accounts_add.html", error = error) 115 | 116 | found = False 117 | for link in j['links']: 118 | if link['rel'] == 'self': 119 | # this is a link formatted like "https://instan.ce/users/username", which is what we need 120 | uri = link['href'] 121 | found = True 122 | break 123 | if not found: 124 | error = "Couldn't find a valid ActivityPub outbox URL." 125 | return render_template("bot/accounts_add.html", error = error) 126 | 127 | # 3. format as outbox URL and check to make sure it works 128 | outbox = "{}/outbox?page=true".format(uri) 129 | r = requests.get(outbox, headers={"Accept": "application/json,application/activity+json"}, timeout=10) 130 | if r.status_code == 200: 131 | # success!! 132 | c = mysql.connection.cursor() 133 | c.execute("INSERT IGNORE INTO `fedi_accounts` (`handle`, `outbox`) VALUES (%s, %s)", (session['handle'], outbox)) 134 | c.execute("INSERT INTO `bot_learned_accounts` (`bot_id`, `fedi_id`) VALUES (%s, %s)", (session['bot'], session['handle'])) 135 | c.close() 136 | mysql.connection.commit() 137 | 138 | return redirect("/bot/accounts/{}".format(session['bot']), 303) 139 | else: 140 | error = "Couldn't access ActivityPub outbox. {} may require authenticated fetches, which FediBooks doesn't support yet.".format(session['instance']) 141 | return render_template("bot/accounts_add.html", error = error) 142 | else: 143 | # new account add request 144 | session['step'] = 1 145 | 146 | return render_template("bot/accounts_add.html", error = session.pop('error', None)) 147 | -------------------------------------------------------------------------------- /app/pages/bot/create.py: -------------------------------------------------------------------------------- 1 | from flask import request, session, render_template, redirect, url_for 2 | import requests 3 | from mastodon import Mastodon 4 | import re, json 5 | 6 | def bot_create(mysql, cfg, scopes, scopes_pleroma): 7 | if request.method == 'POST': 8 | if session['step'] == 1: 9 | # strip leading https://, if provided 10 | session['instance'] = re.match(r"^(?:https?:\/\/)?(.*)", request.form['instance']).group(1) 11 | 12 | if session['instance'] in json.load(open("blacklist.json")): 13 | session['error'] = "Creating a bot on this instance is not allowed." 14 | return redirect(url_for("render_bot_create")) 15 | 16 | # check for mastodon/pleroma 17 | try: 18 | r = requests.get("https://{}/api/v1/instance".format(session['instance']), timeout=10) 19 | except requests.ConnectionError: 20 | session['error'] = "Couldn't connect to https://{}.".format(session['instance']) 21 | return render_template("bot/create.html", error = session.pop('error', None)) 22 | except: 23 | session['error'] = "An unknown error occurred while trying to load https://{}".format(session['instance']) 24 | return render_template("bot/create.html", error = session.pop('error', None)) 25 | 26 | if r.status_code == 200: 27 | j = r.json() 28 | if "Pleroma" in j['version']: 29 | session['instance_type'] = "Pleroma" 30 | session['step'] += 1 31 | else: 32 | if 'contact_account' in j and 'is_pro' in j['contact_account']: 33 | # gab instance 34 | session['error'] = "Gab instances are not supported." 35 | else: 36 | session['instance_type'] = "Mastodon" 37 | session['step'] += 1 38 | 39 | else: 40 | # not a masto/pleroma instance 41 | # misskey is currently unsupported 42 | # all other instance types are also unsupported 43 | # return an error message 44 | #TODO: misskey 45 | session['error'] = "Unsupported instance type. Misskey support is planned." 46 | 47 | elif session['step'] == 2: 48 | # nothing needs to be done here, this step just informs the user that their instance type is supported 49 | session['step'] += 1 50 | 51 | elif session['step'] == 3: 52 | # authenticate with the given instance and obtain credentials 53 | if session['instance_type'] in ['Mastodon', 'Pleroma']: 54 | redirect_uri = '{}/do/authenticate_bot'.format(cfg['base_uri']) 55 | 56 | session['client_id'], session['client_secret'] = Mastodon.create_app( 57 | "FediBooks", 58 | api_base_url="https://{}".format(session['instance']), 59 | scopes=scopes if session['instance_type'] == 'Mastodon' else scopes_pleroma, 60 | redirect_uris=[redirect_uri], 61 | website=cfg['base_uri'] 62 | ) 63 | 64 | client = Mastodon( 65 | client_id=session['client_id'], 66 | client_secret=session['client_secret'], 67 | api_base_url="https://{}".format(session['instance']) 68 | ) 69 | 70 | url = client.auth_request_url( 71 | client_id=session['client_id'], 72 | redirect_uris=redirect_uri, 73 | scopes=scopes if session['instance_type'] == 'Mastodon' else scopes_pleroma 74 | ) 75 | return redirect(url, code=303) 76 | 77 | elif session['instance_type'] == 'Misskey': 78 | # todo 79 | pass 80 | 81 | else: 82 | # the user clicked next on step 2 while having an unsupported instance type 83 | # take them back home 84 | del session['instance'] 85 | del session['instance_type'] 86 | session['step'] = 1 87 | return redirect(url_for("home"), 303) 88 | 89 | else: 90 | if 'step' in session and session['step'] == 4: 91 | try: 92 | # test authentication 93 | client = Mastodon(client_id=session['client_id'], client_secret=session['client_secret'], api_base_url=session['instance']) 94 | session['secret'] = client.log_in( 95 | code = session['code'], 96 | scopes=scopes if session['instance_type'] == 'Mastodon' else scopes_pleroma, 97 | redirect_uri='{}/do/authenticate_bot'.format(cfg['base_uri']) 98 | ) 99 | username = client.account_verify_credentials()['username'] 100 | handle = "@{}@{}".format(username, session['instance']) 101 | except: 102 | # authentication error occurred 103 | error = "Authentication failed." 104 | session['step'] = 3 105 | return render_template("bot/create.html", error = error) 106 | 107 | c = mysql.connection.cursor() 108 | c.execute("SELECT COUNT(*) FROM bots WHERE handle = %s", (handle,)) 109 | count = c.fetchone() 110 | if count != None and count[0] == 1: 111 | session['error'] = "{} is currently in use by another FediBooks bot.".format(handle) 112 | session['step'] = 1 113 | return redirect(url_for("render_bot_create"), 303) 114 | 115 | # authentication success!! 116 | c.execute("INSERT INTO `credentials` (client_id, client_secret, secret) VALUES (%s, %s, %s)", (session['client_id'], session['client_secret'], session['secret'])) 117 | credentials_id = c.lastrowid 118 | mysql.connection.commit() 119 | 120 | # get webpush url 121 | privated, publicd = client.push_subscription_generate_keys() 122 | private = privated['privkey'] 123 | public = publicd['pubkey'] 124 | secret = privated['auth'] 125 | client.push_subscription_set("{}/push/{}".format(cfg['base_uri'], handle), publicd, mention_events = True) 126 | 127 | c.execute("INSERT INTO `bots` (handle, user_id, credentials_id, push_public_key, push_private_key, push_secret, instance_type) VALUES (%s, %s, %s, %s, %s, %s, %s)", (handle, session['user_id'], credentials_id, public, private, secret, session['instance_type'])) 128 | mysql.connection.commit() 129 | c.close() 130 | 131 | # clean up unneeded variables 132 | del session['code'] 133 | del session['instance'] 134 | del session['instance_type'] 135 | del session['client_id'] 136 | del session['client_secret'] 137 | 138 | else: 139 | # user is starting a new bot create request 140 | session['step'] = 1 141 | 142 | 143 | return render_template("bot/create.html", error = session.pop('error', None)) 144 | -------------------------------------------------------------------------------- /app/pages/bot/edit.py: -------------------------------------------------------------------------------- 1 | from flask import session, request, redirect, render_template 2 | import MySQLdb 3 | 4 | def bot_edit(id, mysql): 5 | if request.method == "GET": 6 | dc = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 7 | dc.execute("SELECT * FROM bots WHERE handle = %s", (id,)) 8 | return render_template("bot/edit.html", bot = dc.fetchone(), error = session.pop('error', None), success = session.pop('success', None)) 9 | else: 10 | # update stored settings 11 | replies_enabled = 'replies' in request.form 12 | learn_from_cw = 'cw-learning' in request.form 13 | 14 | if request.form['fake-mention-style'] not in ['full', 'brief']: 15 | session['error'] = "Invalid setting for fake mention style." 16 | return redirect("/bot/edit/{}".format(id), 303) 17 | 18 | if request.form['fake-mentions'] not in ['always', 'middle', 'never']: 19 | session['error'] = "Invalid setting for fake mentions." 20 | return redirect("/bot/edit/{}".format(id), 303) 21 | 22 | if request.form['privacy'] not in ['public', 'unlisted', 'private']: 23 | session['error'] = "Invalid setting for post privacy." 24 | return redirect("/bot/edit/{}".format(id), 303) 25 | 26 | if int(request.form['length']) < 100 or int(request.form['length']) > 5000: 27 | session['error'] = "Invalid setting for maximum post length." 28 | return redirect("/bot/edit/{}".format(id), 303) 29 | 30 | if int(request.form['freq']) < 15 or int(request.form['freq']) > 240 or int(request.form['freq']) % 5: 31 | session['error'] = "Invalid setting for post frequency." 32 | return redirect("/bot/edit/{}".format(id), 303) 33 | 34 | if len(request.form['cw']) > 128: 35 | session['error'] = "Content warning cannot exceed 128 characters." 36 | return redirect("/bot/edit/{}".format(id), 303) 37 | 38 | c = mysql.connection.cursor() 39 | try: 40 | c.execute("UPDATE bots SET replies_enabled = %s, post_frequency = %s, content_warning = %s, length = %s, fake_mentions = %s, fake_mentions_full = %s, post_privacy = %s, learn_from_cw = %s WHERE handle = %s", ( 41 | replies_enabled, 42 | request.form['freq'], 43 | request.form['cw'] if request.form['cw'] != "" else None, 44 | request.form['length'], 45 | request.form['fake-mentions'], 46 | request.form['fake-mention-style'] == 'full', 47 | request.form['privacy'], 48 | learn_from_cw, 49 | id 50 | )) 51 | mysql.connection.commit() 52 | c.close() 53 | except: 54 | session['error'] = "Couldn't save your settings." 55 | return redirect("/bot/edit/{}".format(id), 303) 56 | 57 | session['success'] = True 58 | return redirect("/bot/edit/{}".format(id), 303) 59 | -------------------------------------------------------------------------------- /app/pages/home.py: -------------------------------------------------------------------------------- 1 | from flask import render_template, session 2 | import MySQLdb 3 | 4 | def home(mysql): 5 | if 'user_id' in session: 6 | c = mysql.connection.cursor() 7 | c.execute("SELECT COUNT(*) FROM `bots` WHERE user_id = %s", (session['user_id'],)) 8 | bot_count = c.fetchone()[0] 9 | active_count = None 10 | bots = {} 11 | bot_users = {} 12 | next_posts = {} 13 | 14 | if bot_count > 0: 15 | c.execute("SELECT COUNT(*) FROM `bots` WHERE user_id = %s AND enabled = TRUE", (session['user_id'],)) 16 | active_count = c.fetchone()[0] 17 | dc = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 18 | dc.execute("SELECT handle, enabled, last_post, post_frequency, icon FROM `bots` WHERE user_id = %s", (session['user_id'],)) 19 | bots = dc.fetchall() 20 | dc.close() 21 | 22 | for bot in bots: 23 | # multiple SELECTS is slow, maybe SELECT all at once and filter with python? 24 | c.execute("SELECT COUNT(*) FROM `bot_learned_accounts` WHERE bot_id = %s", (bot['handle'],)) 25 | bot_users[bot['handle']] = c.fetchone()[0] 26 | c.execute("SELECT post_frequency - TIMESTAMPDIFF(MINUTE, last_post, CURRENT_TIMESTAMP()) FROM bots WHERE TIMESTAMPDIFF(MINUTE, last_post, CURRENT_TIMESTAMP()) <= post_frequency AND enabled = TRUE AND handle = %s", (bot['handle'],)) 27 | next_post = c.fetchone() 28 | if next_post is not None: 29 | next_posts[bot['handle']] = next_post 30 | 31 | c.close() 32 | return render_template("home.html", bot_count = bot_count, active_count = active_count, bots = bots, bot_users = bot_users, next_posts = next_posts) 33 | else: 34 | return render_template("front_page.html") 35 | -------------------------------------------------------------------------------- /app/pages/settings.py: -------------------------------------------------------------------------------- 1 | from flask import render_template, session, request, redirect, url_for 2 | import bcrypt 3 | import MySQLdb 4 | import hashlib 5 | 6 | def settings(mysql): 7 | if request.method == 'GET': 8 | dc = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 9 | dc.execute("SELECT * FROM `users` WHERE id = %s", (session['user_id'],)) 10 | user = dc.fetchone() 11 | dc.close() 12 | return render_template("settings.html", user = user, error = session.pop('error', None), success = session.pop('success', None)) 13 | 14 | else: 15 | # update settings 16 | c = mysql.connection.cursor() 17 | 18 | c.execute("SELECT COUNT(*) FROM users WHERE email = %s AND id != %s", (request.form['email'], session['user_id'])) 19 | if c.fetchone()[0] > 0: 20 | session['error'] = "Email address already in use." 21 | return redirect(url_for("render_settings"), 303) 22 | 23 | for setting in [request.form['fetch-error'], request.form['submit-error'], request.form['reply-error'], request.form['generation-error']]: 24 | if setting not in ['once', 'always', 'never']: 25 | session['error'] = 'Invalid option "{}".'.format(setting) 26 | return redirect(url_for('render_settings'), 303) 27 | 28 | if request.form['password'] != '': 29 | # user is updating their password 30 | if len(request.form['password']) < 8: 31 | session['error'] = "Password too short." 32 | return redirect(url_for("render_settings"), 303) 33 | 34 | pw_hashed = hashlib.sha256(request.form['password'].encode('utf-8')).digest().replace(b"\0", b"\1") 35 | pw = bcrypt.hashpw(pw_hashed, bcrypt.gensalt(12)) 36 | c.execute("UPDATE users SET password = %s WHERE id = %s", (pw, session['user_id'])) 37 | 38 | # don't require email verification again if the new email address is the same as the old one 39 | c.execute("SELECT email_verified FROM users WHERE id = %s", (session['user_id'],)) 40 | if c.fetchone()[0]: 41 | c.execute("SELECT email FROM users WHERE id = %s", (session['user_id'],)) 42 | previous_email = c.fetchone()[0] 43 | 44 | email_verified = (previous_email == request.form['email']) 45 | else: 46 | email_verified = False 47 | 48 | try: 49 | c.execute("UPDATE users SET email = %s, email_verified = %s, `fetch` = %s, submit = %s, generation = %s, reply = %s WHERE id = %s", ( 50 | request.form['email'], 51 | email_verified, 52 | request.form['fetch-error'], 53 | request.form['submit-error'], 54 | request.form['generation-error'], 55 | request.form['reply-error'], 56 | session['user_id'] 57 | )) 58 | c.close() 59 | mysql.connection.commit() 60 | except: 61 | session['error'] = "Encountered an error while updating the database." 62 | return redirect(url_for('render_settings'), 303) 63 | 64 | session['success'] = True 65 | return redirect(url_for('render_settings'), 303) 66 | -------------------------------------------------------------------------------- /app/scrape.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import MySQLdb 4 | import requests 5 | import json, re 6 | import functions 7 | 8 | cfg = json.load(open('config.json')) 9 | 10 | def scrape_posts(account): 11 | db = MySQLdb.connect( 12 | host = cfg['db_host'], 13 | user=cfg['db_user'], 14 | passwd=cfg['db_pass'], 15 | db=cfg['db_name'], 16 | use_unicode=True, 17 | charset="utf8mb4" 18 | ) 19 | handle = account[0] 20 | outbox = account[1] 21 | # print("Scraping {}".format(handle)) 22 | c = db.cursor() 23 | last_post = 0 24 | c.execute("SELECT COUNT(*) FROM `posts` WHERE `fedi_id` = %s", (handle,)) 25 | count = c.fetchone() 26 | if count is not None and int(count[0]) > 0: 27 | # we've downloaded this user's posts before 28 | # find out the most recently downloaded post of theirs 29 | c.execute("SELECT `post_id` FROM `posts` WHERE `fedi_id` = %s ORDER BY `id` DESC LIMIT 1", (handle,)) 30 | last_post = c.fetchone()[0] 31 | 32 | done = False 33 | 34 | try: 35 | r = requests.get(outbox, timeout = 10) 36 | j = r.json() 37 | # check for pleroma 38 | pleroma = 'next' not in j 39 | if pleroma: 40 | if 'first' in j: 41 | # backwards compatibility for older (pre-v1.0.7) pleroma instances 42 | j = j['first'] 43 | else: 44 | uri = "{}&min_id={}".format(outbox, last_post) 45 | r = requests.get(uri, timeout = 10) 46 | j = r.json() 47 | except: 48 | print("Couldn't load or parse outbox at URL {}".format(outbox)) 49 | done = True 50 | 51 | # here we go! 52 | # warning: scraping posts from outbox.json is messy stuff 53 | while not done and 'orderedItems' in j and len(j['orderedItems']) > 0: 54 | for oi in j['orderedItems']: 55 | if oi['type'] == "Create": 56 | # this is a status/post/toot/florp/whatever 57 | # first, check to see if we already have this in the database 58 | post_id = re.search(r"([^\/]+)/?$", oi['object']['id']).group(1) # extract 123 from https://example.com/posts/123/ 59 | c.execute("SELECT COUNT(*) FROM `posts` WHERE `fedi_id` = %s AND `post_id` = %s", (handle, post_id)) 60 | count = c.fetchone() 61 | if count is not None and int(count[0]) > 0: 62 | # this post is already in the DB. 63 | # we'll set done to true because we've caught up to where we were last time. 64 | done = True 65 | # we'll still iterate over the rest of the posts, though, in case there are still some new ones on this page. 66 | continue 67 | 68 | content = oi['object']['content'] 69 | # remove HTML tags and such from post 70 | content = functions.extract_post(content) 71 | 72 | if len(content) > 65535: 73 | # post is too long to go into the DB 74 | continue 75 | 76 | try: 77 | c.execute("INSERT INTO `posts` (`fedi_id`, `post_id`, `content`, `cw`) VALUES (%s, %s, %s, %s)", ( 78 | handle, 79 | post_id, 80 | content, 81 | 1 if (oi['object']['summary'] != None and oi['object']['summary'] != "") else 0 82 | )) 83 | except: 84 | #TODO: error handling 85 | print("Failed to insert post {} for user {}".format(post_id, handle)) 86 | 87 | if not done: 88 | try: 89 | if pleroma: 90 | if 'next' in j: 91 | r = requests.get(j['next'], timeout = 10) 92 | else: 93 | done = True 94 | else: 95 | if 'prev' in j: 96 | r = requests.get(j['prev'], timeout = 10) 97 | else: 98 | done = True 99 | except requests.Timeout: 100 | print("Timed out while loading next page for {}".format(handle)) 101 | except: 102 | print("Encountered unknown error while getting next page for {}".format(handle)) 103 | 104 | if r.status_code == 429: 105 | # we are now being ratelimited, move on to the next user 106 | print("Hit rate limit while scraping {}".format(handle)) 107 | done = True 108 | else: 109 | j = r.json() 110 | 111 | db.commit() 112 | 113 | db.commit() 114 | # print("Finished scraping {}".format(handle)) 115 | 116 | print("Establishing DB connection") 117 | db = MySQLdb.connect( 118 | host = cfg['db_host'], 119 | user=cfg['db_user'], 120 | passwd=cfg['db_pass'], 121 | db=cfg['db_name'], 122 | use_unicode=True, 123 | charset="utf8mb4" 124 | ) 125 | 126 | cursor = db.cursor() 127 | 128 | print("Downloading posts") 129 | cursor.execute("SELECT `handle`, `outbox` FROM `fedi_accounts` ORDER BY RAND()") 130 | accounts = cursor.fetchall() 131 | cursor.close() 132 | db.close() 133 | 134 | functions.do_in_pool(scrape_posts, accounts, timeout=60) 135 | 136 | print("Done!") 137 | -------------------------------------------------------------------------------- /app/service.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import json 3 | 4 | import MySQLdb 5 | from mastodon import Mastodon 6 | import requests 7 | 8 | import functions 9 | 10 | cfg = json.load(open('config.json')) 11 | 12 | def update_icon(bot): 13 | try: 14 | db = MySQLdb.connect( 15 | host = cfg['db_host'], 16 | user=cfg['db_user'], 17 | passwd=cfg['db_pass'], 18 | db=cfg['db_name'], 19 | use_unicode=True, 20 | charset="utf8mb4" 21 | ) 22 | except: 23 | print("Failed to connect to database.") 24 | return 25 | 26 | 27 | url = "https://{}".format(bot['handle'].split("@")[2]) 28 | try: 29 | r = requests.head(url, timeout=10, allow_redirects = True) 30 | if r.status_code != 200: 31 | raise 32 | except: 33 | print("{} is down - can't update icon for {}.".format(url, bot['handle'])) 34 | return 35 | 36 | client = Mastodon( 37 | client_id = bot['client_id'], 38 | client_secret = bot['client_secret'], 39 | access_token = bot['secret'], 40 | api_base_url = url 41 | ) 42 | 43 | 44 | c = db.cursor() 45 | try: 46 | avatar = client.account_verify_credentials()['avatar'] 47 | except: 48 | c.execute("UPDATE bots SET icon_update_time = CURRENT_TIMESTAMP() WHERE handle = %s", (bot['handle'],)) 49 | db.commit() 50 | c.close() 51 | return 52 | c.execute("UPDATE bots SET icon = %s, icon_update_time = CURRENT_TIMESTAMP() WHERE handle = %s", (avatar, bot['handle'])) 53 | db.commit() 54 | c.close() 55 | 56 | print("Establishing DB connection") 57 | db = MySQLdb.connect( 58 | host = cfg['db_host'], 59 | user=cfg['db_user'], 60 | passwd=cfg['db_pass'], 61 | db=cfg['db_name'], 62 | use_unicode=True, 63 | charset="utf8mb4" 64 | ) 65 | 66 | print("Cleaning up database") 67 | # delete any fedi accounts we no longer need 68 | cursor = db.cursor() 69 | cursor.execute("DELETE FROM fedi_accounts WHERE handle NOT IN (SELECT fedi_id FROM bot_learned_accounts)") 70 | db.commit() 71 | 72 | print("Generating posts") 73 | cursor.execute("SELECT handle FROM bots WHERE enabled = TRUE AND TIMESTAMPDIFF(MINUTE, last_post, CURRENT_TIMESTAMP()) >= post_frequency") 74 | # cursor.execute("SELECT handle FROM bots WHERE enabled = TRUE") 75 | bots = cursor.fetchall() 76 | 77 | functions.do_in_pool(functions.make_post, bots, 15) 78 | 79 | print("Updating cached icons") 80 | dc = db.cursor(MySQLdb.cursors.DictCursor) 81 | dc.execute(""" 82 | SELECT handle, instance_type, client_id, client_secret, secret 83 | FROM bots 84 | INNER JOIN credentials 85 | ON bots.credentials_id = credentials.id 86 | WHERE TIMESTAMPDIFF(HOUR, icon_update_time, CURRENT_TIMESTAMP()) > 2""") 87 | bots = dc.fetchall() 88 | 89 | functions.do_in_pool(update_icon, bots) 90 | 91 | db.commit() 92 | -------------------------------------------------------------------------------- /app/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from mastodon import Mastodon 4 | import json 5 | 6 | cfg = json.load(open("config.json")) 7 | 8 | scopes = ["write:statuses"] 9 | 10 | print("FediBooks needs access to an account to notify users when they've been added to bots.") 11 | print("What instance would you like FediBooks' account to be on?") 12 | instance = input("https://") 13 | client_id, client_secret = Mastodon.create_app( 14 | "FediBooks", 15 | api_base_url="https://{}".format(instance), 16 | scopes=scopes, 17 | website=cfg['base_uri'] 18 | ) 19 | 20 | client = Mastodon( 21 | client_id=client_id, 22 | client_secret=client_secret, 23 | api_base_url="https://{}".format(instance) 24 | ) 25 | 26 | url = client.auth_request_url( 27 | client_id=client_id, 28 | scopes=scopes 29 | ) 30 | print("Create an account on {}, then click this link to give FediBooks access to the account: {}".format(instance, url)) 31 | print("Authorise FediBooks to access the account, then paste the code below.") 32 | code = input("Code: ") 33 | 34 | print("Authenticating...") 35 | 36 | secret = client.log_in( 37 | code = code, 38 | scopes=scopes 39 | ) 40 | client.status_post("FediBooks has successfully been set up to use this account.") 41 | 42 | cfg['account'] = { 43 | 'client_id': client_id, 44 | 'client_secret': client_secret, 45 | 'secret': secret, 46 | 'instance': instance 47 | } 48 | 49 | json.dump(cfg, open('config.json', 'w')) 50 | 51 | print("Done! Thanks for using FediBooks!") 52 | -------------------------------------------------------------------------------- /app/static/bot_generic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lynnesbian/FediBooks/ebdc384454246a330ef954c670b2cafb88943c71/app/static/bot_generic.png -------------------------------------------------------------------------------- /app/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lynnesbian/FediBooks/ebdc384454246a330ef954c670b2cafb88943c71/app/static/favicon.ico -------------------------------------------------------------------------------- /app/static/script.js: -------------------------------------------------------------------------------- 1 | var chatlog = []; 2 | 3 | function sendMessage() { 4 | let id = window.location.href.split("/").slice(-1)[0] 5 | message = document.getElementById("chatbox-input-box").value 6 | document.getElementById("chatbox-input-box").value = '' 7 | document.getElementById("chatbox-input-box").disabled = true; 8 | chatlog.push(["user", message]) 9 | renderChatlog(); 10 | var xhttp = new XMLHttpRequest(); 11 | xhttp.onreadystatechange = function() { 12 | if (this.readyState == 4) { 13 | if (this.status == 200) { 14 | message = this.responseText.replace("\n", "
"); 15 | } else { 16 | message = "Encountered an error while trying to get a response."; 17 | } 18 | chatlog.push(["bot", message]); 19 | renderChatlog(); 20 | document.getElementById("chatbox-input-box").disabled = false; 21 | 22 | } 23 | }; 24 | xhttp.open("GET", `/bot/chat/${id}/message`, true); 25 | xhttp.send(); 26 | return false; 27 | } 28 | 29 | function renderChatlog() { 30 | let chatbox = document.getElementById("chatbox"); 31 | let out = ""; 32 | if (chatlog.length > 50) { 33 | chatlog.shift(); //only keep the 50 most recent messages to avoid slowdown 34 | } 35 | chatlog.forEach(function(item, i) { 36 | if (item[0] == "user") { 37 | out += `

`; 38 | } else { 39 | out += `
${item[1]}
`; 40 | } 41 | }) 42 | chatbox.innerHTML = out; 43 | chatbox.scrollTop = chatbox.scrollHeight; 44 | } 45 | -------------------------------------------------------------------------------- /app/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: "Roboto", sans-serif; 3 | margin: 2%; 4 | background-color: #282c37; 5 | color: white; 6 | } 7 | * { 8 | box-sizing: border-box; 9 | } 10 | 11 | .container { 12 | background-color: #444a5c; 13 | padding: 10px; 14 | } 15 | .light { 16 | background-color: #4d5366; 17 | } 18 | .column { 19 | flex-grow: 1; 20 | flex-basis: 0; 21 | padding: 10px; 22 | } 23 | .large { 24 | font-size: 1.2em; 25 | } 26 | .small { 27 | font-size: 0.8em; 28 | } 29 | .tiny { 30 | font-size: 0.5em; 31 | } 32 | .centred { 33 | text-align: center; 34 | } 35 | .thin { 36 | font-weight: 300; 37 | } 38 | .subtle { 39 | color: #ccc; 40 | } 41 | .row { 42 | display: flex; 43 | } 44 | .full-width { 45 | width: 100%; 46 | } 47 | .no-margin { 48 | margin: 0; 49 | } 50 | .left-align { 51 | text-align: left; 52 | } 53 | 54 | .panel-icon { 55 | width: 100px; 56 | height: 100px; 57 | background: center/contain url("/img/bot_generic.png"); 58 | background-repeat: no-repeat; 59 | } 60 | .panel-icon.large { 61 | width: 150px; 62 | height: 150px; 63 | } 64 | .panel-icon.online, .panel-icon.offline { 65 | width: 105px; 66 | } 67 | .panel-icon.online { 68 | border-left: 5px #5c5 solid; 69 | } 70 | .panel-icon.offline { 71 | border-left: 5px #c33 solid; 72 | } 73 | .panel-icon, .panel-text, .panel-actions { 74 | display: inline-block; 75 | align-self: center; 76 | } 77 | .panel-text { 78 | flex-grow: 1; 79 | margin: 0 0 10px 15px; 80 | } 81 | .panel-name { 82 | font-size: 1.8em; 83 | margin: 10px 0; 84 | } 85 | .panel-actions { 86 | margin-right: 10px; 87 | } 88 | 89 | .button { 90 | color: white; 91 | line-height: 1.2em; 92 | padding: 10px; 93 | text-decoration: none; 94 | display: inline-block; 95 | margin: 5px 0; 96 | transition: 0.2s linear; 97 | border: none; 98 | } 99 | .button:visited { 100 | color: white; 101 | } 102 | input.button, button.button { 103 | font-size: 1em; 104 | cursor: pointer; 105 | } 106 | 107 | .btn-primary { 108 | background-color: #9370db; 109 | border-color: #9370db; 110 | } 111 | .btn-primary:hover { 112 | background-color: #7859b6; 113 | border-color: #7859b6; 114 | } 115 | 116 | .btn-secondary { 117 | background-color: #999; 118 | } 119 | .btn-secondary:hover { 120 | background-color: #777; 121 | } 122 | 123 | .btn-large, button.btn-large { 124 | font-size: 1.6em; 125 | } 126 | 127 | .btn-dangerous { 128 | background-color: #e22; 129 | } 130 | .btn-dangerous:hover { 131 | background-color: #c22; 132 | } 133 | 134 | a { 135 | color: mediumpurple; 136 | text-decoration: none; 137 | } 138 | a:visited { 139 | color: mediumpurple; 140 | } 141 | 142 | p { 143 | line-height: 1.4em; 144 | } 145 | 146 | h1 { 147 | font-size: 4em; 148 | margin-top: 10px !important; 149 | } 150 | h1, h2, h3, h4, h5, h6 { 151 | font-weight: 400; 152 | margin: 0; 153 | } 154 | 155 | form { 156 | display: inline-block; 157 | } 158 | label.important { 159 | font-size: 1.4em; 160 | margin: 10px 0; 161 | font-weight: 300; 162 | display: block; 163 | text-align: center; 164 | } 165 | input, select, textarea { 166 | font-size: 1.2em; 167 | line-height: 1.4em; 168 | border: 3px grey solid; 169 | border-radius: none; 170 | padding: 3px; 171 | font-family: "Roboto", sans-serif; 172 | } 173 | input:focus, select:focus, textarea:focus { 174 | border: 3px mediumpurple solid; 175 | } 176 | 177 | input[type="checkbox"] { 178 | height: 1.4em; 179 | } 180 | 181 | label, input { 182 | flex-basis: 0; 183 | text-align: left; 184 | } 185 | label { 186 | flex-grow: 1; 187 | } 188 | 189 | form .row { 190 | margin: 10px 0; 191 | } 192 | 193 | .coming-soon { 194 | height: 200px; 195 | width: 200px; 196 | background: center/contain url("https://lynnesbian.space/img/bune.png"); 197 | display: inline-block; 198 | } 199 | 200 | .error, .success { 201 | color: white; 202 | text-align: center; 203 | font-size: 1.6em; 204 | padding: 10px; 205 | } 206 | .error { 207 | background-color: #e66; 208 | } 209 | .error.err-small { 210 | font-size: 1.0em; 211 | } 212 | .success { 213 | background-color: #6e6; 214 | } 215 | 216 | #chatbox { 217 | height: 90vh; 218 | background-color: #3d4353; 219 | padding: 10px; 220 | overflow-y: scroll; 221 | } 222 | #chatbox-input, #chatbox-input input{ 223 | width: 100%; 224 | } 225 | #chatbox, #chatbox-input { 226 | max-width: 600px; 227 | margin: 0 auto; 228 | } 229 | #chatbox-input { 230 | display: block; 231 | } 232 | .message { 233 | display: inline-block; 234 | padding: 5px; 235 | min-height: 30px; 236 | max-width: 60%; 237 | margin-bottom: 5px; 238 | } 239 | .message-container.user { 240 | text-align: right; 241 | } 242 | .message-container .bot-icon { 243 | height: 30px; 244 | width: 30px; 245 | display: inline-block; 246 | padding: 5px; 247 | } 248 | .message.bot { 249 | background-color: mediumpurple; 250 | color: white; 251 | vertical-align: top; 252 | } 253 | .message.user { 254 | background-color: #ddd; 255 | color: #333; 256 | } 257 | -------------------------------------------------------------------------------- /app/templates/about.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 |
15 | 16 |
17 |

What's an ebooks bot?

18 |

An ebooks bot, named after the Twitter account horse_ebooks, is a bot that learns from posts made by users and generates its own posts, similarly to how your phone keyboard predicts what you're about to type next. The results are always messy, frequently nonsensical, and occasionally hilarious.

19 | 20 |

What happened to the old FediBooks?

21 |

It was too ambitious a project, and I got burned out on it. Progress was slow and the code was messy. I had a ridiculous number of features planned for it, such as complex decision trees, allowing for absurdly specific rules like "only reply to users with a T in their username if it's between 4am and 5pm on a Wednesday". I had too much planned, and additionally, I'm don't particularly like developing desktop apps.

22 |

The source code is still available here, although it's of little use to anyone.

23 | 24 |

Why create FediBooks?

25 |

I've been working on ebooks bots for a long time. My first project, mstdn-ebooks, dates back to October 2018. It's a much less ambitious project than FediBooks, but maintaining and developing it has still been a formidable undertaking. It's changed a lot since the initial version, and has worked very well for a long time.

26 |

Using mstdn-ebooks is nowhere near as easy as using FediBooks. There's a long guide you'll need to follow, and you'll have to install some programs like Python and possibly Git to get it working. It runs on your own computer, meaning that if you put it into sleep mode or disconnect from the internet, it stops working. Updating mstdn-ebooks to the latest version is also your responsibility, and the error messages it gives aren't exactly user friendly.

27 |

To help with these issues, I decided to create a Patreon where I offered a $2.50 per month tier to host up to three bots for you. I would take care of configuration, maintenance, updating, et cetera. This worked pretty well up until recently.

28 |

A recent change in Mastodon and Pleroma adds something called authenticated fetches. Reffered to as "authorised mode" by Mastodon, this new feature prevents unauthorised instances and programs from accessing the API. In other words, if instance A blocks instance B, then instance B won't be able to see instance A's public posts anymore. However, this also means mstdn-ebooks can't see your posts. This can be fixed, however, by requesting permission from instance B. So what's the problem?

29 |

Without getting too technical, downloading posts from an instance using authenticated fetches requires you to be running a server. mstdn-ebooks is not a server. FediBooks, however, does run on a server, making it possible to support authenticated fetches. Furthermore, mstdn-ebooks' code base is starting to show its age (I used to be even worse at programming, believe it or not), and I thought this gave me a good motivation to create a new project.

30 |

Note that although it is possible for FediBooks to use authenticated fetches, this feature is not supported yet.

31 |

FediBooks is easier to use for both me and the end user. I won't have to worry about manually patching ebooks bots and handling outdated code, and you won't have to worry about installing and running mstdn-ebooks on your own computer (or paying me to do it for you). Sounds pretty good, right? 0u0

32 |

FediBooks is one of the biggest projects I've ever taken on, and it's been wonderful working on it. I hope you enjoy it!

33 | 34 |

You used to charge for hosting ebooks bots for people. Why make it free? Aren't you automating yourself out of a job?

35 |

Yup! I'm making this free because I believe all software should be free, not just in cost, but in distributability, accessibility, and so on. mstdn-ebooks is also free software, meaning that even though I charged for a mstdn-ebooks hosting service in the past, you could still do it yourself for free (or ask someone other than me to do it for you). In fact, this is still true - if you don't like FediBooks, or you want to be able to modify the code, you can use mstdn-ebooks. There's a guide here.

36 |

I used to provide free hosting for mstdn-ebooks bots, but stopped when it became too much for me to handle. In the end, I was running 108 ebooks bots! The worst moment was when I accidentally wiped all the configuration files for them and had to log in to all 108 accounts and re-authorise them all...

37 |

FediBooks should (fingers crossed!) require much less maintenance on my part. All I have to do is make sure the server is running, which it is at all times, and make the occasional change or update to reflect new needs. The real concern is my server, not me - let's hope it can handle all these bots!

38 |

FediBooks doesn't display ads. It doesn't have any subscription models, donation bonuses, or cryptocurrency mining JavaScript (as useless as that is). It will never have any of these things. What it does have is a donation link at the bottom of the main page. If you have some money to spare and you want to donate, feel free to do so. Paying for the server will be a little tricky since I've just cut off my main source of income, but I should manage. Hopefully.

39 | 40 |

I'm concerned about my privacy. If FediBooks learns from my posts, doesn't that mean you have access to all my posts?

41 |

By necessity, yes. FediBooks will have access to all of your public posts. Anything you've set to followers only will not be seen by FediBooks. Additionally, FediBooks has no way of accessing your direct messages. However, if you delete a post, FediBooks will still have it stored in its database. This is because checking if every single post has been deleted is impractically slow, and your instance would soon tell FediBooks to stop making so many API requests.

42 |

If you create two bots that learn from account X, and then delete one of them, account X's posts will still stay in the database. If you delete both bots, and no other bots are learning from account X, then account X's posts will be deleted from the database permanently. If you then add a new bot that learns from account X, FediBooks will need to download all of your posts again, which can take quite a while.

43 |
44 | {% include 'footer.html' %} 45 | 46 | 47 | -------------------------------------------------------------------------------- /app/templates/ap/actor.json: -------------------------------------------------------------------------------- 1 | { 2 | "@context": [ 3 | "https://www.w3.org/ns/activitystreams", 4 | { 5 | "manuallyApprovesFollowers": "as:manuallyApprovesFollowers" 6 | } 7 | ], 8 | "endpoints": {}, 9 | "name": "FediBooks", 10 | "type": "Application", 11 | "id": "{{ base_uri }}/actor", 12 | "manuallyApprovesFollowers": true, 13 | "publicKey": { 14 | "id": "{{ base_uri }}/actor#main-key", 15 | "owner": "{{ base_uri }}/actor", 16 | "publicKeyPem": "{{ pubkey }}" 17 | }, 18 | "summary": "FediBooks Actor", 19 | "preferredUsername": "fedibooks", 20 | "url": "{{ base_uri }}/actor" 21 | } -------------------------------------------------------------------------------- /app/templates/ap/webfinger.json: -------------------------------------------------------------------------------- 1 | { 2 | "aliases": [ 3 | "{{ base_uri }}/actor" 4 | ], 5 | "links": [ 6 | { 7 | "href": "{{ base_uri }}/actor", 8 | "rel": "self", 9 | "type": "application/activity+json" 10 | } 11 | ], 12 | "subject": "acct:fedibooks@{{ base_uri }}" 13 | } -------------------------------------------------------------------------------- /app/templates/bot/accounts.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Set accounts to learn from

12 |

{{ handle }}

13 |

14 | Add account 15 | Back 16 |

17 |
18 | 19 |
20 | {% for user in users %} 21 |
22 |
23 |
24 | {% set handle_list = user['fedi_id'].split('@') %} 25 |
@{{ handle_list[1] }}@{{ handle_list[2] }}
26 |
{{ "Active" if user['enabled'] else "Inactive" }}, {{ post_count[user['fedi_id']] }} posts in database
27 |
28 |
29 | 30 |
31 |
32 | {% endfor %} 33 |
34 | 35 | {% include 'footer.html' %} 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/templates/bot/accounts_add.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Add account

12 |
13 | 14 | {%include 'error.html' %} 15 | 16 |
17 |
18 | {% if session['step'] == 1 %} 19 |

Please enter the full handle of the account you'd like your bot to learn from. Note that this is case sensitive.

20 | 21 | 22 |
23 | 24 | {% elif session['step'] == 2 %} 25 |

Authentication required

26 |

You now need to authenticate with {{ session['instance'] }}. If {{ session['handle'] }} is your account, click "Open". If it's someone else's account, copy the URL in the box below and send it to them, and ask them to send you the code they receive.

27 | Open 28 |

After you've authenticated, paste the code returned by {{ session['instance'] }} into the textbox below.

29 | 30 | 31 | {% elif session['step'] == 3 %} 32 | 33 |

Authentication failure

34 |

FediBooks was unable to authenticate with {{ session['instance'] }}.

35 |

Click back to try again. If you believe this is in error, you may file a bug report.

36 | 37 | {% else %} 38 |

Error

39 |

An unknown error has occurred.

40 | 41 | {% endif %} 42 | 43 |
44 | Cancel 45 | {% if session['step'] != 1 %} 46 | Back 47 | {% endif %} 48 | 49 |
50 |
51 |
52 | 53 | {% include 'footer.html' %} 54 | 55 | 56 | -------------------------------------------------------------------------------- /app/templates/bot/accounts_delete.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Stop learning from account

12 |
13 | 14 |
15 |
16 |
17 |
18 |

Are you sure you want {{ bot }} to stop learning from {{ user }}?

19 | Cancel 20 | 21 |
22 |
23 |
24 | 25 | {% include 'footer.html' %} 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/templates/bot/chat.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 12 | 18 | 19 | 20 | 21 |
22 |

Chat

23 |

Talking to {{ bot }}

24 |

25 | Home 26 |

27 |
28 | 29 | 34 | 35 |
36 |
37 | 38 |
39 | 40 |
41 | 42 |
43 |
44 | 45 | {% include 'footer.html' %} 46 | 47 | 48 | -------------------------------------------------------------------------------- /app/templates/bot/create.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Create bot

12 |
13 | 14 | {% include 'error.html' %} 15 | 16 |
17 |
18 | {% if session['step'] == 1 %} 19 | 20 | 21 |
22 | 23 | {% elif session['step'] == 2 %} 24 |

Detected instance type: {{ session['instance_type'] }}

25 |

{{ session['instance'] }} is a {{ session['instance_type'] }} instance. {% if session['instance_type'] == 'Pleroma' %}Pleroma's support for the Mastodon API is incomplete, and some functions may not work correctly. Additionally, FediBooks will need to request full read and write access to your account, as Pleroma does not support fine-grained app permissions.{% else %}{{ session['instance_type'] }} instances are fully supported, and your bot will have all functionality available.{% endif %}

26 | 27 | {% elif session['step'] == 3 %} 28 |

You now need to give your bot access to the {{ session['instance'] }} account you have created for it. If you have not yet created an account on {{ session['instance'] }} for your bot to use, please do so now.

29 |

In another tab, sign in to the {{ session['instance'] }} account you want your bot to use. Once that's done, click next to begin the authorisation process.

30 | 31 | {% elif session['step'] == 4 %} 32 |

Congratulations!

33 |

FediBooks has successfully authenticated with your instance, and your bot is ready to be configured. Click finish to return to the bot management screen.

34 |

Important: To get your bot working, you need to add at least one account for it to learn from. You can do so by clicking the button. To configure settings such as posting frequency and content warnings, click the button.

35 | 36 | {% else %} 37 |

Error

38 |

An unknown error has occurred.

39 | 40 | {% endif %} 41 | 42 |
43 | Cancel 44 | {% if session['step'] != 1 %} 45 | Back 46 | {% endif %} 47 | {% if session['step'] < 4 %} 48 | 49 | {% else %} 50 | Finish 51 | {% endif %} 52 |
53 |
54 |
55 | 56 | {% include 'footer.html' %} 57 | 58 | 59 | -------------------------------------------------------------------------------- /app/templates/bot/delete.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Delete bot

12 |
13 | 14 |
15 |
16 |
17 |
18 |

Are you sure you want to permanently delete this bot?

19 |

The account on {{ instance }} will remain open, but FediBooks will stop posting from it.

20 | Cancel 21 | 22 |
23 |
24 |
25 | 26 | {% include 'footer.html' %} 27 | 28 | 29 | -------------------------------------------------------------------------------- /app/templates/bot/edit.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Configure bot

12 |

{{ bot['handle'] }}

13 |
14 | 15 | {% include 'error.html' %} 16 | {% include 'success.html' %} 17 | 18 |
19 |
20 | 24 |
25 | 26 | 27 |
28 |
29 | 30 | 31 |
32 |
33 | 34 | 35 |
36 |
37 | 38 | 43 |
44 |
45 | 46 | 50 |
51 |
52 | 53 | 58 |
59 |
60 | 61 | 62 |
63 |
64 | 65 | 66 |
67 |
68 | 69 | Cancel 70 | Help 71 |
72 |
73 |
74 | 75 | {% include 'footer.html' %} 76 | 77 | 78 | -------------------------------------------------------------------------------- /app/templates/close_account.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Close your FediBooks account

12 |
13 | 14 | {% include 'error.html' %} 15 | 16 |
17 |
18 |

19 | 20 |

21 |
22 |

Are you sure you want to permanently delete your account?

23 |

All of your FediBooks bots will stop working, but their accounts will remain open. You can delete them manually or repurpose them for something else.

24 |

If you're sure you want to delete your account, enter your password below and click "Close my account".

25 |

26 | 27 |

28 | Cancel 29 | 30 |
31 |
32 |
33 | 34 | {% include 'footer.html' %} 35 | 36 | 37 | -------------------------------------------------------------------------------- /app/templates/coming_soon.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Coming soon!

12 |
13 |
14 | Home 15 |
16 | 17 | {% include 'footer.html' %} 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/templates/error.html: -------------------------------------------------------------------------------- 1 | {% if error != None %} 2 |
3 | {{ error }} 4 | 5 |
6 | {% endif %} 7 | -------------------------------------------------------------------------------- /app/templates/footer.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

FediBooks is beta software. It might behave unexpectedly. You can learn more about FediBooks here.
4 | Website design and FediBooks software by Lynne. This site uses Font Awesome.
5 | Some of FediBooks' functionality requires JavaScript to be enabled, although the core functions such as bot configuration do not.
6 | FediBooks uses a cookie to keep you logged in. Deleting this cookie will log you out, and your bots will still work. You can also sign out here.
7 | Source code is available here under the AGPLv3 license.

8 |
9 |
10 | -------------------------------------------------------------------------------- /app/templates/front_page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 |
10 |

FediBooks

11 |

Easily create your own Mastodon/Pleroma ebooks bot from your browser. No coding required.

12 |

13 | Get started 14 |
15 | Learn more 16 | Source code 17 |

18 |
19 | 20 |
21 |
22 |
23 |

Simple

24 |

FediBooks is easy to use. Everything from the profile picture to the accounts learned from is customisable with an intuitive web UI.

25 |
26 |
27 |

Truly Free

28 |

FediBooks is licensed under the GNU AGPLv3, a libre, copyleft license. This means that it will always be not only free of charge, but also free to distribute, free from access restrictions, and free to modify.

29 |
30 |
31 |

Personal

32 |

Found a bug, or have an idea for a feature? Open a GitHub issue. Want something a little more personal? Get in touch with the developer.

33 |
34 |
35 |
36 | 37 |
38 |

Support the author

39 |

FediBooks is a passion project I develop and maintain in my free time. If you'd like to contribute, you can do so here.

40 | 41 | PayPal 42 | Ko-fi 43 |
44 | {% include 'footer.html' %} 45 | 46 | 47 | -------------------------------------------------------------------------------- /app/templates/help/settings.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 |
10 |

About the Settings menu

11 |

12 | Home 13 |

14 |
15 | 16 |
17 |

The settings menu allows you to change your account's email or password, as well as updating your contact information.

18 |

The email and password inputs allow you to change your account's email address or password respectively. If you don't edit these inputs, your login info will not be changed.

19 |

The contact settings menu allows you to specify when FediBooks should send you automated emails. There are four options for you to configure.

20 |

You can specify whether you'd like to be contacted always, once, or never. Always means you will be emailed every time this error occurs. Once means you will be emailed once if this occurs, and you won't be emailed again until you check FediBooks by viewing the home page. Never means you will never be emailed if this error occurs.

21 |

When my bot(s) can't get new posts

22 |

This error happens when your bot fails to download new posts from its followed accounts. This might happen because the instance is down, or when the admin changes authentication settings for the instance.

23 |

When my bot(s) can't submit new posts

24 |

This means that your bot was unable to post something. This might happen because the instance is down, or because you have revoked FediBooks' access to your bot from the Apps menu on your instance.

25 |

When my bot(s) encounter an error generating new posts

26 |

This happens when your bot is unable to generate a new post. This can happen when the database doesn't contain enough unique information for your bot to synthesise a new post. For example, if your bot only has one post to learn from, this will happen.

27 |

When my bot(s) can't send replies

28 |

This error occurs when your bot is unable to send a new reply. This generally happens for the same reason as submission errors.

29 |
30 | {% include 'footer.html' %} 31 | 32 | 33 | -------------------------------------------------------------------------------- /app/templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 |
10 |

Home

11 |

Hi there! You have {{ bot_count }} bot{% if bot_count != 1 %}s{% endif %}{% if bot_count != 0 %}, {{ active_count }} of which {% if active_count == 1 %}is{% else %}are{% endif %} currently active.{% else %}.{% endif %}

12 |

13 | New bot 14 | Account settings 15 | Sign out 16 |

17 |
18 | 19 |
20 | {% for bot in bots %} 21 |
22 |
23 |
24 | {% set handle_list = bot['handle'].split('@') %} 25 |
@{{ handle_list[1] }}@{{ handle_list[2] }}
26 |
{{ "Online" if bot['enabled'] else "Offline"}}, learning from {{ bot_users[bot['handle']] }} accounts.{% if bot['handle'] in next_posts %} Next post in {{ next_posts[bot['handle']][0] }} minute{% if next_posts[bot['handle']][0] != 1 %}s{% endif %}{% endif %}.
27 |
28 |
29 | 30 |
31 |
32 | {% endfor %} 33 |
34 | 35 |
36 |

Support the author

37 |

FediBooks is a passion project I develop and maintain in my free time. If you'd like to contribute, you can do so here.

38 | 39 | PayPal 40 | Ko-fi 41 |
42 | {% include 'footer.html' %} 43 | 44 | 45 | -------------------------------------------------------------------------------- /app/templates/imports.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

{% if signup %}Sign up{% else %}Log in{% endif %}

12 |
13 | 14 | {% include 'error.html' %} 15 | 16 |
17 |
18 |

19 | 20 | 21 | {% if signup %} 22 |

23 | FediBooks requires your email address in order to send you alerts when your bot stops working, and for password resets. 24 |

25 | {% endif %} 26 |
27 | 28 | 29 | {% if signup %} 30 |

31 | Passwords must be at least eight characters long. 32 |

33 | {% endif %} 34 |

35 | 36 |
37 |
38 | 39 | {% include 'footer.html' %} 40 | 41 | 42 | -------------------------------------------------------------------------------- /app/templates/report_bug.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Report a bug

12 |
13 | 14 |
15 |
16 | 17 |

A short, concise description of what happened.

18 | 19 | 20 | 21 |

A more detailed description of what happened, including the steps you took that caused this issue to appear.

22 | 23 | 24 | 25 |

If you'd like to, you may add a comment here with any additional information.

26 | 27 | 28 |
29 | Cancel 30 | 31 |
32 |
33 |
34 | 35 | {% include 'footer.html' %} 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/templates/settings.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Account settings

12 |
13 | 14 | {% include 'error.html' %} 15 | {% include 'success.html' %} 16 | 17 |
18 |
19 |
20 |

Login settings

21 |

Update your email and password here, or close your account.

22 |
23 | 24 |
25 | 26 | 27 |
28 |
29 | 30 | 31 |
32 |
33 | 34 | Close account 35 |
36 | 37 |
38 |

Contact settings

39 |

When should FediBooks send you email?

40 |
41 | 42 |
43 | Note: This feature isn't ready yet. As of now, FediBooks will not send you email. 44 |
45 | 46 |
47 | 48 | 53 |
54 |
55 | 56 | 61 |
62 |
63 | 64 | 69 |
70 |
71 | 72 | 77 |
78 | 79 |
80 | 81 | Cancel 82 | Help 83 |
84 |
85 |
86 | 87 | {% include 'footer.html' %} 88 | 89 | 90 | -------------------------------------------------------------------------------- /app/templates/success.html: -------------------------------------------------------------------------------- 1 | {% if success != None %} 2 |
3 | Information updated succesfully. 4 |
5 | {% endif %} 6 | -------------------------------------------------------------------------------- /app/templates/welcome.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FediBooks 6 | {% include 'imports.html' %} 7 | 8 | 9 | 10 |
11 |

Welcome!

12 |
13 | 14 |
15 |

16 | Log in 17 |
18 | Log in to your existing account. 19 |

20 | 21 |

22 | Sign up 23 |
24 | Create a new account. 25 |

26 |
27 | 28 | {% include 'footer.html' %} 29 | 30 | 31 | -------------------------------------------------------------------------------- /app/webui.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, session, request, redirect, url_for, send_file, jsonify 2 | from flask_mysqldb import MySQL 3 | 4 | from mastodon import Mastodon 5 | 6 | import requests 7 | import MySQLdb 8 | import bcrypt 9 | import json, hashlib, re 10 | 11 | import functions 12 | from pages.home import home 13 | from pages.settings import settings 14 | from pages.bot.edit import bot_edit 15 | from pages.bot.accounts_add import bot_accounts_add 16 | from pages.bot.create import bot_create 17 | 18 | cfg = json.load(open("config.json")) 19 | 20 | app = Flask(__name__) 21 | app.secret_key = cfg['secret_key'] 22 | 23 | app.config['MYSQL_HOST'] = cfg['db_host'] 24 | app.config['MYSQL_DB'] = cfg['db_name'] 25 | app.config['MYSQL_USER'] = cfg['db_user'] 26 | app.config['MYSQL_PASSWORD'] = cfg['db_pass'] 27 | 28 | mysql = MySQL(app) 29 | 30 | scopes = ['write:statuses', 'write:accounts', 'read:accounts', 'read:notifications', 'read:statuses', 'push'] 31 | scopes_pleroma = ['read', 'write', 'push'] 32 | 33 | @app.before_request 34 | def login_check(): 35 | if request.path not in ['/', '/about', '/welcome', '/login', '/signup', '/do/login', '/do/signup'] \ 36 | and not request.path.startswith("/push") \ 37 | and not request.path.startswith('/static') \ 38 | and not request.path.startswith('/actor') \ 39 | and not request.path.startswith('/.well-known'): 40 | # page requires authentication 41 | if 'user_id' not in session: 42 | return redirect(url_for('render_home')) 43 | 44 | @app.route("/") 45 | def render_home(): 46 | return home(mysql) 47 | 48 | @app.route("/welcome") 49 | def welcome(): 50 | return render_template("welcome.html") 51 | 52 | @app.route("/about") 53 | def about(): 54 | return render_template("about.html") 55 | 56 | @app.route("/login") 57 | def show_login_page(): 58 | return render_template("login.html", signup = False, error = session.pop('error', None)) 59 | 60 | @app.route("/signup") 61 | def show_signup_page(): 62 | return render_template("login.html", signup = True, error = session.pop('error', None)) 63 | 64 | @app.route("/settings", methods=['GET', 'POST']) 65 | def render_settings(): 66 | return settings(mysql) 67 | 68 | @app.route("/delete", methods=['GET', 'POST']) 69 | def render_delete(): 70 | if request.method == 'GET': 71 | return render_template("close_account.html", error = session.pop('error', None)) 72 | else: 73 | # deletion logic 74 | pw_hashed = hashlib.sha256(request.form['password'].encode('utf-8')).digest().replace(b"\0", b"\1") 75 | c = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 76 | c.execute("SELECT * FROM users WHERE id = %s", (session['user_id'],)) 77 | data = c.fetchone() 78 | c.close() 79 | if data == None: 80 | # should never happen ;) 81 | session['error'] = "An unknown error occurred." 82 | return redirect(url_for("render_delete"), 303) 83 | 84 | if bcrypt.checkpw(pw_hashed, data['password']): 85 | # passwords match, delete the account 86 | session['error'] = "succ ess" 87 | c = mysql.connection.cursor() 88 | c.execute("SELECT credentials_id FROM bots WHERE user_id = %s", (session['user_id'],)) 89 | credentials_list = c.fetchall() 90 | for credentials_id in credentials_list: 91 | c.execute("SELECT client_id, client_secret, secret FROM credentials WHERE id = %s", (credentials_id,)) 92 | # TODO: maybe schedule the push deletions on a cron job or something, if the user has a lot of accounts (or they're on slow instances) this could take a while or even time out 93 | credentials = c.fetchone() 94 | try: 95 | client = Mastodon( 96 | credentials[0], 97 | credentials[1], 98 | credentials[2], 99 | "https://{}".format(id.split("@")[2]) 100 | ) 101 | client.push_subscription_delete() 102 | except: 103 | # if it fails, don't prevent the user from deleting their account 104 | # TODO: maybe notify that some accounts failed to unregister push 105 | pass 106 | c.execute("DELETE FROM `credentials` WHERE `id` = %s", (credentials_id,)) 107 | 108 | # the big boy step 109 | c.execute("DELETE FROM users WHERE id = %s", (session['user_id'],)) 110 | 111 | c.close() 112 | mysql.connection.commit() 113 | 114 | # TODO: show a "deletion successful" message or something 115 | return redirect(url_for("do_signout"), 303) 116 | 117 | else: 118 | session['error'] = "Password incorrect." 119 | return redirect(url_for("render_delete"), 303) 120 | 121 | @app.route("/bot/edit/", methods = ['GET', 'POST']) 122 | def render_bot_edit(id): 123 | return bot_edit(id, mysql) 124 | 125 | @app.route("/bot/delete/", methods=['GET', 'POST']) 126 | def bot_delete(id): 127 | if bot_check(id): 128 | if request.method == 'GET': 129 | instance = id.split("@")[2] 130 | c = mysql.connection.cursor() 131 | c.execute("SELECT icon FROM bots WHERE handle = %s", (id,)) 132 | icon = c.fetchone()[0] 133 | return render_template("bot/delete.html", instance = instance, icon = icon) 134 | else: 135 | # delete bot by deleting its credentials 136 | # FK constraint will delete bot 137 | c = mysql.connection.cursor() 138 | c.execute("SELECT credentials_id FROM bots WHERE handle = %s", (id,)) 139 | credentials_id = c.fetchone()[0] 140 | c.execute("SELECT client_id, client_secret, secret FROM credentials WHERE id = %s", (credentials_id,)) 141 | credentials = c.fetchone() 142 | client = Mastodon( 143 | credentials[0], 144 | credentials[1], 145 | credentials[2], 146 | "https://{}".format(id.split("@")[2]) 147 | ) 148 | client.push_subscription_delete() 149 | c.execute("DELETE FROM `credentials` WHERE `id` = %s", (credentials_id,)) 150 | c.close() 151 | mysql.connection.commit() 152 | 153 | return redirect(url_for("render_home"), 303) 154 | 155 | @app.route("/bot/toggle/") 156 | def bot_toggle(id): 157 | if bot_check(id): 158 | c = mysql.connection.cursor() 159 | c.execute("UPDATE `bots` SET `enabled` = NOT `enabled` WHERE `handle` = %s", (id,)) 160 | mysql.connection.commit() 161 | c.close() 162 | return redirect(url_for("render_home"), 303) 163 | 164 | @app.route("/bot/chat/") 165 | def bot_chat(id): 166 | # return render_template("coming_soon.html") 167 | if bot_check(id): 168 | c = mysql.connection.cursor() 169 | c.execute("SELECT icon FROM `bots` WHERE handle = %s", (id,)) 170 | icon = c.fetchone()[0] 171 | if icon is None: 172 | icon = "/img/bot_generic.png" 173 | return render_template("/bot/chat.html", bot = id, icon = icon) 174 | 175 | @app.route("/bot/chat//message") 176 | def bot_chat_message(id): 177 | if bot_check(id): 178 | _, message = functions.generate_output(id) 179 | return message 180 | 181 | @app.route("/bot/blacklist/") 182 | def bot_blacklist(id): 183 | return render_template("coming_soon.html") 184 | 185 | @app.route("/bot/accounts/") 186 | def bot_accounts(id): 187 | if bot_check(id): 188 | session['bot'] = id 189 | c = mysql.connection.cursor() 190 | c.execute("SELECT COUNT(*) FROM `bot_learned_accounts` WHERE `bot_id` = %s", (id,)) 191 | user_count = c.fetchone()[0] 192 | users = {} 193 | post_count = {} 194 | 195 | if user_count > 0: 196 | dc = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 197 | dc.execute("SELECT `fedi_id`, `enabled` FROM `bot_learned_accounts` WHERE `bot_id` = %s", (id,)) 198 | users = dc.fetchall() 199 | dc.close() 200 | 201 | post_count = {} 202 | for user in users: 203 | c.execute("SELECT COUNT(*) FROM `posts` WHERE `fedi_id` = %s", (user['fedi_id'],)) 204 | post_count[user['fedi_id']] = c.fetchone()[0] 205 | 206 | c.close() 207 | 208 | return render_template("bot/accounts.html", users = users, post_count = post_count) 209 | 210 | @app.route("/bot/accounts/add", methods = ['GET', 'POST']) 211 | def render_bot_accounts_add(): 212 | return bot_accounts_add(mysql, cfg) 213 | 214 | @app.route("/bot/accounts/toggle/") 215 | def bot_accounts_toggle(id): 216 | c = mysql.connection.cursor() 217 | c.execute("UPDATE `bot_learned_accounts` SET `enabled` = NOT `enabled` WHERE `fedi_id` = %s AND `bot_id` = %s", (id, session['bot'])) 218 | mysql.connection.commit() 219 | c.close() 220 | return redirect("/bot/accounts/{}".format(session['bot']), 303) 221 | 222 | @app.route("/bot/accounts/delete/", methods=['GET', 'POST']) 223 | def bot_accounts_delete(id): 224 | if request.method == 'GET': 225 | instance = id.split("@")[2] 226 | return render_template("bot/accounts_delete.html", user = id, instance = instance) 227 | else: 228 | #NOTE: when user credential support is added, we'll need to delete the creds too 229 | c = mysql.connection.cursor() 230 | c.execute("DELETE FROM `bot_learned_accounts` WHERE `fedi_id` = %s AND bot_id = %s", (id, session['bot'])) 231 | # check to see if anyone else is learning from this account 232 | c.execute("SELECT COUNT(*) FROM `bot_learned_accounts` WHERE `fedi_id` = %s", (id,)) 233 | if c.fetchone()[0] == 0: 234 | # nobody else learns from this account, remove it from the db 235 | c.execute("DELETE FROM `fedi_accounts` WHERE `handle` = %s", (id,)) 236 | c.close() 237 | mysql.connection.commit() 238 | 239 | return redirect("/bot/accounts/{}".format(session['bot']), 303) 240 | 241 | @app.route("/bot/create/", methods=['GET', 'POST']) 242 | def render_bot_create(): 243 | return bot_create(mysql, cfg, scopes, scopes_pleroma) 244 | 245 | @app.route("/bot/create/back") 246 | def bot_create_back(): 247 | session['step'] -= 1 248 | return redirect(url_for("render_bot_create"), 303) 249 | 250 | @app.route("/do/authenticate_bot") 251 | def do_authenticate_bot(): 252 | session['code'] = request.args.get('code') 253 | session['step'] = 4 254 | return redirect(url_for("render_bot_create"), 303) 255 | 256 | @app.route("/push/", methods = ['POST']) 257 | def push(id): 258 | c = mysql.connection.cursor() 259 | c.execute("SELECT client_id, client_secret, secret FROM credentials WHERE id = (SELECT credentials_id FROM bots WHERE handle = %s)", (id,)) 260 | login = c.fetchone() 261 | client = Mastodon( 262 | client_id = login[0], 263 | client_secret = login[1], 264 | access_token = login[2], 265 | api_base_url = "https://{}".format(id.split("@")[2]) 266 | ) 267 | 268 | c.execute("SELECT push_private_key, push_secret, replies_enabled FROM bots WHERE handle = %s", (id,)) 269 | bot = c.fetchone() 270 | if not bot[2]: 271 | return "Replies disabled." 272 | 273 | params = { 274 | 'privkey': int(bot[0].rstrip("\0")), 275 | 'auth': bot[1] 276 | } 277 | try: 278 | push_object = client.push_subscription_decrypt_push(request.data, params, request.headers['Encryption'], request.headers['Crypto-Key']) 279 | notification = client.notifications(id = push_object['notification_id']) 280 | me = client.account_verify_credentials()['id'] 281 | except: 282 | return "Push failed - do we still have access to {}?".format(id) 283 | 284 | # first, check how many times the bot has posted in this thread. 285 | # if it's over 15, don't reply. 286 | # this is to stop endless reply chains between two bots. 287 | try: 288 | context = client.status_context(notification['status']['id']) 289 | my_posts = 0 290 | for post in context['ancestors']: 291 | if post['account']['id'] == me: 292 | my_posts += 1 293 | if my_posts >= 15: 294 | # don't reply 295 | return "Didn't reply." 296 | except: 297 | # failed to fetch context 298 | # assume we haven't been participating in this thread 299 | pass 300 | 301 | functions.make_post([id, notification['status']['id'], notification['status']['visibility'], "@" + notification['account']['acct']]) 302 | 303 | return "Success!" 304 | 305 | @app.route("/do/signup", methods=['POST']) 306 | def do_signup(): 307 | # email validation is basically impossible without actually sending an email to the address 308 | # because fedibooks can't send email yet, we'll just check if the string contains an @ ;) 309 | if "@" not in request.form['email']: 310 | session['error'] = "Invalid email address." 311 | return redirect(url_for("show_signup_page"), 303) 312 | 313 | if len(request.form['password']) < 8: 314 | session['error'] = "Password too short." 315 | return redirect(url_for("show_signup_page"), 303) 316 | 317 | c = mysql.connection.cursor() 318 | c.execute("SELECT COUNT(*) FROM users WHERE email = %s", (request.form['email'],)) 319 | if c.fetchone()[0] > 0: 320 | session['error'] = "Email address already in use." 321 | return redirect(url_for("show_signup_page"), 303) 322 | 323 | pw_hashed = hashlib.sha256(request.form['password'].encode('utf-8')).digest().replace(b"\0", b"\1") 324 | pw = bcrypt.hashpw(pw_hashed, bcrypt.gensalt(12)) 325 | 326 | # try to sign up 327 | c.execute("INSERT INTO `users` (email, password) VALUES (%s, %s)", (request.form['email'], pw)) 328 | user_id = c.lastrowid 329 | mysql.connection.commit() 330 | c.close() 331 | 332 | # success! 333 | session['user_id'] = user_id 334 | return redirect(url_for('render_home')) 335 | 336 | @app.route("/do/signout") 337 | def do_signout(): 338 | session.clear() 339 | return redirect(url_for("render_home")) 340 | 341 | @app.route("/do/login", methods=['POST']) 342 | def do_login(): 343 | pw_hashed = hashlib.sha256(request.form['password'].encode('utf-8')).digest().replace(b"\0", b"\1") 344 | c = mysql.connection.cursor(MySQLdb.cursors.DictCursor) 345 | c.execute("SELECT * FROM users WHERE email = %s", (request.form['email'],)) 346 | data = c.fetchone() 347 | c.close() 348 | if data == None: 349 | session['error'] = "Incorrect login information." 350 | return redirect(url_for("show_login_page"), 303) 351 | 352 | if bcrypt.checkpw(pw_hashed, data['password']): 353 | session['user_id'] = data['id'] 354 | return redirect(url_for("render_home")) 355 | 356 | else: 357 | session['error'] = "Incorrect login information." 358 | return redirect(url_for("show_login_page"), 303) 359 | 360 | @app.route("/issue/bug") 361 | def report_bug(): 362 | # return render_template("report_bug.html") 363 | return render_template("coming_soon.html") 364 | 365 | @app.route("/help/settings") 366 | def help_settings(): 367 | return render_template("help/settings.html") 368 | 369 | @app.route("/img/bot_generic.png") 370 | def img_bot_generic(): 371 | return send_file("static/bot_generic.png", mimetype="image/png") 372 | 373 | @app.route("/favicon.ico") 374 | def favicon(): 375 | return send_file("static/favicon.ico") 376 | 377 | @app.route("/.well-known/webfinger") 378 | def webfinger(): 379 | return render_template("ap/webfinger.json", base_uri = cfg['base_uri']), 200, {'Content-type':'application/json'} 380 | 381 | @app.route("/actor") 382 | def actor(): 383 | # pubkey = functions.get_key()['public'].replace("\n", "\\n") 384 | pubkey = functions.signed_get("https://fedi.lynnesbian.space/users/lynnesbian/outbox.json?page=true") 385 | return render_template("ap/actor.json", base_uri = cfg['base_uri'], pubkey = pubkey), 200, {'Content-type':'application/json'} 386 | 387 | 388 | def bot_check(bot): 389 | # check to ensure bot is owned by user 390 | c = mysql.connection.cursor() 391 | c.execute("SELECT COUNT(*) FROM `bots` WHERE `handle` = %s AND `user_id` = %s", (bot, session['user_id'])) 392 | return c.fetchone()[0] == 1 393 | -------------------------------------------------------------------------------- /app/wsgi.py: -------------------------------------------------------------------------------- 1 | from webui import app 2 | 3 | if __name__ == "__main__": 4 | app.run() 5 | -------------------------------------------------------------------------------- /db/setup.sql: -------------------------------------------------------------------------------- 1 | USE `fedibooks`; 2 | CREATE TABLE IF NOT EXISTS `users` ( 3 | `id` INT AUTO_INCREMENT PRIMARY KEY, 4 | `email` VARCHAR(128) UNIQUE NOT NULL, 5 | `password` BINARY(60) NOT NULL, 6 | `email_verified` BOOLEAN DEFAULT 0, 7 | `fetch` ENUM('always', 'once', 'never') DEFAULT 'once', 8 | `submit` ENUM('always', 'once', 'never') DEFAULT 'once', 9 | `generation` ENUM('always', 'once', 'never') DEFAULT 'once', 10 | `reply` ENUM('always', 'once', 'never') DEFAULT 'once' 11 | ) ENGINE = INNODB; 12 | CREATE TABLE IF NOT EXISTS `credentials` ( 13 | `id` INT AUTO_INCREMENT PRIMARY KEY, 14 | `client_id` VARCHAR(128) NOT NULL, 15 | `client_secret` VARCHAR(128) NOT NULL, 16 | `secret` VARCHAR(128) NOT NULL 17 | ) ENGINE = INNODB; 18 | CREATE TABLE IF NOT EXISTS `bots` ( 19 | `handle` VARCHAR(128) PRIMARY KEY, 20 | `user_id` INT NOT NULL, 21 | `credentials_id` INT NOT NULL, 22 | `push_private_key` BINARY(128) NOT NULL, 23 | `push_public_key` BINARY(128) NOT NULL, 24 | `push_secret` BINARY(16), 25 | `instance_type` VARCHAR(64) NOT NULL DEFAULT 'Mastodon', 26 | `enabled` BOOLEAN DEFAULT 0, 27 | `replies_enabled` BOOLEAN DEFAULT 1, 28 | `post_frequency` SMALLINT UNSIGNED DEFAULT 30, 29 | `content_warning` VARCHAR(128), 30 | `length` SMALLINT UNSIGNED DEFAULT 500, 31 | `fake_mentions` ENUM('always', 'middle', 'never') DEFAULT 'middle', 32 | `fake_mentions_full` BOOLEAN DEFAULT 0, 33 | `post_privacy` ENUM('public', 'unlisted', 'private') DEFAULT 'unlisted', 34 | `learn_from_cw` BOOLEAN DEFAULT 0, 35 | `last_post` DATETIME DEFAULT CURRENT_TIMESTAMP(), 36 | `icon` VARCHAR(512), 37 | `icon_update_time` DATETIME DEFAULT '1000-01-01 00:00:00', 38 | FOREIGN KEY (`user_id`) REFERENCES users(id) ON DELETE CASCADE, 39 | FOREIGN KEY (`credentials_id`) REFERENCES credentials(id) ON DELETE CASCADE 40 | ) ENGINE = INNODB; 41 | CREATE TABLE IF NOT EXISTS `fedi_accounts` ( 42 | `handle` VARCHAR(128) PRIMARY KEY, 43 | `outbox` VARCHAR(256), 44 | `credentials_id` INT, 45 | `icon` VARCHAR(512), 46 | `icon_update_time` DATETIME DEFAULT 0, 47 | FOREIGN KEY (`credentials_id`) REFERENCES credentials(id) ON DELETE CASCADE 48 | ) ENGINE = INNODB; 49 | CREATE TABLE IF NOT EXISTS `bot_learned_accounts` ( 50 | `bot_id` VARCHAR(128) NOT NULL, 51 | `fedi_id` VARCHAR(128) NOT NULL, 52 | `enabled` BOOLEAN DEFAULT 1, 53 | FOREIGN KEY (`bot_id`) REFERENCES bots(handle) ON DELETE CASCADE, 54 | FOREIGN KEY (`fedi_id`) REFERENCES fedi_accounts(handle) ON DELETE CASCADE 55 | ) ENGINE = INNODB; 56 | CREATE TABLE IF NOT EXISTS `posts` ( 57 | `id` BIGINT AUTO_INCREMENT PRIMARY KEY, 58 | `fedi_id` VARCHAR(128), 59 | `post_id` VARCHAR(64) NOT NULL, 60 | `content` TEXT NOT NULL, 61 | `cw` BOOLEAN NOT NULL, 62 | FOREIGN KEY (`fedi_id`) REFERENCES fedi_accounts(handle) ON DELETE CASCADE 63 | ) ENGINE = INNODB; 64 | CREATE TABLE IF NOT EXISTS `word_blacklist` ( 65 | `id` INT AUTO_INCREMENT PRIMARY KEY, 66 | `bot_id` VARCHAR(128) NOT NULL, 67 | `phrase` VARCHAR(128) NOT NULL, 68 | `whole_word` BOOLEAN NOT NULL, 69 | FOREIGN KEY (`bot_id`) REFERENCES bots(handle) ON DELETE CASCADE 70 | ) ENGINE = INNODB; 71 | CREATE TABLE IF NOT EXISTS `contact_history` ( 72 | `user_id` INT NOT NULL, 73 | `fetch` BOOLEAN DEFAULT 0, 74 | `submit` BOOLEAN DEFAULT 0, 75 | `generation` BOOLEAN DEFAULT 0, 76 | `reply` BOOLEAN DEFAULT 0, 77 | FOREIGN KEY (`user_id`) REFERENCES users(id) ON DELETE CASCADE 78 | ) ENGINE = INNODB; 79 | CREATE TABLE IF NOT EXISTS `http_auth_key` ( 80 | `private` TEXT NOT NULL, 81 | `public` TEXT NOT NULL 82 | ) ENGINE = INNODB; -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lynnesbian/FediBooks/ebdc384454246a330ef954c670b2cafb88943c71/logo.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Mastodon.py==1.5.1 2 | markovify==0.8.3 3 | beautifulsoup4==4.9.1 4 | requests==2.24.0 5 | Flask==1.1.2 6 | flask-mysqldb==0.2.0 7 | bcrypt == 3.1.7 8 | requests==2.24.0 9 | http-ece==1.1.0 10 | pycryptodome==3.9.8 11 | cryptography==2.9.2 12 | pebble==4.5.3 13 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | cd app 2 | env FLASK_APP=webui.py flask run 3 | cd .. 4 | --------------------------------------------------------------------------------