diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b8597b21 --- /dev/null +++ b/.gitignore @@ -0,0 +1,124 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# pycharm +.idea/ + +# vs code +.vscode/ + +# project +*.log +.logs +logs/ +.test +test/ +cookies/ +*.cookies +qr_code.png + +# jupyter +.ipynb_checkpoints +/test/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 6562d64f..c81b9f69 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,71 @@ # Jd_Seckill -##### 非常感谢原作者 https://github.com/zhou-xiaojun/jd_mask 提供的代码 -##### 也非常感谢 https://github.com/wlwwu/jd_maotai 进行的优化 +## 特别声明: + +* 本仓库发布的`jd_seckill`项目中涉及的任何脚本,仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。 + +* 本项目内所有资源文件,禁止任何公众号、自媒体进行任何形式的转载、发布。 + +* `huanghyw` 对任何脚本问题概不负责,包括但不限于由任何脚本错误导致的任何损失或损害. + +* 间接使用脚本的任何用户,包括但不限于建立VPS或在某些行为违反国家/地区法律或相关法规的情况下进行传播, `huanghyw` 对于由此引起的任何隐私泄漏或其他后果概不负责。 + +* 请勿将`jd_seckill`项目的任何内容用于商业或非法目的,否则后果自负。 + +* 如果任何单位或个人认为该项目的脚本可能涉嫌侵犯其权利,则应及时通知并提供身份证明,所有权证明,我们将在收到认证文件后删除相关脚本。 + +* 以任何方式查看此项目的人或直接或间接使用`jd_seckill`项目的任何脚本的使用者都应仔细阅读此声明。`huanghyw` 保留随时更改或补充此免责声明的权利。一旦使用并复制了任何相关脚本或`jd_seckill`项目,则视为您已接受此免责声明。 + +* 您必须在下载后的24小时内从计算机或手机中完全删除以上内容。 + +* 本项目遵循`GPL-3.0 License`协议,如果本特别声明与`GPL-3.0 License`协议有冲突之处,以本特别声明为准。 + +> ***您使用或者复制了本仓库且本人制作的任何代码或项目,则视为`已接受`此声明,请仔细阅读*** +> ***您在本声明未发出之时点使用或者复制了本仓库且本人制作的任何代码或项目且此时还在使用,则视为`已接受`此声明,请仔细阅读*** + +## 简介 +通过我这段时间的使用(2020-12-12至2020-12-17),证实这个脚本确实能抢到茅台。我自己三个账号抢了四瓶,帮两个朋友抢了4瓶。 +大家只要确认自己配置文件没有问题,Cookie没有失效,坚持下去总能成功的。 + +根据这段时间大家的反馈,除了茅台,其它不需要加购物车的商品也不能抢。具体原因还没有进行排查,应该是京东非茅台商品抢购流程发生了变化。 +为了避免耽误大家的时间,先不要抢购非茅台商品。 +等这个问题处理好了,会上线新版本。 + + +## 暗中观察 + +根据12月14日以来抢茅台的日志分析,大胆推断再接再厉返回Json消息中`resultCode`与小白信用的关系。 +这里主要分析出现频率最高的`90016`和`90008`。 + +### 样例JSON +```json +{'errorMessage': '很遗憾没有抢到,再接再厉哦。', 'orderId': 0, 'resultCode': 90016, 'skuId': 0, 'success': False} +{'errorMessage': '很遗憾没有抢到,再接再厉哦。', 'orderId': 0, 'resultCode': 90008, 'skuId': 0, 'success': False} +``` + +### 数据统计 + +| 案例 | 小白信用 | 90016 | 90008 | 抢到耗时 | +| ---- | -------- | ------ | ------ | -------- | +| 张三 | 63.8 | 59.63% | 40.37% | 暂未抢到 | +| 李四 | 92.9 | 72.05% | 27.94% | 4天 | +| 王五 | 99.6 | 75.70% | 24.29% | 暂未抢到 | +| 赵六 | 103.4 | 91.02% | 8.9% | 2天 | + +### 猜测 +推测返回90008是京东的风控机制,代表这次请求直接失败,不参与抢购。 +小白信用越低越容易触发京东的风控。 + +从数据来看小白信用与风控的关系大概每十分为一个等级,所以赵六基本上没有被拦截,李四和王五的拦截几率相近,张三的拦截几率最高。 + +风控放行后才会进行抢购,这时候用的应该是水库计数模型,假设无法一次性拿到所有数据的情况下来尽量的做到抢购成功用户的均匀分布,这样就和概率相关了。 + +> 综上,张三想成功有点困难,小白信用是100+的用户成功几率最大。 ## 主要功能 - 登陆京东商城([www.jd.com](http://www.jd.com/)) - - cookies登录 (需要自己手动获取) + - 用京东APP扫码给出的二维码 - 预约茅台 - 定时自动预约 - 秒杀预约后等待抢购 @@ -20,20 +79,54 @@ - 需要使用到的库已经放在requirements.txt,使用pip安装的可以使用指令 `pip install -r requirements.txt` +- 如果国内安装第三方库比较慢,可以使用以下指令进行清华源加速 +`pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/` ## 使用教程 -#### 1. 网页扫码登录 -#### 2. 填写config.ini配置信息 -(1)eid,和fp找个普通商品随便下单,然后抓包就能看到,这两个值可以填固定的 +#### 1. 推荐Chrome浏览器 +#### 2. 网页扫码登录,或者账号密码登录 +#### 3. 填写config.ini配置信息 +(1)`eid`和`fp`找个普通商品随便下单,然后抓包就能看到,这两个值可以填固定的 +> 随便找一个商品下单,然后进入结算页面,打开浏览器的调试窗口,切换到控制台Tab页,在控制台中输入变量`_JdTdudfp`,即可从输出的Json中获取`eid`和`fp`。 > 不会的话参考原作者的issue https://github.com/zhou-xiaojun/jd_mask/issues/22 -(2)cookies_string,sku_id,DEFAULT_USER_AGENT(和cookie获取同一个地方就会看到.直接复制进去就可以了) ->这里注意每次扫码登陆后都需要重新获取cookies_string,其他两个不用 ->sku_id我已经按照茅台的填好 +(2)`sku_id`,`DEFAULT_USER_AGENT` +> `sku_id`已经按照茅台的填好。 +> `cookies_string` 现在已经不需要填写了 +> `DEFAULT_USER_AGENT` 可以用默认的。谷歌浏览器也可以浏览器地址栏中输入about:version 查看`USER_AGENT`替换 (3)配置一下时间 - -以上都是必填的. +> 现在不强制要求同步最新时间了,程序会自动同步京东时间 +>> 但要是电脑时间快慢了好几个小时,最好还是同步一下吧 + +以上都是必须的. +> tips: +> 在程序开始运行后,会检测本地时间与京东服务器时间,输出的差值为本地时间-京东服务器时间,即-50为本地时间比京东服务器时间慢50ms。 +> 本代码的执行的抢购时间以本地电脑/服务器时间为准 + +(4)修改抢购瓶数 +> 代码中默认抢购瓶数为2,且无法在配置文件中修改 +> 如果一个月内抢购过一瓶,最好修改抢购瓶数为1 +> 具体修改为:在`jd_spider_requests.py`文件中搜索`self.seckill_num = 2`,将`2`改为`1` -#### 3.运行main.py -根据提示选择相应功能即可 +#### 4.运行main.py +根据提示选择相应功能即可。如果出现请扫码登录的提示可查看项目目录下是否存在`qr_code.png`文件,若存在打开图片,并使用京东手机APP扫码登录即可。 + +- *Linux下命令行方式显示二维码(以Ubuntu为例)* + +```bash +$ sudo apt-get install qrencode zbar-tools # 安装二维码解析和生成的工具,用于读取二维码并在命令行输出。 +$ zbarimg qr_code.png > qrcode.txt && qrencode -r qrcode.txt -o - -t UTF8 # 解析二维码输出到命令行窗口。 +``` + +#### 5.抢购结果确认 +抢购是否成功通常在程序开始的一分钟内可见分晓! +搜索日志,出现“抢购成功,订单号xxxxx",代表成功抢到了,务必半小时内支付订单!程序暂时不支持自动停止,需要手动STOP! +若两分钟还未抢购成功,基本上就是没抢到!程序暂时不支持自动停止,需要手动STOP! + +## 打赏 +不用再打赏了,抢到茅台的同学请保持这份喜悦,没抢到的继续加油 :) + +## 感谢 +##### 非常感谢原作者 https://github.com/zhou-xiaojun/jd_mask 提供的代码 +##### 也非常感谢 https://github.com/wlwwu/jd_maotai 进行的优化 diff --git a/config.ini b/config.ini index 09bd2754..32637a1e 100644 --- a/config.ini +++ b/config.ini @@ -1,24 +1,43 @@ [config] # eid, fp参数必须填写,具体请参考 wiki-常见问题 # 随意填写可能导致订单无法提交等问题 -eid = "XMKWG35OFYBQN3C5JYD7J4FNOWNXSGBIZNIKBUVVQEMJW6766KKTNYZD43U3Y7VCWA73EEWJRCOTKU7QVG3WKUNNQA" -fp = "2ea01d1acb70ab62c8607786d7273205" -# cookie -cookies_String ="__jdu=1586273021865136663377; shshshfpa=1d79a82c-037d-8e4e-47cb-e35d2f9e66ae-1586273130; shshshfpb=ypTYIktPFs89QK5nxn8nGIw%3D%3D; unpl=V2_ZzNtbRYHRxZ1X0EBfktdDGIDEFoSUhccJlxHXHNOWAQ3V0YJclRCFnQUR1BnGlQUZwQZWEdcQRBFCEdkeB5fA2AFEFlBZxpFK0oYEDlNDEY1WnxdRF9DFnEAR1B9KWwGZzMSXHJXRxxyC0BWehpcDGAHEl9FUEQXdw5AZEsebDVXARpZR1NHJXQ4R2Q5TQAFbgUQXA9XRxxyC0BWehpcDGAHEl9FUEQXdw5AZHopXw%3d%3d; __jdv=76161171|haosou-search|t_262767352_haosousearch|cpc|1791259057_0_ea521f6d4c084136a4e8be099f50aeee|1590741875314; user-key=e7b2ce43-c8ea-498b-aa14-1d72ba811c3b; cn=14; ipLocation=%u5e7f%u897f; pinId=RKLv5CxPY3leYrbiqjD_zrV9-x-f3wj7; pin=243864730-341142; unick=%E8%9B%8B%E9%BB%84%E9%85%B1%E5%95%8A%E5%AE%9D%E5%AE%9D; ceshi3.com=201; _tp=G9fKS8tOq9vYWtFzoQL6S58tnu1J7NXnsaIj9rKmcI8%3D; _pst=243864730-341142; areaId=20; ipLoc-djd=20-1761-25188-0; TrackID=164w4EaXgdVB8pmGgufMvZxffVg93QU3DR1qoyUmb9AbFnt_XMZ4cCggrBVqxQbwH6Sq6wvHiQ0tfbjTM9Mez0AhaI61woZr-qrMvbKOsZZT67SVvoLrkZfKMAeezI4Xx; thor=721925D5F86146929EDB9E937057356EBD65E8075AF346CDA6DFD00A839FDAAE5B800AD469815047B419498006934452FA72C6513EDDC62E79BDBB5883B46087391FF3C8EE2E5C2246FA96BF54ADD140DF2918C35D29DCE2BE90D0FEBEE2263DEEE9DEE73277CFE2BC97AA575462FDE847C8209285C17235C0566829976AABB1BFDA92428C8EA169ADB615E06CB05003B543B48B7BD5F744BDED08A66B10D5D3; __jda=122270672.1586273021865136663377.1586273022.1591320625.1591667887.11; __jdc=122270672; 3AB9D23F7A4B3C9B=XMKWG35OFYBQN3C5JYD7J4FNOWNXSGBIZNIKBUVVQEMJW6766KKTNYZD43U3Y7VCWA73EEWJRCOTKU7QVG3WKUNNQA; __jdb=122270672.8.1586273021865136663377|11.1591667887; shshshfp=4d12604ada2ade89734b633f704fe848; shshshsID=b512228e41868a27ab8199eb73396a90_4_1591667938758" +eid = "" +fp = "" +# cookie现在不需要填写了 +# cookies_String = "" -#cookies_String = "__jdu=1586273021865136663377; shshshfpa=1d79a82c-037d-8e4e-47cb-e35d2f9e66ae-1586273130; shshshfpb=ypTYIktPFs89QK5nxn8nGIw%3D%3D; ceshi3.com=201; unpl=V2_ZzNtbRYHRxZ1X0EBfktdDGIDEFoSUhccJlxHXHNOWAQ3V0YJclRCFnQUR1BnGlQUZwQZWEdcQRBFCEdkeB5fA2AFEFlBZxpFK0oYEDlNDEY1WnxdRF9DFnEAR1B9KWwGZzMSXHJXRxxyC0BWehpcDGAHEl9FUEQXdw5AZEsebDVXARpZR1NHJXQ4R2Q5TQAFbgUQXA9XRxxyC0BWehpcDGAHEl9FUEQXdw5AZHopXw%3d%3d; __jdv=76161171|haosou-search|t_262767352_haosousearch|cpc|1791259057_0_ea521f6d4c084136a4e8be099f50aeee|1590741875314; areaId=20; user-key=e7b2ce43-c8ea-498b-aa14-1d72ba811c3b; TrackID=14zpGGB-OpJ4mkipibzlKLH_cntpvRWi1YuLUjQQ9V-kkhdgGNzIYgnDptMlqfJhNhu8ozJ_qMXppTXszcg6uSBKf3xsYTd9LGMPVWn_V3mfk98AjllQ77oNoZNf0vk_n; pinId=tnz4f2JFgMgyIVQ1is9ieg; pin=275466402_m; unick=%E4%B8%8D%E6%83%B3%E8%B7%91%E6%AD%A5%E7%9A%84%E5%B9%B2%E9%94%85%E9%94%85; _tp=hbuicMy40IDnjEA3yKCYJg%3D%3D; _pst=275466402_m; __jda=122270672.1586273021865136663377.1586273022.1590741875.1590853863.6; __jdc=122270672; shshshfp=4502485e8b520f53be89fe44a27717ee; 3AB9D23F7A4B3C9B=XMKWG35OFYBQN3C5JYD7J4FNOWNXSGBIZNIKBUVVQEMJW6766KKTNYZD43U3Y7VCWA73EEWJRCOTKU7QVG3WKUNNQA; cn=14; ipLoc-djd=20-1761-25188-51466.2052701265; ipLocation=%u5e7f%u897f; __tak=c94559a7e3893645ee7f9f3ba3af391b4381d8e935b4895cf5f4df48e014c4aca54c30a40df88a95e670fcf3ef153823cfc92c013e7e892133119c9f79811f1b9303c52b4dffffebb6b145cbe13fc0e0; thor=A3006E40DFDA6A23E9353F8A5BE5D7B526D907891A33D2D63A28B4F6F19DC6F67E8BAA1251F8FC51DA54936D111277AEF79F42D5BBCA8C7F01068EA42B4B681CF3D78B4CB73DF9E870791980E609BABE4426FF4EF4089405842C640217A10FEC30256F6BC66C63C67D595F08AE093A375782F916DE74D980FE9E18720F2D5987B03269FB13DC923CCCEC51A5FD7155FD; shshshsID=b122acc455c4e500fe48a45f327cbeac_17_1590855792368; __jdb=122270672.25.1586273021865136663377|6.1590853863" # 商品id -sku_id = 100012043978 # 已经是茅台的sku_id了 -# 设定时间 # 2020-02-24 10:00:00.100000 -buy_time = 2020-06-09 10:00:00.150 +# 已经是茅台的sku_id了 +sku_id = 100012043978 +# 设定时间 # 2020-12-09 10:00:00.100000 +buy_time = 2020-12-22 09:59:59.500 # 默认UA -DEFAULT_USER_AGENT = "" +DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" # 是否使用随机 useragent,默认为 false random_useragent = false +[account] +# 支付密码 +# 如果你的账户中有可用的京券(注意不是东券)或 在上次购买订单中使用了京豆, +# 那么京东可能会在下单时自动选择京券支付 或 自动勾选京豆支付。 +# 此时下单会要求输入六位数字的支付密码。请在下方配置你的支付密码,如 123456 。 +# 如果没有上述情况,下方请留空。 +payment_pwd = "" + [messenger] # 使用了Server酱的推送服务 # 如果想开启下单成功后消息推送,则将 enable 设置为 true,默认为 false 不开启推送 # 开启消息推送必须填入 sckey,如何获取请参考 http://sc.ftqq.com/3.version。感谢Server酱~ enable = false sckey = + +# 使用了smtp邮箱推送服务 +# 如果想开启登录二维码邮箱推送,则将 email_enable 设置为 true,默认为 false 不开启邮箱推送 +# 开启消息推送必须填入 email_user、email_pwd,email_host 若不填则会自动判断,email_pwd 如何获取请自行百度。 +email_enable = false +# 邮箱域名 smtp.xx.com +email_host = +# 邮箱地址 xxxxxxxx@xx.com +email_user = +# 邮箱授权码(并不一定是邮箱密码) xxxxxxxxxxxxxxxx +email_pwd = diff --git a/exception.py b/exception.py new file mode 100644 index 00000000..c8fa5080 --- /dev/null +++ b/exception.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python +# -*- encoding=utf8 -*- + + +class SKException(Exception): + + def __init__(self, message): + super().__init__(message) diff --git a/jd_spider_requests.py b/jd_spider_requests.py index b1b7b4f0..f2eb8a25 100644 --- a/jd_spider_requests.py +++ b/jd_spider_requests.py @@ -1,41 +1,334 @@ import random -import sys import time +import requests +import functools +import json +import os +import pickle + +from lxml import etree from jd_logger import logger from timer import Timer -import requests -from util import parse_json, get_session, get_sku_title,send_wechat from config import global_config from concurrent.futures import ProcessPoolExecutor +from exception import SKException +from util import ( + parse_json, + send_wechat, + wait_some_time, + response_status, + save_image, + open_image, + email +) + + +class SpiderSession: + """ + Session相关操作 + """ + def __init__(self): + self.cookies_dir_path = "./cookies/" + self.user_agent = global_config.getRaw('config', 'DEFAULT_USER_AGENT') + + self.session = self._init_session() + + def _init_session(self): + session = requests.session() + session.headers = self.get_headers() + return session + + def get_headers(self): + return {"User-Agent": self.user_agent, + "Accept": "text/html,application/xhtml+xml,application/xml;" + "q=0.9,image/webp,image/apng,*/*;" + "q=0.8,application/signed-exchange;" + "v=b3", + "Connection": "keep-alive"} + + def get_user_agent(self): + return self.user_agent + + def get_session(self): + """ + 获取当前Session + :return: + """ + return self.session + + def get_cookies(self): + """ + 获取当前Cookies + :return: + """ + return self.get_session().cookies + + def set_cookies(self, cookies): + self.session.cookies.update(cookies) + + def load_cookies_from_local(self): + """ + 从本地加载Cookie + :return: + """ + cookies_file = '' + if not os.path.exists(self.cookies_dir_path): + return False + for name in os.listdir(self.cookies_dir_path): + if name.endswith(".cookies"): + cookies_file = '{}{}'.format(self.cookies_dir_path, name) + break + if cookies_file == '': + return False + with open(cookies_file, 'rb') as f: + local_cookies = pickle.load(f) + self.set_cookies(local_cookies) + + def save_cookies_to_local(self, cookie_file_name): + """ + 保存Cookie到本地 + :param cookie_file_name: 存放Cookie的文件名称 + :return: + """ + cookies_file = '{}{}.cookies'.format(self.cookies_dir_path, cookie_file_name) + directory = os.path.dirname(cookies_file) + if not os.path.exists(directory): + os.makedirs(directory) + with open(cookies_file, 'wb') as f: + pickle.dump(self.get_cookies(), f) + + +class QrLogin: + """ + 扫码登录 + """ + def __init__(self, spider_session: SpiderSession): + """ + 初始化扫码登录 + 大致流程: + 1、访问登录二维码页面,获取Token + 2、使用Token获取票据 + 3、校验票据 + :param spider_session: + """ + self.qrcode_img_file = 'qr_code.png' + + self.spider_session = spider_session + self.session = self.spider_session.get_session() + + self.is_login = False + self.refresh_login_status() + + def refresh_login_status(self): + """ + 刷新是否登录状态 + :return: + """ + self.is_login = self._validate_cookies() + + def _validate_cookies(self): + """ + 验证cookies是否有效(是否登陆) + 通过访问用户订单列表页进行判断:若未登录,将会重定向到登陆页面。 + :return: cookies是否有效 True/False + """ + url = 'https://order.jd.com/center/list.action' + payload = { + 'rid': str(int(time.time() * 1000)), + } + try: + resp = self.session.get(url=url, params=payload, allow_redirects=False) + if resp.status_code == requests.codes.OK: + return True + except Exception as e: + logger.error("验证cookies是否有效发生异常", e) + return False + + def _get_login_page(self): + """ + 获取PC端登录页面 + :return: + """ + url = "https://passport.jd.com/new/login.aspx" + page = self.session.get(url, headers=self.spider_session.get_headers()) + return page + + def _get_qrcode(self): + """ + 缓存并展示登录二维码 + :return: + """ + url = 'https://qr.m.jd.com/show' + payload = { + 'appid': 133, + 'size': 147, + 't': str(int(time.time() * 1000)), + } + headers = { + 'User-Agent': self.spider_session.get_user_agent(), + 'Referer': 'https://passport.jd.com/new/login.aspx', + } + resp = self.session.get(url=url, headers=headers, params=payload) + + if not response_status(resp): + logger.info('获取二维码失败') + return False + + save_image(resp, self.qrcode_img_file) + logger.info('二维码获取成功,请打开京东APP扫描') + open_image(self.qrcode_img_file) + if global_config.getRaw('messenger', 'email_enable') == 'true': + email.send('二维码获取成功,请打开京东APP扫描', "", [email.mail_user], 'qr_code.png') + + return True + + def _get_qrcode_ticket(self): + """ + 通过 token 获取票据 + :return: + """ + url = 'https://qr.m.jd.com/check' + payload = { + 'appid': '133', + 'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)), + 'token': self.session.cookies.get('wlfstk_smdl'), + '_': str(int(time.time() * 1000)), + } + headers = { + 'User-Agent': self.spider_session.get_user_agent(), + 'Referer': 'https://passport.jd.com/new/login.aspx', + } + resp = self.session.get(url=url, headers=headers, params=payload) + + if not response_status(resp): + logger.error('获取二维码扫描结果异常') + return False + + resp_json = parse_json(resp.text) + if resp_json['code'] != 200: + logger.info('Code: %s, Message: %s', resp_json['code'], resp_json['msg']) + return None + else: + logger.info('已完成手机客户端确认') + return resp_json['ticket'] + + def _validate_qrcode_ticket(self, ticket): + """ + 通过已获取的票据进行校验 + :param ticket: 已获取的票据 + :return: + """ + url = 'https://passport.jd.com/uc/qrCodeTicketValidation' + headers = { + 'User-Agent': self.spider_session.get_user_agent(), + 'Referer': 'https://passport.jd.com/uc/login?ltype=logout', + } + + resp = self.session.get(url=url, headers=headers, params={'t': ticket}) + if not response_status(resp): + return False + + resp_json = json.loads(resp.text) + if resp_json['returnCode'] == 0: + return True + else: + logger.info(resp_json) + return False + + def login_by_qrcode(self): + """ + 二维码登陆 + :return: + """ + self._get_login_page() + + # download QR code + if not self._get_qrcode(): + raise SKException('二维码下载失败') + + # get QR code ticket + ticket = None + retry_times = 85 + for _ in range(retry_times): + ticket = self._get_qrcode_ticket() + if ticket: + break + time.sleep(2) + else: + raise SKException('二维码过期,请重新获取扫描') + + # validate QR code ticket + if not self._validate_qrcode_ticket(ticket): + raise SKException('二维码信息校验失败') + + self.refresh_login_status() + + logger.info('二维码登录成功') class JdSeckill(object): def __init__(self): + self.spider_session = SpiderSession() + self.spider_session.load_cookies_from_local() + + self.qrlogin = QrLogin(self.spider_session) + # 初始化信息 - self.session = get_session() self.sku_id = global_config.getRaw('config', 'sku_id') self.seckill_num = 2 self.seckill_init_info = dict() self.seckill_url = dict() self.seckill_order_data = dict() self.timers = Timer() - self.default_user_agent = global_config.getRaw('config', 'DEFAULT_USER_AGENT') + self.session = self.spider_session.get_session() + self.user_agent = self.spider_session.user_agent + self.nick_name = None + + def login_by_qrcode(self): + """ + 二维码登陆 + :return: + """ + if self.qrlogin.is_login: + logger.info('登录成功') + return + + self.qrlogin.login_by_qrcode() + + if self.qrlogin.is_login: + self.nick_name = self.get_username() + self.spider_session.save_cookies_to_local(self.nick_name) + else: + raise SKException("二维码登录失败!") + + def check_login(func): + """ + 用户登陆态校验装饰器。若用户未登陆,则调用扫码登陆 + """ + @functools.wraps(func) + def new_func(self, *args, **kwargs): + if not self.qrlogin.is_login: + logger.info("{0} 需登陆后调用,开始扫码登陆".format(func.__name__)) + self.login_by_qrcode() + return func(self, *args, **kwargs) + return new_func + + @check_login def reserve(self): """ 预约 """ - self.__reserve() + self._reserve() + @check_login def seckill(self): """ 抢购 """ - self.__seckill() - - def wati_some_time(self): - time.sleep(random.randint(100, 300) / 1000) + self._seckill() + @check_login def seckill_by_proc_pool(self, work_count=5): """ 多进程进行抢购 @@ -45,59 +338,35 @@ def seckill_by_proc_pool(self, work_count=5): for i in range(work_count): pool.submit(self.seckill) - def __reserve(self): + def _reserve(self): """ 预约 """ - self.login() while True: try: self.make_reserve() + break except Exception as e: logger.info('预约发生异常!', e) - self.wati_some_time() + wait_some_time() - def __seckill(self): + def _seckill(self): """ 抢购 """ - self.login() while True: try: self.request_seckill_url() - self.request_seckill_checkout_page() - self.submit_seckill_order() + while True: + self.request_seckill_checkout_page() + self.submit_seckill_order() except Exception as e: logger.info('抢购发生异常,稍后继续执行!', e) - self.wati_some_time() - - def login(self): - for flag in range(1, 3): - try: - targetURL = 'https://order.jd.com/center/list.action' - payload = { - 'rid': str(int(time.time() * 1000)), - } - resp = self.session.get( - url=targetURL, params=payload, allow_redirects=False) - if resp.status_code == requests.codes.OK: - logger.info('校验是否登录[成功]') - logger.info('用户:{}'.format(self.get_username())) - return True - else: - logger.info('校验是否登录[失败]') - logger.info('请重新输入cookie') - time.sleep(1) - continue - except Exception as e: - logger.info('第【%s】次失败请重新获取cookie', flag) - time.sleep(1) - continue - sys.exit(1) + wait_some_time() def make_reserve(self): """商品预约""" - logger.info('商品名称:{}'.format(get_sku_title())) + logger.info('商品名称:{}'.format(self.get_sku_title())) url = 'https://yushou.jd.com/youshouinfo.action?' payload = { 'callback': 'fetchJSON', @@ -105,7 +374,7 @@ def make_reserve(self): '_': str(int(time.time() * 1000)), } headers = { - 'User-Agent': self.default_user_agent, + 'User-Agent': self.user_agent, 'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id), } resp = self.session.get(url=url, params=payload, headers=headers) @@ -127,11 +396,11 @@ def get_username(self): """获取用户信息""" url = 'https://passport.jd.com/user/petName/getUserInfoForMiniJd.action' payload = { - 'callback': 'jQuery'.format(random.randint(1000000, 9999999)), + 'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)), '_': str(int(time.time() * 1000)), } headers = { - 'User-Agent': self.default_user_agent, + 'User-Agent': self.user_agent, 'Referer': 'https://order.jd.com/center/list.action', } @@ -144,11 +413,19 @@ def get_username(self): resp = self.session.get(url=url, params=payload, headers=headers) else: break - self.wati_some_time() + wait_some_time() # 响应中包含了许多用户信息,现在在其中返回昵称 # jQuery2381773({"imgUrl":"//storage.360buyimg.com/i.imageUpload/xxx.jpg","lastLoginTime":"","nickName":"xxx","plusStatus":"0","realName":"xxx","userLevel":x,"userScoreVO":{"accountScore":xx,"activityScore":xx,"consumptionScore":xxxxx,"default":false,"financeScore":xxx,"pin":"xxx","riskScore":x,"totalScore":xxxxx}}) return parse_json(resp.text).get('nickName') + def get_sku_title(self): + """获取商品名称""" + url = 'https://item.jd.com/{}.html'.format(global_config.getRaw('config', 'sku_id')) + resp = self.session.get(url).content + x_data = etree.HTML(resp) + sku_title = x_data.xpath('/html/head/title/text()') + return sku_title[0] + def get_seckill_url(self): """获取商品的抢购链接 点击"抢购"按钮后,会有两次302跳转,最后到达订单结算页面 @@ -163,7 +440,7 @@ def get_seckill_url(self): '_': str(int(time.time() * 1000)), } headers = { - 'User-Agent': self.default_user_agent, + 'User-Agent': self.user_agent, 'Host': 'itemko.jd.com', 'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id), } @@ -181,17 +458,17 @@ def get_seckill_url(self): return seckill_url else: logger.info("抢购链接获取失败,稍后自动重试") - self.wati_some_time() + wait_some_time() def request_seckill_url(self): """访问商品的抢购链接(用于设置cookie等""" logger.info('用户:{}'.format(self.get_username())) - logger.info('商品名称:{}'.format(get_sku_title())) + logger.info('商品名称:{}'.format(self.get_sku_title())) self.timers.start() self.seckill_url[self.sku_id] = self.get_seckill_url() logger.info('访问商品的抢购连接...') headers = { - 'User-Agent': self.default_user_agent, + 'User-Agent': self.user_agent, 'Host': 'marathon.jd.com', 'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id), } @@ -211,7 +488,7 @@ def request_seckill_checkout_page(self): 'rid': int(time.time()) } headers = { - 'User-Agent': self.default_user_agent, + 'User-Agent': self.user_agent, 'Host': 'marathon.jd.com', 'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id), } @@ -229,11 +506,18 @@ def _get_seckill_init_info(self): 'isModifyAddress': 'false', } headers = { - 'User-Agent': self.default_user_agent, + 'User-Agent': self.user_agent, 'Host': 'marathon.jd.com', } resp = self.session.post(url=url, data=data, headers=headers) - return parse_json(resp.text) + + resp_json = None + try: + resp_json = parse_json(resp.text) + except Exception: + raise SKException('抢购失败,返回信息:{}'.format(resp.text[0: 128])) + + return resp_json def _get_seckill_order_data(self): """生成提交抢购订单所需的请求体参数 @@ -270,7 +554,7 @@ def _get_seckill_order_data(self): 'invoicePhone': invoice_info.get('invoicePhone', ''), 'invoicePhoneKey': invoice_info.get('invoicePhoneKey', ''), 'invoice': 'true' if invoice_info else 'false', - 'password': '', + 'password': global_config.get('account', 'payment_pwd'), 'codTimeType': 3, 'paymentType': 4, 'areaCode': '', @@ -281,6 +565,7 @@ def _get_seckill_order_data(self): 'token': token, 'pru': '' } + return data def submit_seckill_order(self): @@ -291,10 +576,15 @@ def submit_seckill_order(self): payload = { 'skuId': self.sku_id, } - self.seckill_order_data[self.sku_id] = self._get_seckill_order_data() + try: + self.seckill_order_data[self.sku_id] = self._get_seckill_order_data() + except Exception as e: + logger.info('抢购失败,无法获取生成订单的基本信息,接口返回:【{}】'.format(str(e))) + return False + logger.info('提交抢购订单...') headers = { - 'User-Agent': self.default_user_agent, + 'User-Agent': self.user_agent, 'Host': 'marathon.jd.com', 'Referer': 'https://marathon.jd.com/seckill/seckill.action?skuId={0}&num={1}&rid={2}'.format( self.sku_id, self.seckill_num, int(time.time())), @@ -305,7 +595,12 @@ def submit_seckill_order(self): data=self.seckill_order_data.get( self.sku_id), headers=headers) - resp_json = parse_json(resp.text) + resp_json = None + try: + resp_json = parse_json(resp.text) + except Exception as e: + logger.info('抢购失败,返回信息:{}'.format(resp.text[0: 128])) + return False # 返回信息 # 抢购失败: # {'errorMessage': '很遗憾没有抢到,再接再厉哦。', 'orderId': 0, 'resultCode': 60074, 'skuId': 0, 'success': False} @@ -317,9 +612,7 @@ def submit_seckill_order(self): order_id = resp_json.get('orderId') total_money = resp_json.get('totalMoney') pay_url = 'https:' + resp_json.get('pcUrl') - logger.info( - '抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}'.format(order_id,total_money,pay_url) - ) + logger.info('抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}'.format(order_id, total_money, pay_url)) if global_config.getRaw('messenger', 'enable') == 'true': success_message = "抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}".format(order_id, total_money, pay_url) send_wechat(success_message) @@ -329,4 +622,4 @@ def submit_seckill_order(self): if global_config.getRaw('messenger', 'enable') == 'true': error_message = '抢购失败,返回信息:{}'.format(resp_json) send_wechat(error_message) - return False \ No newline at end of file + return False diff --git a/main.py b/main.py index 9b703146..9a7c949b 100644 --- a/main.py +++ b/main.py @@ -5,20 +5,18 @@ if __name__ == '__main__': a = """ - _____ _______ ______ __ __ __ __ - / |/ \ / \ / | / |/ |/ | - $$$$$ |$$$$$$$ | /$$$$$$ | ______ _______ $$ | __ $$/ $$ |$$ | - $$ |$$ | $$ | ______ $$ \__$$/ / \ / |$$ | / |/ |$$ |$$ | - __ $$ |$$ | $$ |/ |$$ \ /$$$$$$ |/$$$$$$$/ $$ |_/$$/ $$ |$$ |$$ | -/ | $$ |$$ | $$ |$$$$$$/ $$$$$$ |$$ $$ |$$ | $$ $$< $$ |$$ |$$ | -$$ \__$$ |$$ |__$$ | / \__$$ |$$$$$$$$/ $$ \_____ $$$$$$ \ $$ |$$ |$$ | -$$ $$/ $$ $$/ $$ $$/ $$ |$$ |$$ | $$ |$$ |$$ |$$ | - $$$$$$/ $$$$$$$/ $$$$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$/ - + oooo oooooooooo. .oooooo..o oooo o8o oooo oooo + `888 `888' `Y8b d8P' `Y8 `888 `"' `888 `888 + 888 888 888 Y88bo. .ooooo. .ooooo. 888 oooo oooo 888 888 + 888 888 888 `"Y8888o. d88' `88b d88' `"Y8 888 .8P' `888 888 888 + 888 888 888 8888888 `"Y88b 888ooo888 888 888888. 888 888 888 + 888 888 d88' oo .d8P 888 .o 888 .o8 888 `88b. 888 888 888 + .o. 88P o888bood8P' 8""88888P' `Y8bod8P' `Y8bod8P' o888o o888o o888o o888o o888o + `Y888P + 功能列表: 1.预约商品 2.秒杀抢购商品 - """ print(a) diff --git a/timer.py b/timer.py index 1f838efe..8eaceca1 100644 --- a/timer.py +++ b/timer.py @@ -1,20 +1,52 @@ # -*- coding:utf-8 -*- import time +import requests +import json + from datetime import datetime from jd_logger import logger from config import global_config + class Timer(object): def __init__(self, sleep_interval=0.5): # '2018-09-28 22:45:50.000' self.buy_time = datetime.strptime(global_config.getRaw('config','buy_time'), "%Y-%m-%d %H:%M:%S.%f") + self.buy_time_ms = int(time.mktime(self.buy_time.timetuple()) * 1000.0 + self.buy_time.microsecond / 1000) self.sleep_interval = sleep_interval + self.diff_time = self.local_jd_time_diff() + + def jd_time(self): + """ + 从京东服务器获取时间毫秒 + :return: + """ + url = 'https://a.jd.com//ajax/queryServerData.html' + ret = requests.get(url).text + js = json.loads(ret) + return int(js["serverTime"]) + + def local_time(self): + """ + 获取本地毫秒时间 + :return: + """ + return int(round(time.time() * 1000)) + + def local_jd_time_diff(self): + """ + 计算本地与京东服务器时间差 + :return: + """ + return self.local_time() - self.jd_time() + def start(self): - logger.info('正在等待到达设定时间:%s' % self.buy_time) - now_time = datetime.now + logger.info('正在等待到达设定时间:{},检测本地时间与京东服务器时间误差为【{}】毫秒'.format(self.buy_time, self.diff_time)) while True: - if now_time() >= self.buy_time: + # 本地时间减去与京东的时间差,能够将时间误差提升到0.1秒附近 + # 具体精度依赖获取京东服务器时间的网络时间损耗 + if self.local_time() - self.diff_time >= self.buy_time_ms: logger.info('时间到达,开始执行……') break else: diff --git a/util.py b/util.py index 6ed2e883..48114a19 100644 --- a/util.py +++ b/util.py @@ -1,8 +1,17 @@ import json import random import requests +import os +import time +import smtplib + +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from email.mime.image import MIMEImage + from config import global_config -from lxml import etree +from jd_logger import logger + USER_AGENTS = [ "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", @@ -57,50 +66,23 @@ "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14" ] + def parse_json(s): begin = s.find('{') end = s.rfind('}') + 1 return json.loads(s[begin:end]) + def get_random_useragent(): """生成随机的UserAgent :return: UserAgent字符串 """ return random.choice(USER_AGENTS) -def get_cookies(): - """解析cookies内容并添加到cookiesJar""" - manual_cookies = {} - for item in global_config.getRaw('config','cookies_String').split(';'): - name, value = item.strip().split('=', 1) - # 用=号分割,分割1次 - manual_cookies[name] = value - # 为字典cookies添加内容 - cookiesJar = requests.utils.cookiejar_from_dict(manual_cookies, cookiejar=None, overwrite=True) - return cookiesJar - -def get_session(): - # 初始化session - session = requests.session() - session.headers = {"User-Agent": global_config.getRaw('config', 'DEFAULT_USER_AGENT'), - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", - "Connection": "keep-alive"} - checksession = requests.session() - checksession.headers = {"User-Agent": global_config.getRaw('config', 'DEFAULT_USER_AGENT'), - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", - "Connection": "keep-alive"} - # 获取cookies保存到session - session.cookies = get_cookies() - return session - -def get_sku_title(): - """获取商品名称""" - url = 'https://item.jd.com/{}.html'.format(global_config.getRaw('config','sku_id')) - session = get_session() - resp = session.get(url).content - x_data = etree.HTML(resp) - sku_title = x_data.xpath('/html/head/title/text()') - return sku_title[0] + +def wait_some_time(): + time.sleep(random.randint(100, 300) / 1000) + def send_wechat(message): """推送信息到微信""" @@ -113,3 +95,94 @@ def send_wechat(message): 'User-Agent':global_config.getRaw('config', 'DEFAULT_USER_AGENT') } requests.get(url, params=payload, headers=headers) + + +def response_status(resp): + if resp.status_code != requests.codes.OK: + print('Status: %u, Url: %s' % (resp.status_code, resp.url)) + return False + return True + + +def open_image(image_file): + if os.name == "nt": + os.system('start ' + image_file) # for Windows + else: + if os.uname()[0] == "Linux": + if "deepin" in os.uname()[2]: + os.system("deepin-image-viewer " + image_file) # for deepin + else: + os.system("eog " + image_file) # for Linux + else: + os.system("open " + image_file) # for Mac + + +def save_image(resp, image_file): + with open(image_file, 'wb') as f: + for chunk in resp.iter_content(chunk_size=1024): + f.write(chunk) + + +class Email(): + + def __init__(self, mail_user, mail_pwd, mail_host=''): + if global_config.getRaw('messenger', 'email_enable') == 'false': + return + + smtpObj = smtplib.SMTP() + # 没传会自动判断 判断不出来默认QQ邮箱 + if mail_host: + self.mail_host = mail_host + elif mail_user.endswith('163.com'): + self.mail_host = 'smtp.163.com' + elif mail_user.endswith(('sina.com', 'sina.cn')): + self.mail_host = 'smtp.163.com' + elif mail_user.endswith('qq.com'): + self.mail_host = 'smtp.qq.com' + elif mail_user.endswith('sohu.com'): + self.mail_host = 'smtp.sohu.com' + else: + self.mail_host = 'smtp.qq.com' + self.mail_user = mail_user + self.is_login = False + try: + smtpObj.connect(mail_host, 25) + smtpObj.login(mail_user, mail_pwd) + self.is_login = True + except Exception as e: + logger.info('邮箱登录失败!', e) + self.smtpObj = smtpObj + + def send(self, title, msg, receivers: list, img=''): + """ + 发送smtp邮件至收件人 + :param title: + :param msg: 如果发送图片,需在msg内嵌入,xxx为图片名 + :param receivers: + :param img: 图片名 + :return: + """ + if self.is_login: + message = MIMEMultipart('alternative') + msg_html = MIMEText(msg, 'html', 'utf-8') + message.attach(msg_html) + message['Subject'] = title + message['From'] = self.mail_user + if img: + with open(img, "rb") as f: + msg_img = MIMEImage(f.read()) + msg_img.add_header('Content-ID', img) + message.attach(msg_img) + try: + self.smtpObj.sendmail(self.mail_user, receivers, message.as_string()) + except Exception as e: + logger.info('邮件发送失败!', e) + else: + logger.info('邮箱未登录') + + +email = Email( + mail_host=global_config.getRaw('messenger', 'email_host'), + mail_user=global_config.getRaw('messenger', 'email_user'), + mail_pwd=global_config.getRaw('messenger', 'email_pwd'), + )