├── .gitignore ├── LICENSE ├── README.md ├── api.py ├── config.py ├── controllers ├── __init__.py ├── accounts.py ├── incoming.py └── jobs.py ├── library ├── __init__.py ├── errors.py ├── grab_bag.py ├── mailer.py └── phaxio.py ├── log └── README.md ├── media └── cover_sheets │ └── default.pdf ├── models ├── __init__.py ├── account.py ├── failed_payment.py ├── incoming_fax.py ├── incoming_number.py ├── job.py ├── password_reset.py └── transaction.py ├── more_requirements.txt ├── raise_price.py ├── requirements.txt ├── templates ├── accounts_bootstrap.html ├── accounts_create.html ├── accounts_email_password_reset.html ├── accounts_login.html ├── jobs_create.html └── jobs_restart.html ├── worker.py └── workers ├── __init__.py ├── cron.py └── jobs.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | ._.DS_Store 3 | venv 4 | .env 5 | tmp 6 | *.pyc 7 | uwsgi.ini 8 | log 9 | scripts 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Fax Robot API 2 | ============= 3 | #### A Python API to send faxes. Now, with chicken! 4 | 5 | Introduction 6 | ------------ 7 | Fax Robot is an easy-to-use API for sending faxes through your own faxmodem(s). 8 | It's based on a Flask web API and one or more worker processes. Faxes are sent 9 | into a queue, so you can send tons of them in, and they'll be 10 | processed one by one. Or, if you have a bunch of faxmodems and phone lines, you 11 | can run multiple workers and power through them really quickly. 12 | 13 | Sending faxes to long distance numbers is not free, so Fax Robot can optionally 14 | collect payments from API users via [Stripe][2]. Users purchase stored credit, 15 | and faxes are charged against this credit based on a fixed cost per page. Or, if 16 | you're feeling generous, you can make it free for anyone with network access. 17 | 18 | Fax Robot was designed to be easy to set up and configure by anyone with basic 19 | Python devops skills. It's licensed under 20 | [the GNU General Public License, Version 3][3]. 21 | 22 | **Also check out [faxrobot-www][7], which is a frontend webapp for the Fax Robot 23 | API.** 24 | 25 | Dependencies 26 | ------------ 27 | * One or more physical faxmodems hooked up to land lines 28 | * Python 2.7 29 | * PostgreSQL 30 | * Redis 31 | * ImageMagick (particularly the `convert` and `composite` commands) 32 | * [paps][8] 33 | * [efax][9] (the linux command to send faxes) 34 | * (Optional) [Stripe API][2], only needed if you're collecting payments. 35 | * (Optional) [SparkPost API][5], for sending account-related emails to 36 | API users. 37 | * (Optional) [Amazon S3 storage][4]. Only needed if you have multiple servers 38 | for your workers (basically stores your temp files in the cloud) 39 | 40 | Installation 41 | ------------ 42 | There are two pieces to Fax Robot: a Python Flask API and the worker process 43 | that actually runs through the queue and sends the faxes. How you run these in 44 | production will vary depending on your hosting infrastructure (production 45 | deployment is left as an exercise to the reader), but local testing is easy. 46 | 47 | #### Set up your Virtualenv and packages 48 | 49 | You should use [Virtualenv] to isolate Fax Robot's required package dependencies 50 | away from your system Python installation. You don't have to, but come on. 51 | Assuming you have `virtualenv` installed, do the following commands from within 52 | your Fax Robot project directory to install Fax Robot's required packages: 53 | 54 | ``` 55 | virtualenv venv 56 | source venv/bin/activate 57 | pip install -r requirements.txt 58 | ``` 59 | 60 | #### Set up your environment variables 61 | 62 | Fax Robot's configuration is stored in system environment variables. You should 63 | create a file called `.env` in your Fax Robot project directory (or wherever you 64 | like). The file should look something like this: 65 | 66 | ``` 67 | export DEBUG=true 68 | export SECRET_KEY=asdf1234 69 | export DATABASE_URI=postgres://username:password@localhost/faxrobot 70 | export REDIS_URI=redis://127.0.0.1:6379?db=1 71 | export REQUIRE_PAYMENTS=on 72 | export DEFAULT_COST_PER_PAGE=0.06 73 | export AWS_STORAGE=off 74 | export AWS_ACCESS_KEY=AKSPLGHLOL 75 | export AWS_SECRET_KEY='trolol' 76 | export AWS_S3_BUCKET='s3.faxrobot.io' 77 | export FAXROBOT_DIR=/htdocs/faxrobot 78 | export GLOBAL_SALT=omgtrolol 79 | export STRIPE_SECRET_KEY=sk_test_12345678 80 | export SERVEOFFICE2PDF_URL=http://convert.dev/convert 81 | export PROJECT_NAME='Fax Robot' 82 | export SPARKPOST_API_KEY=asdf 83 | export EMAIL_FROM='support@faxrobot.io' 84 | export EMAIL_FROM_NAME='Fax Robot' 85 | export EMAIL_SUPPORT='support@faxrobot.io' 86 | export EMAIL_FEEDBACK='human@faxrobot.io' 87 | export FAXROBOT_URL='https://faxrobot.io' 88 | ``` 89 | 90 | Here are the specific environment variables, and what they do: 91 | 92 | * **`DEBUG`**: Whether to run the API in debug mode. Useful for local testing. 93 | 94 | * **`SECRET_KEY`**: Secret key used by Flask for sessions. It's probably not 95 | used for anything, but good practice to have it just in case. 96 | 97 | * **`DATABASE_URI` (required)**: A PostgreSQL connection string to use for 98 | database access. Database tables are created automatically with SQLAlchemy, so 99 | you don't have to set the schema up manually. 100 | 101 | * **`REDIS_URI` (required)**: A Redis connection string. Required for the 102 | [rq][1] worker to operate. 103 | 104 | * **`DEFAULT_COST_PER_PAGE`**: The default cost per page in USD to charge for 105 | outgoing faxes. The default is 0.06. 106 | 107 | * **`REQUIRE_PAYMENTS`**: If set to "on" then API users will need to purchase 108 | credit via [Stripe][2] API endpoints in order to send faxes. This also means 109 | you will need a valid `STRIPE_SECRET_KEY` in the configuration. 110 | 111 | * **`AWS_STORAGE`**: If set to "on" then temporary data for jobs will be 112 | uploaded to Amazon S3. This is only useful if you have more than one physical 113 | server running the Fax Robot worker process. Turning this on also means you'll 114 | have to set up the other `AWS_` prefixed configuration variables. 115 | 116 | * **`AWS_ACCESS_KEY`**: Your Amazon AWS Access Key ID. 117 | 118 | * **`AWS_SECRET_KEY`**: Your Amazon AWS Secret Key. 119 | 120 | * **`AWS_S3_BUCKET`**: The Amazon S3 bucket to use for data storage. 121 | 122 | * **`FAXROBOT_DIR` (required)**: The directory you have the Fax Robot project 123 | stored in. 124 | 125 | * **`GLOBAL_SALT` (required)**: A global salt value used for hashing passwords 126 | and other secret values. This should be an arbitrary string (longer is better) 127 | 128 | * **`STRIPE_SECRET_KEY`**: Only required if `REQUIRE_PAYMENTS` is turned on. 129 | This is your Stripe secret key used for processing payments. 130 | 131 | * **`SERVEOFFICE2PDF_URL`**: ServeOffice2PDF is a separate web application that 132 | converts Microsoft Office file formats (like .doc and .docx) to PDF. This is 133 | optional, and only used to support faxing these formats via the Fax Robot API. 134 | By default Microsoft Office formats are unsupported. 135 | 136 | * **`PROJECT_NAME`**: The name you're giving to your instance of the project. 137 | 138 | * **`SPARKPOST_API_KEY`**: Used for sending transactional emails to Fax Robot 139 | API accounts. If not present, then emails are disabled. 140 | 141 | * **`EMAIL_FROM`**: The from email address for transactional emails. 142 | 143 | * **`EMAIL_FROM_NAME`**: The from email name for transactional emails. 144 | 145 | * **`EMAIL_SUPPORT`**: A support email address to include in relevent 146 | transactional emails. 147 | 148 | * **`EMAIL_FEEDBACK`**: A feedback email address to include in relevent 149 | transactional emails. 150 | 151 | * **`FAXROBOT_URL`**: The URL to a front-end client webapp for your Fax Robot 152 | instance. 153 | 154 | Once your environment variables are configured, load them into your shell using 155 | the `source` command: 156 | 157 | ``` 158 | source .env 159 | ``` 160 | 161 | #### Running the Fax Robot API 162 | 163 | The API listens for incoming fax jobs (and other CRUD type API requests) and 164 | pushes faxes onto the worker's queue. To start it, you'll simply run 165 | `python api.py` after following the steps above. To recap: 166 | 167 | ``` 168 | source venv/bin/activate 169 | source .env 170 | python api.py 171 | ``` 172 | 173 | When running in Debug mode, the API will listen on `localhost:9001`. 174 | 175 | #### Running the Worker 176 | 177 | The worker listens for fax jobs on the [rq][1] queue and processes them. 178 | After loading your environment up, you'll run `python worker.py` with your 179 | faxmodem device specified as an argument. For example: 180 | 181 | ``` 182 | source venv/bin/activate 183 | source .env 184 | python worker.py --device /dev/ttyUSB0 --callerid '+1 202 555 1212' 185 | ``` 186 | 187 | If you have more than one faxmodem hooked up, you can run multiple instances of 188 | `worker.py` for maximum pwnage. 189 | 190 | **worker.py command line arguments** 191 | 192 | * **`--help`**: show help message 193 | 194 | * **`--device`**: the modem device to send faxes through, eg `/dev/ttyUSB0`. 195 | The device for your faxmodem must be accessible by the user account 196 | you're running the `worker.py` process under. (hint: add your user account to 197 | the `dialout` group) 198 | 199 | * **`--callerid`**: the caller ID string to display on outgoing faxes, in 200 | international format. Some fax machines may not accept characters other than 201 | numbers, space, and '+'. 202 | 203 | * **`--listen`**: which queue(s) the worker should listen to. Can be `high`, 204 | `default`, or `low`, or a comma-separated list thereof, where the first 205 | items in the list are prioritized more highly. See the section below on queue 206 | priorities. 207 | 208 | 209 | #### Worker queue priorities 210 | 211 | Fax Robot uses [rq][1] to process jobs asynchronously from incoming API 212 | requests. These jobs are tagged by priority: `high`, `default`, and `low`. You 213 | should always have at least one `worker.py` instance dedicated to `high` 214 | priority queue items. 215 | 216 | * **`high`**: The job which does the initial cost processing and image 217 | conversion for new faxes is high priority, because users will often poll the 218 | fax status endpoint to see cost information before sending faxes. 219 | 220 | * **`default`**: Sending faxes is a default priority task. Each faxmodem should 221 | be given its own worker process listening on the `default` queue. 222 | 223 | * **`low`**: You can optionally flag certain accounts as `low` priority by 224 | editing them in the database. This allows you to prioritize outgoing faxes 225 | from other accounts before sending any from the low priority accounts (if both 226 | are pending at the same time). Be sure to set your fax worker instance to 227 | favor `default` jobs above `low` jobs like so: 228 | 229 | ``` 230 | python worker.py --listen 'default,low' 231 | ``` 232 | 233 | 234 | API Documentation 235 | ----------------- 236 | **Read the full API documentation at https://faxrobot.io/api** 237 | 238 | [1]: http://python-rq.org/ 239 | [2]: https://stripe.com 240 | [3]: https://www.gnu.org/copyleft/gpl.html 241 | [4]: http://aws.amazon.com/s3/ 242 | [5]: https://www.sparkpost.com 243 | [6]: https://virtualenv.pypa.io/en/latest/ 244 | [7]: https://github.com/lyonbros/faxrobot-www 245 | [8]: http://linux.die.net/man/1/paps 246 | [9]: http://linux.die.net/man/1/efax 247 | -------------------------------------------------------------------------------- /api.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, session, g, redirect, url_for, abort, \ 2 | render_template, flash, jsonify, Response 3 | from flask.ext.cors import CORS 4 | from flask_sqlalchemy import SQLAlchemy 5 | from models import db, initialize_database 6 | import sys 7 | 8 | app = Flask(__name__) 9 | cors = CORS(app, allow_headers='Content-Type, Origin, Accept') 10 | app.config.from_object('config.Config') 11 | db.init_app(app) 12 | initialize_database(app) 13 | 14 | from controllers.jobs import jobs as jobs_module 15 | from controllers.accounts import accounts as accounts_module 16 | from controllers.incoming import incoming as incoming_module 17 | 18 | app.register_blueprint(jobs_module) 19 | app.register_blueprint(accounts_module) 20 | app.register_blueprint(incoming_module) 21 | 22 | if __name__ == '__main__': 23 | if app.config['DEBUG'] == True: 24 | print >> sys.stderr, 'Running locally in debug mode.' 25 | app.run('0.0.0.0', 9001) 26 | else: 27 | app.run() -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from distutils.util import strtobool 3 | 4 | class Config(object): 5 | JSON_AS_ASCII = False 6 | DEBUG = strtobool(os.environ.get('DEBUG', 'false')) 7 | SECRET_KEY = os.environ.get('SECRET_KEY') 8 | SQLALCHEMY_POOL_RECYCLE = 60 * 60 9 | SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI') 10 | REDIS_URI = os.environ.get('REDIS_URI') 11 | PROPAGATE_EXCEPTIONS = True -------------------------------------------------------------------------------- /controllers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lyonbros/faxrobot/4dfdd6c9bd4cd335a7dc4aaaa6188ad808b78d71/controllers/__init__.py -------------------------------------------------------------------------------- /controllers/accounts.py: -------------------------------------------------------------------------------- 1 | import os 2 | from flask import Blueprint, request, render_template, jsonify, current_app 3 | from models import db 4 | from sqlalchemy.exc import IntegrityError 5 | from rq import Queue 6 | from redis import Redis 7 | from rq import Queue 8 | from library.grab_bag import fix_ip, password_hash, random_hash, o 9 | from library.errors import api_error, ValidationError 10 | from models.account import Account 11 | from models.transaction import Transaction 12 | from models.failed_payment import FailedPayment 13 | from models.password_reset import PasswordReset 14 | from workers.cron import charge_subscribers 15 | 16 | accounts = Blueprint('accounts', __name__, url_prefix='/accounts') 17 | 18 | @accounts.route('/create', methods=['GET', 'POST', 'OPTIONS']) 19 | def create(): 20 | """Creates a new user account""" 21 | 22 | from library.mailer import email_registration 23 | 24 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 25 | 26 | if request.method == 'POST': 27 | 28 | v = request.values.get 29 | data = { 30 | 'email': v('email'), 31 | 'password': v('password'), 32 | 'first_name': v('first_name'), 33 | 'last_name': v('last_name'), 34 | 'address': v('address'), 35 | 'address2': v('address2'), 36 | 'city': v('city'), 37 | 'state': v('state'), 38 | 'zip': v('zip'), 39 | } 40 | try: 41 | account = Account(**data) 42 | account.validate() 43 | except ValidationError, err: 44 | return jsonify(api_error(err.ref)), 400 45 | 46 | try: 47 | db.session.add(account) 48 | db.session.commit() 49 | except IntegrityError: 50 | return jsonify(api_error('ACCOUNTS_CREATE_FAIL')), 400 51 | 52 | email_registration(account) 53 | 54 | return jsonify(account.public_data()) 55 | 56 | else: 57 | return render_template('accounts_create.html'); 58 | 59 | @accounts.route('/login', methods=['GET', 'POST']) 60 | def login(): 61 | """Logs into a user account""" 62 | 63 | if request.method == 'POST': 64 | v = request.values.get 65 | emails = Account.query.filter_by(email=v('email')) 66 | account = emails.first() 67 | 68 | if account == None: 69 | return jsonify(api_error('ACCOUNTS_LOGIN_ERROR')), 401 70 | elif account.password != password_hash(v('password')): 71 | return jsonify(api_error('ACCOUNTS_LOGIN_ERROR')), 401 72 | 73 | return jsonify(account.public_data()) 74 | else: 75 | return render_template('accounts_login.html'); 76 | 77 | @accounts.route('/get', methods=['GET']) 78 | def get(): 79 | """Gets the account information, provided a correct api_key is specified.""" 80 | account_id = Account.authorize(request.values.get('api_key')) 81 | if account_id == None: 82 | return jsonify(api_error('API_UNAUTHORIZED')), 401 83 | 84 | account = Account.query.get(account_id) 85 | 86 | return jsonify(account.public_data()) 87 | 88 | @accounts.route('/update', methods=['POST']) 89 | def update(): 90 | """Updates an account""" 91 | 92 | from datetime import datetime 93 | import stripe 94 | import traceback 95 | import json 96 | from library.mailer import email_password_change 97 | 98 | stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') 99 | 100 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 101 | 102 | account_id = Account.authorize(request.values.get('api_key')) 103 | if not account_id: 104 | return jsonify(api_error('API_UNAUTHORIZED')), 401 105 | 106 | account = Account.query.get(account_id) 107 | 108 | v = request.values.get 109 | 110 | try: 111 | if v('email'): 112 | 113 | existing = Account.query.filter_by(email=v('email')) 114 | 115 | if existing.first() and not existing.first().id == account.id: 116 | raise ValidationError('ACCOUNTS_EMAIL_TAKEN') 117 | 118 | account.email = v('email') 119 | 120 | if v('password'): 121 | 122 | if not v('old_password'): 123 | raise ValidationError('ACCOUNTS_INVALID_OLD_PASSWORD') 124 | 125 | if not account.password == password_hash(v('old_password')): 126 | raise ValidationError('ACCOUNTS_INVALID_OLD_PASSWORD') 127 | 128 | account.password = password_hash(v('password')) 129 | 130 | if v('first_name'): 131 | account.first_name = v('first_name') 132 | 133 | if v('last_name'): 134 | account.last_name = v('last_name') 135 | 136 | if v('address'): 137 | account.address = v('address') 138 | 139 | if v('address2'): 140 | account.address2 = v('address2') 141 | 142 | if v('city'): 143 | account.city = v('city') 144 | 145 | if v('state'): 146 | account.state = v('state') 147 | 148 | if v('zip'): 149 | account.zip = v('zip') 150 | 151 | if v('auto_recharge') != None: 152 | account.auto_recharge = 1 if v('auto_recharge') == "1" else 0 153 | 154 | if v('email_success') != None: 155 | account.email_success = 1 if v('email_success') == "1" else 0 156 | 157 | if v('email_fail') != None: 158 | account.email_fail = 1 if v('email_fail') == "1" else 0 159 | 160 | if v('email_list') != None: 161 | account.email_list = 1 if v('email_list') == "1" else 0 162 | 163 | if v('stripe_token') and v('last4'): 164 | try: 165 | customer = stripe.Customer.create( 166 | description="%s Customer %s" % ( 167 | os.environ.get('PROJECT_NAME'), account.id), 168 | email=account.email, 169 | source=v('stripe_token') # 'trol' 170 | ) 171 | account.stripe_token = customer["id"] 172 | account.stripe_card = customer["sources"]["data"][0]["id"] 173 | account.last4 = v('last4') 174 | except: 175 | payment = {'_DEBUG': traceback.format_exc()} 176 | data = { 177 | 'amount': 0, 178 | 'account_id': account.id, 179 | 'source': 'stripe', 180 | 'debug': json.dumps(payment), 181 | 'ip_address': ip, 182 | 'payment_type': 'stored_payment' 183 | } 184 | failed_payment = FailedPayment(**data) 185 | db.session.add(failed_payment) 186 | db.session.commit() 187 | return jsonify(api_error('ACCOUNTS_STORED_PAYMENT_FAIL')), 400 188 | 189 | account.mod_date = datetime.now() 190 | account.validate() 191 | db.session.commit() 192 | 193 | # Send notification email for password / API key change 194 | if v('password'): 195 | email_password_change(account) 196 | 197 | info = account.public_data() 198 | info['mod_date'] = datetime.now() 199 | 200 | except ValidationError, err: 201 | return jsonify(api_error(err.ref)), 400 202 | 203 | return jsonify(info) 204 | 205 | @accounts.route('/reset_api_key', methods=['POST']) 206 | def reset_api_key(): 207 | """Resets the API key for an account""" 208 | 209 | from library.mailer import email_api_key_change 210 | from datetime import datetime 211 | 212 | account_id = Account.authorize(request.values.get('api_key')) 213 | if not account_id: 214 | return jsonify(api_error('API_UNAUTHORIZED')), 401 215 | 216 | account = Account.query.get(account_id) 217 | if account.password != password_hash(request.values.get('password')): 218 | return jsonify(api_error('ACCOUNTS_LOGIN_ERROR')), 401 219 | 220 | account.api_key = random_hash("%s%s" % (account.email, account.password)) 221 | account.mod_date = datetime.now() 222 | db.session.commit() 223 | 224 | email_api_key_change(account) 225 | 226 | return jsonify({ 227 | 'api_key': account.api_key 228 | }) 229 | 230 | 231 | @accounts.route('/remove_card', methods=['POST']) 232 | def remove_card(): 233 | """Removes stored credit card info from the account""" 234 | 235 | from datetime import datetime 236 | import json 237 | import stripe 238 | 239 | stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') 240 | 241 | account_id = Account.authorize(request.values.get('api_key')) 242 | if not account_id: 243 | return jsonify(api_error('API_UNAUTHORIZED')), 401 244 | 245 | account = Account.query.get(account_id) 246 | 247 | if account.stripe_token and account.stripe_card: 248 | try: 249 | customer = stripe.Customer.retrieve(account.stripe_token) 250 | customer.sources.retrieve(account.stripe_card).delete() 251 | except: 252 | pass # oh well, whatever. fuck it. 253 | 254 | account.stripe_token = None 255 | account.stripe_card = None 256 | account.last4 = None 257 | account.auto_recharge = 0 258 | account.mod_date = datetime.now() 259 | db.session.commit() 260 | 261 | return jsonify(account.public_data()) 262 | 263 | @accounts.route('/bootstrap', methods=['GET', 'POST', 'OPTIONS']) 264 | def bootstrap(): 265 | """ 266 | Implicitly creates a user account and logs them in by processing a Stripe 267 | payment and email. If the email address belongs to a registered account, it 268 | requires the account password to authorize the payment and login attempt. 269 | """ 270 | import json 271 | import stripe 272 | import sys 273 | import traceback 274 | from library.mailer import email_payment 275 | from datetime import datetime 276 | 277 | stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') 278 | 279 | account_id = Account.authorize(request.values.get('api_key')) 280 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 281 | 282 | if request.method == 'POST': 283 | 284 | v = request.values.get 285 | emails = Account.query.filter_by(email=v('email')) 286 | account = emails.first() 287 | 288 | o("Received bootstrap payment login: %s" % v('email')) 289 | 290 | if account_id and account != None and account.id != account_id: 291 | o("Account exists but user is logged in as someone else. Error.") 292 | return jsonify(api_error('ACCOUNTS_LOGIN_ERROR')), 401 293 | 294 | if account != None and account.password != password_hash(v('password'))\ 295 | and not account_id: 296 | o("Account exists but password mismatch. Erroring out.") 297 | return jsonify(api_error('ACCOUNTS_LOGIN_ERROR')), 401 298 | 299 | temporary_password = None 300 | 301 | if account == None: 302 | o("Creating account with temporary password.") 303 | temporary_password = random_hash(v('email'))[:8] 304 | data = { 305 | 'email': v('email'), 306 | 'password': temporary_password 307 | } 308 | try: 309 | account = Account(**data) 310 | except ValidationError, err: 311 | return jsonify(api_error(err.ref)), 400 312 | 313 | try: 314 | account.validate() 315 | db.session.add(account) 316 | except IntegrityError: 317 | return jsonify(api_error('ACCOUNTS_CREATE_FAIL')), 400 318 | 319 | o("Verifying payment with Stripe API.") 320 | failed = False 321 | 322 | try: 323 | payment = stripe.Charge.create( 324 | amount=int(float(v('amount')) * 100), 325 | currency="usd", 326 | source=v('stripe_token'), 327 | description="Bootstrap payment" 328 | ) 329 | except: 330 | o("STRIPE UNEXPECTED ERROR:", sys.exc_info()[0]) 331 | failed = True 332 | payment = {'_DEBUG': traceback.format_exc()} 333 | 334 | o(payment) 335 | 336 | if not failed and payment and payment.status == "succeeded": 337 | o("Payment success.") 338 | db.session.commit() 339 | data = { 340 | 'account_id': account.id, 341 | 'amount': v('amount'), 342 | 'source': 'stripe', 343 | 'source_id': payment.id, 344 | 'ip_address': ip, 345 | 'initial_balance': account.credit, 346 | 'trans_type': 'payment' 347 | } 348 | trans = Transaction(**data) 349 | db.session.add(trans) 350 | db.session.commit() 351 | 352 | o("Adding credit to account.") 353 | charged = float(payment.amount) / float(100) 354 | account.add_credit(charged) 355 | email_payment(account, charged, trans.id, payment.source.last4, 356 | temporary_password) 357 | 358 | else: 359 | o("--- PAYMENT FAIL. LOGGING INFO ---") 360 | db.session.expunge_all() 361 | data = { 362 | 'amount': v('amount'), 363 | 'account_id': account.id, 364 | 'source': 'stripe', 365 | 'debug': json.dumps(payment), 366 | 'ip_address': ip, 367 | 'payment_type': 'bootstrap' 368 | } 369 | failed_payment = FailedPayment(**data) 370 | db.session.add(failed_payment) 371 | db.session.commit() 372 | return jsonify(api_error('ACCOUNTS_PAYMENT_FAIL')), 400 373 | 374 | result = account.public_data() 375 | if temporary_password: 376 | result['temporary_password'] = temporary_password 377 | 378 | return jsonify(result) 379 | 380 | else: 381 | return render_template('accounts_bootstrap.html'); 382 | 383 | @accounts.route('/transactions', methods=['GET']) 384 | def transactions(): 385 | """List transactions""" 386 | 387 | v = request.values.get 388 | 389 | page = int(v('page', 1)) 390 | 391 | account_id = Account.authorize(v('api_key')) 392 | if not account_id: 393 | return jsonify(api_error('API_UNAUTHORIZED')), 401 394 | 395 | account = Account.query.get(account_id) 396 | 397 | res = Transaction.query.filter_by(account_id= account_id) 398 | res = res.order_by(Transaction.create_date.desc()).paginate(page, 15, False) 399 | 400 | return jsonify({ 401 | 'page': res.page, 402 | 'pages': res.pages, 403 | 'per_page': res.per_page, 404 | 'total': res.total, 405 | 'has_next': res.has_next, 406 | 'has_prev': res.has_prev, 407 | 'transactions': [trans.public_data() for trans in res.items] 408 | }) 409 | 410 | @accounts.route('/email_password_reset', methods=['GET', 'POST']) 411 | def email_password_reset(): 412 | """Emails a password reset""" 413 | 414 | if request.method == 'POST': 415 | 416 | from library.mailer import email_password_reset 417 | 418 | v = request.values.get 419 | 420 | emails = Account.query.filter_by(email=v('email')) 421 | account = emails.first() 422 | 423 | if account: 424 | password_reset = PasswordReset(account.id) 425 | db.session.add(password_reset) 426 | db.session.commit() 427 | email_password_reset(v('email'), password_reset, account) 428 | 429 | return jsonify({'ok': 'whatever'}) 430 | else: 431 | return render_template('accounts_email_password_reset.html'); 432 | 433 | 434 | @accounts.route('/reset_password', methods=['POST']) 435 | def reset_password(): 436 | """Actually reset a password using the hash""" 437 | 438 | from datetime import datetime 439 | 440 | v = request.values.get 441 | 442 | reset_hash = PasswordReset.query.filter_by(reset_hash=v('reset_hash')) 443 | reset_hash = reset_hash.first() 444 | 445 | if not reset_hash: 446 | return jsonify(api_error('ACCOUNTS_INVALID_RESET_HASH')), 401 447 | 448 | if reset_hash.used: 449 | return jsonify(api_error('ACCOUNTS_INVALID_RESET_HASH')), 401 450 | 451 | account = Account.query.get(reset_hash.account_id) 452 | account.password = account.password = password_hash(v('password')) 453 | account.mod_date = datetime.now() 454 | reset_hash.used = 1 455 | reset_hash.mod_date = datetime.now() 456 | db.session.commit() 457 | 458 | return jsonify(account.public_data()) 459 | 460 | @accounts.route('/charge', methods=['GET']) 461 | def charge(): 462 | if request.values.get("admin_token") != os.environ.get("ADMIN_TOKEN"): 463 | return jsonify(api_error("ADMIN_BAD_ADMIN_TOKEN")), 401 464 | 465 | redis_conn = Redis.from_url(current_app.config['REDIS_URI']) 466 | q = Queue('default', connection=redis_conn) 467 | q.enqueue_call(func=charge_subscribers, timeout=300) 468 | 469 | return jsonify({"kthx": "bai"}) 470 | -------------------------------------------------------------------------------- /controllers/incoming.py: -------------------------------------------------------------------------------- 1 | import os 2 | from flask import Blueprint, request, render_template, jsonify, current_app, \ 3 | make_response 4 | from models import db 5 | from sqlalchemy.exc import IntegrityError 6 | from library.grab_bag import fix_ip, password_hash, random_hash, o 7 | from library.errors import api_error, ValidationError 8 | from library.phaxio import valid_signature 9 | from models.account import Account 10 | from models.transaction import Transaction 11 | from models.failed_payment import FailedPayment 12 | from models.incoming_number import IncomingNumber 13 | from models.incoming_fax import IncomingFax 14 | import stripe 15 | import json 16 | import requests 17 | import traceback 18 | 19 | incoming = Blueprint('incoming', __name__, url_prefix='/incoming') 20 | 21 | @incoming.route('/provision', methods=['POST', 'OPTIONS']) 22 | def provision(): 23 | """Provision a Phaxio fax number""" 24 | 25 | from library.mailer import email_provision_info 26 | 27 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 28 | 29 | account_id = Account.authorize(request.values.get('api_key')) 30 | if account_id == None: 31 | return jsonify(api_error('API_UNAUTHORIZED')), 401 32 | 33 | account = Account.query.get(account_id) 34 | 35 | if len(account.incoming_numbers) > 0: 36 | return jsonify(api_error('INCOMING_NUMBER_EXISTS')), 400 37 | 38 | if account.credit < 6 and not account.allow_overflow: 39 | if account.stripe_card and account.auto_recharge: 40 | if not auto_recharge(account, ip) == True: 41 | return jsonify(api_error('INCOMING_CARD_DECLINED')), 401 42 | else: 43 | return jsonify(api_error('INCOMING_INSUFFICIENT_CREDIT')), 401 44 | 45 | payload = { 46 | "area_code": request.values.get("area_code"), 47 | "api_key": os.environ.get('PHAXIO_API_KEY'), 48 | "api_secret": os.environ.get('PHAXIO_API_SECRET') 49 | } 50 | if os.environ.get('PHAXIO_OVERRIDE_RECEIVED'): 51 | payload["callback_url"] = os.environ.get('PHAXIO_OVERRIDE_RECEIVED') 52 | 53 | try: 54 | url = "https://api.phaxio.com/v1/provisionNumber" 55 | r = requests.post(url, data=payload) 56 | response = json.loads(r.text) 57 | 58 | if response["success"] == False or not "data" in response \ 59 | or not "number" in response["data"]: 60 | return jsonify(api_error('INCOMING_BOGUS_AREA_CODE')), 400 61 | except: 62 | return jsonify(api_error('INCOMING_FAILED_TO_PROVISION')), 500 63 | 64 | data = { 65 | 'account_id': account_id, 66 | 'fax_number': response["data"]["number"], 67 | } 68 | incoming_number = IncomingNumber(**data); 69 | db.session.add(incoming_number) 70 | db.session.commit() 71 | 72 | data2 = { 73 | 'account_id': account.id, 74 | 'amount': -6.00, 75 | 'source': "phaxio", 76 | 'source_id': data["fax_number"], 77 | 'ip_address': ip, 78 | 'initial_balance': account.credit, 79 | 'trans_type': "incoming_autopay" 80 | } 81 | trans = Transaction(**data2) 82 | db.session.add(trans) 83 | db.session.commit() 84 | 85 | account.subtract_credit(6) 86 | email_provision_info(account, data["fax_number"]) 87 | 88 | return jsonify(account.public_data()) 89 | 90 | @incoming.route('/deprovision', methods=['POST', 'OPTIONS']) 91 | def deprovision(): 92 | """Derovision a Phaxio fax number""" 93 | 94 | from library.mailer import email_registration 95 | 96 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 97 | 98 | account_id = Account.authorize(request.values.get('api_key')) 99 | if account_id == None: 100 | return jsonify(api_error('API_UNAUTHORIZED')), 401 101 | 102 | account = Account.query.get(account_id) 103 | 104 | if len(account.incoming_numbers) == 0: 105 | return jsonify(api_error('INCOMING_CANNOT_REMOVE')), 400 106 | 107 | if not delete_number_from_phaxio(account.incoming_numbers[0].fax_number): 108 | return jsonify(api_error('INCOMING_FAILED_TO_DEPROVISION')), 500 109 | 110 | db.session.delete(account.incoming_numbers[0]) 111 | db.session.commit() 112 | 113 | return jsonify({"success": True}) 114 | 115 | @incoming.route('/webhook', methods=['POST', 'OPTIONS']) 116 | def webhook_received(): 117 | """Webhook for Phaxio Receive Faxes""" 118 | 119 | from library.mailer import email_receive_fail, email_admin, email_fax 120 | from boto.s3.connection import S3Connection 121 | from boto.s3.key import Key 122 | from werkzeug.utils import secure_filename 123 | 124 | sig = request.headers.get("X-Phaxio-Signature") 125 | url = request.base_url 126 | 127 | if not valid_signature(os.environ.get("PHAXIO_CALLBACK_TOKEN"), url, 128 | request.values, request.files, sig): 129 | return ":(" 130 | 131 | if not request.values.get("success") or not request.files.get("filename"): 132 | return ":(" 133 | 134 | fax = json.loads(request.values.get("fax")) 135 | file = request.files.get("filename") 136 | 137 | external_id = fax["id"] 138 | num_pages = fax["num_pages"] 139 | from_number = fax["from_number"].replace("+1", "") 140 | to_number = fax["to_number"].replace("+1", "") 141 | 142 | incoming_numbers = IncomingNumber.query.filter_by(fax_number = to_number) 143 | 144 | if not incoming_numbers or incoming_numbers.first() == None: 145 | return ":(" 146 | 147 | incoming_number = incoming_numbers.first() 148 | account = incoming_number.account 149 | 150 | if account.base_rate: 151 | page_cost = account.base_rate 152 | else: 153 | page_cost = float(os.environ.get('DEFAULT_COST_PER_PAGE', '0.10')) 154 | 155 | cost = num_pages * page_cost 156 | 157 | if account.credit < cost and not account.allow_overflow: 158 | if account.stripe_card and account.auto_recharge: 159 | if not auto_recharge(account, ip) == True: 160 | email_receive_fail(account, "DECLINE", external_id, from_number, 161 | num_pages, cost) 162 | else: 163 | email_receive_fail(account, "NO_FUNDS", external_id, from_number, 164 | num_pages, cost) 165 | return ":(" 166 | 167 | data = { 168 | 'account_id': account.id, 169 | 'external_id': external_id, 170 | 'num_pages': num_pages, 171 | 'cost': cost, 172 | 'from_number': from_number, 173 | 'to_number': to_number, 174 | } 175 | incoming_fax = IncomingFax(**data) 176 | 177 | try: 178 | filename = secure_filename(file.filename) 179 | file.save("./tmp/%s" % filename) 180 | except: 181 | email_admin("Could not save file for Phaxio: %s" % external_id) 182 | return ":(" 183 | 184 | try: 185 | conn = S3Connection(os.environ.get('AWS_ACCESS_KEY'), 186 | os.environ.get('AWS_SECRET_KEY')) 187 | bucket = conn.get_bucket(os.environ.get('AWS_S3_BUCKET')) 188 | except: 189 | email_admin("AWS S3 connect fail for Phaxio: %s" % external_id) 190 | return ":(" 191 | 192 | try: 193 | k = Key(bucket) 194 | k.key = 'incoming/' + incoming_fax.access_key + '/fax.pdf' 195 | k.set_contents_from_filename("./tmp/%s" % filename) 196 | k.set_acl('public-read') 197 | incoming_fax.hosted_url = k.generate_url(expires_in=0, query_auth=False) 198 | except: 199 | email_admin("AWS S3 write fail for Phaxio: %s" % external_id) 200 | return ":(" 201 | 202 | db.session.add(incoming_fax) 203 | db.session.commit() 204 | 205 | data2 = { 206 | 'account_id': account.id, 207 | 'amount': 0 - cost, 208 | 'source': 'phaxio', 209 | 'source_id': from_number, 210 | 'initial_balance': account.credit, 211 | 'trans_type': 'received_fax' 212 | } 213 | trans = Transaction(**data2) 214 | db.session.add(trans) 215 | db.session.commit() 216 | 217 | account.subtract_credit(cost) 218 | 219 | email_fax(account, external_id, from_number, num_pages, cost, 220 | "./tmp/%s" % filename, incoming_fax.access_key) 221 | 222 | return jsonify({"kthx": "bai"}) 223 | 224 | @incoming.route('/list', methods=['GET']) 225 | def list(): 226 | """List faxes""" 227 | 228 | v = request.values.get 229 | 230 | account_id = Account.authorize(v('api_key')) 231 | if not account_id: 232 | return jsonify(api_error('API_UNAUTHORIZED')), 401 233 | 234 | try: 235 | page = int(v('page', 1)) 236 | if page < 1: 237 | raise 238 | except: 239 | return jsonify(api_error('INCOMING_BAD_PAGINATION_VALUE')), 400 240 | 241 | 242 | faxes = IncomingFax.query.filter_by(account_id= account_id) 243 | faxes = faxes.order_by(IncomingFax.create_date.desc()).paginate(page, 20, 244 | False) 245 | 246 | return jsonify({ 247 | 'page': faxes.page, 248 | 'pages': faxes.pages, 249 | 'per_page': faxes.per_page, 250 | 'total': faxes.total, 251 | 'has_next': faxes.has_next, 252 | 'has_prev': faxes.has_prev, 253 | 'faxes': [fax.public_data() for fax in faxes.items] 254 | }) 255 | 256 | @incoming.route('/view', methods=['GET']) 257 | def view(): 258 | """View a fax""" 259 | 260 | import urllib 261 | from library.mailer import email_admin 262 | 263 | v = request.values.get 264 | 265 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 266 | 267 | account_id = Account.authorize(v('api_key')) 268 | if not account_id: 269 | return jsonify(api_error('API_UNAUTHORIZED')), 401 270 | 271 | try: 272 | faxes = IncomingFax.query.filter_by(access_key = v('access_key')) 273 | fax = faxes.first() 274 | 275 | f = urllib.urlopen(fax.hosted_url) 276 | data = f.read() 277 | 278 | response = make_response(data) 279 | response.headers['Content-Type'] = 'application/pdf' 280 | response.headers['Content-Disposition'] = 'attachment; filename=fax.pdf' 281 | return response 282 | except: 283 | msg = ("

Something weird is going on.

" 284 | "

endpoint: /incoming/view
" 285 | "api_key: %s
" 286 | "access_key: %s
" 287 | "ip: %s
") % (v('api_key'), v('access_key'), 288 | ip) 289 | 290 | email_admin(msg, "Security alert!") 291 | 292 | return ("

File not found.

Apologies for the glitch! Our staff" 293 | " has been notified in order to better assist you.

"), 401 294 | 295 | @incoming.route('/delete', methods=['POST', 'OPTIONS']) 296 | def delete(): 297 | """Delete an incoming fax""" 298 | 299 | from library.mailer import email_admin 300 | from boto.s3.connection import S3Connection 301 | from boto.s3.key import Key 302 | 303 | v = request.values.get 304 | 305 | access_key = v('access_key') 306 | account_id = Account.authorize(v('api_key')) 307 | 308 | if not account_id: 309 | return jsonify(api_error('API_UNAUTHORIZED')), 401 310 | 311 | faxes = IncomingFax.query.filter_by(access_key = access_key) 312 | fax = faxes.first() 313 | 314 | db.session.delete(fax) 315 | db.session.commit() 316 | 317 | try: 318 | conn = S3Connection(os.environ.get('AWS_ACCESS_KEY'), 319 | os.environ.get('AWS_SECRET_KEY')) 320 | bucket = conn.get_bucket(os.environ.get('AWS_S3_BUCKET')) 321 | k = Key(bucket) 322 | k.key ='incoming/' + access_key + '/fax.pdf' 323 | k.delete() 324 | except: 325 | email_admin("AWS S3 connect fail for fax deletion: %s" % access_key) 326 | 327 | return jsonify({"success": True}) 328 | 329 | def auto_recharge(account, ip, session = None): 330 | 331 | if not session: 332 | session = db.session 333 | 334 | try: 335 | stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') 336 | 337 | charge = stripe.Charge.create( 338 | amount=1000, 339 | currency="usd", 340 | customer=account.stripe_token, 341 | description="FaxRobot.com: recurring service account #%s"%account.id 342 | ) 343 | data = { 344 | 'account_id': account.id, 345 | 'amount': 10, 346 | 'source': 'stripe', 347 | 'source_id': charge["id"], 348 | 'ip_address': ip, 349 | 'initial_balance': account.credit, 350 | 'trans_type': 'auto_recharge' 351 | } 352 | trans = Transaction(**data) 353 | session.add(trans) 354 | session.commit() 355 | 356 | account.add_credit(10, session) 357 | 358 | return True 359 | 360 | except: 361 | payment = {'_DEBUG': traceback.format_exc()} 362 | data = { 363 | 'amount': 10, 364 | 'account_id': account.id, 365 | 'source': 'stripe', 366 | 'debug': json.dumps(payment), 367 | 'ip_address': ip, 368 | 'payment_type': 'auto_recharge' 369 | } 370 | failed_payment = FailedPayment(**data) 371 | session.add(failed_payment) 372 | session.commit() 373 | return False 374 | 375 | def delete_number_from_phaxio(fax_number): 376 | payload = { 377 | "number": fax_number, 378 | "api_key": os.environ.get('PHAXIO_API_KEY'), 379 | "api_secret": os.environ.get('PHAXIO_API_SECRET') 380 | } 381 | 382 | try: 383 | url = "https://api.phaxio.com/v1/releaseNumber" 384 | r = requests.post(url, data=payload) 385 | response = json.loads(r.text) 386 | 387 | if response["success"] == False: 388 | return False 389 | except: 390 | return False 391 | 392 | return True -------------------------------------------------------------------------------- /controllers/jobs.py: -------------------------------------------------------------------------------- 1 | import os 2 | from flask import Blueprint, request, render_template, jsonify, current_app 3 | from models import db 4 | from library.grab_bag import fix_ip, o 5 | from library.errors import api_error, ValidationError 6 | from library.phaxio import valid_signature 7 | from models.job import Job 8 | from models.account import Account 9 | from rq import Queue 10 | from redis import Redis 11 | from workers.jobs import initial_process, send_fax, fail, mark_job_sent 12 | from datetime import datetime 13 | 14 | 15 | jobs = Blueprint('jobs', __name__, url_prefix='/jobs') 16 | 17 | @jobs.route('/create', methods=['GET', 'POST']) 18 | def create(): 19 | """Creates a new outgoing fax""" 20 | 21 | account_id = Account.authorize(request.values.get('api_key')) 22 | if account_id == None: 23 | return jsonify(api_error('API_UNAUTHORIZED')), 401 24 | 25 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 26 | 27 | if request.method == 'POST': 28 | 29 | if request.files and 'file' in request.files: 30 | uploaded_file = request.files['file'] 31 | else: 32 | uploaded_file = None 33 | 34 | v = request.values.get 35 | 36 | if uploaded_file or v('body'): 37 | 38 | data = { 39 | 'account_id': account_id, 40 | 'ip_address': ip, 41 | 'destination': v('destination'), 42 | 'send_authorized': v('send_authorized', 0), 43 | 'cover': v('cover', 0), 44 | 'cover_name': v('cover_name'), 45 | 'cover_address': v('cover_address'), 46 | 'cover_city': v('cover_city'), 47 | 'cover_state': v('cover_state'), 48 | 'cover_zip': v('cover_zip'), 49 | 'cover_country': v('cover_country'), 50 | 'cover_phone': v('cover_phone'), 51 | 'cover_email': v('cover_email'), 52 | 'cover_company': v('cover_company'), 53 | 'cover_to_name': v('cover_to_name'), 54 | 'cover_cc': v('cover_cc'), 55 | 'cover_subject': v('cover_subject'), 56 | 'cover_status': v('cover_status','review'), 57 | 'cover_comments': v('cover_comments'), 58 | 'callback_url': v('callback_url') 59 | } 60 | if uploaded_file: 61 | data['filename'] = uploaded_file.filename 62 | else: 63 | data['body'] = v('body') 64 | 65 | o(data) 66 | 67 | try: 68 | job = Job(**data); 69 | job.validate() 70 | job.determine_international() 71 | except ValidationError, err: 72 | return jsonify(api_error(err.ref)), 400 73 | 74 | db.session.add(job) 75 | db.session.commit() 76 | 77 | if uploaded_file: 78 | binary = uploaded_file.stream.read() 79 | else: 80 | binary = job.body.replace("\r\n", "\n").encode('utf-8') 81 | 82 | redis_conn = Redis.from_url(current_app.config['REDIS_URI']) 83 | q = Queue('high', connection=redis_conn) 84 | q.enqueue_call(func=initial_process, args=(job.id, binary), 85 | timeout=300) 86 | 87 | return jsonify(job.public_data()) 88 | else: 89 | return jsonify(api_error("JOBS_NO_ATTACHMENT")), 400 90 | 91 | else: 92 | return render_template('jobs_create.html') 93 | 94 | 95 | @jobs.route('/update/', methods=['POST']) 96 | def update(access_key): 97 | """Updates a fax""" 98 | 99 | account_id = Account.authorize(request.values.get('api_key')) 100 | if not account_id: 101 | account_id = 0 102 | # return jsonify(api_error('API_UNAUTHORIZED')), 401 103 | 104 | v = request.values.get 105 | 106 | jobs = Job.query.filter_by(access_key = access_key) 107 | job = jobs.first() 108 | 109 | if job == None: 110 | return jsonify(api_error('API_UNAUTHORIZED')), 401 111 | elif job.account_id and not job.account_id == account_id: 112 | return jsonify(api_error('API_UNAUTHORIZED')), 401 113 | elif not job.status == 'ready' and not job.status == 'new' and \ 114 | not job.status == 'uploading': 115 | return jsonify(api_error('JOBS_NOT_READY')), 401 116 | 117 | if job.data_deleted: 118 | return jsonify(api_error('JOBS_DATA_DELETED')), 400 119 | 120 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 121 | 122 | job.ip_address = ip 123 | job.account_id = account_id 124 | 125 | try: 126 | if v('destination'): 127 | job.destination = v('destination') 128 | 129 | if v('send_authorized') and v('send_authorized').lower() != "false" \ 130 | and v('send_authorized') != "0": 131 | job.send_authorized = 1; 132 | 133 | if v('cover') and v('cover').lower() != "false" and v('cover') != "0": 134 | job.cover = 1; 135 | 136 | if v('cover_name'): 137 | job.cover_name = v('cover_name') 138 | 139 | if v('cover_address'): 140 | job.cover_address = v('cover_address') 141 | 142 | if v('cover_city'): 143 | job.cover_city = v('cover_city') 144 | 145 | if v('cover_state'): 146 | job.cover_state = v('cover_state') 147 | 148 | if v('cover_zip'): 149 | job.cover_zip = v('cover_zip') 150 | 151 | if v('cover_country'): 152 | job.cover_country = v('cover_country') 153 | 154 | if v('cover_phone'): 155 | job.cover_phone = v('cover_phone') 156 | 157 | if v('cover_email'): 158 | job.cover_email = v('cover_email') 159 | 160 | if v('cover_company'): 161 | job.cover_company = v('cover_company') 162 | 163 | if v('cover_to_name'): 164 | job.cover_to_name = v('cover_to_name') 165 | 166 | if v('cover_cc'): 167 | job.cover_cc = v('cover_cc') 168 | 169 | if v('cover_subject'): 170 | job.cover_subject = v('cover_subject') 171 | 172 | if v('cover_status'): 173 | job.cover_status = v('cover_status') 174 | 175 | if v('cover_comments'): 176 | job.cover_comments = v('cover_comments') 177 | 178 | if v('callback_url'): 179 | job.callback_url = v('callback_url') 180 | 181 | job.mod_date = datetime.now() 182 | job.validate() 183 | job.determine_international() 184 | job.compute_cost() 185 | job.rate_limit(account_id) 186 | 187 | if job.status == 'ready' and job.send_authorized: 188 | job.status = 'queued' 189 | db.session.commit() 190 | redis_conn = Redis.from_url(os.environ.get('REDIS_URI')) 191 | q = Queue(job.account.get_priority(), connection=redis_conn) 192 | q.enqueue_call(func=send_fax, args=(job.id,), timeout=3600) 193 | else: 194 | db.session.commit() 195 | 196 | except ValidationError, err: 197 | return jsonify(api_error(err.ref)), 400 198 | 199 | return jsonify(job.public_data()) 200 | 201 | 202 | @jobs.route('/get/', methods=['GET']) 203 | def get(access_key): 204 | """Get the status of a job""" 205 | 206 | account_id = Account.authorize(request.values.get('api_key')) 207 | 208 | jobs = Job.query.filter_by(access_key = access_key) 209 | job = jobs.first() 210 | 211 | if job == None or (job.account_id != 0 and (not account_id or \ 212 | account_id != job.account_id)): 213 | return jsonify(api_error('API_UNAUTHORIZED')), 401 214 | 215 | return jsonify(job.public_data()) 216 | 217 | @jobs.route('/get_by_id/', methods=['GET']) 218 | def get_by_id(id): 219 | """Get the status of a job by id""" 220 | 221 | account_id = Account.authorize(request.values.get('api_key')) 222 | 223 | jobs = Job.query.filter_by(id = id) 224 | job = jobs.first() 225 | 226 | if job == None or not account_id or job.account_id != account_id: 227 | return jsonify(api_error('API_UNAUTHORIZED')), 401 228 | 229 | return jsonify(job.public_data()) 230 | 231 | @jobs.route('/restart/', methods=['POST']) 232 | def restart(access_key): 233 | """Restarts a failed job""" 234 | 235 | account_id = Account.authorize(request.values.get('api_key')) 236 | 237 | jobs = Job.query.filter_by(access_key = access_key) 238 | job = jobs.first() 239 | 240 | if job == None or not account_id or not account_id == job.account_id: 241 | return jsonify(api_error('API_UNAUTHORIZED')), 401 242 | 243 | if not job.failed: 244 | return jsonify(api_error('JOBS_NOT_RESTARTABLE')), 400 245 | 246 | if job.data_deleted: 247 | return jsonify(api_error('JOBS_DATA_DELETED')), 400 248 | 249 | ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr)) 250 | 251 | job.ip_address = ip 252 | job.failed = 0 253 | job.fail_code = 0 254 | job.status = 'queued' 255 | db.session.commit() 256 | redis_conn = Redis.from_url(os.environ.get('REDIS_URI')) 257 | q = Queue(job.account.get_priority(), connection=redis_conn) 258 | q.enqueue_call(func=send_fax, args=(job.id,), timeout=3600) 259 | 260 | return jsonify(job.public_data()) 261 | 262 | @jobs.route('/delete_data/', methods=['POST', 'GET']) 263 | def delete(access_key): 264 | """Deletes data associated with a job.""" 265 | 266 | account_id = Account.authorize(request.values.get('api_key')) 267 | 268 | jobs = Job.query.filter_by(access_key = access_key) 269 | job = jobs.first() 270 | 271 | if job == None or (job.account_id != 0 and (not account_id or \ 272 | account_id != job.account_id)): 273 | return jsonify(api_error('API_UNAUTHORIZED')), 401 274 | 275 | if not job.status == 'ready' and not job.status == 'sent' and \ 276 | not job.status == 'failed': 277 | return jsonify(api_error('JOBS_CANNOT_DELETE_NOW')), 401 278 | 279 | job.delete_data() 280 | 281 | return jsonify(job.public_data()) 282 | 283 | @jobs.route('/list', methods=['GET']) 284 | def list(): 285 | """List faxes""" 286 | 287 | v = request.values.get 288 | 289 | account_id = Account.authorize(v('api_key')) 290 | if not account_id: 291 | return jsonify(api_error('API_UNAUTHORIZED')), 401 292 | 293 | try: 294 | page = int(v('page', 1)) 295 | if page < 1: 296 | raise 297 | except: 298 | return jsonify(api_error('JOBS_BAD_PAGINATION_VALUE')), 400 299 | 300 | if v('filter'): 301 | jobs = Job.query.filter_by(account_id= account_id, status= v('filter')) 302 | else: 303 | jobs = Job.query.filter_by(account_id= account_id) 304 | jobs = jobs.order_by(Job.create_date.desc()).paginate(page, 20, False) 305 | 306 | return jsonify({ 307 | 'page': jobs.page, 308 | 'pages': jobs.pages, 309 | 'per_page': jobs.per_page, 310 | 'total': jobs.total, 311 | 'has_next': jobs.has_next, 312 | 'has_prev': jobs.has_prev, 313 | 'jobs': [job.public_data() for job in jobs.items] 314 | }) 315 | 316 | @jobs.route('/webhook', methods=['GET', 'POST']) 317 | def webhook(): 318 | """Listens for fax send receipts from Phaxio""" 319 | 320 | import json 321 | import requests 322 | 323 | raw = request.values.get("fax") 324 | fax = json.loads(raw) 325 | sig = request.headers.get("X-Phaxio-Signature") 326 | url = request.base_url 327 | 328 | # print request.headers 329 | # print raw 330 | 331 | if not valid_signature(os.environ.get("PHAXIO_CALLBACK_TOKEN"), url, 332 | request.values, request.files, sig): 333 | return ":(" 334 | 335 | jobs = Job.query.filter_by(external_id=fax["id"]) 336 | 337 | if not jobs or jobs.first() == None: 338 | return ":(" 339 | 340 | job = jobs.first() 341 | 342 | if not job.status == "started": 343 | return ":(" 344 | 345 | if fax["status"] == "failure": 346 | if "error_code" in fax: 347 | msg = fax["error_code"] 348 | code = fax["error_type"] 349 | else: 350 | msg = fax["recipients"][0]["error_code"] 351 | code = fax["recipients"][0]["error_type"] 352 | 353 | if code == "documentConversionError": 354 | fail("JOBS_IMG_CONVERT_FAIL", job, db, raw, db.session) 355 | 356 | elif code == "lineError" and "Busy" in msg: 357 | fail("JOBS_TRANSMIT_BUSY", job, db, raw, db.session) 358 | 359 | elif code == "lineError": 360 | fail("JOBS_TRANSMIT_NO_ANSWER", job, db, raw, db.session) 361 | 362 | else: 363 | fail('JOBS_TRANSMIT_FAIL', job, db, raw, db.session) 364 | 365 | elif fax["status"] == "success": 366 | 367 | cost = job.cost if not job.cover else job.cost + job.cover_cost 368 | mark_job_sent(job, cost, db.session) 369 | 370 | # delete job data from Phaxio 371 | payload = { 372 | "id": fax["id"], 373 | "files_only": True, 374 | "api_key": os.environ.get('PHAXIO_API_KEY'), 375 | "api_secret": os.environ.get('PHAXIO_API_SECRET') 376 | } 377 | r = requests.post("https://api.phaxio.com/v1/deleteFax", data=payload) 378 | print "deleted: %s" % r.text 379 | 380 | return "lol" -------------------------------------------------------------------------------- /library/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lyonbros/faxrobot/4dfdd6c9bd4cd335a7dc4aaaa6188ad808b78d71/library/__init__.py -------------------------------------------------------------------------------- /library/errors.py: -------------------------------------------------------------------------------- 1 | api_errors = { 2 | # file upload errors 3 | "API_UNAUTHORIZED": { 4 | "code": 4000, 5 | "msg": "Unauthorized." 6 | }, 7 | "JOBS_NO_ATTACHMENT": { 8 | "code": 5000, 9 | "msg": "/jobs/create was called without a file or text body attachment." 10 | }, 11 | "JOBS_BAD_DESTINATION": { 12 | "code": 5001, 13 | "msg": "An invalid destination phone number was passed for this job." 14 | }, 15 | "JOBS_BAD_COVER": { 16 | "code": 5002, 17 | "msg": "An invalid value passed for cover." 18 | }, 19 | "JOBS_BAD_FILENAME": { 20 | "code": 5003, 21 | "msg": "The specified filename was invalid." 22 | }, 23 | "JOBS_BAD_SEND_AUTHORIZED": { 24 | "code": 5004, 25 | "msg": "Invalid value passed for send_authorized." 26 | }, 27 | "JOBS_BAD_COVER_NAME": { 28 | "code": 5005, 29 | "msg": "Invalid cover sheet name field (Max 64 characters).", 30 | "field": "cover_name" 31 | }, 32 | "JOBS_BAD_COVER_ADDRESS": { 33 | "code": 5006, 34 | "msg": "Invalid cover sheet address field (Max 128 characters).", 35 | "field": "cover_address" 36 | }, 37 | "JOBS_BAD_COVER_CITY": { 38 | "code": 5007, 39 | "msg": "Invalid cover sheet city field (Max 64 characters).", 40 | "field": "cover_city" 41 | }, 42 | "JOBS_BAD_COVER_STATE": { 43 | "code": 5008, 44 | "msg": "Invalid cover sheet state field (Max 64 characters).", 45 | "field": "cover_state" 46 | }, 47 | "JOBS_BAD_COVER_ZIP": { 48 | "code": 5009, 49 | "msg": "Invalid cover sheet zip field (Max 64 characters).", 50 | "field": "cover_zip" 51 | }, 52 | "JOBS_BAD_COVER_COUNTRY": { 53 | "code": 5010, 54 | "msg": "Invalid cover sheet country field (Max 64 characters).", 55 | "field": "cover_country" 56 | }, 57 | "JOBS_BAD_COVER_PHONE": { 58 | "code": 5011, 59 | "msg": "Invalid cover sheet phone number field (Max 64 characters).", 60 | "field": "cover_phone" 61 | }, 62 | "JOBS_BAD_COVER_EMAIL": { 63 | "code": 5012, 64 | "msg": "Invalid cover sheet email field (Max 128 characters).", 65 | "field": "cover_email" 66 | }, 67 | "JOBS_BAD_COVER_COMPANY": { 68 | "code": 5013, 69 | "msg": "Invalid cover sheet company field (Max 128 characters).", 70 | "field": "cover_company" 71 | }, 72 | "JOBS_BAD_COVER_TO_NAME": { 73 | "code": 5014, 74 | "msg": "Invalid cover sheet to name field (Max 64 characters).", 75 | "field": "cover_to_name" 76 | }, 77 | "JOBS_BAD_COVER_CC": { 78 | "code": 5015, 79 | "msg": "Invalid cover sheet cc field (Max 64 characters).", 80 | "field": "cover_cc" 81 | }, 82 | "JOBS_BAD_COVER_SUBJECT": { 83 | "code": 5016, 84 | "msg": "Invalid cover sheet subject field (Max 64 characters).", 85 | "field": "cover_subject" 86 | }, 87 | "JOBS_BAD_COVER_STATUS": { 88 | "code": 5017, 89 | "msg": "Invalid cover sheet status field (Max 64 characters).", 90 | "field": "cover_status" 91 | }, 92 | "JOBS_BAD_CALLBACK_URL": { 93 | "code": 5018, 94 | "msg": "Invalid callback_url field (Max 255 characters).", 95 | "field": "callback_url" 96 | }, 97 | "JOBS_MISSING_DESTINATION": { 98 | "code": 5019, 99 | "msg": "Could not start the job because no destination was passed." 100 | }, 101 | "JOBS_NOT_READY": { 102 | "code": 5020, 103 | "msg": "This job has begun processing, so you can't change it anymore." 104 | }, 105 | "JOBS_BAD_PAGINATION_VALUE": { 106 | "code": 5021, 107 | "msg": "You sent an unacceptable page parameter." 108 | }, 109 | "JOBS_NOT_RESTARTABLE": { 110 | "code": 5022, 111 | "msg": "The specified job is not failed and cannot be restarted." 112 | }, 113 | "JOBS_DATA_DELETED": { 114 | "code": 5023, 115 | "msg": "The data for this job has been deleted from the server. Please recreate." 116 | }, 117 | "JOBS_CANNOT_DELETE_NOW": { 118 | "code": 5024, 119 | "msg": "The job is being processed and cannot be deleted now." 120 | }, 121 | "JOBS_RATE_LIMIT_REACHED": { 122 | "code": 5025, 123 | "msg": "Rate limit exceeded. Please try again later." 124 | }, 125 | "ACCOUNTS_MISSING_EMAIL": { 126 | "code": 6000, 127 | "msg": "Please enter an email address.", 128 | "field": "email" 129 | }, 130 | "ACCOUNTS_BAD_EMAIL": { 131 | "code": 6001, 132 | "msg": "Please enter a valid email address.", 133 | "field": "email" 134 | }, 135 | "ACCOUNTS_MISSING_PASSWORD": { 136 | "code": 6002, 137 | "msg": "Please enter a password.", 138 | "field": "password" 139 | }, 140 | "ACCOUNTS_CREATE_FAIL": { 141 | "code": 6003, 142 | "msg": "Could not create that account. Perhaps it already exists?", 143 | "field": "email" 144 | }, 145 | "ACCOUNTS_LOGIN_ERROR": { 146 | "code": 6004, 147 | "msg": "Could not find an account with that username and password." 148 | }, 149 | "ACCOUNTS_PAYMENT_FAIL": { 150 | "code": 6005, 151 | "msg": "Could not process payment." 152 | }, 153 | "ACCOUNTS_STORED_PAYMENT_FAIL": { 154 | "code": 6006, 155 | "msg": "Could not process stored payment info." 156 | }, 157 | "ACCOUNTS_BAD_FIRST_NAME": { 158 | "code": 6007, 159 | "msg": "First name was too long. Max 255 characters.", 160 | "field": "first_name" 161 | }, 162 | "ACCOUNTS_BAD_LAST_NAME": { 163 | "code": 6008, 164 | "msg": "Last name was too long. Max 255 characters.", 165 | "field": "last_name" 166 | }, 167 | "ACCOUNTS_BAD_ADDRESS": { 168 | "code": 6009, 169 | "msg": "Address was too long. Max 255 characters.", 170 | "field": "address" 171 | }, 172 | "ACCOUNTS_BAD_ADDRESS2": { 173 | "code": 6010, 174 | "msg": "Address (second field) was too long. Max 255 characters.", 175 | "field": "address2" 176 | }, 177 | "ACCOUNTS_BAD_CITY": { 178 | "code": 6011, 179 | "msg": "City was too long. Max 255 characters.", 180 | "field": "city" 181 | }, 182 | "ACCOUNTS_BAD_STATE": { 183 | "code": 6012, 184 | "msg": "Please enter a valid state..", 185 | "field": "state" 186 | }, 187 | "ACCOUNTS_BAD_ZIP": { 188 | "code": 6013, 189 | "msg": "Please enter a valid zip code.", 190 | "field": "zip" 191 | }, 192 | "ACCOUNTS_BAD_REQUEST": { 193 | "code": 6014, 194 | "msg": "WTF." 195 | }, 196 | "ACCOUNTS_EMAIL_TAKEN": { 197 | "code": 6015, 198 | "msg": "The email address you entered is not available.", 199 | "field": "email" 200 | }, 201 | "ACCOUNTS_INVALID_OLD_PASSWORD": { 202 | "code": 6016, 203 | "msg": "The old password you provided was not correct.", 204 | "field": "old_password" 205 | }, 206 | "ACCOUNTS_INVALID_RESET_HASH": { 207 | "code": 6017, 208 | "msg": "The reset hash was not valid. Perhaps the link expired?", 209 | "field": "reset_hash" 210 | }, 211 | "INCOMING_INSUFFICIENT_CREDIT": { 212 | "code": 6018, 213 | "msg": "No funds were available in the account to provision the fax number." 214 | }, 215 | "INCOMING_CARD_DECLINED": { 216 | "code": 6019, 217 | "msg": "The account's stored credit information didn't work." 218 | }, 219 | "INCOMING_FAILED_TO_PROVISION": { 220 | "code": 6020, 221 | "msg": "INTERNAL ERROR. Unable to provision that phone number." 222 | }, 223 | "INCOMING_BOGUS_AREA_CODE": { 224 | "code": 6021, 225 | "msg": "The area code you chose is invalid or has no numbers at this time." 226 | }, 227 | "INCOMING_NUMBER_EXISTS": { 228 | "code": 6022, 229 | "msg": "You already have an incoming number set up for your account." 230 | }, 231 | "INCOMING_CANNOT_REMOVE": { 232 | "code": 6023, 233 | "msg": "There was no incoming number associated with this account to remove." 234 | }, 235 | "INCOMING_FAILED_TO_DEPROVISION": { 236 | "code": 6024, 237 | "msg": "An error occurred while deprovisioning your number. Please contact support." 238 | }, 239 | "INCOMING_BAD_PAGINATION_VALUE": { 240 | "code": 6025, 241 | "msg": "You sent an unacceptable page parameter." 242 | }, 243 | "ADMIN_BAD_ADMIN_TOKEN": { 244 | "code": 7000, 245 | "msg": "The specified admin token was invalid." 246 | }, 247 | } 248 | worker_errors = { 249 | "JOBS_UPLOAD_S3_FAIL": { 250 | "code": 501, 251 | "status": "internal_error", 252 | "msg": "Upload of file to Amazon S3 failed." 253 | }, 254 | "JOBS_CONNECT_S3_FAIL": { 255 | "code": 502, 256 | "status": "internal_error", 257 | "msg": "Could not connect to Amazon S3." 258 | }, 259 | "JOBS_LOCAL_SAVE_FAIL": { 260 | "code": 503, 261 | "status": "internal_error", 262 | "msg": "Could not store file locally. Disk full? Permissions?" 263 | }, 264 | "JOBS_IMG_CONVERT_FAIL": { 265 | "code": 504, 266 | "status": "processing_error", 267 | "msg": "Could not process the attached file. Was it a valid image?" 268 | }, 269 | "JOBS_CREATE_DIR_FAIL": { 270 | "code": 505, 271 | "status": "internal_error", 272 | "msg": "Could not create directory for file uploads." 273 | }, 274 | # "JOBS_TOUCH_HACK_FAIL": { 275 | # "code": 506, 276 | # "status": "internal_error", 277 | # "msg": "Could not run convert.sh to initiate PDF conversion." 278 | # }, 279 | "JOBS_PDF_CONVERT_FAIL": { 280 | "code": 507, 281 | "status": "internal_error", 282 | "msg": "PDF conversion failed. FFFFFFFUUUUUUUUUUUU" 283 | }, 284 | "JOBS_COVER_MAIN_FAIL": { 285 | "code": 508, 286 | "status": "internal_error", 287 | "msg": "The main cover generation phase failed (overlaying text on PDF)" 288 | }, 289 | "JOBS_COVER_COMPANY_FAIL": { 290 | "code": 509, 291 | "status": "internal_error", 292 | "msg": "Could not generate image containing the coversheet company text" 293 | }, 294 | "JOBS_COVER_OVERLAY_FAIL": { 295 | "code": 510, 296 | "status": "internal_error", 297 | "msg": "Could not overlay generated text over main cover image" 298 | }, 299 | "JOBS_COVER_COMMENTS_FAIL": { 300 | "code": 511, 301 | "status": "internal_error", 302 | "msg": "Could not generate image containting the coversheet comments" 303 | }, 304 | "JOBS_COVER_TIFF_FAIL": { 305 | "code": 512, 306 | "status": "internal_error", 307 | "msg": "Could not convert the generated coversheet .png to G3 .tiff" 308 | }, 309 | "JOBS_INSUFFICIENT_CREDIT": { 310 | "code": 513, 311 | "status": "insufficient_credit", 312 | "msg": "No funds were available in the account to process this job." 313 | }, 314 | "JOBS_DOWNLOAD_S3_FAIL": { 315 | "code": 514, 316 | "status": "internal_error", 317 | "msg": "Could not download image file from Amazon S3." 318 | }, 319 | "JOBS_TRANSMIT_FAIL": { 320 | "code": 515, 321 | "status": "transmit_failure", 322 | "msg": ("Could not transmit the fax. Please try again and contact " 323 | "support if the problem persists.") 324 | }, 325 | "JOBS_TRANSMIT_NO_ANSWER": { 326 | "code": 516, 327 | "status": "no_answer", 328 | "msg": ("The number you dialed didn't answer or was not a fax machine. " 329 | "Please try again.") 330 | }, 331 | "JOBS_TRANSMIT_BUSY": { 332 | "code": 517, 333 | "status": "busy", 334 | "msg": "The number you dialed was busy. Please try again later." 335 | }, 336 | "JOBS_UNSUPPORTED_FORMAT": { 337 | "code": 518, 338 | "status": "unsupported_format", 339 | "msg": "The attached file was not of a supported format." 340 | }, 341 | "JOBS_CARD_DECLINED": { 342 | "code": 520, 343 | "status": "card_declined", 344 | "msg": "The account's stored credit information didn't work." 345 | }, 346 | "JOBS_NO_ATTACHMENT_FOUND": { 347 | "code": 521, 348 | "status": "internal_error", 349 | "msg": "There was no body and no filename attached to this job." 350 | }, 351 | "JOBS_TXT_CONVERT_FAIL": { 352 | "code": 522, 353 | "status": "internal_error", 354 | "msg": "Could not convert the attached TXT file to Postscript." 355 | }, 356 | "JOBS_FAIL_DATA_DELETED": { 357 | "code": 523, 358 | "status": "gone", 359 | "msg": "The data for this job has been deleted from the server." 360 | }, 361 | "JOBS_CANNOT_SEND_NOW": { 362 | "code": 524, 363 | "status": "not_ready", 364 | "msg": "The job is not ready for sending." 365 | }, 366 | "JOBS_NO_SERVEOFFICE2PDF": { 367 | "code": 525, 368 | "status": "processing_error", 369 | "msg": "No suitable converter specified for exporting Office to PDF." 370 | }, 371 | "JOBS_PHAXIO_TRANSMIT_FAIL": { 372 | "code": 526, 373 | "status": "api_Error", 374 | "msg": "Could not transmit the fax to our telecommunications provider." 375 | }, 376 | "JOBS_PHAXIO_BAD_NUMBER": { 377 | "code": 527, 378 | "status": "api_Error", 379 | "msg": "The given fax number was not valid." 380 | }, 381 | "JOBS_RATE_LIMIT_REACHED": { 382 | "code": 528, 383 | "status": "api_Error", 384 | "msg": "Rate limit exceeded. Please try again later." 385 | } 386 | } 387 | 388 | def api_error(ref): 389 | data = api_errors.get(ref, {"code": -1, "msg": "Unknown error."}); 390 | data["error"] = True 391 | data["ref"] = ref 392 | return data 393 | 394 | def worker_error(ref): 395 | data = worker_errors.get(ref, { 396 | "code": 500, 397 | "status": "internal_error", 398 | "msg": "Unknown error." 399 | }); 400 | data["error"] = True 401 | data["ref"] = ref 402 | return data 403 | 404 | class ValidationError(Exception): 405 | def __init__(self, arg): 406 | self.ref = arg -------------------------------------------------------------------------------- /library/grab_bag.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def fix_ip(ip_address): 4 | """Fixes an ugly, broken IP address string that came from Heroku""" 5 | 6 | if "," in ip_address: 7 | ips = ip_address.split(", ") 8 | ip_address = ips[0] 9 | 10 | return ip_address 11 | 12 | def random_hash(entropy): 13 | 14 | import time, hashlib, os 15 | _str = "%s%s%s" % (entropy, time.time()*1000, os.environ.get('GLOBAL_SALT')) 16 | return hashlib.sha256(_str).hexdigest() 17 | 18 | def password_hash(password): 19 | 20 | import hashlib, os 21 | _str = "%s%s" % (password, os.environ.get('GLOBAL_SALT')) 22 | return hashlib.sha256(_str).hexdigest() 23 | 24 | def o(output): 25 | print >> sys.stderr, output -------------------------------------------------------------------------------- /library/mailer.py: -------------------------------------------------------------------------------- 1 | import os 2 | from library.grab_bag import o 3 | 4 | base_url = os.environ.get('FAXROBOT_URL') 5 | email_support = os.environ.get('EMAIL_SUPPORT') 6 | email_feedback = os.environ.get('EMAIL_FEEDBACK') 7 | project = os.environ.get('PROJECT_NAME') 8 | email_headers = { 9 | "Authorization": os.environ.get('SPARKPOST_API_KEY'), 10 | "Content-Type": "application/json" 11 | } 12 | 13 | def email_registration(account): 14 | message = { 15 | 'subject': 'Welcome to %s!' % project, 16 | 'html': ('

Thanks for registering for %s! Your new account is ' 17 | 'ready. To log in, visit %s' 18 | '/accounts/login.

I\'ll send you emails with ' 19 | 'important account-related updates, like a notification when ' 20 | 'your faxes are sent (or they fail to send for some reason). ' 21 | 'I respect your email address and won\'t send you junk email. ' 22 | 'You can change your email notification preferences by ' 23 | 'visiting %s/account.

I hope ' 24 | 'you have as much fun using the service as I do ' 25 | 'sending faxes on your behalf.

Thanks again,

%s' 26 | '

') % (project, base_url, base_url, base_url, base_url, 27 | project) 28 | } 29 | 30 | send_email(message, account) 31 | 32 | def email_password_change(account): 33 | message = { 34 | 'subject': '%s password changed' % project, 35 | 'html': ('

Just a heads up: your %s password was changed.

' 36 | '

If you weren\'t aware of this, please email ' 37 | '%s ' 38 | 'as soon as possible.

--%s

') % (project, 39 | email_support, email_support, project) 40 | } 41 | send_email(message, account) 42 | 43 | def email_pending_deletion_warning(account, reason, fax_number): 44 | 45 | msg = '

Hello!

' 46 | 47 | if reason == "NO_FUNDS": 48 | msg += ("

Your %s account does not have sufficient funds for this " 49 | "month's incoming fax service, and automatic payments are " 50 | "disabled for your account.

") % project 51 | else: 52 | msg += ("

Your credit card was declined and your %s account has " 53 | "insufficient remaining funds for this month's incoming " 54 | "fax service.

") % project 55 | 56 | msg += ("

Please update your payment information in your " 57 | "Account Settings as " 58 | "soon as possible. If we are still unable to charge your account " 59 | "after 7 days, your fax number will automatically be suspended." 60 | "

Need assistance? Please reply to this email or contact " 61 | "%s.

Thanks!

--%s

") % ( 62 | base_url, email_support, email_support, project) 63 | 64 | message = { 65 | 'subject': 'Payment overdue for your incoming fax number', 66 | 'html': msg 67 | } 68 | send_email(message, account) 69 | 70 | def email_deleted_number(account): 71 | message = { 72 | 'subject': 'Your fax number was suspended :(', 73 | 'html': ('

Your monthly payment for incoming fax service could ' 74 | 'not be processed, and so the service was automatically ' 75 | 'suspended. For more information, please contact ' 76 | '%s ' 77 | 'as soon as possible.

--%s

') % ( 78 | email_support, email_support, project) 79 | } 80 | send_email(message, account) 81 | 82 | def email_api_key_change(account): 83 | message = { 84 | 'subject': '%s API key changed' % project, 85 | 'html': ('

Just a heads up: your %s API key was changed.

' 86 | '

If you weren\'t aware of this, please email ' 87 | '%s ' 88 | 'as soon as possible.

--%s

') % (project, 89 | email_support, email_support, project) 90 | } 91 | send_email(message, account) 92 | 93 | def email_provision_info(account, fax_number): 94 | message = { 95 | 'subject': 'Your fax number is activated!', 96 | 'html': ('

Congratulations! You can now receive faxes at %s.

' 97 | '

Your %s account will be charged $6 per month to ' 98 | 'keep your number active. You can manage your subscription by ' 99 | 'visiting your Account Settings' 100 | ' page.

Happy faxing!

--%s

') % ( 101 | fax_number, project, base_url, project) 102 | } 103 | send_email(message, account) 104 | 105 | def email_payment(account, charged, transaction_id, payment_last4, 106 | temporary_password = None): 107 | 108 | from datetime import datetime 109 | 110 | if temporary_password: 111 | html = ('

Your temporary password is: %s' 112 | '

Thanks for your business! Your purchase of %s ' 113 | 'Credit allows you to send faxes any ' 114 | 'time, without worrying about monthly subscription fees. We ' 115 | 'hope you enjoy using the service. If you have any questions ' 116 | 'or feedback, please email ' 117 | '%s.

' 118 | '

You can log into your account at ' 119 | '%s/accounts/login.') % ( 120 | temporary_password, project, email_feedback, email_feedback, 121 | base_url, base_url) 122 | subject = 'Welcome to %s! Here\'s your receipt.' % project 123 | else: 124 | html = '

Thanks for being a %s customer!

' % project 125 | subject = '%s payment receipt' % project 126 | 127 | html = html + ('
' 128 | '

Account: %s
' 129 | 'Transaction ID: %s
' 130 | 'Payment Date: %s
' 131 | 'Payment Card: %s
' 132 | 'Amount: $%.2f

' 133 | '

This is your receipt of payment against your credit card. ' 134 | 'Thanks!

For account information ' 135 | 'and current balance, please visit ' 136 | '%s/account.

' 137 | '

--%s

') % (account.email, transaction_id, 138 | datetime.now().strftime('%B %d, %Y'), payment_last4, charged, 139 | base_url, base_url, project) 140 | 141 | message = { 142 | 'subject': subject, 143 | 'html': html 144 | } 145 | send_email(message, account) 146 | 147 | def email_receive_fail(account,reason,external_id,from_number,num_pages,cost): 148 | 149 | html = ("

%s was unable to deliver an incoming fax from %s" 150 | " due to insufficient funds in your account.

") % ( 151 | project, from_number) 152 | 153 | if reason == "NO_FUNDS": 154 | html += ("

Please visit your Account " 155 | "Settings page to add funds, and consider turning" 156 | " on the automatic charging feature. ") % base_url 157 | else: 158 | html += ("

Your credit card was declined. Please visit " 159 | "your Account Settings" 160 | " page to update your credit card info.") % base_url 161 | 162 | html += ("

Once your account is funded, please reply to this email " 163 | "and we can deliver your fax.

") 164 | 165 | html += ("
" 166 | "

Reference #: %s
" 167 | "From: %s
" 168 | "Pages: %s
" 169 | "Cost: $%.2f

") % (external_id, from_number, 170 | num_pages, cost) 171 | 172 | message = { 173 | "subject": "Unable to receive fax :(", 174 | "html": html 175 | } 176 | send_email(message, account) 177 | 178 | def email_fax(account, external_id, from_number, num_pages, cost, 179 | filename, access_key): 180 | 181 | html = ("

You've received a fax from %s

Your fax is attached. " 182 | "You can also download or delete it from " 183 | "%s.

") % ( 184 | from_number, base_url, project) 185 | 186 | html += ("
" 187 | "

Reference #: %s
" 188 | "From: %s
" 189 | "Pages: %s
" 190 | "Cost: $%.2f


" 191 | "Remaining Account Balance: $%.2f

") % ( 192 | external_id, from_number, num_pages, cost, account.credit) 193 | 194 | message = { 195 | "subject": "Received fax from %s" % from_number, 196 | "html": html 197 | } 198 | send_email(message, account, "%s.pdf" % external_id, filename, 199 | "application/pdf") 200 | 201 | def email_recharge_payment(account, charged, transaction_id, payment_last4): 202 | 203 | from datetime import datetime 204 | 205 | message = { 206 | 'subject': '%s payment receipt' % project, 207 | 'html': ('

Thanks for being a %s customer!

Your ' 208 | 'remaining account credit dropped to $0, so we recharged it ' 209 | 'by $%.2f. You can manage your stored payment information and ' 210 | 'auto-recharge preferences at ' 211 | '%s/account.


' 212 | '

Account: %s
' 213 | 'Transaction ID: %s
' 214 | 'Payment Date: %s
' 215 | 'Payment Card: %s
' 216 | 'Amount: $%.2f

' 217 | '

This is your receipt of payment against your credit card. ' 218 | 'Thanks!

For account information ' 219 | 'and current balance, please visit ' 220 | '%s/account.

' 221 | '

--%s

') % (project, charged, base_url, base_url, 222 | account.email, transaction_id, 223 | datetime.now().strftime('%B %d, %Y'), payment_last4, charged, 224 | base_url, base_url, project) 225 | } 226 | send_email(message, account) 227 | 228 | def email_fail(job, msg, code, status, debug_data=None): 229 | 230 | from datetime import datetime 231 | 232 | account = job.account 233 | 234 | body = ('

Visit the fax details page to ' 235 | 'retry.

An error occurred while sending ' 236 | 'your fax:

' 237 | '

Job ID: %s
' 238 | 'Destination: %s
' 239 | 'Error: %s (Code %s)
' 240 | 'Date: %s
' 241 | ) % (base_url, job.access_key, job.id, job.destination, 242 | 'Internal error' if status == 'internal_error' else msg, 243 | code, datetime.now().strftime('%B %d, %Y')) 244 | 245 | if job.account.debug_mode and debug_data: 246 | 247 | if debug_data["device"]: 248 | body += 'Device: %s
' % debug_data["device"] 249 | 250 | if debug_data["output"]: 251 | output = "
".join(debug_data["output"].split("\n")) 252 | body += 'Output: %s
' % output 253 | 254 | body +=('

If you\'re having trouble, please email ' 255 | '%s ' 256 | 'and we\'ll do our best to help.

To change your email ' 257 | 'notification preferences, visit ' 258 | '%s/account.

--%s

') % ( 259 | email_support, email_support, base_url, base_url, project) 260 | 261 | message = { 262 | 'subject': 'Your fax could not be sent :(', 263 | 'html': body 264 | } 265 | send_email(message, account) 266 | 267 | def email_success(job): 268 | 269 | from datetime import datetime 270 | 271 | account = job.account 272 | 273 | message = { 274 | 'subject': 'Your fax was sent!', 275 | 'html': ('

Great news! Your fax to %s was sent.

' 276 | '

Visit the fax details page ' 277 | 'for more info.

To change your email ' 278 | 'notification preferences, visit ' 279 | '%s/account.

--%s

' 280 | ) % (job.destination, base_url, job.access_key, base_url, 281 | base_url, project) 282 | } 283 | send_email(message, account) 284 | 285 | def email_password_reset(email, password_reset, account): 286 | 287 | message = { 288 | 'subject': 'Reset your %s password' % project, 289 | 'html': ('

To reset your %s password, click on the link ' 290 | 'below:

%s/reset/%s

If ' 291 | 'you weren\'t expecting this email, or weren\'t trying to ' 292 | 'reset your password, please contact ' 293 | '%s' 294 | '

--%s

' 295 | ) % (project, base_url, password_reset.reset_hash, base_url, 296 | password_reset.reset_hash, email_support, email_support, 297 | project) 298 | } 299 | send_email(message, account) 300 | 301 | def send_email(message, account = None, attach_name=None, attach_file=None, 302 | attach_mime=None): 303 | 304 | if not os.environ.get('SPARKPOST_API_KEY'): 305 | return False 306 | 307 | import requests 308 | import base64 309 | 310 | url = 'https://api.sparkpost.com/api/v1/transmissions' 311 | 312 | payload = {} 313 | 314 | payload['content'] = message 315 | payload['content']['from'] = { 316 | "name": os.environ.get('EMAIL_FROM_NAME'), 317 | "email": os.environ.get('EMAIL_FROM') 318 | } 319 | 320 | if account: 321 | if account.first_name and account.last_name: 322 | payload['recipients'] = [{ 323 | 'address': { 324 | 'email': account.email, 325 | 'name': account.first_name + ' ' + account.last_name 326 | } 327 | }] 328 | else: 329 | payload['recipients'] = [{'address': account.email}] 330 | 331 | if attach_name and attach_file and attach_mime: 332 | 333 | with open(attach_file) as f: 334 | attach_data = base64.b64encode(f.read()) 335 | 336 | payload['content']['attachments'] = [ 337 | { 338 | "type": attach_mime, 339 | "name": attach_name, 340 | "data": attach_data 341 | } 342 | ] 343 | 344 | try: 345 | response = requests.post(url, headers=email_headers, json=payload) 346 | except: 347 | o('SparkPost API Fail: %s' % response.text) 348 | 349 | def email_admin(message, subject = None): 350 | 351 | if not os.environ.get('SPARKPOST_API_KEY'): 352 | return False 353 | 354 | import requests 355 | 356 | url = 'https://api.sparkpost.com/api/v1/transmissions' 357 | 358 | payload = { 359 | "content": { 360 | "subject": subject if subject else "%s CRITICAL ERROR" % project, 361 | "html": message, 362 | "from": { 363 | "name": os.environ.get('EMAIL_FROM_NAME'), 364 | "email": os.environ.get('EMAIL_FROM') 365 | } 366 | }, 367 | "recipients": [{'address': os.environ.get('EMAIL_FROM')}] 368 | } 369 | 370 | try: 371 | response = requests.post(url, headers=email_headers, json=payload) 372 | except: 373 | o('SparkPost API Fail: %s' % response.text) 374 | 375 | 376 | 377 | 378 | -------------------------------------------------------------------------------- /library/phaxio.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import hmac 3 | 4 | def valid_signature(token, url, parameters, files, signature): 5 | # sort the post fields and add them to the URL 6 | for key in sorted(parameters.keys()): 7 | url += '{}{}'.format(key, parameters[key]) 8 | 9 | # sort the files and add their SHA1 sums to the URL 10 | for filename in sorted(files.keys()): 11 | file_hash = hashlib.sha1() 12 | file_hash.update(files[filename].read()) 13 | files[filename].stream.seek(0) 14 | url += '{}{}'.format(filename, file_hash.hexdigest()) 15 | 16 | return signature == hmac.new(key=token.encode('utf-8'), msg=url.encode('utf-8'), digestmod=hashlib.sha1).hexdigest() 17 | 18 | -------------------------------------------------------------------------------- /log/README.md: -------------------------------------------------------------------------------- 1 | This page intentionally left blank 2 | -------------------------------------------------------------------------------- /media/cover_sheets/default.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lyonbros/faxrobot/4dfdd6c9bd4cd335a7dc4aaaa6188ad808b78d71/media/cover_sheets/default.pdf -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | from flask_sqlalchemy import SQLAlchemy 2 | db = SQLAlchemy() 3 | 4 | def initialize_database(app): 5 | from models.account import Account 6 | from models.job import Job 7 | from models.transaction import Transaction 8 | from models.failed_payment import FailedPayment 9 | from models.password_reset import PasswordReset 10 | from models.incoming_number import IncomingNumber 11 | from models.incoming_fax import IncomingFax 12 | import psycopg2 13 | import os 14 | 15 | with app.app_context(): 16 | try: 17 | db.create_all() 18 | account = Account.query.get(0) 19 | if not account: 20 | # insert guest account if needed. 21 | conn = psycopg2.connect(os.environ.get('DATABASE_URI')) 22 | query = ("INSERT INTO account (id, email, password, api_key) " 23 | "VALUES (%s, %s, %s, %s);") 24 | data = (0, 'anon@faxrobot.internal', 'trol', 'lol') 25 | cursor = conn.cursor() 26 | cursor.execute(query, data) 27 | conn.commit() 28 | conn.close() 29 | except: 30 | print("ERROR: COULD NOT AUTO-GENERATE DATABASE TABLES") 31 | print("Make sure your SQLALCHEMY_DATABASE_URI environment is set!") -------------------------------------------------------------------------------- /models/account.py: -------------------------------------------------------------------------------- 1 | from models import db 2 | from datetime import datetime 3 | from sqlalchemy import func, Column, BigInteger, SmallInteger, Integer, \ 4 | String, DateTime, ForeignKey, Text, Float 5 | from sqlalchemy.exc import SQLAlchemyError 6 | from validate_email import validate_email 7 | from library.grab_bag import random_hash, password_hash 8 | from library.errors import ValidationError 9 | import os 10 | 11 | default_cost_per_page = float(os.environ.get('DEFAULT_COST_PER_PAGE', '0.10')) 12 | 13 | class Account(db.Model): 14 | __tablename__ = 'account' 15 | 16 | id = Column(BigInteger, primary_key=True) 17 | email = Column(String(255), nullable=False,unique=True,index=True) 18 | password = Column(String(64), nullable=False) 19 | api_key = Column(String(64), nullable=False,unique=True,index=True) 20 | credit = Column(Float, default=0.00) 21 | base_rate = Column(Float, default=default_cost_per_page) 22 | allow_overflow = Column(SmallInteger, default=0) 23 | first_name = Column(String(255)) 24 | last_name = Column(String(255)) 25 | address = Column(String(255)) 26 | address2 = Column(String(255)) 27 | city = Column(String(255)) 28 | state = Column(String(64)) 29 | zip = Column(String(24)) 30 | stripe_token = Column(String(255)) 31 | stripe_card = Column(String(255)) 32 | last4 = Column(Integer) 33 | auto_recharge = Column(SmallInteger, default=0) 34 | email_success = Column(SmallInteger, default=1) 35 | email_fail = Column(SmallInteger, default=1) 36 | email_list = Column(SmallInteger, default=1) 37 | debug_mode = Column(SmallInteger, default=0) 38 | low_priority = Column(SmallInteger, default=0) 39 | create_date = Column(DateTime) 40 | mod_date = Column(DateTime) 41 | 42 | def __init__(self, email, password, first_name=None, last_name=None, 43 | address=None, address2=None, city=None, state=None, zip=None): 44 | 45 | self.create_date = datetime.now() 46 | 47 | if not email: 48 | raise ValidationError('ACCOUNTS_MISSING_EMAIL') 49 | elif not validate_email(email): 50 | raise ValidationError('ACCOUNTS_BAD_EMAIL') 51 | else: 52 | self.email = email 53 | 54 | if not password: 55 | raise ValidationError('ACCOUNTS_MISSING_PASSWORD') 56 | else: 57 | self.password = password_hash(password) 58 | 59 | self.api_key = random_hash("%s%s" % (email, self.password)) 60 | self.first_name = first_name 61 | self.last_name = last_name 62 | self.address = address 63 | self.address2 = address2 64 | self.city = city 65 | self.state = state 66 | self.zip = zip 67 | 68 | def validate(self): 69 | 70 | if not self.email: 71 | raise ValidationError('ACCOUNTS_MISSING_EMAIL') 72 | 73 | if not validate_email(self.email): 74 | raise ValidationError('ACCOUNTS_BAD_EMAIL') 75 | 76 | if self.first_name and len(self.first_name) > 255: 77 | raise ValidationError('ACCOUNTS_BAD_FIRST_NAME') 78 | 79 | if self.last_name and len(self.last_name) > 255: 80 | raise ValidationError('ACCOUNTS_BAD_LAST_NAME') 81 | 82 | if self.address and len(self.address) > 255: 83 | raise ValidationError('ACCOUNTS_BAD_ADDRESS') 84 | 85 | if self.address2 and len(self.address2) > 255: 86 | raise ValidationError('ACCOUNTS_BAD_ADDRESS2') 87 | 88 | if self.city and len(self.city) > 255: 89 | raise ValidationError('ACCOUNTS_BAD_CITY') 90 | 91 | if self.state and len(self.state) > 64: 92 | raise ValidationError('ACCOUNTS_BAD_STATE') 93 | 94 | if self.zip and len(self.zip) > 24: 95 | raise ValidationError('ACCOUNTS_BAD_ZIP') 96 | 97 | if self.email_success and self.email_success != 0 and \ 98 | self.email_success != 1: 99 | raise ValidationError('ACCOUNTS_BAD_REQUEST') 100 | 101 | if self.email_fail and self.email_fail != 0 and self.email_fail != 1: 102 | raise ValidationError('ACCOUNTS_BAD_REQUEST') 103 | 104 | if self.email_list and self.email_list != 0 and self.email_list != 1: 105 | raise ValidationError('ACCOUNTS_BAD_REQUEST') 106 | 107 | return True 108 | 109 | def add_credit(self, amount, session=None): 110 | 111 | if not session: 112 | session = db.session 113 | 114 | session.query(Account).filter_by(id=self.id).update( 115 | {Account.credit: Account.credit + amount} 116 | ) 117 | session.commit() 118 | 119 | def subtract_credit(self, amount, session=None): 120 | 121 | if not session: 122 | session = db.session 123 | 124 | session.query(Account).filter_by(id=self.id).update( 125 | {Account.credit: Account.credit - amount} 126 | ) 127 | session.commit() 128 | 129 | def get_priority(self): 130 | 131 | return "low" if self.low_priority else "default" 132 | 133 | # why have two nearly identical methods doing nearly exactly the same thing? 134 | # BECAUSE FUCK YOU. that's why. 135 | 136 | def public_data(self): 137 | """ 138 | Returns a dictionary of fields that are safe to display to the client. 139 | """ 140 | 141 | data = { 142 | 'api_key': self.api_key, 143 | 'email': self.email, 144 | 'first_name': self.first_name, 145 | 'last_name': self.last_name, 146 | 'address': self.address, 147 | 'address2': self.address2, 148 | 'city': self.city, 149 | 'state': self.state, 150 | 'zip': self.zip, 151 | 'credit': self.credit, 152 | 'auto_recharge': self.auto_recharge, 153 | 'has_stripe_token': True if self.stripe_token else False, 154 | 'last4': self.last4, 155 | 'email_success': self.email_success, 156 | 'email_fail': self.email_fail, 157 | 'email_list': self.email_list, 158 | }; 159 | 160 | if len(self.incoming_numbers) > 0: 161 | data["incoming_number"] = self.incoming_numbers[0].fax_number 162 | 163 | return data; 164 | 165 | @classmethod 166 | def authorize(cls_obj, api_key, required = False): 167 | """ 168 | Checks that any given api_key is valid 169 | """ 170 | if required == False and not api_key: 171 | return 0 # guest account ID is 0 172 | 173 | accounts = cls_obj.query.filter_by(api_key = api_key) 174 | return None if accounts.first() == None else accounts.first().id 175 | 176 | def __repr__(self): 177 | return "" % (self.id, self.email) -------------------------------------------------------------------------------- /models/failed_payment.py: -------------------------------------------------------------------------------- 1 | from models import db 2 | from datetime import datetime 3 | from sqlalchemy import func, Column, BigInteger, SmallInteger, Integer, \ 4 | String, Float, DateTime, ForeignKey, Text 5 | from sqlalchemy.orm.session import Session 6 | from sqlalchemy.exc import SQLAlchemyError 7 | 8 | class FailedPayment(db.Model): 9 | __tablename__ = 'failed_payment' 10 | 11 | id = Column(BigInteger, primary_key=True) 12 | account_id = Column(BigInteger) 13 | amount = Column(Float) 14 | source = Column(String(10)) 15 | debug = Column(Text) 16 | ip_address = Column(String(255)) 17 | payment_type = Column(String(64)) 18 | create_date = Column(DateTime) 19 | mod_date = Column(DateTime) 20 | 21 | def __init__(self, amount, account_id=None, source=None, debug=None, 22 | ip_address=None, payment_type=None): 23 | 24 | self.create_date = datetime.now() 25 | self.account_id = account_id 26 | self.amount = amount 27 | self.source = source 28 | self.debug = debug 29 | self.ip_address = ip_address 30 | self.payment_type = payment_type 31 | 32 | def __repr__(self): 33 | return ""%\ 34 | (self.id, self.account_id, self.amount, self.source) -------------------------------------------------------------------------------- /models/incoming_fax.py: -------------------------------------------------------------------------------- 1 | import os 2 | from models import db 3 | from models.account import Account 4 | from datetime import datetime 5 | from sqlalchemy import func, Column, BigInteger, SmallInteger, Integer, \ 6 | String, Float, DateTime, ForeignKey, Text 7 | from sqlalchemy.orm.session import Session 8 | from sqlalchemy.exc import SQLAlchemyError 9 | from library.grab_bag import random_hash, o 10 | from library.errors import ValidationError 11 | 12 | class IncomingFax(db.Model): 13 | __tablename__ = 'incoming_fax' 14 | 15 | id = Column(BigInteger, primary_key=True) 16 | account_id = Column(BigInteger, ForeignKey('account.id')) 17 | external_id = Column(BigInteger) 18 | account = db.relationship('Account', 19 | backref=db.backref('incoming_faxes',order_by=id)) 20 | access_key = Column(String(64), unique=True, index=True) 21 | num_pages = Column(Integer) 22 | cost = Column(Float) 23 | from_number = Column(String(32)) 24 | to_number = Column(String(32)) 25 | hosted_url = Column(String(255)) 26 | data_deleted = Column(SmallInteger, default=0) 27 | create_date = Column(DateTime) 28 | mod_date = Column(DateTime) 29 | 30 | def __init__(self, account_id, external_id, num_pages, cost, from_number, 31 | to_number): 32 | 33 | self.create_date = datetime.now() 34 | self.account_id = account_id 35 | self.external_id = external_id 36 | self.num_pages = num_pages 37 | self.cost = cost 38 | self.from_number = from_number 39 | self.to_number = to_number 40 | self.access_key = random_hash("%s%s%s%s%s" % (from_number, 41 | to_number, cost, num_pages, account_id)) 42 | 43 | 44 | def public_data(self): 45 | """ 46 | Returns a dictionary of fields that are safe to display to the end user. 47 | """ 48 | 49 | data = { 50 | 'id': self.id, 51 | 'access_key': self.access_key, 52 | 'num_pages': self.num_pages, 53 | 'cost': self.cost, 54 | 'from_number': self.from_number, 55 | 'to_number': self.to_number, 56 | 'data_deleted': self.data_deleted, 57 | 'create_date': self.create_date, 58 | 'mod_date': self.mod_date 59 | } 60 | 61 | return data; 62 | 63 | def __repr__(self): 64 | return "" % \ 65 | (self.id, self.account_id, self.from_number) -------------------------------------------------------------------------------- /models/incoming_number.py: -------------------------------------------------------------------------------- 1 | from models import db 2 | from datetime import datetime 3 | from sqlalchemy import func, Column, BigInteger, SmallInteger, Integer, \ 4 | String, Float, DateTime, ForeignKey, Text 5 | from sqlalchemy.orm.session import Session 6 | from sqlalchemy.exc import SQLAlchemyError 7 | 8 | class IncomingNumber(db.Model): 9 | __tablename__ = 'incoming_number' 10 | 11 | id = Column(BigInteger, primary_key=True) 12 | account_id = Column(BigInteger, ForeignKey('account.id')) 13 | account = db.relationship('Account', 14 | backref=db.backref('incoming_numbers')) 15 | fax_number = Column(String(64), unique=True) 16 | flagged_for_deletion = Column(Integer, default=0) 17 | last_billed = Column(DateTime) 18 | create_date = Column(DateTime) 19 | mod_date = Column(DateTime) 20 | 21 | def __init__(self, account_id, fax_number): 22 | 23 | self.create_date = datetime.now() 24 | self.last_billed = datetime.now() 25 | self.account_id = account_id 26 | self.fax_number = fax_number 27 | 28 | def __repr__(self): 29 | return ""%\ 30 | (self.id, self.account_id, self.fax_number) -------------------------------------------------------------------------------- /models/job.py: -------------------------------------------------------------------------------- 1 | import os 2 | from models import db 3 | from models.account import Account 4 | from datetime import datetime 5 | from sqlalchemy import func, Column, BigInteger, SmallInteger, Integer, \ 6 | String, Float, DateTime, ForeignKey, Text 7 | from sqlalchemy.orm.session import Session 8 | from sqlalchemy.exc import SQLAlchemyError 9 | from library.grab_bag import random_hash, o 10 | from library.errors import ValidationError 11 | import psycopg2 12 | 13 | class Job(db.Model): 14 | __tablename__ = 'job' 15 | 16 | id = Column(BigInteger, primary_key=True) 17 | account_id = Column(BigInteger, ForeignKey('account.id')) 18 | external_id = Column(BigInteger, index=True) 19 | account = db.relationship('Account', 20 | backref=db.backref('jobs',order_by=id)) 21 | filename = Column(String(255)) 22 | body = Column(Text) 23 | destination = Column(String(32)) 24 | attempts = Column(Integer, default=0) 25 | num_pages = Column(Integer) 26 | cost = Column(Float) 27 | cover_cost = Column(Float) 28 | international = Column(SmallInteger, default=0) 29 | device = Column(String(64)) 30 | failed = Column(SmallInteger, default=0) 31 | fail_code = Column(Integer, default=0) 32 | status = Column(String(255), index=True) 33 | debug = Column(Text) 34 | access_key = Column(String(64), unique=True, index=True) 35 | ip_address = Column(String(255)) 36 | send_authorized = Column(SmallInteger, default=0) 37 | data_deleted = Column(SmallInteger, default=0) 38 | 39 | cover = Column(SmallInteger, default=0) 40 | cover_name = Column(String(64)) 41 | cover_address = Column(String(128)) 42 | cover_city = Column(String(64)) 43 | cover_state = Column(String(64)) 44 | cover_zip = Column(String(64)) 45 | cover_country = Column(String(64)) 46 | cover_phone = Column(String(64)) 47 | cover_email = Column(String(128)) 48 | cover_company = Column(String(128)) 49 | cover_to_name = Column(String(64)) 50 | cover_cc = Column(String(64)) 51 | cover_subject = Column(String(64)) 52 | cover_status = Column(String(64)) 53 | cover_comments = Column(Text) 54 | 55 | callback_url = Column(String(255)) 56 | callback_fail = Column(Integer, default=0, index=True) 57 | callback_date = Column(DateTime) 58 | 59 | create_date = Column(DateTime) 60 | mod_date = Column(DateTime) 61 | start_date = Column(DateTime) 62 | fail_date = Column(DateTime) 63 | end_date = Column(DateTime) 64 | 65 | def __init__(self, account_id, ip_address, filename=None, destination=None, 66 | send_authorized=0, cover=0, cover_name=None, cover_address=None, 67 | cover_city=None, cover_state=None, cover_zip=None, 68 | cover_country=None, cover_phone=None, cover_email=None, 69 | cover_company=None, cover_to_name=None, cover_cc=None, 70 | cover_subject=None, cover_status=None, cover_comments=None, 71 | body=None, callback_url=None): 72 | 73 | if destination != None: 74 | self.validate_destination(destination) 75 | self.destination = destination 76 | 77 | self.create_date = datetime.now() 78 | self.account_id = account_id 79 | self.filename = filename 80 | self.ip_address = ip_address 81 | self.send_authorized = send_authorized 82 | self.access_key = random_hash("%s%s" % (account_id, filename)) 83 | self.status = 'new' 84 | 85 | self.cover = cover 86 | self.cover_name = cover_name 87 | self.cover_address = cover_address 88 | self.cover_city = cover_city 89 | self.cover_state = cover_state 90 | self.cover_zip = cover_zip 91 | self.cover_country = cover_country 92 | self.cover_phone = cover_phone 93 | self.cover_email = cover_email 94 | self.cover_company = cover_company 95 | self.cover_to_name = cover_to_name 96 | self.cover_cc = cover_cc 97 | self.cover_subject = cover_subject 98 | self.cover_status = cover_status 99 | self.cover_comments = cover_comments 100 | self.body = body 101 | self.callback_url = callback_url 102 | 103 | def validate_destination(self, destination): 104 | if len(destination) < 10: 105 | raise ValidationError('JOBS_BAD_DESTINATION') 106 | if not destination.isdigit(): 107 | raise ValidationError('JOBS_BAD_DESTINATION') 108 | return True 109 | 110 | def determine_international(self): 111 | if not self.destination: 112 | return 113 | 114 | destination = self.destination 115 | 116 | if len(destination) == 10: 117 | self.destination = u"1%s" % destination 118 | self.international = 0 119 | 120 | elif len(destination) > 11 or \ 121 | (len(destination) == 11 and not destination.startswith(u"1")): 122 | self.international = 1 123 | 124 | else: 125 | self.international = 0 126 | 127 | def compute_cost(self): 128 | if self.account.base_rate: 129 | page_cost = self.account.base_rate 130 | else: 131 | page_cost = float(os.environ.get('DEFAULT_COST_PER_PAGE', '0.10')) 132 | 133 | international_multiplier = self.international + 1 134 | 135 | self.cost = page_cost * self.num_pages * international_multiplier 136 | self.cover_cost = page_cost * international_multiplier 137 | 138 | def delete_data(self, session=None): 139 | """ 140 | Removes job data from the server (including optionally Amazon S3). 141 | """ 142 | import shutil 143 | import os 144 | from boto.s3.connection import S3Connection 145 | from boto.s3.key import Key 146 | 147 | if not session: 148 | session = db.session 149 | 150 | self.data_deleted = 1 151 | self.cover_name = None 152 | self.cover_address = None 153 | self.cover_city = None 154 | self.cover_state = None 155 | self.cover_zip = None 156 | self.cover_country = None 157 | self.cover_phone = None 158 | self.cover_email = None 159 | self.cover_company = None 160 | self.cover_to_name = None 161 | self.cover_cc = None 162 | self.cover_subject = None 163 | self.cover_status = None 164 | self.cover_comments = None 165 | self.body = None 166 | self.mod_date = datetime.now() 167 | 168 | session.commit() 169 | 170 | if os.path.isdir('./tmp/' + self.access_key): 171 | shutil.rmtree('./tmp/' + self.access_key) 172 | 173 | if os.environ.get('AWS_STORAGE') == "on": 174 | try: 175 | conn = S3Connection(os.environ.get('AWS_ACCESS_KEY'), 176 | os.environ.get('AWS_SECRET_KEY')) 177 | bucket = conn.get_bucket(os.environ.get('AWS_S3_BUCKET')) 178 | except: 179 | o("COULD NOT CONNECT TO S3 WTF WTF WTF WTF") 180 | return 181 | 182 | try: 183 | for i in range(0, self.num_pages): 184 | 185 | n = ("0%s" % i) if i < 10 else "%s" % i 186 | k = Key(bucket) 187 | k.key ='fax/%s/%s.%s.tiff'%(self.access_key,self.filename,n) 188 | k.delete() 189 | 190 | except: 191 | o("COULD NOT DELETE FILES FROM LOCAL OMG SHIT") 192 | 193 | return True 194 | 195 | def rate_limit(self, account_id): 196 | conn = psycopg2.connect(os.environ.get('DATABASE_URI')) 197 | query = ( 198 | "SELECT count(id) " 199 | "FROM job " 200 | "WHERE create_date > now() - \'5 minutes\'::interval " 201 | "AND account_id = %s " 202 | "AND send_authorized = 1; " 203 | ) 204 | data = [account_id] 205 | 206 | cursor = conn.cursor() 207 | cursor.execute(query, data) 208 | result = cursor.fetchone() 209 | 210 | if result[0] > 0: 211 | raise ValidationError('JOBS_RATE_LIMIT_REACHED') 212 | 213 | return True 214 | 215 | def validate(self): 216 | """ 217 | I had as much fun writing this as you'll probably have reading it. 218 | """ 219 | 220 | if self.destination: 221 | self.validate_destination(self.destination) 222 | 223 | if self.cover and self.cover != 0 and self.cover != 1 and \ 224 | self.cover != "0" and self.cover != "1": 225 | raise ValidationError('JOBS_BAD_COVER') 226 | 227 | if self.send_authorized and self.send_authorized != 0 and \ 228 | self.send_authorized != 1 and self.send_authorized != "0" and \ 229 | self.send_authorized != "1": 230 | raise ValidationError('JOBS_BAD_SEND_AUTHORIZED') 231 | 232 | if self.send_authorized and not self.destination: 233 | raise ValidationError('JOBS_MISSING_DESTINATION') 234 | 235 | if self.filename and len(self.filename) > 255: 236 | raise ValidationError('JOBS_BAD_FILENAME') 237 | 238 | if self.cover_name and len(self.cover_name) > 64: 239 | raise ValidationError('JOBS_BAD_COVER_NAME') 240 | 241 | if self.cover_address and len(self.cover_address) > 128: 242 | raise ValidationError('JOBS_BAD_COVER_ADDRESS') 243 | 244 | if self.cover_city and len(self.cover_city) > 64: 245 | raise ValidationError('JOBS_BAD_COVER_CITY') 246 | 247 | if self.cover_state and len(self.cover_state) > 64: 248 | raise ValidationError('JOBS_BAD_COVER_STATE') 249 | 250 | if self.cover_zip and len(self.cover_zip) > 64: 251 | raise ValidationError('JOBS_BAD_COVER_ZIP') 252 | 253 | if self.cover_country and len(self.cover_country) > 64: 254 | raise ValidationError('JOBS_BAD_COVER_COUNTRY') 255 | 256 | if self.cover_phone and len(self.cover_phone) > 64: 257 | raise ValidationError('JOBS_BAD_COVER_PHONE') 258 | 259 | if self.cover_email and len(self.cover_email) > 128: 260 | raise ValidationError('JOBS_BAD_COVER_EMAIL') 261 | 262 | if self.cover_company and len(self.cover_company) > 128: 263 | raise ValidationError('JOBS_BAD_COVER_COMPANY') 264 | 265 | if self.cover_to_name and len(self.cover_to_name) > 64: 266 | raise ValidationError('JOBS_BAD_COVER_TO_NAME') 267 | 268 | if self.cover_cc and len(self.cover_cc) > 64: 269 | raise ValidationError('JOBS_BAD_COVER_CC') 270 | 271 | if self.cover_subject and len(self.cover_subject) > 64: 272 | raise ValidationError('JOBS_BAD_COVER_SUBJECT') 273 | 274 | if self.cover_status and len(self.cover_status) > 64: 275 | raise ValidationError('JOBS_BAD_COVER_STATUS') 276 | 277 | if self.callback_url and len(self.callback_url) > 255: 278 | raise ValidationError('JOBS_BAD_CALLBACK_URL') 279 | 280 | return True 281 | 282 | def public_data(self): 283 | """ 284 | Returns a dictionary of fields that are safe to display to the end user. 285 | """ 286 | if self.cost and self.cover_cost: 287 | total = self.cost if not self.cover else self.cost+self.cover_cost 288 | else: 289 | total = "0" 290 | 291 | data = { 292 | 'id': self.id, 293 | 'status': self.status, 294 | 'access_key': self.access_key, 295 | 'ip_address': self.ip_address, 296 | 'filename': self.filename if self.filename else "(text)", 297 | 'destination': self.destination, 298 | 'attempts': self.attempts, 299 | 'num_pages': self.num_pages, 300 | 'cover': self.cover, 301 | 'cost': self.cost, 302 | 'cover_cost': self.cover_cost, 303 | 'international': self.international, 304 | 'total_cost': total, 305 | 'send_authorized': self.send_authorized, 306 | 'data_deleted': self.data_deleted, 307 | 'create_date': self.create_date, 308 | 'mod_date': self.mod_date, 309 | 'start_date': self.start_date, 310 | 'end_date': self.end_date, 311 | 'failed': self.failed, 312 | 'fail_code': self.fail_code, 313 | 'fail_date': self.fail_date 314 | } 315 | if self.status == 'new' or self.status == 'uploading': 316 | note = ('We have not yet computed the \'cost\', ' 317 | '\'cover_cost\', \'total_cost\', or \'num_pages\' fields. ' 318 | 'Do not rely on them yet.') 319 | data.pop("cost", None) 320 | data.pop("cover_cost", None) 321 | data.pop("total_cost", None) 322 | data.pop("num_pages", None) 323 | data['NOTE'] = note 324 | 325 | return data; 326 | 327 | def __repr__(self): 328 | return "" % (self.id, \ 329 | self.account_id, self.filename) -------------------------------------------------------------------------------- /models/password_reset.py: -------------------------------------------------------------------------------- 1 | from models import db 2 | from datetime import datetime 3 | from sqlalchemy import func, Column, BigInteger, SmallInteger, Integer, \ 4 | String, Float, DateTime, ForeignKey, Text 5 | from sqlalchemy.orm.session import Session 6 | from sqlalchemy.exc import SQLAlchemyError 7 | from library.grab_bag import random_hash 8 | 9 | class PasswordReset(db.Model): 10 | __tablename__ = 'password_reset' 11 | 12 | id = Column(BigInteger, primary_key=True) 13 | account_id = Column(BigInteger) 14 | reset_hash = Column(String(64),index=True) 15 | used = Column(SmallInteger, default=0) 16 | create_date = Column(DateTime) 17 | mod_date = Column(DateTime) 18 | 19 | def __init__(self, account_id): 20 | 21 | self.create_date = datetime.now() 22 | self.account_id = account_id 23 | self.reset_hash = random_hash("%s%s"%(account_id,str(self.create_date))) 24 | 25 | def __repr__(self): 26 | return ""%\ 27 | (self.id, self.account_id, self.used) -------------------------------------------------------------------------------- /models/transaction.py: -------------------------------------------------------------------------------- 1 | from models import db 2 | from datetime import datetime 3 | from sqlalchemy import func, Column, BigInteger, SmallInteger, Integer, \ 4 | String, Float, DateTime, ForeignKey, Text 5 | from sqlalchemy.orm.session import Session 6 | from sqlalchemy.exc import SQLAlchemyError 7 | 8 | class Transaction(db.Model): 9 | __tablename__ = 'transaction' 10 | 11 | id = Column(BigInteger, primary_key=True) 12 | account_id = Column(Integer, ForeignKey('account.id')) 13 | account = db.relationship('Account', 14 | backref=db.backref('transactions',order_by=id)) 15 | amount = Column(Float) 16 | initial_balance = Column(Float) 17 | job_id = Column(BigInteger, index=True) 18 | job_destination = Column(String(32)) 19 | source = Column(String(10)) 20 | source_id = Column(String(64)) 21 | ip_address = Column(String(255)) 22 | note = Column(String(255)) 23 | trans_type = Column(String(64)) 24 | create_date = Column(DateTime) 25 | mod_date = Column(DateTime) 26 | 27 | def __init__(self, account_id, amount, job_id=None, job_destination=None, 28 | source=None, source_id=None, ip_address=None, initial_balance=None, 29 | note=None, trans_type=None): 30 | 31 | self.create_date = datetime.now() 32 | self.account_id = account_id 33 | self.amount = amount 34 | self.job_id = job_id 35 | self.job_destination = job_destination 36 | self.source = source 37 | self.source_id = source_id 38 | self.ip_address = ip_address 39 | self.initial_balance = initial_balance 40 | self.note = note 41 | self.trans_type = trans_type 42 | 43 | def public_data(self): 44 | """ 45 | Returns a dictionary of fields that are safe to display to the client. 46 | """ 47 | 48 | return { 49 | 'id': self.id, 50 | 'amount': self.amount, 51 | 'initial_balance': self.initial_balance, 52 | 'job_id': self.job_id, 53 | 'job_destination': self.job_destination, 54 | 'source': self.source, 55 | 'source_id': self.source_id, 56 | 'ip_address': self.ip_address, 57 | 'trans_type': self.trans_type, 58 | 'create_date': self.create_date 59 | }; 60 | 61 | def __repr__(self): 62 | return "" % \ 63 | (self.id, self.account_id, self.amount, self.source) -------------------------------------------------------------------------------- /more_requirements.txt: -------------------------------------------------------------------------------- 1 | paps 2 | Liberation Mono font -------------------------------------------------------------------------------- /raise_price.py: -------------------------------------------------------------------------------- 1 | from controllers.incoming import auto_recharge, delete_number_from_phaxio 2 | from models.account import Account 3 | from models.incoming_number import IncomingNumber 4 | from models.transaction import Transaction 5 | from library.mailer import email_admin, email_deleted_number, \ 6 | email_pending_deletion_warning 7 | import psycopg2 8 | import os 9 | from sqlalchemy.orm import sessionmaker 10 | from sqlalchemy import create_engine 11 | from datetime import datetime 12 | 13 | engine = create_engine(os.environ.get('DATABASE_URI').strip()) 14 | Session = sessionmaker(bind=engine) 15 | session = Session() 16 | 17 | new_price = float(os.environ.get('DEFAULT_COST_PER_PAGE')) 18 | 19 | print "NEW PRICE IS %s" % new_price 20 | print "QUERYING USERS WHO HAVE OLD PRICE RATE" 21 | print " " 22 | 23 | conn = psycopg2.connect(os.environ.get('DATABASE_URI')) 24 | query = ( 25 | "SELECT id, base_rate, credit, email, create_date, mod_date " 26 | "FROM account " 27 | ) 28 | cursor = conn.cursor() 29 | cursor.execute(query, (float(new_price),)) 30 | 31 | for row in cursor: 32 | id = row[0] 33 | base_rate = row[1] 34 | credit = row[2] 35 | email = row[3] 36 | 37 | if not base_rate or not base_rate < new_price: 38 | continue 39 | 40 | print "Found account %s: %s" % (id, email) 41 | print " - base_rate: %s" % base_rate 42 | print " - credit: %s" % credit 43 | 44 | 45 | conn.commit() 46 | conn.close() 47 | 48 | print "ALL DONE!" -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto==2.34.0 2 | docopt==0.4.0 3 | Flask==0.10.1 4 | Flask-Cors==1.10.2 5 | Flask-SQLAlchemy==2.0 6 | gevent==1.0.1 7 | greenlet==0.4.5 8 | itsdangerous==0.24 9 | Jinja2==2.7.3 10 | MarkupSafe==0.23 11 | pkg-resources==0.0.0 12 | poster==0.8.1 13 | psycopg2==2.8.3 14 | redis==2.10.3 15 | requests==2.5.1 16 | rq==0.4.6 17 | six==1.9.0 18 | SQLAlchemy==0.9.8 19 | stripe==1.21.0 20 | validate-email==1.3 21 | Werkzeug==0.9.6 -------------------------------------------------------------------------------- /templates/accounts_bootstrap.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Bootstrap an Account (TEST) 4 | 8 | 9 | 10 |

Bootstrap an Account (TEST)

11 |

This is really just for testing. We shouldn't ever actually use this.

12 |
13 | 14 | 15 |
16 | 17 | 18 |
19 | 20 | 21 |
22 | 23 | 24 |
25 | 26 |
27 | 28 | -------------------------------------------------------------------------------- /templates/accounts_create.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Create an Account (TEST) 4 | 8 | 9 | 10 |

Create an Account (TEST)

11 |

This is really just for testing. We shouldn't ever actually use this.

12 |
13 | 14 | 15 |
16 | 17 | 18 |
19 | 20 | 21 |
22 | 23 | 24 |
25 | 26 | 27 |
28 | 29 | 30 |
31 | 32 | 33 |
34 | 35 | 36 |
37 | 38 | 39 |
40 | 41 |
42 | 43 | -------------------------------------------------------------------------------- /templates/accounts_email_password_reset.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Reset Password (TEST) 4 | 8 | 9 | 10 |

Reset Password (TEST)

11 |

This is really just for testing. We shouldn't ever actually use this.

12 |
13 | 14 | 15 |
16 | 17 |
18 | 19 | -------------------------------------------------------------------------------- /templates/accounts_login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Login to Account (TEST) 4 | 8 | 9 | 10 |

Login to Account (TEST)

11 |

This is really just for testing. We shouldn't ever actually use this.

12 |
13 | 14 | 15 |
16 | 17 | 18 |
19 | 20 |
21 | 22 | -------------------------------------------------------------------------------- /templates/jobs_create.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Create a Job (TEST) 4 | 8 | 9 | 10 |

Create a Job (TEST)

11 |

This is really just for testing. We shouldn't ever actually use this.

12 |
13 | 14 | 15 |
16 | 17 | 34 |
35 | 36 | 40 |
41 | 42 | 43 |
44 | 45 | 46 |
47 | 48 | 52 |
53 | 54 | 55 |
56 | 57 | 58 |
59 | 60 | 61 |
62 | 63 | 64 |
65 | 66 | 67 |
68 | 69 | 70 |
71 | 72 | 73 |
74 | 75 | 76 |
77 | 78 | 79 |
80 | 81 | 82 |
83 | 84 | 85 |
86 | 87 | 88 |
89 | 90 | 91 |
92 | 93 | 112 |
113 | 114 | 115 |
116 | 117 |
118 | 119 | -------------------------------------------------------------------------------- /templates/jobs_restart.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Create a Job (TEST) 4 | 8 | 9 | 10 |

Create a Job (TEST)

11 |

This is really just for testing. We shouldn't ever actually use this.

12 |
13 | 14 | 15 |
16 | 17 | 34 |
35 | 36 | 40 |
41 | 42 | 43 |
44 | 45 | 46 |
47 | 48 | 52 |
53 | 54 | 55 |
56 | 57 | 58 |
59 | 60 | 61 |
62 | 63 | 64 |
65 | 66 | 67 |
68 | 69 | 70 |
71 | 72 | 73 |
74 | 75 | 76 |
77 | 78 | 79 |
80 | 81 | 82 |
83 | 84 | 85 |
86 | 87 | 88 |
89 | 90 | 91 |
92 | 93 | 112 |
113 | 114 | 115 |
116 | 117 |
118 | 119 | -------------------------------------------------------------------------------- /worker.py: -------------------------------------------------------------------------------- 1 | import os 2 | import redis 3 | from rq import Worker, Queue, Connection 4 | import sys 5 | import argparse 6 | 7 | parser = argparse.ArgumentParser(description='Run the Fax Robot Worker.') 8 | parser.add_argument('--listen', nargs=1, help='Listen queue: high|default|low') 9 | parser.add_argument('--device', nargs=1, help='Modem device to use for faxing') 10 | parser.add_argument('--callerid', nargs=1, help='Caller ID string for faxes') 11 | 12 | args = parser.parse_args() 13 | 14 | if args.listen: 15 | listen = args.listen[0].split(',') 16 | else: 17 | listen = ['high', 'default', 'low'] 18 | 19 | MODEM_DEVICE = args.device[0] if args.device else '/dev/ttyUSB0' 20 | CALLER_ID = args.callerid[0] if args.callerid else '' 21 | 22 | print >> sys.stderr, "Binding to modem device: " + MODEM_DEVICE 23 | 24 | conn = redis.from_url(os.environ.get('REDIS_URI')) 25 | 26 | if __name__ == '__main__': 27 | with Connection(conn): 28 | Worker.MODEM_DEVICE = MODEM_DEVICE 29 | Worker.CALLER_ID = CALLER_ID 30 | worker = Worker(map(Queue, listen)) 31 | worker.work() 32 | -------------------------------------------------------------------------------- /workers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lyonbros/faxrobot/4dfdd6c9bd4cd335a7dc4aaaa6188ad808b78d71/workers/__init__.py -------------------------------------------------------------------------------- /workers/cron.py: -------------------------------------------------------------------------------- 1 | from controllers.incoming import auto_recharge, delete_number_from_phaxio 2 | from models.account import Account 3 | from models.incoming_number import IncomingNumber 4 | from models.transaction import Transaction 5 | from library.mailer import email_admin, email_deleted_number, \ 6 | email_pending_deletion_warning 7 | import psycopg2 8 | import os 9 | from sqlalchemy.orm import sessionmaker 10 | from sqlalchemy import create_engine 11 | from datetime import datetime 12 | from library.grab_bag import o 13 | 14 | engine = create_engine(os.environ.get('DATABASE_URI').strip()) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | def charge_subscribers(): 19 | 20 | o("QUERYING INCOMING FAX NUMBERS FOR PAYMENT PROCESSING!") 21 | o(" ") 22 | 23 | conn = psycopg2.connect(os.environ.get('DATABASE_URI')) 24 | query = ( 25 | "SELECT id, account_id, fax_number, flagged_for_deletion, " 26 | " last_billed, create_date, mod_date " 27 | "FROM incoming_number " 28 | "WHERE ( " 29 | " mod_date IS NULL " 30 | " OR " 31 | " mod_date < now() - \'7 days\'::interval " 32 | " ) " 33 | "AND ( " 34 | " last_billed IS NULL " 35 | " OR " 36 | " last_billed < now() - \'30 days\'::interval " 37 | " ) " 38 | ) 39 | 40 | cursor = conn.cursor() 41 | cursor.execute(query) 42 | 43 | for row in cursor: 44 | id = row[0] 45 | account_id = row[1] 46 | fax_number = row[2] 47 | flagged_for_deletion = row[3] 48 | last_billed = row[4] 49 | 50 | account = session.query(Account).get(account_id) 51 | incoming_number = session.query(IncomingNumber).get(id) 52 | 53 | account_status = "SUCCESS" 54 | 55 | o("Fax number %s for account %s" % (fax_number, account_id)) 56 | 57 | if account.credit < 6 and not account.allow_overflow: 58 | 59 | o(" - account credit below threshold") 60 | 61 | if account.stripe_card and account.auto_recharge: 62 | if not auto_recharge(account, "localhost", session) == True: 63 | account_status = "DECLINE" 64 | o(" - CARD DECLINED :(") 65 | else: 66 | o(" - payment succeeded :)") 67 | else: 68 | account_status = "NO_FUNDS" 69 | o(" - AUTO-CHARGED DISABLED AND NO FUNDS IN ACCOUNT :(") 70 | 71 | if not account_status == "SUCCESS" and flagged_for_deletion: 72 | 73 | o(" - number is already marked for deletion >_<") 74 | 75 | session.delete(incoming_number) 76 | session.commit() 77 | 78 | if not delete_number_from_phaxio(fax_number): 79 | email_admin("Failed to delete Phaxio number: %s" % fax_number) 80 | 81 | email_deleted_number(account) 82 | 83 | o(" - deleted number and emailed customer.") 84 | 85 | elif not account_status == "SUCCESS" and not flagged_for_deletion: 86 | 87 | incoming_number.mod_date = datetime.now() 88 | incoming_number.flagged_for_deletion = 1 89 | session.commit() 90 | 91 | email_pending_deletion_warning(account, account_status, fax_number) 92 | 93 | o(" - flagged number for deletion, emailed warning to customer.") 94 | 95 | else: 96 | 97 | o(" - account successfully charged. hooray!") 98 | 99 | incoming_number.mod_date = datetime.now() 100 | incoming_number.last_billed = datetime.now() 101 | incoming_number.flagged_for_deletion = 0 102 | session.commit() 103 | 104 | data = { 105 | 'account_id': account.id, 106 | 'amount': -6.00, 107 | 'source': "phaxio", 108 | 'source_id': fax_number, 109 | 'ip_address': "localhost", 110 | 'initial_balance': account.credit, 111 | 'trans_type': "incoming_autopay" 112 | } 113 | trans = Transaction(**data) 114 | session.add(trans) 115 | session.commit() 116 | 117 | account.subtract_credit(6, session) 118 | 119 | o(" ") 120 | 121 | conn.commit() 122 | conn.close() 123 | 124 | email_admin("YAY!", "Payments cron job success!") 125 | 126 | o("ALL DONE!") 127 | return "lulz" 128 | -------------------------------------------------------------------------------- /workers/jobs.py: -------------------------------------------------------------------------------- 1 | import os 2 | from time import sleep 3 | from models import db 4 | from datetime import datetime 5 | from sqlalchemy import create_engine 6 | from sqlalchemy.orm import sessionmaker 7 | from library.errors import worker_error 8 | from library.grab_bag import o 9 | from models.job import Job 10 | from models.transaction import Transaction 11 | from models.failed_payment import FailedPayment 12 | from models.incoming_number import IncomingNumber 13 | 14 | engine = create_engine(os.environ.get('DATABASE_URI').strip()) 15 | Session = sessionmaker(bind=engine) 16 | session = Session() 17 | 18 | def initial_process(id, data = None): 19 | 20 | from boto.s3.connection import S3Connection 21 | from boto.s3.key import Key 22 | from subprocess import call, check_output, CalledProcessError 23 | from os.path import isfile, join 24 | import redis 25 | from rq import Worker, Queue, Connection 26 | 27 | from poster.encode import multipart_encode 28 | from poster.streaminghttp import register_openers 29 | import urllib2 30 | 31 | import requests 32 | 33 | job = session.query(Job).get(id) 34 | job.mod_date = datetime.now() 35 | job.status = 'uploading' 36 | session.commit() 37 | 38 | ######################################################################## 39 | # G3 TIFF CONVERSION PHASE 40 | ######################################################################## 41 | 42 | path = './tmp/' + job.access_key 43 | o('Creating temporary directory: %s' % path) ########################### 44 | 45 | try: 46 | if not os.path.exists(path): 47 | os.makedirs(path) 48 | except: 49 | return fail('JOBS_CREATE_DIR_FAIL', job, db) 50 | 51 | if job.filename: 52 | file_prefix, file_extension = os.path.splitext(job.filename) 53 | elif job.body: 54 | file_extension = '.txt' 55 | else: 56 | return fail('JOBS_NO_ATTACHMENT_FOUND', job, db) 57 | 58 | if file_extension == '.docx' or file_extension == '.doc': 59 | 60 | if not os.environ.get('SERVEOFFICE2PDF_URL'): 61 | return fail('JOBS_NO_SERVEOFFICE2PDF', job, db) 62 | 63 | try: 64 | job.filename = save_local_file(job.access_key, job.filename, data) 65 | except: 66 | return fail('JOBS_LOCAL_SAVE_FAIL', job, db) 67 | 68 | o('Calling ServeOffice2PDF to convert DOCX to PDF.') ############### 69 | 70 | office_url = os.environ.get('SERVEOFFICE2PDF_URL').strip() 71 | files = {"data": open('%s/%s' % (path, job.filename), 'rb')} 72 | params = {'filename': job.filename} 73 | response = requests.post(office_url, files=files, data=params) 74 | 75 | if not response.status_code == 200: 76 | return fail('JOBS_PDF_CONVERT_FAIL', job, db) 77 | 78 | o('Successfully converted file to PDF. Now converting to tiff.') ### 79 | pdf_file = open('%s/%s.pdf' % (path, job.filename), 'wb') 80 | pdf_file.write(response.content) 81 | pdf_file.close() 82 | 83 | try: 84 | convert_to_tiff(job.access_key, job.filename + '.pdf', True) 85 | except CalledProcessError, e: 86 | return fail('JOBS_IMG_CONVERT_FAIL', job, db, str(e)) 87 | 88 | elif file_extension == '.pdf': 89 | 90 | try: 91 | job.filename = save_local_file(job.access_key, job.filename, data) 92 | except: 93 | return fail('JOBS_LOCAL_SAVE_FAIL', job, db) 94 | 95 | try: 96 | convert_to_tiff(job.access_key, job.filename, True) 97 | except CalledProcessError, e: 98 | return fail('JOBS_IMG_CONVERT_FAIL', job, db, str(e)) 99 | 100 | elif file_extension == '.png' or file_extension == '.jpg': 101 | 102 | try: 103 | job.filename = save_local_file(job.access_key, job.filename, data) 104 | except: 105 | return fail('JOBS_LOCAL_SAVE_FAIL', job, db) 106 | 107 | try: 108 | convert_to_tiff(job.access_key, job.filename) 109 | except CalledProcessError, e: 110 | return fail('JOBS_IMG_CONVERT_FAIL', job, db, str(e)) 111 | 112 | elif file_extension == '.txt': 113 | 114 | txt_filename = job.filename if job.filename else "fax.txt" 115 | job.filename = save_local_file(job.access_key, txt_filename, data) 116 | 117 | try: 118 | convert_txt_to_ps(job.access_key, job.filename + ".ps") 119 | except CalledProcessError, e: 120 | return fail('JOBS_TXT_CONVERT_FAIL', job, db, str(e)) 121 | 122 | try: 123 | convert_to_tiff(job.access_key, job.filename + ".ps", True) 124 | except CalledProcessError, e: 125 | return fail('JOBS_IMG_CONVERT_FAIL', job, db, str(e)) 126 | 127 | else: 128 | return fail('JOBS_UNSUPPORTED_FORMAT', job, db) 129 | 130 | files = [ f for f in os.listdir(path) if isfile(join(path,f)) ] 131 | 132 | num_pages = 0 133 | 134 | for f in files: 135 | file_prefix, file_extension = os.path.splitext(f) 136 | if file_extension == '.tiff': 137 | num_pages = num_pages + 1 138 | 139 | job.status = 'processing' 140 | job.mod_date = datetime.now() 141 | job.num_pages = num_pages 142 | job.compute_cost() 143 | session.commit() 144 | 145 | ######################################################################## 146 | # OPTIONAL AMAZON S3 UPLOAD PHASE 147 | ######################################################################## 148 | 149 | if os.environ.get('AWS_STORAGE') == "on": 150 | o('Connecting to S3') ############################################## 151 | try: 152 | conn = S3Connection(os.environ.get('AWS_ACCESS_KEY'), 153 | os.environ.get('AWS_SECRET_KEY')) 154 | bucket = conn.get_bucket(os.environ.get('AWS_S3_BUCKET')) 155 | except: 156 | return fail('JOBS_CONNECT_S3_FAIL', job, db) 157 | 158 | for f in files: 159 | try: 160 | file_prefix, file_extension = os.path.splitext(f) 161 | 162 | if file_extension == '.tiff': 163 | o('Uploading to S3: ' + f) ############################# 164 | k = Key(bucket) 165 | k.key = 'fax/' + job.access_key + '/' + f 166 | k.set_contents_from_filename(path + '/' + f) 167 | k.set_acl('public-read') 168 | except: 169 | return fail('JOBS_UPLOAD_S3_FAIL', job, db) 170 | 171 | job.mod_date = datetime.now() 172 | 173 | if job.send_authorized: 174 | try: 175 | job.rate_limit(job.account_id) 176 | except: 177 | return fail('JOBS_RATE_LIMIT_REACHED', job, db) 178 | job.status = 'queued' 179 | session.commit() 180 | redis_conn = redis.from_url(os.environ.get('REDIS_URI')) 181 | q = Queue(job.account.get_priority(), connection=redis_conn) 182 | q.enqueue_call(func=send_fax, args=(id,), timeout=3600) 183 | else: 184 | job.status = 'ready' 185 | session.commit() 186 | if job.callback_url: 187 | send_job_callback(job, session) 188 | 189 | return "SUCCESS: %s" % id 190 | 191 | def send_fax(id): 192 | 193 | from boto.s3.connection import S3Connection 194 | from boto.s3.key import Key 195 | from datetime import date 196 | from subprocess import check_output, CalledProcessError, STDOUT 197 | import stripe 198 | import traceback 199 | import json 200 | from library.mailer import email_recharge_payment 201 | from rq import Worker 202 | 203 | device = Worker.MODEM_DEVICE 204 | caller_id = Worker.CALLER_ID 205 | 206 | stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') 207 | 208 | job = session.query(Job).get(id) 209 | 210 | if not job.status == 'ready' and not job.status == 'queued': 211 | return fail('JOBS_CANNOT_SEND_NOW', job, db) 212 | 213 | if job.data_deleted: 214 | return fail('JOBS_FAIL_DATA_DELETED', job, db) 215 | 216 | cost = job.cost if not job.cover else job.cost + job.cover_cost 217 | 218 | ######################################################################## 219 | # MAKE SURE THE CUSTOMER ACTUALLY HAS MONEY PHASE 220 | ######################################################################## 221 | 222 | if os.environ.get('REQUIRE_PAYMENTS') == 'on': 223 | if job.account.credit - cost < 0 and not job.account.allow_overflow: 224 | if job.account.stripe_card and job.account.auto_recharge: 225 | try: 226 | charge = stripe.Charge.create( 227 | amount=1000, 228 | currency="usd", 229 | customer=job.account.stripe_token, 230 | description="Auto-recharging account %s"% job.account.id 231 | ) 232 | data = { 233 | 'account_id': job.account.id, 234 | 'amount': 10, 235 | 'source': 'stripe', 236 | 'source_id': charge["id"], 237 | 'job_id': job.id, 238 | 'job_destination': job.destination, 239 | 'ip_address': job.ip_address, 240 | 'initial_balance': job.account.credit, 241 | 'trans_type': 'auto_recharge' 242 | } 243 | trans = Transaction(**data) 244 | session.add(trans) 245 | session.commit() 246 | 247 | job.account.add_credit(10, session) 248 | # email_recharge_payment(job.account, 10, trans.id, 249 | # charge.source.last4) 250 | 251 | except: 252 | payment = {'_DEBUG': traceback.format_exc()} 253 | data = { 254 | 'amount': 10, 255 | 'account_id': job.account.id, 256 | 'source': 'stripe', 257 | 'debug': json.dumps(payment), 258 | 'ip_address': job.ip_address, 259 | 'payment_type': 'auto_recharge' 260 | } 261 | failed_payment = FailedPayment(**data) 262 | session.add(failed_payment) 263 | session.commit() 264 | # JL TODO ~ Notify customer that the card was declined 265 | return fail('JOBS_CARD_DECLINED', job, db) 266 | else: 267 | return fail('JOBS_INSUFFICIENT_CREDIT', job, db) 268 | 269 | job.mod_date = datetime.now() 270 | job.start_date = datetime.now() 271 | job.attempts = job.attempts + 1 272 | job.device = device 273 | job.status = 'started' 274 | session.commit() 275 | 276 | files_to_send = [] 277 | 278 | ######################################################################## 279 | # COVER SHEET GENERATION PHASE 280 | ######################################################################## 281 | 282 | path = './tmp/' + job.access_key 283 | o('Touching temporary directory: %s' % path) ########################### 284 | 285 | try: 286 | if not os.path.exists(path): 287 | os.makedirs(path) 288 | except: 289 | return fail('JOBS_CREATE_DIR_FAIL', job, db) 290 | 291 | if job.cover: 292 | o('Generating cover sheet') ######################################## 293 | 294 | try: 295 | o('Generating cover.png') ###################################### 296 | 297 | cmd = ["convert", "-density", "400", "-flatten", 298 | "./media/cover_sheets/default.pdf", "-gravity", 299 | "None"] 300 | v = 300 301 | 302 | if job.cover_name: 303 | cmd.extend(["-annotate", "+468+%s" % v, job.cover_name]) 304 | cmd.extend(["-annotate", "+2100+1215", job.cover_name]) 305 | v = v + 80 306 | 307 | if job.cover_address: 308 | cmd.extend(["-annotate", "+468+%s" % v, job.cover_address]) 309 | v = v + 80 310 | 311 | if job.cover_city or job.cover_state or job.cover_zip: 312 | cmd.extend(["-annotate", "+468+%s" % v, 313 | "%s, %s %s" % (job.cover_city, job.cover_state, 314 | job.cover_zip)]) 315 | v = v + 80 316 | 317 | if job.cover_country: 318 | cmd.extend(["-annotate", "+468+%s" % v, job.cover_country]) 319 | v = v + 80 320 | 321 | if job.cover_phone: 322 | cmd.extend(["-annotate", "+468+%s" % v, job.cover_phone]) 323 | v = v + 80 324 | 325 | if job.cover_email: 326 | cmd.extend(["-annotate", "+468+%s" % v, job.cover_email]) 327 | v = v + 80 328 | 329 | if job.cover_to_name: 330 | cmd.extend(["-annotate", "+800+1215", job.cover_to_name]) 331 | 332 | if job.cover_subject: 333 | cmd.extend(["-annotate", "+800+1340", job.cover_subject]) 334 | 335 | cmd.extend(["-annotate", "+2100+1340", "%s" % job.num_pages]) 336 | cmd.extend(["-annotate", "+800+1465", "%s" % date.today()]) 337 | 338 | if job.cover_cc: 339 | cmd.extend(["-annotate", "+2100+1465", job.cover_cc]) 340 | 341 | if "urgent" in job.cover_status: 342 | cmd.extend(["-annotate", "+473+1740", "X"]) 343 | 344 | if "review" in job.cover_status: 345 | cmd.extend(["-annotate", "+825+1740", "X"]) 346 | 347 | if "comment" in job.cover_status: 348 | cmd.extend(["-annotate", "+1285+1740", "X"]) 349 | 350 | if "reply" in job.cover_status: 351 | cmd.extend(["-annotate", "+1910+1740", "X"]) 352 | 353 | if "shred" in job.cover_status: 354 | cmd.extend(["-annotate", "+2420+1740", "X"]) 355 | 356 | cmd.extend([ 357 | "-pointsize", 358 | "11", 359 | "./tmp/" + job.access_key + "/cover.png" 360 | ]) 361 | output = check_output(cmd) 362 | except CalledProcessError, e: 363 | return fail('JOBS_COVER_MAIN_FAIL', job, db, str(e)) 364 | 365 | if job.cover_company: 366 | try: 367 | o('Generating company.png') ################################ 368 | 369 | cmd = ["convert", "-density", "400", "-gravity", "Center", 370 | "-background", "black", "-fill", "white", 371 | "-pointsize", "20", "-size", "1400x", 372 | "caption:%s" % job.cover_company, "-bordercolor", 373 | "black", "-border", "30", 374 | "./tmp/" + job.access_key + "/company.png"] 375 | output = check_output(cmd) 376 | except CalledProcessError, e: 377 | return fail('JOBS_COVER_COMPANY_FAIL', job, db, str(e)) 378 | 379 | try: 380 | o('Overlaying company.png on cover.png') ################### 381 | 382 | cmd = ["composite", "-density", "400", "-gravity", 383 | "NorthEast", "-geometry", "+300+200", 384 | "./tmp/" + job.access_key + "/company.png", 385 | "./tmp/" + job.access_key + "/cover.png", 386 | "./tmp/" + job.access_key + "/cover.png"] 387 | output = check_output(cmd) 388 | except CalledProcessError, e: 389 | return fail('JOBS_COVER_OVERLAY_FAIL', job, db, str(e)) 390 | 391 | if job.cover_comments: 392 | try: 393 | o('Generating comments.png') ############################### 394 | 395 | cmd = ["convert", "-density", "400", "-gravity", 396 | "NorthWest", "-background", "white", "-fill", 397 | "black", "-pointsize", "11", "-size", "2437x2000", 398 | "-font", "Liberation-Mono-Regular", 399 | "caption:%s" % job.cover_comments, 400 | "./tmp/" + job.access_key + "/comments.png"] 401 | output = check_output(cmd) 402 | except CalledProcessError, e: 403 | return fail('JOBS_COVER_COMMENTS_FAIL', job, db, str(e)) 404 | 405 | try: 406 | o('Overlaying comments.png on cover.png') ################## 407 | 408 | cmd = ["composite", "-density", "400", "-gravity", "None", 409 | "-geometry", "+468+2000", 410 | "./tmp/" + job.access_key + "/comments.png", 411 | "./tmp/" + job.access_key + "/cover.png", 412 | "./tmp/" + job.access_key + "/cover.png"] 413 | output = check_output(cmd) 414 | except CalledProcessError, e: 415 | return fail('JOBS_COVER_OVERLAY_FAIL', job, db, str(e)) 416 | 417 | try: 418 | o('Converting cover.png to G3 .tiff') ########################## 419 | 420 | cmd = ["convert", "-scale", "50%", 421 | "./tmp/" + job.access_key + "/cover.png", 422 | "fax:./tmp/" + job.access_key + "/cover.tiff"] 423 | output = check_output(cmd) 424 | except CalledProcessError, e: 425 | return fail('JOBS_COVER_TIFF_FAIL', job, db, str(e)) 426 | 427 | files_to_send.append(u'%s/cover.tiff' % path) 428 | 429 | ######################################################################## 430 | # LOAD FILES PHASE 431 | ######################################################################## 432 | 433 | filename = job.filename if job.filename else "fax.txt" 434 | 435 | if os.environ.get('AWS_STORAGE') == "on": 436 | o('Connecting to S3') ################################################## 437 | try: 438 | conn = S3Connection(os.environ.get('AWS_ACCESS_KEY'), 439 | os.environ.get('AWS_SECRET_KEY')) 440 | bucket = conn.get_bucket(os.environ.get('AWS_S3_BUCKET')) 441 | except: 442 | return fail('JOBS_CONNECT_S3_FAIL', job, db) 443 | 444 | try: 445 | for i in range(0, job.num_pages): 446 | 447 | num = ("0%s" % i) if i < 10 else "%s" % i 448 | 449 | o('Download: %s/%s.%s.tiff' % (job.access_key, filename, num)) 450 | 451 | k = Key(bucket) 452 | k.key = 'fax/%s/%s.%s.tiff' %(job.access_key, filename, num) 453 | k.get_contents_to_filename('%s/%s.%s.tiff' % (path, 454 | filename, num)) 455 | 456 | files_to_send.append('%s/%s.%s.tiff' %(path, filename, num)) 457 | except: 458 | return fail('JOBS_DOWNLOAD_S3_FAIL', job, db) 459 | else: 460 | for i in range(0, job.num_pages): 461 | num = ("0%s" % i) if i < 10 else "%s" % i 462 | files_to_send.append('%s/%s.%s.tiff' %(path, filename, num)) 463 | 464 | ######################################################################## 465 | # SEND FAX PHASE 466 | ######################################################################## 467 | if os.environ.get('PHAXIO_SENDING') == 'on': 468 | 469 | import requests 470 | from mimetypes import MimeTypes 471 | 472 | payload = { 473 | "to": "+%s" % job.destination, 474 | "api_key": os.environ.get('PHAXIO_API_KEY'), 475 | "api_secret": os.environ.get('PHAXIO_API_SECRET') 476 | } 477 | if os.environ.get('PHAXIO_OVERRIDE_RECEIVED'): 478 | payload["callback_url"] = os.environ.get('PHAXIO_OVERRIDE_SENT') 479 | 480 | incoming_numbers = session.query(IncomingNumber).filter_by( 481 | account_id= job.account.id) 482 | 483 | if incoming_numbers and incoming_numbers.first(): 484 | payload["caller_id"] = incoming_numbers.first().fax_number 485 | 486 | files = [] 487 | 488 | if job.cover: 489 | 490 | cover_filename = u'%s/cover.png' % path 491 | f1 = open(cover_filename) 492 | files.append( 493 | ('filename[]', ('cover.png', f1, 'image/png')) 494 | ) 495 | 496 | mime = MimeTypes() 497 | mimetype = mime.guess_type(job.filename) 498 | 499 | job_filename = u'%s/%s' % (path, job.filename) 500 | 501 | f2 = open(job_filename) 502 | files.append( 503 | ('filename[]', (job.filename, f2, mimetype)) 504 | ) 505 | 506 | try: 507 | url = "https://api.phaxio.com/v1/send" 508 | r = requests.post(url, data=payload, files=files) 509 | response = json.loads(r.text) 510 | 511 | o('Got response from Twilio...') 512 | o(r.text) 513 | 514 | if response["success"] == False or not "data" in response \ 515 | or not "faxId" in response["data"]: 516 | 517 | bad_number = "Phone number is not formatted correctly" 518 | 519 | if "message" in response and bad_number in response["message"]: 520 | return fail('JOBS_PHAXIO_BAD_NUMBER', job, db, r.text) 521 | else: 522 | return fail('JOBS_PHAXIO_TRANSMIT_FAIL', job, db, r.text) 523 | except: 524 | return fail('JOBS_PHAXIO_TRANSMIT_FAIL', job, db, "bah") 525 | 526 | if f2: 527 | f2.close() 528 | 529 | if job.cover: 530 | f1.close() 531 | 532 | job.external_id = response["data"]["faxId"] 533 | job.debug = r.text 534 | session.commit() 535 | 536 | return "waiting..." 537 | 538 | else: 539 | try: 540 | o('Modem dialing: 1%s' % job.destination) 541 | 542 | cmd = ["efax", "-d", device, "-o1flll ", "-vchewmainrft ", "-l", 543 | caller_id, "-t", "%s" % job.destination] 544 | cmd.extend(files_to_send) 545 | output = check_output(cmd, stderr=STDOUT) 546 | o('%s' % output) 547 | 548 | except CalledProcessError, e: 549 | 550 | output = str(e.output) 551 | 552 | if "No Answer" in output: 553 | if os.environ.get('REQUIRE_PAYMENTS') == 'on': 554 | o('No answer. Charge the customer for wasting our time.') 555 | o('Debiting $%s on account ID %s' % (cost, job.account.id)) 556 | commit_transaction(job, cost, 'no_answer_charge') 557 | 558 | return fail('JOBS_TRANSMIT_NO_ANSWER', job, db, output) 559 | 560 | elif "number busy or modem in use" in output: 561 | o('Line busy.') 562 | return fail('JOBS_TRANSMIT_BUSY', job, db, output) 563 | 564 | else: 565 | o('Transmit error: %s' % output) 566 | return fail('JOBS_TRANSMIT_FAIL', job, db, output) 567 | 568 | o('Job completed without error!') 569 | job.debug = output 570 | 571 | return mark_job_sent(job, cost) 572 | 573 | def mark_job_sent(job, cost, db_session = None): 574 | 575 | from library.mailer import email_success 576 | 577 | if not db_session: 578 | db_session = session 579 | 580 | job.mod_date = datetime.now() 581 | job.end_date = datetime.now() 582 | job.status = 'sent' 583 | db_session.commit() 584 | 585 | o('Deleting data lol.') 586 | job.delete_data(db_session) 587 | 588 | if job.account.email_success: 589 | email_success(job) 590 | 591 | if job.callback_url: 592 | send_job_callback(job, db_session) 593 | 594 | if os.environ.get('REQUIRE_PAYMENTS') == 'on': 595 | o('Debiting $%s on account ID %s' % (cost, job.account.id)) 596 | commit_transaction(job, cost, 'job_complete') 597 | 598 | return True 599 | 600 | def commit_transaction(job, cost, trans_type, note = None): 601 | data = { 602 | 'account_id': job.account.id, 603 | 'amount': cost * -1, 604 | 'job_id': job.id, 605 | 'job_destination': job.destination, 606 | 'ip_address': job.ip_address, 607 | 'initial_balance': job.account.credit, 608 | 'trans_type': trans_type 609 | } 610 | if note: 611 | data['note'] = note 612 | 613 | transaction = Transaction(**data) 614 | session.add(transaction) 615 | session.commit() 616 | 617 | job.account.subtract_credit(cost, session) 618 | 619 | def convert_to_tiff(access_key, filename, flatten = False): 620 | 621 | from subprocess import check_output 622 | 623 | o('Convert %s to .tiff' % filename) ######################################## 624 | 625 | file_prefix, file_extension = os.path.splitext(filename) 626 | 627 | if not flatten: 628 | command = [ 629 | "convert", 630 | "-density", 631 | "400 ", 632 | "-resize", 633 | "1760x2200 ", 634 | "./tmp/" + access_key + "/" + filename, 635 | "fax:./tmp/" + access_key + "/"+ file_prefix +".%02d.tiff" 636 | ] 637 | else: 638 | command = [ 639 | "convert", 640 | "-density", 641 | "400 ", 642 | "-resize", 643 | "1760x2200 ", 644 | "-background", 645 | "White", 646 | "-alpha", 647 | "Background", 648 | "./tmp/" + access_key + "/" + filename, 649 | "fax:./tmp/" + access_key + "/"+ file_prefix +".%02d.tiff" 650 | ] 651 | output = check_output(command) 652 | 653 | def convert_txt_to_ps(access_key, filename): 654 | 655 | from subprocess import check_output 656 | 657 | o('Convert %s to .ps' % filename) ######################################## 658 | 659 | file_prefix, file_extension = os.path.splitext(filename) 660 | 661 | command = [ 662 | "paps", 663 | "--font", 664 | "Liberation Mono", 665 | "--cpi", 666 | " 12", 667 | # "--header", # JL NOTE ~ probably don't want to have this 668 | file_prefix 669 | ] 670 | output = check_output(command, cwd="./tmp/"+access_key) 671 | 672 | f = open('./tmp/' + access_key + '/' + filename, 'wb') 673 | f.write(output) 674 | f.close() 675 | 676 | def save_local_file(access_key, filename, data): 677 | 678 | from werkzeug.utils import secure_filename 679 | 680 | o('Saving local file: %s' % filename) ###################################### 681 | 682 | safe_filename = secure_filename(filename) 683 | 684 | f = open(u'./tmp/' + access_key + u'/' + safe_filename, 'wb') 685 | f.write(data) 686 | f.close() 687 | 688 | return safe_filename 689 | 690 | def fail(ref, job, db, debug=None, db_session=None): 691 | 692 | from library.mailer import email_fail 693 | from rq import Worker 694 | 695 | if not db_session: 696 | db_session = session 697 | 698 | try: 699 | device = Worker.MODEM_DEVICE 700 | except AttributeError: 701 | device = "" 702 | 703 | o('JOB FAILED: %s (%s)' % (ref, debug)) 704 | 705 | error = worker_error(ref) 706 | job.failed = 1 707 | job.fail_code = error["code"] 708 | job.fail_date = datetime.now() 709 | job.mod_date = datetime.now() 710 | job.status = 'failed' 711 | job.debug = error["msg"] if debug == None else debug 712 | db_session.commit() 713 | 714 | if job.account.email_fail: 715 | email_fail(job, error["msg"], error["code"], error["status"], 716 | { 717 | "device": device, 718 | "output": debug 719 | } 720 | ) 721 | 722 | if job.callback_url: 723 | send_job_callback(job, db_session) 724 | 725 | return "FAILED" 726 | 727 | def send_job_callback(job, db_session): 728 | import requests 729 | import traceback 730 | 731 | job.callback_date = datetime.now() 732 | 733 | try: 734 | r = requests.post(job.callback_url, data=job.public_data(), timeout=5) 735 | r.raise_for_status() 736 | o("Sent callback: %s; (HTTP 200)" % job.callback_url) 737 | except: 738 | o("CALLBACK FAIL: %s / %s" % (job.callback_url, traceback.format_exc())) 739 | job.callback_fail = job.callback_fail + 1 740 | 741 | db_session.commit() 742 | 743 | 744 | 745 | --------------------------------------------------------------------------------