[
  {
    "path": ".dockerignore",
    "content": ".git\n.gitignore\n.dockerignore\n.github\n.DS_Store\n\nDockerfile\ndocker-compose.yml\n\nREADME.md\nOther.md\nLICENSE\n\n.vscode\n.idea\nimg/\ntests/\n.pytest_cache/\n.venv//\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/1.bug.yml",
    "content": "name: Bug report 🐛\ndescription: 项目运行中遇到的Bug或问题。\nlabels: [\"status: issue-bug\"]\nbody:\n  - type: checkboxes\n    attributes:\n      label: ⚠️ 搜索issues中是否已存在类似问题\n      description: >\n        请在 [历史issue](https://github.com/rongchenlin/BiliBili-Lucky-Draw/issues) 中清空输入框，搜索你的问题\n        或相关日志的关键词来查找是否存在类似问题。\n      options:\n        - label: 我已经搜索过issues和disscussions，没有跟我遇到的问题相关的issue\n          required: true\n  - type: dropdown\n    attributes:\n      label: 操作系统类型?\n      description: >\n        请选择你运行程序的操作系统类型。\n      options:\n        - Windows\n        - Linux\n        - MacOS\n        - Docker\n        - Railway\n        - Windows Subsystem for Linux (WSL)\n        - Other (请在问题中说明)\n    validations:\n      required: true\n  - type: dropdown\n    attributes:\n      label: 运行的python版本是?\n      description: |\n        请选择你运行程序的`python`版本。\n      options:\n        - python 3.7\n        - python 3.8\n        - python 3.9\n        - python 3.10\n        - python 3.11\n        - other\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: 复现步骤 🕹\n      description: |\n        **⚠️ 不能复现将会关闭issue.**\n  - type: textarea\n    attributes:\n      label: 问题描述 😯\n      description: 详细描述出现的问题，或提供有关截图。\n  - type: textarea\n    attributes:\n      label: 终端日志 📒\n      description: |\n        在此处粘贴终端日志\n      value: |\n        ```log\n        <此处粘贴终端日志>\n        ```\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/2.feature.yml",
    "content": "name: Feature request 🚀\ndescription: 提出你对项目的新想法或建议。\nlabels: [\"status: issue-feature\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        请在上方的`title`中填写简略总结，谢谢❤️。\n  - type: checkboxes\n    attributes:\n      label: ⚠️ 搜索是否存在类似issue\n      description: >\n        请在 [历史issue](https://github.com/rongchenlin/BiliBili-Lucky-Draw/issues) 中清空输入框，搜索关键词查找是否存在相似issue。\n      options:\n        - label: 我已经搜索过issues和disscussions，没有发现相似issue\n          required: true\n  - type: textarea\n    attributes:\n      label: 描述\n      description: 描述feature的功能。\n  - type: textarea\n    attributes:\n      label: 举例(可选)\n      description: 提供功能相关的聊天示例，草图或相关网址。\n  - type: textarea\n    attributes:\n      label: 动机\n      description: 描述你提出该feature的动机，比如没有这项feature对你的使用造成了怎样的影响\n"
  },
  {
    "path": ".gitignore",
    "content": "pyvenv\n.idea\nLog\n\n\n__pycache__\n*/__pycache__\n/service/*/__pycache__\n/*/__pycache__"
  },
  {
    "path": "Dockerfile",
    "content": "FROM python:3\n\n# 复制项目文件到容器中\nCOPY . /app\n\n# 设置工作目录为项目目录\nWORKDIR /app\n\n# 安装项目依赖项\nRUN pip install -r requirements.txt -i http://pypi.douban.com/simple --trusted-host pypi.douban.com\n\n# 运行docker run命令\nCMD python main.py\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Other.md",
    "content": "## <a id=\"debug_doc\">Windows系统调试本程序</a>\n\n### 环境准备\n\n![image-20230716184756757](img/Other.assets/image-20230716184756757.png)\n\n- 创建MySQL，导入lib目录中的SQL脚本`init_db_script.sql`\n- 创建Selenium环境\n  - 点击这个链接：[chromedriver下载地址](http://chromedriver.storage.googleapis.com/index.html) 或者 [下载地址2](https://chromedriver.chromium.org/downloads)，下载和当前Chrome匹配的`chromedriver`\n  - 将下载的`chromedriver.exe`放到lib目录中。\n\n#### 修改代码\n\n到`utils/selenium_util.py`位置，将原本使用docker启动方式的代码注释，本地启动代码。\n\n![image-20230716185149619](img/Other.assets/image-20230716185149619.png)\n"
  },
  {
    "path": "Readme.md",
    "content": "<div align=\"center\">\r\n    <img align=\"center\" src=\"https://github.com/rongchenlin/BiliBili-Lucky-Draw/blob/master/img/Readme.assets/logo.png\" alt=\"logo\" width=\"600\">\r\n    <p align=\"center\">· BiliBili-Lucky-Draw ·</p>\r\n    <p align=\"center\">\r\n        <img src=\"https://img.shields.io/github/stars/rongchenlin/BiliBili-Lucky-Draw?color=red&style=flat-square\">\r\n        <a href=\"mailto:2702739215@qq.com\">\r\n            <img src=\"https://img.shields.io/static/v1?label=contact%20me&message=email&color=green&style=flat-square\">\r\n        </a>\r\n        <a href=\"https://github.com/rongchenlin/BiliBili-Lucky-Draw/blob/master/LICENSE\" target=\"_blank\">\r\n            <img src=\"https://img.shields.io/static/v1?label=license&message=GPL-3.0&color=orange&style=flat-square\">\r\n        </a>\r\n        <a href=\"https://github.com/rongchenlin/BiliBili-Lucky-Draw/issues/new/choose\" target=\"_blank\">\r\n            <img src=\"https://img.shields.io/static/v1?label=feedback&message=issues&color=pink&style=flat-square\">\r\n        </a>\r\n    </p>\r\n    </br>\r\n</div>\r\n\r\n## Ⅰ.简介\r\n\r\n常刷B站的伙伴们，是不是每次看到Up主的抽奖活动都心动不已，毕竟`抽奖总得试试吗，万一中奖了呢`，然后一波关注+转发之后，迎来的每每都是`从不缺席，从不中奖`。\r\n\r\nSo，如果有个小脚本能够帮助你去看看**今天有哪些Up有抽奖活动，然后还能帮助你自动进行抽奖（转发动态+关注）**，那么你是不是可以花更多时间去看看二次元动漫呀。本着有羊毛一起薅的想法，我做了一个B站自动抽奖活动转发的小脚本，帮助伙伴们自动参与Up主的活动转发，提高伙伴们的中奖率，同时还能解放大家的双手，开开心心薅羊毛。\r\n\r\n**声明**: <u>**此脚本仅用于学习和测试，作者本人并不对其负责，请于运行测试完成后自行删除，请勿滥用！**</u>\r\n\r\n## Ⅱ.效果\r\n\r\n本程序内置一个扫描脚本，该脚本去挖掘那些经常转发抽奖动态的伙伴，然后每天定时去扫描他们今天的动态信息，随后再利用一个抽奖动态识别与转发脚本来进行活动参与，转发后的效果是这样的：\r\n\r\n![image-20230630234051479](img/Readme.assets/image-20230630234051479.png)\r\n\r\n## III.使用：Docker部署（推荐）\r\n\r\n### 1.Clone本项目\r\n\r\n### 2.获取B站Cookie\r\n\r\n> 苹果Mac电脑参考：[点击这里](https://github.com/BilibiliVideoDownload/BilibiliVideoDownload/wiki/%E8%8E%B7%E5%8F%96SESSDATA)\r\n\r\n> window电脑详细方法参考：[点击这里](https://zhuanlan.zhihu.com/p/383171889)\r\n\r\n在浏览器进入[B站](https://www.bilibili.com/)，然后登录，随后按照下图获取cookie值\r\n\r\n在`.env`文件中，修改相关信息：\r\n\r\n![](img/Readme.assets/2024-01-31-15-08-26-image.png)\r\n\r\n### 3.设置Cookie和本机IP\r\n\r\n注意：本机IP建议不要填127.0.0.1，而是填写实际IP。\r\n\r\n在本项目的.env文件中，将第2步获取的cookie值填入下图位置\r\n\r\n![](img/Readme.assets/2024-01-31-17-13-39-image.png)\r\n\r\n### 4.在Docker中分别执行下面两条命令\r\n\r\n编译命令：\r\n\r\n```dockerfile\r\ndocker-compose build\r\n```\r\n\r\n运行容器：\r\n\r\n```\r\ndocker-compose up -d\r\n```\r\n\r\n<u>Tip：如果要停止容器，可以使用命令：`docker-compose down`</u>\r\n\r\n### 5.确认是否运行成功\r\n\r\n等待docker运行成功后，点击进入 your_ip:5555/ui/sessions，然后点击正在执行的项目，看是否出现如下截图\r\n\r\n## IV.TODO && Updated\r\n\r\n- [x] 项目采用Docker部署\r\n- [x] 扫描B站二维码登录B站，自动生成Cookie并保存到本地项目文件夹cookie中\r\n- [x] 登录过期，使用Cookie续期\r\n- [x] 每日任务执行情况推送（之前用的方糖酱，后续将重新加入）\r\n- [x] 将数据库搭建的工作使用Docker部署\r\n- [x] Docker服务编排，一键部署\r\n- [x] 开发桌面程序(目前只是简单版本)\r\n- [x] 过期动态的删除\r\n- [x] 接入B站UP主每日总结的抽奖动态列表，自动完成对其转发\r\n\r\n---\r\n\r\n## Ⅶ.Thanks\r\n\r\n**本程序仅用于学习**\r\n\r\n**有问题欢迎大家提Issue，有时间我会帮忙解决，也请大佬有好的解决方案在Issue上分享，更加欢迎大家提出PR，成为项目的贡献者。**\r\n\r\n如果大家觉得这个项目有点意思，期待给个Star :star:，你的Star :star:是作者更新最大的动力鸭!\r\n\r\n<picture>\r\n  <source\r\n    media=\"(prefers-color-scheme: dark)\"\r\n    srcset=\"\r\n      https://api.star-history.com/svg?repos=rongchenlin/BiliBili-Lucky-Draw&type=Date&theme=dark\r\n    \"\r\n  />\r\n  <source\r\n    media=\"(prefers-color-scheme: light)\"\r\n    srcset=\"\r\n      https://api.star-history.com/svg?repos=rongchenlin/BiliBili-Lucky-Draw&type=Date\r\n    \"\r\n  />\r\n  <img\r\n    alt=\"Star History Chart\"\r\n    src=\"https://api.star-history.com/svg?repos=rongchenlin/BiliBili-Lucky-Draw&type=Date\"\r\n  />\r\n</picture>\r\n\r\n"
  },
  {
    "path": "dao/common_dao.py",
    "content": "from dao.init_db import init_db\n\n\nclass CommonDao(object):\n    def __init__(self, db):\n        self.db = db\n\n    def common_query(self, table_name=\"\", cond_dict=\"\", order=\"\", fields=\"*\"):\n        try:\n            \"\"\"\n            调用方法：\n            data = common_query(table_name=\"t_share_info\")\n            data = common_query(table_name=\"t_share_info\", order='order by id')\n            data = common_query(table_name=\"t_share_info\", cond_dict={'status': '0'}, order='order by id', fields=[\"id\", \"share_url\"])\n            \"\"\"\n            return self.db.select(table_name, cond_dict, order, fields)\n        except Exception as e:\n            return {}\n\n    def common_insertMany(self, table, attrs, values):\n        \"\"\"\n        调用方法：\n        data = common_query(table_name=\"t_share_info\")\n        data = common_query(table_name=\"t_share_info\", order='order by id')\n        data = common_query(table_name=\"t_share_info\", cond_dict={'status': '0'}, order='order by id', fields=[\"id\", \"share_url\"])\n        \"\"\"\n        try:\n            self.db.insertMany(table, attrs, values)\n            return 0\n        except Exception as e:\n            return 1\n\n"
  },
  {
    "path": "dao/draw_dynamic_dao.py",
    "content": "from datetime import datetime\n\n\nclass DrawDynamicDao(object):\n    def __init__(self, db):\n        self.table_name = 't_draw_dynamic'\n        self.db = db\n\n    def query_by_time(self, time, limit=2000, status=1):\n        try:\n            sql = (\"SELECT * FROM \" + self.table_name\n                   + \" where status = '\" + str(status)\n                   + \"' and insert_time >= '\" + time\n                   + \"' limit \" + str(limit))\n            data = self.db.select_db(sql)  # 用mysql_operate文件中的db的select_db方法进行查询\n            return data\n        except Exception as e:\n            return {}\n\n    def query_by_dyn_url(self, dyn_url):\n        try:\n            sql = \"SELECT * FROM \" + self.table_name + \" where dyn_url = '\" + dyn_url + \"'\";\n            data = self.db.select_db(sql)  # 用mysql_operate文件中的db的select_db方法进行查询\n            return data\n        except Exception as e:\n            return {}\n\n    def insert(self, dyn_url, source, note):\n        try:\n            params = {}\n            params['dyn_url'] = str(dyn_url)\n            params['source'] = str(source)\n            params['status'] = '0'\n            params['note'] = str(note)\n            params['insert_time'] = str(datetime.now())\n            self.db.insert(self.table_name, params)\n            return True\n        except Exception as e:\n            return False\n\n    def update_sharedUrl(self, url, status):\n        try:\n            params = {'status': str(status)}\n            cond_dict = {'dyn_url': url}\n            self.db.update(self.table_name, params, cond_dict)\n        except Exception as e:\n            print(e)\n"
  },
  {
    "path": "dao/follow_up_dao.py",
    "content": "from datetime import datetime\n\nclass FollowUpInfoDao(object):\n    def __init__(self,db):\n        self.db = None\n        self.table_name = 't_followdups'\n        self.db = db\n    def query_followUpInfo_by_UpId(self, up_id, user_id):\n        try:\n            sql = \"SELECT * FROM \" + self.table_name + \" where up_id = '\" + up_id + \"'\" + \" and user_id = '\" + user_id + \"'\";\n            data = self.db.select_db(sql)  # 用mysql_operate文件中的db的select_db方法进行查询\n            return data\n        except Exception as e:\n            return {}\n\n\n    def saverUpdate(self, up_id, up_url, user_id):\n        try:\n            params = {}\n            params['up_id'] = str(up_id)\n            params['user_id'] = str(user_id)\n            params['up_url'] = str(up_url)\n            params['update_time'] = str(datetime.now())\n            data = self.query_followUpInfo_by_UpId(up_id, user_id)\n            if len(data) == 0:\n                params['status'] = str(1)\n                self.db.insert(self.table_name, params)\n            else:\n                status = int(data[0]['status'])\n                status = status + 1\n                params['status'] = str(status)\n                cond_dict = {'up_id': up_id,'user_id': user_id}\n                self.db.update(self.table_name, params, cond_dict)\n        except Exception as e:\n            print(e)\n\n\n"
  },
  {
    "path": "dao/init_db.py",
    "content": "import logging\n\nimport pymysql\n\nfrom utils.mysql_operate import MysqldbHelper\n\nfrom utils.globals import db_host, port, user, passwd, charset, dbname\n\n\ndef init_db():\n    \"\"\"\n    初始化数据库连接\n    :return:\n    \"\"\"\n    config = {\n        'host': db_host,\n        'port': port,\n        'user': user,\n        'passwd': passwd,\n        'charset': charset,\n        'cursorclass': pymysql.cursors.DictCursor\n    }\n    logging.warning(\"ip :\" + str(db_host))\n    logging.info(\"db info :\")\n    logging.info(config)\n    db = MysqldbHelper(config)\n    db.selectDataBase(dbname)\n    logging.warning(\"创建数据库连接信息 :\" + str(config))\n    return db\n\n"
  },
  {
    "path": "dao/share_info_dao.py",
    "content": "from dao.init_db import init_db\nfrom service.share_service.share_one_dynamic import DynamicShareBase\n\n\nclass ShareInfoDao(object):\n    def __init__(self, db):\n        self.table_name = 't_share_info'\n        self.db = db\n\n    def query_shareInfo_by_userIdAndTime(self,  user_id, share_time):\n        \"\"\"\n        根据转发的url查询\n        :param user_id:\n        :param share_url:\n        :return:\n        \"\"\"\n        try:\n            sql = \"SELECT * FROM \" + self.table_name + \" where user_id = '\" + user_id + \"'\" + \" and share_time >= '\" + share_time + \"'\";\n            data = self.db.select_db(sql)\n            return data\n        except Exception as e:\n            return {}\n\n    def query_shareInfo_by_shareUrl(self, share_url, user_id):\n        \"\"\"\n        根据转发的url查询\n        :param user_id:\n        :param share_url:\n        :return:\n        \"\"\"\n        try:\n            sql = \"SELECT * FROM \" + self.table_name + \" where share_url = '\" + share_url + \"'\" + \" and user_id = '\" + user_id + \"'\";\n            data = self.db.select_db(sql)\n            return data\n        except Exception as e:\n            return {}\n\n\n    def insert_shareInfo(self, shareInfo):\n        try:\n            params = {}\n            params['upId'] = str(shareInfo.upId)\n            params['upUrl'] = str(shareInfo.upUrl)\n            params['share_url'] = str(shareInfo.share_url)\n            params['status'] = str(shareInfo.status)\n            params['machine_ip'] = str(shareInfo.machine_ip)\n            params['share_time'] = str(shareInfo.share_time)\n            params['user_id'] = str(shareInfo.user_id)\n            params['share_status'] = str(shareInfo.share_status)\n            self.db.insert(self.table_name, params)\n        except Exception as e:\n            print(e)\n\nif __name__ == '__main__':\n    db = init_db()\n    shareInfodao = ShareInfoDao(db)\n    # dyn = DynamicShareBase()\n    # dyn.upUrl = '1'\n    # dyn.upId = '2'\n    # dyn.share_url = '2share_url'\n    # dyn.status = 1\n    # dyn.machine_ip = '2machine_ip'\n    # dyn.share_time = '2022-12-12'\n    # dyn.share_status = 1\n\n\n"
  },
  {
    "path": "dao/shared_url_dao.py",
    "content": "from datetime import datetime\n\nfrom dao.init_db import init_db\nfrom service.share_service.share_one_dynamic import DynamicShareBase\n\n\nclass SharedUrlDao(object):\n    def __init__(self, db):\n        self.table_name = 't_shared_urls'\n        self.db = db\n\n    def query_sharedUrls_limit(self, user_id, status, limit):\n        \"\"\"\n        根据转发的url查询\n        :param user_id:\n        :param share_url:\n        :return:\n        \"\"\"\n        try:\n            sql = (\"SELECT * FROM \" + self.table_name\n                   + \" where user_id = '\" + user_id + \"'\" + \" and status = '\" + status + \"'\"\n                   + \" ORDER BY dyn_url\"\n                   + \" limit \" + str(limit) + \";\");\n            data = self.db.select_db(sql)\n            return data\n        except Exception as e:\n            print(e)\n            return {}\n\n    def insert_sharedUrl(self, user_id, url):\n        try:\n            params = {'dyn_url': str(url), 'user_id': user_id, 'insert_time': str(datetime.now()), 'status': '0'}\n            self.db.insert(self.table_name, params)\n        except Exception as e:\n            print(e)\n\n    def update_sharedUrl(self, user_id, url, status):\n        try:\n            params = {'update_time': str(datetime.now()), 'status': str(status)}\n            cond_dict = {'dyn_url': url, 'user_id': user_id}\n            self.db.update(self.table_name, params, cond_dict)\n        except Exception as e:\n            print(e)\n"
  },
  {
    "path": "dao/statistics_dao.py",
    "content": "from datetime import datetime, timedelta\n\nfrom dao.init_db import init_db\n\n\nclass StatisticsDao(object):\n    def __init__(self, db):\n        self.table_name = 't_statistics'\n        self.db = db\n\n    def query_by_time(self, time):\n        try:\n            sql = \"SELECT * FROM \" + self.table_name + \" where insert_time >= '\" + time + \"'\";\n            data = self.db.select_db(sql)  # 用mysql_operate文件中的db的select_db方法进行查询\n            return data\n        except Exception as e:\n            return {}\n\n\n\n    def query_today_data(self):\n        # 获取今天的日期\n        today = datetime.now()\n        # 计算昨天的日期\n        yesterday = today - timedelta(days=1)\n        # 将日期格式化为字符串\n        yesterday_str = yesterday.strftime(\"%Y-%m-%d\")\n\n        today_str = today.strftime(\"%Y-%m-%d\")\n        text = \"\"\n        datas = self.query_by_time(today_str)\n        for data in datas:\n            text = text + str(data['insert_time']) + \"\\n内容:[\" + data['user_id'] + data['content'] + \"]\\n备注:[\" + data['note'] + \"]\\n\\n\"\n        return text\n\n    def insert(self, user_id, content, note):\n        try:\n            params = {'user_id': str(user_id), 'content': str(content), 'note': str(note),\n                      'insert_time': str(datetime.now())}\n            self.db.insert(self.table_name, params)\n            return True\n        except:\n            return False\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "\n\nversion: '3'\nservices:\n  bili-db:\n    image: mysql:5.7\n    container_name: bili-db\n    environment:\n      MYSQL_ROOT_PASSWORD: luckybililuckybili\n      MYSQL_DATABASE: luckybili\n      MYSQL_USER: luckybili\n      MYSQL_PASSWORD: luckybililuckybili\n    ports:\n      - \"3206:3306\"\n    volumes:\n      - ./lib/init_db_script.sql:/docker-entrypoint-initdb.d/init_db_script.sql  # 挂载init_db_script.sql文件到容器内的初始化目录\n      - ./db_data:/var/lib/mysql  # 持久化MySQL数据\n    command: --default-authentication-plugin=mysql_native_password\n\n\n  bili-selenium:\n    image: selenium/standalone-chrome:latest\n    container_name: bili-selenium\n    ports:\n      - 5555:4444\n      - 7900:7900\n    shm_size: 1g\n    environment:\n      - SE_NODE_MAX_SESSIONS=5\n      - SE_NODE_MAX_INSTANCES=5\n      - SE_NODE_OVERRIDE_MAX_SESSIONS=true\n\n  # 执行转发动态的服务\n  dynamic_share:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    volumes:\n      - .:/app\n    restart: always\n    depends_on:\n      - bili-selenium\n      - bili-db\n\n\n\n"
  },
  {
    "path": "lib/init_db_script.sql",
    "content": "-- create database luckybili default character set utf8mb4 collate utf8mb4_general_ci;\nuse luckybili;\n\ncreate table t_draw_dynamic\n(\n    dyn_url     varchar(255) charset latin1 not null\n        primary key,\n    insert_time datetime                    null,\n    source      varchar(255) charset latin1 null,\n    note        varchar(255)                null,\n    status      varchar(20)                 null\n)\n    collate = utf8_bin;\n\ncreate table t_followdups\n(\n    id          int auto_increment\n        primary key,\n    up_id       varchar(255) null,\n    up_url      varchar(255) null,\n    status      int          null,\n    update_time datetime     null,\n    user_id     varchar(50)  null\n)\n    comment '关注的up主信息';\n\ncreate table t_prize\n(\n    id        int auto_increment\n        primary key,\n    status    int          null,\n    prize_url varchar(255) null,\n    user_id   varchar(50)  null\n)\n    comment '中奖信息表';\n\ncreate table t_share_info\n(\n    id           int auto_increment,\n    share_url    varchar(255) null,\n    status       int          not null comment '当前动态状态',\n    upId         varchar(50)  null,\n    upUrl        varchar(255) null,\n    machine_ip   varchar(20)  null,\n    share_time   datetime     null,\n    share_status int          null,\n    user_id      varchar(50)  null,\n    constraint t_share_info_pk\n        unique (id)\n)\n    comment '动态转发的基本信息表';\n\ncreate table t_shared_urls\n(\n    dyn_url     varchar(255) not null,\n    insert_time datetime     null,\n    update_time datetime     null,\n    status      varchar(50)  null,\n    user_id     varchar(20)  not null,\n    primary key (user_id, dyn_url)\n);\n\ncreate table t_statistics\n(\n    id          int auto_increment\n        primary key,\n    content     varchar(255) collate utf8_bin null,\n    insert_time datetime                      null,\n    note        varchar(500) collate utf8_bin null comment '备注',\n    user_id     varchar(50)                   null\n);\n\n"
  },
  {
    "path": "main.py",
    "content": "import time\nimport schedule\nfrom service.search_draw_dynamic_service.SearchDynamicByUps import SearchDynamicByUps\nfrom service.share_service.multi_users_share import MultiUsersShareService\nfrom utils import globals\n\n\ndef do_search():\n    SearchDynamicByUps(globals.my_user_id).init_search()\ndef do_share():\n    MultiUsersShareService().do_multi_uses_share()\n\nif __name__ == '__main__':\n    time.sleep(15)\n    do_search()\n    do_share()\n\n    schedule.every().day.at(\"15:42\").do(do_search)\n    schedule.every().day.at(\"15:45\").do(do_share)\n    while True:\n        try:\n            schedule.run_pending()\n            time.sleep(1)\n        except Exception as e:\n            time.sleep(1)\n\n\n\n"
  },
  {
    "path": "notify.py",
    "content": "from service.notify_service.notify_service import NotifyService\nfrom service.remove_share import RemoveShareService\nfrom service.statistics_service import StatisticsService\nfrom utils import globals\n\n\nif __name__ == '__main__':\n    cnt, content = StatisticsService().today_data()\n    NotifyService().fangtang_msg_push_by_content(title=\"每日统计\", content=content)\n    print('每日统计结果: ' + content)\n    RemoveShareService(globals.my_user_id, cnt=globals.remove_cnt).start_remove_service()\n"
  },
  {
    "path": "service/follow_service/cancel_follow_service.py",
    "content": "\n\nclass CancelFollowService(object):\n\n    def __init__(self):\n        print()"
  },
  {
    "path": "service/log_service/TextHandler.py",
    "content": "import logging\nimport tkinter as tk\n\n\nclass TextHandler(logging.Handler):\n    def __init__(self, text_widget):\n        super().__init__()\n        self.text_widget = text_widget\n\n    def emit(self, record):\n        log_msg = self.format(record) + \"\\n\"\n        self.text_widget.config(state=tk.NORMAL)\n        self.text_widget.insert(tk.END, log_msg)\n        self.text_widget.see(tk.END)\n        self.text_widget.config(state=tk.DISABLED)\n\n"
  },
  {
    "path": "service/log_service/log_printer_service.py",
    "content": "import logging\nimport time\nimport os\n\n\nclass MyLogger(object):\n\n    def __init__(self, name=None):\n        self.name = name\n        # ①创建一个记录器\n        self.logger = logging.getLogger(self.name)\n        self.logger.setLevel(\"INFO\")  # 设置日志级别为 'level'，即只有日志级别大于等于'level'的日志才会输出\n        self.formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")  # 创建formatter\n        # ②创建屏幕-输出到控制台，设置输出等级\n        self.streamHandler = logging.StreamHandler()\n        self.streamHandler.setLevel(\"INFO\")\n        # ③创建log文件，设置输出等级\n        PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 根目录\n        time_now = time.strftime('%Y_%m_%d_%H', time.localtime()) + '_err' + '.log'  # log文件命名：2022_04_02_21.log\n        self.fileHandler = logging.FileHandler(os.path.join('./', \"Log\", time_now ), 'a', encoding='utf-8')\n        self.fileHandler.setLevel(\"ERROR\")\n        # ④用formatter渲染这两个Handler\n        self.streamHandler.setFormatter(self.formatter)\n        self.fileHandler.setFormatter(self.formatter)\n        # ⑤将这两个Handler加入logger内\n        self.logger.addHandler(self.streamHandler)\n        self.logger.addHandler(self.fileHandler)\n\n    def getLogger(self):\n        return self.logger\n\n    def print_run_time(self, name, begin_time, end_time):\n        \"\"\"\n        计算运行时间\n        :param name:\n        :param begin_time:\n        :param end_time:\n        :return:\n        \"\"\"\n        run_time = round(end_time - begin_time)\n        # 计算时分秒\n        hour = run_time // 3600\n        minute = (run_time - 3600 * hour) // 60\n        second = run_time - 3600 * hour - 60 * minute\n        run_time_show = f'\\r\\n\\r\\n{name} 总共运行时间：{hour}小时{minute}分钟{second}秒'\n        return run_time_show\n"
  },
  {
    "path": "service/login_service/check_login_status.py",
    "content": "import logging\nimport os\nfrom utils.file_util import get_value_from_env\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef check_cookie_status():\n    try:\n        file_name = ''\n        if os.path.exists(os.path.join('./', '.env')):\n            # 加载 .env 文件\n            my_user_id_value = get_value_from_env(\".env\", \"my_user_id\")\n            file_name = my_user_id_value + '.txt'\n        if os.path.exists(os.path.join('./cookie', file_name)):\n            return True\n        else:\n            return False\n    except Exception as e:\n        return False\n"
  },
  {
    "path": "service/login_service/login_service.py",
    "content": "import json\nfrom time import sleep\nfrom urllib.parse import urlparse\nfrom selenium.webdriver.common.by import By\nfrom service.log_service.log_printer_service import MyLogger\nfrom utils import globals\nfrom utils.file_util import append_data_to_env\nfrom utils.time_util import random_sleep\nfrom utils.webdriver_util import ElementUtil, init_webdriver\n\nmylogger = MyLogger('login_service.py').getLogger()\n\n\nclass LoginService(object):\n    def __init__(self, bro, chains, my_user_id='0'):\n        self.bro = bro\n        self.chains = chains\n        self.my_user_id = my_user_id\n        mylogger.info('启动登录模块')\n\n    def login_manual(self):\n        self.bro.get(globals.home_url)\n        while ElementUtil.is_xpath_exist(self.bro, self.chains,\n                                         '//*[@id=\"i_cecream\"]/div[2]/div[1]/div[1]/ul[2]/li[1]/li/div') is True:\n            random_sleep()\n        dict_cookies = self.bro.get_cookies()\n        json_cookies = json.dumps(dict_cookies)\n        try:\n            url = self.bro.find_element(By.XPATH,\n                                        '//*[@id=\"i_cecream\"]/div[2]/div[1]/div[1]/ul[2]/li[1]/div[1]/a[1]').get_attribute(\n                \"href\")\n        except Exception as e:\n            print(e)\n        result = urlparse(url)\n        id = str(result[2])[1:]\n        cookie_path = './cookie/' + id + '.txt'\n        with open(cookie_path, 'w') as f:\n            f.write(json_cookies)\n\n    def login_by_cookie(self):\n        \"\"\"\n        根据保存的Cookie信息进行登录\n        :param bro:\n        :return:\n        \"\"\"\n        try:\n            self.bro.get(globals.home_url)\n            cookie_value = globals.cookie_value\n            cookie = {\"domain\": \".bilibili.com\", \"expiry\": 1717635533, \"name\": \"SESSDATA\", \"path\": \"/\", \"sameSite\": \"Lax\", \"value\": cookie_value}\n            self.bro.add_cookie(cookie)\n            self.bro.refresh()\n            mylogger.info('使用cookie自动登录成功！')\n            random_sleep(start=1, end=2)\n        except Exception as e:\n            mylogger.error('登录失败')\n            mylogger.error(\"[出错原因为：%s]\" % e)\n\n    def login_by_cookie2(self):\n        \"\"\"\n        根据保存的Cookie信息进行登录\n        :param bro:\n        :return:\n        \"\"\"\n        try:\n            cookie_path = './cookie/' + self.my_user_id + '.txt'\n            self.bro.get(globals.home_url)\n            with open(cookie_path, 'r', encoding='utf-8') as f:\n                cookies = f.readlines()\n            for cookie in cookies:\n                cookie = cookie.replace(r'\\n', '')\n                cookie_li = json.loads(cookie)\n                random_sleep(start=1, end=2)\n                for cookie in cookie_li:\n                    self.bro.add_cookie(cookie)\n                self.bro.refresh()\n            mylogger.info('使用cookie自动登录成功！')\n            random_sleep(start=1, end=2)\n        except Exception as e:\n            mylogger.error('登录失败')\n            mylogger.error(\"[出错原因为：%s]\" % e)\n"
  },
  {
    "path": "service/notify_service/notify_service.py",
    "content": "import requests\n\nfrom dao.init_db import init_db\nfrom dao.statistics_dao import StatisticsDao\nfrom utils import globals\n\nclass NotifyService(object):\n\n    def __init__(self):\n        self.key = globals.FangTang_KEY\n        self.statistics_dao = StatisticsDao(init_db())\n\n\n    def fangtang_msg_push(self):\n        \"\"\"\n        方糖\n        https://zhuanlan.zhihu.com/p/377659574\n        https://sct.ftqq.com/sendkey\n        :return:\n        \"\"\"\n        try:\n            self.text = self.statistics_dao.query_today_data()\n            url = 'https://sc.ftqq.com/%s.send' % self.key\n            requests.post(url, data={'text': \"程序通知\", 'desp': self.text})\n        except Exception as e:\n            print()\n\n    def fangtang_msg_push_by_content(self, title=\"\", content=\"\"):\n        \"\"\"\n        方糖\n        https://zhuanlan.zhihu.com/p/377659574\n        https://sct.ftqq.com/sendkey\n        :param key:\n        :return:\n        \"\"\"\n        try:\n            url = 'https://sc.ftqq.com/%s.send' % self.key\n            if globals.notify_switch == 'Y':\n                requests.post(url, data={'text': title, 'desp': content})\n        except Exception as e:\n            print()\n\n\nif __name__ == '__main__':\n    # NotifyService().fangtang_msg_push(key=\"b0e892e8856d5a45a415c739489b13b9\")\n    print()\n"
  },
  {
    "path": "service/remove_msg.py",
    "content": "import time\n\nfrom selenium.webdriver import ActionChains, Keys\n\nfrom service.log_service.log_printer_service import MyLogger\nfrom service.login_service.login_service import LoginService\nfrom utils.time_util import random_sleep\nfrom utils.webdriver_util import init_webdriver, ElementUtil\nfrom utils import globals\n\nmylogger = MyLogger('remove_msg.py').getLogger()\n\n\nclass RemoveMsgService(object):\n    \"\"\"\n    多用户转发模式\n    \"\"\"\n\n    def __init__(self, user_id, cnt, bro, chains):\n        self.user_id = user_id\n        self.cnt = cnt\n        self.bro = bro\n        self.chains = chains\n        mylogger.error('移除通知信息!')\n\n    def do_remove(self):\n        base_url = 'https://message.bilibili.com/?spm_id_from=333.1007.0.0#/whisper'\n        try:\n            # bro, chains = init_webdriver()\n            # LoginService(self.bro, self.chains, self.user_id).login_by_cookie()\n            self.bro.get(base_url)\n            first_dyn_element = ElementUtil.get_element_by_xpath(self.bro, self.chains,'//*[@id=\"link-message-container\"]/div[1]/div[2]/div[2]/div[1]/div/div/div[4]/div[2]/div[1]/div[1]')\n            # 创建ActionChains对象\n            actions = ActionChains(self.bro)\n            actions.move_to_element(first_dyn_element).perform()\n            # 循环滚动和点击\n            scroll_distance = 2\n            for i in range(self.cnt):  # 你可以根据需要设置循环次数\n                # 模拟滚轮滚动\n                ActionChains(self.bro).send_keys(Keys.ARROW_DOWN * scroll_distance).perform()\n                # 等待一段时间，确保页面有足够的时间进行滚动\n                time.sleep(1)\n                ActionChains(self.bro).click().perform()\n                random_sleep(start=1, end=5)\n        except:\n            mylogger.error(\"[移除通知信息流程 出错]\")\n        finally:\n            print(1)\n\nif __name__ == '__main__':\n    RemoveMsgService(globals.my_user_id).do_remove()\n"
  },
  {
    "path": "service/remove_share.py",
    "content": "import time\n\nfrom selenium.webdriver import ActionChains, Keys\n\nfrom dao.init_db import init_db\nfrom dao.shared_url_dao import SharedUrlDao\nfrom service.log_service.log_printer_service import MyLogger\nfrom service.login_service.login_service import LoginService\nfrom utils.time_util import random_sleep\nfrom utils.webdriver_util import init_webdriver, ElementUtil\nfrom utils import globals\n\nmylogger = MyLogger('remove_share.py').getLogger()\n\n\nclass RemoveShareService(object):\n    \"\"\"\n    多用户转发模式\n    \"\"\"\n\n    def __init__(self, user_id, cnt=None, bro=None, chains=None):\n        self.user_id = user_id\n        self.db = init_db()\n        self.sharedUrlDao = SharedUrlDao(self.db)\n        if bro is None:\n            self.bro, self.chains = init_webdriver()\n            LoginService(self.bro, self.chains, self.user_id).login_by_cookie()\n        else:\n            self.bro = bro\n            self.chains = chains\n        self.cnt = cnt\n        mylogger.error('移除通知信息!')\n\n    def get_expired_url(self, scroll_cnt):\n        base_url = 'https://space.bilibili.com/385649497/dynamic'\n        try:\n            self.bro.get(base_url)\n            scroll_path = '//*[@id=\"page-dynamic\"]'\n            first_dyn_element = ElementUtil.get_element_by_xpath(self.bro, self.chains, scroll_path)\n            # 创建ActionChains对象\n            actions = ActionChains(self.bro)\n            actions.move_to_element(first_dyn_element).perform()\n            # 循环滚动和点击\n            scroll_distance = 400\n            for i in range(scroll_cnt):  # 你可以根据需要设置循环次数\n                # 模拟滚轮滚动\n                ActionChains(self.bro).send_keys(Keys.ARROW_DOWN * scroll_distance).perform()\n                random_sleep(start=1, end=4)\n\n            div_elements = self.bro.find_elements_by_xpath(\"//div[@class='bili-dyn-more__menu__item']\")\n            # 遍历每个<div>元素，检查是否包含data-params属性，并提取dynamic_id的值\n            for div_element in div_elements:\n                class_attribute = div_element.get_attribute(\"class\")\n                data_params_attribute = div_element.get_attribute(\"data-params\")\n                # 检查是否包含class=\"bili-dyn-more__menu__item\"以及data-params属性\n                if \"bili-dyn-more__menu__item\" in class_attribute and data_params_attribute:\n                    # 提取dynamic_id的值\n                    dynamic_id_start = data_params_attribute.find('\"dynamic_id\"') + len('\"dynamic_id\"') + 1\n                    dynamic_id_end = data_params_attribute.find('\"', dynamic_id_start + 1)\n                    dynamic_id_value = data_params_attribute[dynamic_id_start + 1:dynamic_id_end].strip()\n                    if dynamic_id_value != '':\n                        url = 'https://www.bilibili.com/opus/' + dynamic_id_value\n                        self.sharedUrlDao.insert_sharedUrl(self.user_id, url)\n        except Exception as e:\n            mylogger.error(\"[获取过期动态流程 出错 %s]\" % e, exc_info=True)\n\n    def do_remove(self):\n        \"\"\"\n        批量删除过期url\n        :return:\n        \"\"\"\n        try:\n            datas = self.sharedUrlDao.query_sharedUrls_limit(self.user_id, '0', self.cnt)\n            for data in datas:\n                lucky_dynamic_url = data['dyn_url']\n                self.remove_one(lucky_dynamic_url)\n        except:\n            mylogger.error(\"[do_remove 批量删除过期url 出错]\")\n\n    def remove_one(self, lucky_dynamic_url):\n        \"\"\"\n        移除一个过期url\n        :param lucky_dynamic_url: 需要进行转发的抽奖动态的URL\n        :return:\n        \"\"\"\n        try:\n            self.bro.get(lucky_dynamic_url)\n            self.bro.refresh()\n            ElementUtil.wait_to_go(self.bro)\n            self.click_delete(self.bro, self.chains)\n            random_sleep()\n            # 回填状态\n            self.sharedUrlDao.update_sharedUrl(self.user_id, lucky_dynamic_url, '1')\n        except Exception as e:\n            mylogger.error(\"remove_one 移除一个过期url 出错url : \" + lucky_dynamic_url)\n        finally:\n            mylogger.info('移除一个过期url--执行结束')\n\n    def click_delete(self, bro, chains):\n        \"\"\"\n        点赞\n        :param bro:\n        :param chains:\n        :return:\n        \"\"\"\n        try:\n            find_path = '//*[@id=\"app\"]/div[3]/div/div/div[1]/div[2]/div[4]/div'\n            find_path_ele = ElementUtil.get_element_by_xpath(bro, chains, find_path)\n            chains.click(find_path_ele).perform()\n            random_sleep(start=1, end=3)\n\n            delete_path = '//*[@id=\"app\"]/div[3]/div/div/div[1]/div[2]/div[4]/div/div'\n            delete_path_ele = ElementUtil.get_element_by_xpath(bro, chains, delete_path)\n            chains.click(delete_path_ele).perform()\n            random_sleep(start=1, end=3)\n\n            do_delete_path = '/html/body/div[4]/div[2]/div[4]/button[2]'\n            do_delete_ele = ElementUtil.get_element_by_xpath(bro, chains, do_delete_path)\n            chains.click(do_delete_ele).perform()\n            random_sleep(start=1, end=3)\n\n        except Exception as e:\n            mylogger.error(\"[click_like 点击“删除” 出错 %s]\" % e, exc_info=True)\n            raise\n\n    def quilt_bro(self):\n        self.bro.quit()\n\n    def start_remove_service(self):\n        if globals.is_remove == 'Y':\n            self.do_remove()\n            self.get_expired_url(10)\n            self.quilt_bro()\n        else:\n            mylogger.error(\"移除过期url开关未打开\")\n"
  },
  {
    "path": "service/search_draw_dynamic_service/SearchDynamicByUps.py",
    "content": "import time\nfrom datetime import datetime\n\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom dao.draw_dynamic_dao import DrawDynamicDao\nfrom dao.init_db import init_db\nfrom dao.statistics_dao import StatisticsDao\nfrom service.log_service.log_printer_service import MyLogger\nfrom service.login_service.login_service import LoginService\nfrom service.notify_service.notify_service import NotifyService\nfrom utils.ip_util import remove_query_string\nfrom utils.time_util import random_sleep\nfrom utils.webdriver_util import init_webdriver, ElementUtil\nfrom utils import globals\nmylogger = MyLogger('SearchDynamicByUps.py').getLogger()\n\n\nclass SearchDynamicByUps(object):\n\n    def __init__(self, user_id):\n        self.count = 0\n        self.user_id = user_id\n        self.search_note = \"\"\n        db = init_db()\n        self.draw_dynamic_dao = DrawDynamicDao(db)\n        self.statistics_dao = StatisticsDao(db)\n\n\n    def searchFromFiftyUps(self, bro, chains):\n        \"\"\"\n        up主：你的工具人老公\n        up主链接：https://space.bilibili.com/100680137/dynamic\n        来源：https://space.bilibili.com/100680137/dynamic\n        :return:\n        \"\"\"\n        base_url = 'https://space.bilibili.com/100680137/dynamic'\n        try:\n            # 前往主页\n            bro.get(base_url)\n            bro.refresh()\n            pathOne = '//*[@id=\"page-dynamic\"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div/div[2]'\n            first_dyn_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)\n            first_dyn_element.click()\n            ElementUtil.wait_to_go(bro)\n            bro.switch_to.window(bro.window_handles[-1])\n            bro.refresh()\n            random_sleep()\n            # 到达动态列表页\n            source_url = bro.current_url\n            # 获取链接所在的块\n            all_links_ele = ElementUtil.get_element_by_xpath(bro, chains, '/html/body/div[3]/div/div[3]/div[1]/div[4]/div')\n            # 在<div>元素下找到所有<a>标签元素\n            link_elements = all_links_ele.find_elements_by_xpath(\".//a\")\n            links = [element.get_attribute(\"href\") for element in link_elements]\n            self.dynLinks_to_db(links, remove_query_string(source_url), \"你的工具人老公\")\n        except Exception as e:\n            mylogger.error(\"[searchFromFiftyUps 从“你的工具人老公”查找抽奖动态 出错 %s]\" % e, exc_info=True)\n            NotifyService().fangtang_msg_push_by_content(title=\"“你的工具人老公”查找抽奖动态出错\", content='从“你的工具人老公”查找抽奖动态 出错')\n\n    def searchFromBigFish(self, bro, chains):\n        \"\"\"\n        up主：_大锦鲤_\n        up主链接：https://space.bilibili.com/226257459/dynamic\n        :return:\n        \"\"\"\n        base_url = 'https://space.bilibili.com/226257459/dynamic'\n        try:\n            bro.get(base_url)\n            bro.refresh()\n            pathOne = '//*[@id=\"page-dynamic\"]/div[1]/div/div[1]/div[1]/div/div/div[3]/div/div/div/div'\n            base_link_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)\n            base_link_element.click()\n            WebDriverWait(bro, 10).until(EC.new_window_is_opened)\n            bro.switch_to.window(bro.window_handles[-1])\n            bro.refresh()\n            random_sleep()\n            # 到达动态列表页\n            source_url = bro.current_url\n            # 获取这些<a>标签的href属性值\n            elements = ElementUtil.get_elementArr_by_xpath(bro, chains, '//a[contains(text(), \"网页链接\")]')\n            links = [element.get_attribute(\"href\") for element in elements]\n            filtered_links = [link for link in links if \"mall.bilibili\" not in link]\n            self.dynLinks_to_db(filtered_links, remove_query_string(source_url), \"_大锦鲤_\")\n        except Exception as e:\n            mylogger.error(\"[searchFromBigFish 从“_大锦鲤_”查找抽奖动态 出错 %s]\" % e, exc_info=True)\n            NotifyService().fangtang_msg_push_by_content(title=\"“_大锦鲤_”查找抽奖动态出错\", content='从“_大锦鲤_”查找抽奖动态 出错')\n\n    def searchFromCarcinus_(self, bro, chains):\n        \"\"\"\n        up主：Carcinus_\n        up主链接：https://space.bilibili.com/27332255/dynamic\n        :return:\n        \"\"\"\n        base_url = 'https://space.bilibili.com/27332255/dynamic'\n        try:\n            bro.get(base_url)\n            bro.refresh()\n            pathOne = '//*[@id=\"page-dynamic\"]/div[1]/div/div[1]/div[1]/div/div/div[3]/div/div/div/div/div[1]'\n            base_link_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)\n            base_link_element.click()\n            WebDriverWait(bro, 10).until(EC.new_window_is_opened)\n            bro.switch_to.window(bro.window_handles[-1])\n            bro.refresh()\n            random_sleep()\n            # 到达动态列表页\n            source_url = bro.current_url\n            # 获取这些<a>标签的href属性值\n            elements = ElementUtil.get_elementArr_by_xpath(bro, chains, '//a[contains(text(), \"LINK\")]')\n            links = [element.get_attribute(\"href\") for element in elements]\n            self.dynLinks_to_db(links, remove_query_string(source_url), \"Carcinus_\")\n        except Exception as e:\n            mylogger.error(\"[searchFromCarcinus_ 从“Carcinus_”查找抽奖动态 出错 %s]\" % e, exc_info=True)\n            NotifyService().fangtang_msg_push_by_content(title=\"“Carcinus_”查找抽奖动态出错\", content='从“Carcinus_”查找抽奖动态 出错')\n\n    def searchFromSmile(self, bro, chains):\n        \"\"\"\n        up主：闻不着味\n        up主链接：https://space.bilibili.com/280025263/dynamic\n        :return:\n        \"\"\"\n        base_url = 'https://space.bilibili.com/280025263/dynamic'\n        try:\n            bro.get(base_url)\n            bro.refresh()\n            pathOne = self.find_first_ele(bro, chains)\n            base_link_element = ElementUtil.get_element_by_xpath(bro, chains, pathOne)\n            base_link_element.click()\n            WebDriverWait(bro, 10).until(EC.new_window_is_opened)\n            bro.switch_to.window(bro.window_handles[-1])\n            bro.refresh()\n            random_sleep()\n            # 到达动态列表页\n            source_url = bro.current_url\n            # 获取这些<a>标签的href属性值\n            elements = ElementUtil.get_elementArr_by_xpath(bro, chains, '//a[contains(text(), \"http\")]')\n            links = [element.get_attribute(\"href\") for element in elements]\n            self.dynLinks_to_db(links, remove_query_string(source_url), \"闻不着味\")\n        except Exception as e:\n            mylogger.error(\"[searchFromSmile 从“闻不着味”查找抽奖动态 出错 %s]\" % e, exc_info=True)\n            NotifyService().fangtang_msg_push_by_content(title=\"“闻不着味”查找抽奖动态出错\", content='从“闻不着味”查找抽奖动态 出错')\n\n    def find_first_ele(self, bro, chains):\n        pathOnes = [\n            '//*[@id=\"page-dynamic\"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div/div[1]'\n            '//*[@id=\"page-dynamic\"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div',\n            '//*[@id=\"page-dynamic\"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div/div/div/div[2]',\n            '//*[@id=\"page-dynamic\"]/div[1]/div/div[1]/div[1]/div/div[2]/div[3]/div/div[3]/div[2]/div/div[1]',\n        ]\n        for pathOne in pathOnes:\n            if ElementUtil.is_xpath_exist(bro, chains,pathOne):\n                return pathOne\n        return None;\n\n    def dynLinks_to_db(self, dynLinks, source, note):\n        cnt = 0\n        break_flag = 0\n        ignore_links = self.get_ignore_link()\n        for link in dynLinks:\n            try:\n                # 跳过非抽奖动态\n                for ign_lnk in ignore_links:\n                    if ign_lnk in link:\n                        break_flag = 1\n                if break_flag == 1:\n                    break_flag = 0\n                    continue\n                break_flag = 0\n                # 跳过已经入库的\n                if len(self.draw_dynamic_dao.query_by_dyn_url(remove_query_string(link))) == 0:\n                    self.draw_dynamic_dao.insert(remove_query_string(link), source, note)\n                    cnt = cnt + 1\n            except Exception as e:\n                mylogger.error(\"[dynLinks_to_db 动态插入数据库 出错 %s]\" % e, exc_info=True)\n        self.count = self.count + cnt\n        self.search_note = self.search_note + note + \":\" + str(cnt) + \";  \"\n\n    def get_ignore_link(self):\n        links = globals.ignore_link\n        if len(links) != 0:\n            return links.split('|')\n        return {}\n\n    def init_search(self):\n        bro = None\n        try:\n            bro, chains = init_webdriver()\n            LoginService(bro, chains, self.user_id).login_by_cookie()\n            if \"你的工具人老公\" in globals.ups:\n                self.searchFromFiftyUps(bro, chains)\n            if \"_大锦鲤_\" in globals.ups:\n                self.searchFromBigFish(bro, chains)\n            if \"Carcinus_\" in globals.ups:\n                self.searchFromCarcinus_(bro, chains)\n            if \"闻不着味\" in globals.ups:\n                self.searchFromSmile(bro, chains)\n            # 统计入库\n            self.statistics_dao.insert(\"\", \"搜索到的抽奖动态条数为: \" + str(self.count), self.search_note)\n        except:\n            mylogger.error(\"[搜索抽奖动态列表主流程 出错]\")\n        finally:\n            bro.quit()\n\n\nif __name__ == '__main__':\n    SearchDynamicByUps().init_search()\n"
  },
  {
    "path": "service/share_service/cancel_share_service.py",
    "content": "\nclass CancelShareService(object):\n\n    def __init__(self):\n        print()"
  },
  {
    "path": "service/share_service/multi_users_share.py",
    "content": "from service.log_service.log_printer_service import MyLogger\nfrom service.search_draw_dynamic_service.SearchDynamicByUps import SearchDynamicByUps\nfrom service.share_service.share_from_biliLink import BiliLinkShare\nfrom utils import globals\n\nmylogger = MyLogger('multi_users_share.py').getLogger()\n\n\nclass MultiUsersShareService(object):\n    \"\"\"\n    多用户转发模式\n    \"\"\"\n\n    def __init__(self):\n        mylogger.error('启动多用户转发模式!')\n\n\n    def do_multi_uses_share(self):\n        try:\n            users = self.get_multi_uses()\n            for user in users:\n                mylogger.error('用户: ' + user + '开始转发动态.')\n                BiliLinkShare(user).do_share_by_links()\n        except Exception as e:\n            mylogger.error(\"[do_multi_uses_share 多用户模式转发动态 出错 %s]\" % e, exc_info=True)\n\n    def get_multi_uses(self):\n        users = globals.multi_users\n        if len(users) != 0:\n            return users.split('|')\n        return {}\n"
  },
  {
    "path": "service/share_service/share_from_biliLink.py",
    "content": "from datetime import datetime\n\nfrom dao.draw_dynamic_dao import DrawDynamicDao\nfrom dao.follow_up_dao import FollowUpInfoDao\nfrom dao.init_db import init_db\nfrom dao.share_info_dao import ShareInfoDao\nfrom dao.statistics_dao import StatisticsDao\nfrom service.log_service.log_printer_service import MyLogger\nfrom service.login_service.login_service import LoginService\nfrom service.notify_service.notify_service import NotifyService\nfrom service.remove_msg import RemoveMsgService\nfrom service.share_service.share_one_dynamic import DynamicShareBase\nfrom utils import globals\nfrom utils.globals import get_random_comment_content, get_random_share_content\nfrom utils.ip_util import remove_query_string\nfrom utils.webdriver_util import init_webdriver\n\nmylogger = MyLogger('share_from_biliLick.py').getLogger()\n\n\nclass BiliLinkShare(object):\n    def __init__(self, user_id, bro=None, chains=None):\n        db = init_db()\n        self.share_note = \"\"\n        self.user_id = user_id\n        if bro is None:\n            self.bro, self.chains = init_webdriver()\n        else:\n            self.bro = bro\n            self.chains = chains\n        self.share_info_dao = ShareInfoDao(db)\n        self.follow_up_dao = FollowUpInfoDao(db)\n        self.draw_dynamic_dao = DrawDynamicDao(db)\n        self.statistics_dao = StatisticsDao(db)\n        mylogger.error(\"启动：根据B站up主的分享链接进行抽奖动态转发!\")\n\n    def do_share_by_links(self):\n        do_share_cnt = 0\n        success_share_cnt = 0\n        break_flag = 0\n        try:\n            LoginService(self.bro, self.chains, self.user_id).login_by_cookie()\n            datas = self.get_today_dynamic_links()\n            ignore_links = self.get_ignore_link()\n            for data in datas:\n                lucky_dynamic_url = remove_query_string(data['dyn_url'])\n                # lucky_dynamic_url = 'https://www.bilibili.com/opus/886341319897645089'\n                for ign_lnk in ignore_links:\n                    if ign_lnk in lucky_dynamic_url:\n                        break_flag = 1\n                # 跳过已经转发过的\n                if break_flag == 1:\n                    break_flag = 0\n                    continue\n                break_flag = 0\n                shared = self.share_info_dao.query_shareInfo_by_shareUrl(lucky_dynamic_url, self.user_id)\n                if len(shared) != 0:\n                    continue\n                do_share_cnt = do_share_cnt + 1\n                dyn = DynamicShareBase()\n                dyn.user_id = self.user_id\n                dyn.share_one(self.bro, self.chains, lucky_dynamic_url, get_random_share_content(), get_random_comment_content())\n                # 保存转发状态和关注的up主信息\n                if dyn.share_status == 0:\n                    self.draw_dynamic_dao.update_sharedUrl(url=lucky_dynamic_url, status=1)\n                    self.share_info_dao.insert_shareInfo(dyn)\n                    self.follow_up_dao.saverUpdate(dyn.upId, dyn.upUrl, self.user_id)\n                    success_share_cnt = success_share_cnt + 1\n        except:\n            mylogger.error(\"[do_share_by_links 根据url转发动态 出错]\")\n        finally:\n            if do_share_cnt == 0:\n                percentage = 0\n            else:\n                percentage = (success_share_cnt / do_share_cnt) * 100\n            succ_percentage = f\"成功率为 : {percentage:.2f}%\"\n            content = \" 成功的转发条数为：\" + str(success_share_cnt) + \";\" + succ_percentage\n            if 50 > percentage > 0:\n                NotifyService().fangtang_msg_push_by_content(title=\"程序预警，需要处理！\", content=content)\n            self.statistics_dao.insert(self.user_id, content, \"\")\n            # 暂时停止移除\n            # RemoveMsgService(self.user_id, success_share_cnt, bro=self.bro, chains=self.chains).do_remove()\n            self.bro.quit()\n\n    def get_ignore_link(self):\n        links = globals.ignore_link\n        if len(links) != 0:\n            return links.split('|')\n        return {}\n\n    def get_today_dynamic_links(self):\n        \"\"\"\n        从数据库中获取当天的分享链接\n        :return:\n        \"\"\"\n        today = str(datetime.now().strftime(\"%Y-%m-%d\"))\n        return self.draw_dynamic_dao.query_by_time(today, limit=60, status=0)\n\n"
  },
  {
    "path": "service/share_service/share_one_dynamic.py",
    "content": "import time\nfrom datetime import datetime\nfrom service.log_service.log_printer_service import MyLogger\nfrom utils.ip_util import get_host_ip, get_partContent_from_lick\nfrom utils.time_util import random_sleep\nfrom utils.webdriver_util import ElementUtil\n\nmylogger = MyLogger('share_one_dynamic.py').getLogger()\n\n\nclass DynamicShareBase(object):\n\n    def __init__(self):\n        # 公有属性，可以在类外部访问\n        self.upId = None\n        self.upUrl = None\n        self.share_url = None\n        self.status = 1\n        self.machine_ip = None\n        self.share_time = None\n        self.share_status = 1\n        self.user_id = None\n\n    def share_one(self, bro, chains, lucky_dynamic_url, share_content, comment_content):\n        \"\"\"\n        提供需要转发的抽奖动态URL，然后“执行状态、up主的ID、up主的主页URL”等信息\n        :param bro:\n        :param chains:\n        :param lucky_dynamic_url: 需要进行转发的抽奖动态的URL\n        :return:\n        \"\"\"\n        try:\n            bro.get(lucky_dynamic_url)\n            bro.refresh()\n            ElementUtil.wait_to_go(bro)\n            # 新版转旧版本\n            self.to_old_version(bro, chains)\n            # 点击关注\n            self.click_follow(bro, chains)\n            random_sleep()\n            # 点赞\n            self.click_like(bro, chains)\n            random_sleep()\n            # 预约抽奖\n            self.click_reserve(bro, chains)\n            random_sleep()\n            # 评论\n            self.commit_comment(bro, chains, comment_content)\n            random_sleep()\n            # 移动到“分享”按钮, 点击“转发”\n            self.click_share(bro, chains, share_content)\n            random_sleep()\n            # 回填状态\n            self.share_status = 0\n            self.status = 0\n            self.share_url = lucky_dynamic_url\n        except Exception as e:\n            mylogger.error(\"share_one 转发单条动态主流程 出错url : \" + lucky_dynamic_url)\n        finally:\n            self.share_time = str(datetime.now())\n            self.machine_ip = get_host_ip()\n            mylogger.info('单条动态转发--执行结束')\n\n    def click_follow(self, bro, chains):\n        \"\"\"\n        点击关注，并且返回相关的up主信息\n        :param bro:\n        :param chains:\n        :return:\n        \"\"\"\n        try:\n            username = ElementUtil.get_element_by_xpath(bro, chains,\n                                                        '//*[@id=\"app\"]/div[3]/div/div/div[1]/div[2]/div[1]/span')\n            # 跳转到新页面（up主的主页）\n            username.click()\n            ElementUtil.wait_to_go(bro)\n            bro.switch_to.window(bro.window_handles[-1])\n            bro.refresh()\n            random_sleep()\n            current_url = bro.current_url\n            user_id = get_partContent_from_lick(current_url)\n            self.upId = str(user_id)\n            self.upUrl = 'https://space.bilibili.com/' + self.upId\n            # 是否包含“已关注”标签\n            has_followd = ElementUtil.get_element_by_xpath(bro, chains,\n                                                           '//*[@id=\"app\"]/div[1]/div[1]/div[2]/div[4]/div[1]/div')\n            if \"已关注\" not in has_followd.get_attribute('innerText'):\n                do_follow_btn = ElementUtil.get_element_by_xpath(bro, chains,\n                                                                 '//*[@id=\"app\"]/div[1]/div[1]/div[2]/div[4]/span')\n                chains.click(do_follow_btn).perform()\n            bro.close()\n            bro.switch_to.window(bro.window_handles[-1])\n        except Exception as e:\n            mylogger.error(\"[click_follow 点击“关注” 出错 %s]\" % e, exc_info=True)\n            # 将异常传递给上一级函数\n            raise\n\n    def click_like(self, bro, chains):\n        \"\"\"\n        点赞\n        :param bro:\n        :param chains:\n        :return:\n        \"\"\"\n        try:\n            path = '//*[@id=\"app\"]/div[3]/div[2]/div/div[1]/div[1]'\n            like_btn_old = ElementUtil.get_element_by_xpath(bro, chains, path)\n            chains.click(like_btn_old).perform()\n        except Exception as e:\n            mylogger.error(\"[click_like 点击“点赞” 出错 %s]\" % e, exc_info=True)\n            raise\n\n\n    def click_reserve(self, bro, chains):\n        \"\"\"\n        预约抽奖\n        :param bro:\n        :param chains:\n        :return:\n        \"\"\"\n        try:\n            reserve_path = '//*[@id=\"app\"]/div[3]/div[1]/div[1]/div/div[3]/div/div/div[3]/div/div/div[2]/button'\n            if ElementUtil.is_xpath_exist(bro, chains, reserve_path):\n                reserve_btn = ElementUtil.get_element_by_xpath(bro, chains, reserve_path)\n                chains.click(reserve_btn).perform()\n        except Exception as e:\n            mylogger.error(\"[click_like 点击“预约抽奖” 出错 %s]\" % e, exc_info=True)\n            raise\n\n    def commit_comment(self, bro, chains, comment_content):\n        \"\"\"\n        评论\n        :param comment_content:\n        :param bro:\n        :param chains:\n        :return:\n        \"\"\"\n        try:\n            comment_old = ElementUtil.get_element_by_xpath(bro, chains,\n                '//*[@id=\"app\"]/div[3]/div[1]/div[2]/div[2]/div[1]/div/div/div/div/div[2]/div[1]/div/div[1]/div[2]/div')\n            chains.click(comment_old).perform()\n            comment_xx_path = '//*[@id=\"app\"]/div[3]/div[1]/div[2]/div[2]/div[1]/div/div/div/div/div[2]/div[1]/div/div[1]/div[2]/div/textarea'\n            comment_cont = ElementUtil.get_element_by_xpath(bro, chains,comment_xx_path)\n            comment_cont.send_keys(\"\" + str(comment_content))\n            commit_btn_old = ElementUtil.get_element_by_xpath(bro, chains,\n                            '//*[@id=\"app\"]/div[3]/div[1]/div[2]/div[2]/div[1]/div/div/div/div/div[2]/div[1]/div/div[2]/div[2]/div')\n            chains.click(commit_btn_old).perform()\n        except Exception as e:\n            mylogger.error(\"[commit_comment 点击“评论” 出错 %s]\" % e, exc_info=True)\n            raise\n\n    def click_share(self, bro, chains, share_content):\n        \"\"\"\n        执行转发动态\n        :param bro:\n        :param chains:\n        :return:\n        \"\"\"\n        try:\n            share_btn_old = ElementUtil.get_element_by_xpath(bro, chains,\n                                                    '//*[@id=\"app\"]/div[3]/div[2]/div/div[1]/div[2]')\n            chains.click(share_btn_old).perform()\n            share_text_old = ElementUtil.get_element_by_xpath(bro, chains,\n                        '/html/body/div[4]/div[2]/div[1]/div/div[3]/div[1]/div')\n            share_text_old.send_keys(share_content)\n            do_share_btn_old = ElementUtil.get_element_by_xpath(bro, chains,\n                            '/html/body/div[4]/div[2]/div[1]/div/div[5]/div[2]/div[2]')\n            chains.click(do_share_btn_old).perform()\n            random_sleep()\n        except Exception as e:\n            mylogger.error(\"[click_share 点击“分享” 出错 %s]\" % e, exc_info=True)\n            raise\n\n    def to_old_version(self, bro, chains):\n        \"\"\"\n        新版转旧版\n        :param bro:\n        :param chains:\n        :return:\n        \"\"\"\n        if ElementUtil.is_xpath_exist(bro, chains, '//*[@id=\"app\"]/div[4]/div[3]/div/div[2]/div[1]') is True:\n            to_old_btn = ElementUtil.get_element_by_xpath(bro, chains,\n                                                          '//*[@id=\"app\"]/div[4]/div[3]/div/div[2]/div[1]')\n            to_old_btn.click()\n            ElementUtil.wait_to_go(bro)\n"
  },
  {
    "path": "service/statistics_service.py",
    "content": "from datetime import datetime\nfrom dao.draw_dynamic_dao import DrawDynamicDao\nfrom dao.init_db import init_db\nfrom dao.share_info_dao import ShareInfoDao\nfrom utils import globals\n\n\nclass StatisticsService(object):\n\n    def __init__(self):\n        db = init_db()\n        self.share_info_dao = ShareInfoDao(db)\n        self.dyn_dao = DrawDynamicDao(db)\n\n    def get_today_searchData(self):\n        try:\n            # 获取今天的日期\n            today = datetime.now()\n            today_str = today.strftime(\"%Y-%m-%d\")\n            return self.dyn_dao.query_by_time(today_str, status=1)\n        except Exception as e:\n            return {}\n\n    def get_today_shareData_by_usrId(self, user_id):\n        try:\n            # 获取今天的日期\n            today = datetime.now()\n            today_str = today.strftime(\"%Y-%m-%d\")\n            return self.share_info_dao.query_shareInfo_by_userIdAndTime(user_id, today_str)\n        except Exception as e:\n            return {}\n\n    def today_data(self):\n        userIds = self.get_multi_uses()\n        content = \"今日数据汇总: \" + \"\\n\\n\"\n\n        content = content + \"1.抽奖动态搜索数量: \" + str(len(self.get_today_searchData())) + \";\\n\\n\"\n        content = content + \"2.动态转发情况: \" + \"\\n\\n\"\n        for user_id in userIds:\n            content = content + \"\\t\\t\" + user_id + \":\" + \"成功转发数量:\" + str(len(self.get_today_shareData_by_usrId(user_id))) + \";\\n\\n\"\n        content = content + \"\\n\\n\"\n        cnt = len(userIds)\n        return cnt, content\n\n    def get_multi_uses(self):\n        users = globals.multi_users\n        if len(users) != 0:\n            return users.split('|')\n        return {}\n"
  },
  {
    "path": "utils/file_util.py",
    "content": "\ndef get_value_from_env(file_path, key):\n    with open(file_path, \"r\") as f:\n        for line in f:\n            # 去除换行符和空格，并以等号分割键值对\n            key_value = line.strip().split(\"=\")\n            if len(key_value) == 2 and key_value[0] == key:\n                return key_value[1]\n    return None\n\n\ndef append_data_to_env(key, data_to_append):\n    # 读取.env文件内容\n    with open(\".env\", \"r\") as f:\n        lines = f.readlines()\n\n    # 查找包含key的行并在等号后面追加内容\n    with open(\".env\", \"w\") as f:\n        for line in lines:\n            if line.strip().startswith(f\"{key}=\"):\n                line = f\"{key}={line.strip().split('=')[1]}{data_to_append}\\n\"\n            f.write(line)"
  },
  {
    "path": "utils/globals.py",
    "content": "import os\nimport random\n\nfrom dotenv import load_dotenv\n\nfrom utils.ip_util import get_host_ip\n\n# 加载 .env 文件\nload_dotenv()\n# 读取变量\nmax_checks = int(os.getenv(\"max_checks\"))\nhome_url = os.getenv(\"home_url\")\nmy_user_id = os.getenv(\"my_user_id\")\nignore_link = os.getenv(\"ignore_link\")\nmulti_users = os.getenv(\"multi_users\")\ndo_type = os.getenv(\"do_type\")\nis_remove = os.getenv(\"is_remove\")\nremove_cnt = os.getenv(\"remove_cnt\")\ncookie_value = os.getenv(\"cookie_value\")\n# 读取变量\ndbname = os.getenv(\"MYSQL_DATABASE\")\nuser = os.getenv(\"MYSQL_USER\")\npasswd = os.getenv(\"MYSQL_PASSWORD\")\nroot_passwd = os.getenv(\"MYSQL_ROOT_PASSWORD\")\nport = int(os.getenv(\"PORT\"))\ncharset = 'utf8'\n\nnotify_switch = os.getenv(\"notify_switch\")\nFangTang_KEY = os.getenv(\"FangTang_KEY\")\nDRIVER_VERSION = os.getenv(\"DRIVER_VERSION\")\n\n\ndef getHost():\n    host = get_infos(\"DB_HOST\")\n    print(host)\n    if len(host) != 0:\n        return host\n    return get_host_ip()\n\n\ndef get_infos(str):\n    users = os.getenv(str)\n    return users\n\n\ndef get_random_comment_content():\n    comments = get_multi_infos(\"comment_content\")\n    return get_random_from_list(comments)\n\n\ndef get_random_share_content():\n    shares = get_multi_infos(\"share_content\")\n    return get_random_from_list(shares)\n\n\ndef get_multi_infos(str):\n    users = os.getenv(str)\n    if len(users) != 0:\n        return users.split('|')\n    return {}\n\n\ndef get_random_from_list(list):\n    if len(list) != 0:\n        return random.choice(list)\n    return \"_\"\n\n\nshare_content = get_random_share_content()\ncomment_content = get_random_comment_content()\nups = get_multi_infos(\"ups\")\ndb_host = getHost()\nselenium_url = \"http://\" + getHost() + \":5555\"\n\nif __name__ == '__main__':\n    print(db_host)\n    print(selenium_url)\n"
  },
  {
    "path": "utils/ip_util.py",
    "content": "import socket\n\ndef get_host_ip():\n    \"\"\"\n    查询本机ip地址\n    :return: ip\n    \"\"\"\n    try:\n        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n        s.connect(('8.8.8.8', 80))\n        ip = s.getsockname()[0]\n    finally:\n        s.close()\n    return ip\n\n\ndef get_partContent_from_lick(current_url):\n    user_id = '0'\n    parts = current_url.split('/')\n    if len(parts) > 1:\n        user_id = parts[3]\n    return user_id\n\ndef remove_query_string(url):\n    question_mark_index = url.find('?')\n\n    if question_mark_index != -1:\n        # 如果包含问号，则去掉问号及其后面的内容\n        url_without_query = url[:question_mark_index]\n        return url_without_query\n    else:\n        # 如果不包含问号，则返回原始url\n        return url"
  },
  {
    "path": "utils/mysql_operate.py",
    "content": "import pymysql\n\nclass MysqldbHelper():\n\n    def __init__(self, config):\n        self.host = config['host']\n        self.username = config['user']\n        self.password = config['passwd']\n        self.port = config['port']\n        self.con = None\n        self.cur = None\n\n        try:\n            self.con = pymysql.connect(**config)\n            self.con.autocommit(1)\n            # 所有的查询，都在连接 con 的一个模块 cursor 上面运行的\n            self.cur = self.con.cursor()\n        except:\n            print(\"DataBase connect error,please check the db config.\")\n\n    # 关闭数据库连接\n    def close(self):\n        if not self.con:\n            self.con.close()\n        else:\n            print(\"DataBase doesn't connect,close connectiong error;please check the db config.\")\n\n    # 创建数据库\n    def createDataBase(self, DB_NAME):\n        # 创建数据库\n        self.cur.execute(\n            'CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci' % DB_NAME)\n        self.con.select_db(DB_NAME)\n        print('creatDatabase:' + DB_NAME)\n\n    # 选择数据库\n    def selectDataBase(self, DB_NAME):\n        self.con.select_db(DB_NAME)\n\n    # 获取数据库版本号\n    def getVersion(self):\n        self.cur.execute(\"SELECT VERSION()\")\n        return self.getOneData()\n\n    # 获取上个查询的结果\n    def getOneData(self):\n        # 取得上个查询的结果，是单个结果\n        data = self.cur.fetchone()\n        return data\n\n    # 创建数据库表\n    def creatTable(self, tablename, attrdict, constraint):\n        \"\"\"创建数据库表\n            args：\n                tablename  ：表名字\n                attrdict   ：属性键值对,{'book_name':'varchar(200) NOT NULL'...}\n                constraint ：主外键约束,PRIMARY KEY(`id`)\n        \"\"\"\n        # 　判断表是否存在\n        if self.isExistTable(tablename):\n            print(\"%s is exit\" % tablename)\n            return\n        sql = ''\n        sql_mid = '`id` bigint(11) NOT NULL AUTO_INCREMENT,'\n        for attr, value in attrdict.items():\n            sql_mid = sql_mid + '`' + attr + '`' + ' ' + value + ','\n        sql = sql + 'CREATE TABLE IF NOT EXISTS %s (' % tablename\n        sql = sql + sql_mid\n        sql = sql + constraint\n        sql = sql + ') ENGINE=InnoDB DEFAULT CHARSET=utf8'\n        print('creatTable:' + sql)\n        self.executeCommit(sql)\n\n    def executeSql(self, sql=''):\n        \"\"\"执行sql语句，针对读操作返回结果集\n\n            args：\n                sql  ：sql语句\n        \"\"\"\n        try:\n            self.cur.execute(sql)\n            records = self.cur.fetchall()\n            return records\n        except pymysql.Error as e:\n            error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])\n            print(error)\n\n    def executeCommit(self, sql=''):\n        \"\"\"执行数据库sql语句，针对更新,删除,事务等操作失败时回滚\n\n        \"\"\"\n        try:\n            self.cur.execute(sql)\n            self.con.commit()\n        except pymysql.Error as e:\n            self.con.rollback()\n            error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])\n            print(\"error:\", error)\n            return error\n\n    def insert(self, tablename, params):\n        \"\"\"创建数据库表\n\n            args：\n                tablename  ：表名字\n                key        ：属性键\n                value      ：属性值\n        \"\"\"\n        key = []\n        value = []\n        for tmpkey, tmpvalue in params.items():\n            key.append(tmpkey)\n            if isinstance(tmpvalue, str):\n                value.append(\"\\'\" + tmpvalue + \"\\'\")\n            else:\n                value.append(tmpvalue)\n        attrs_sql = '(' + ','.join(key) + ')'\n        values_sql = ' values(' + ','.join(value) + ')'\n        sql = 'insert into %s' % tablename\n        sql = sql + attrs_sql + values_sql\n        print('_insert:' + sql)\n        self.executeCommit(sql)\n\n    def select(self, tablename, cond_dict='', order='', fields='*'):\n        \"\"\"查询数据\n\n            args：\n                tablename  ：表名字\n                cond_dict  ：查询条件\n                order      ：排序条件\n\n            example：\n                print mydb.select(table)\n                print mydb.select(table, fields=[\"name\"])\n                print mydb.select(table, fields=[\"name\", \"age\"])\n                print mydb.select(table, fields=[\"age\", \"name\"])\n        \"\"\"\n        consql = ' '\n        if cond_dict != '':\n            for k, v in cond_dict.items():\n                consql = consql + '`' + k + '`' + '=' + '\"' + v + '\"' + ' and'\n        consql = consql + ' 1=1 '\n        if fields == \"*\":\n            sql = 'select * from %s where ' % tablename\n        else:\n            if isinstance(fields, list):\n                fields = \",\".join(fields)\n                sql = 'select %s from %s where ' % (fields, tablename)\n            else:\n                print(\"fields input error, please input list fields.\")\n        sql = sql + consql + order\n        print('select:' + sql)\n        return self.executeSql(sql)\n\n    def insertMany(self, table, attrs, values):\n        \"\"\"插入多条数据\n\n            args：\n                tablename  ：表名字\n                attrs        ：属性键\n                values      ：属性值\n\n            example：\n                table='test_mysqldb'\n                key = [\"id\" ,\"name\", \"age\"]\n                value = [[101, \"liuqiao\", \"25\"], [102,\"liuqiao1\", \"26\"], [103 ,\"liuqiao2\", \"27\"], [104 ,\"liuqiao3\", \"28\"]]\n                mydb.insertMany(table, key, value)\n        \"\"\"\n        values_sql = ['%s' for v in attrs]\n        attrs_sql = '(' + ','.join(attrs) + ')'\n        values_sql = ' values(' + ','.join(values_sql) + ')'\n        sql = 'insert into %s' % table\n        sql = sql + attrs_sql + values_sql\n        print('insertMany:' + sql)\n        try:\n            print(sql)\n            for i in range(0, len(values), 20000):\n                self.cur.executemany(sql, values[i:i + 20000])\n                self.con.commit()\n        except pymysql.Error as e:\n            self.con.rollback()\n            error = 'insertMany executemany failed! ERROR (%s): %s' % (e.args[0], e.args[1])\n            print(error)\n            raise\n\n    def delete(self, tablename, cond_dict):\n        \"\"\"删除数据\n\n            args：\n                tablename  ：表名字\n                cond_dict  ：删除条件字典\n\n            example：\n                params = {\"name\" : \"caixinglong\", \"age\" : \"38\"}\n                mydb.delete(table, params)\n\n        \"\"\"\n        consql = ' '\n        if cond_dict != '':\n            for k, v in cond_dict.items():\n                if isinstance(v, str):\n                    v = \"\\'\" + v + \"\\'\"\n                consql = consql + tablename + \".\" + k + '=' + v + ' and '\n        consql = consql + ' 1=1 '\n        sql = \"DELETE FROM %s where%s\" % (tablename, consql)\n        print(sql)\n        return self.executeCommit(sql)\n\n    def update(self, tablename, attrs_dict, cond_dict):\n        \"\"\"更新数据\n\n            args：\n                tablename  ：表名字\n                attrs_dict  ：更新属性键值对字典\n                cond_dict  ：更新条件字典\n\n            example：\n                params = {\"name\" : \"caixinglong\", \"age\" : \"38\"}\n                cond_dict = {\"name\" : \"liuqiao\", \"age\" : \"18\"}\n                mydb.update(table, params, cond_dict)\n\n        \"\"\"\n        attrs_list = []\n        consql = ' '\n        for tmpkey, tmpvalue in attrs_dict.items():\n            attrs_list.append(\"`\" + tmpkey + \"`\" + \"=\" + \"\\'\" + tmpvalue + \"\\'\")\n        attrs_sql = \",\".join(attrs_list)\n        print(\"attrs_sql:\", attrs_sql)\n        if cond_dict != '':\n            for k, v in cond_dict.items():\n                if isinstance(v, str):\n                    v = \"\\'\" + v + \"\\'\"\n                consql = consql + \"`\" + tablename + \"`.\" + \"`\" + k + \"`\" + '=' + v + ' and '\n        consql = consql + ' 1=1 '\n        sql = \"UPDATE %s SET %s where%s\" % (tablename, attrs_sql, consql)\n        print(sql)\n        return self.executeCommit(sql)\n\n    def dropTable(self, tablename):\n        \"\"\"删除数据库表\n\n            args：\n                tablename  ：表名字\n        \"\"\"\n        sql = \"DROP TABLE  %s\" % tablename\n        self.executeCommit(sql)\n\n    def deleteTable(self, tablename):\n        \"\"\"清空数据库表\n\n            args：\n                tablename  ：表名字\n        \"\"\"\n        sql = \"DELETE FROM %s\" % tablename\n        print(\"sql=\", sql)\n        self.executeCommit(sql)\n\n    # def isExistTable(self, tablename):\n    #     \"\"\"判断数据表是否存在\n    #\n    #         args：\n    #             tablename  ：表名字\n    #\n    #         Return:\n    #             存在返回True，不存在返回False\n    #     \"\"\"\n    #     sql = \"select * from %s\" % tablename\n    #     result = self.executeCommit(sql)\n    #     if result is None:\n    #         return True\n    #     else:\n    #         if re.search(\"doesn't exist\", result):\n    #             return False\n    #         else:\n    #             return True\n\n\n    def select_db(self, sql):\n        \"\"\"查询\"\"\"\n        # 检查连接是否断开，如果断开就进行重连\n        self.con.ping(reconnect=True)\n        # 使用 execute() 执行sql\n        self.cur.execute(sql)\n        # 使用 fetchall() 获取查询结果\n        data = self.cur.fetchall()\n        return data\n\n    def __del__(self):  # 对象资源被释放时触发，在对象即将被删除时的最后操作\n        # 关闭游标\n        self.cur.close()\n        # 关闭数据库连接\n        self.con.close()\n\n    def execute_db(self, sql):\n        \"\"\"更新/新增/删除\"\"\"\n        try:\n            # 检查连接是否断开，如果断开就进行重连\n            self.con.ping(reconnect=True)\n            # 使用 execute() 执行sql\n            self.cur.execute(sql)\n            # 提交事务\n            self.con.commit()\n            return \"插入成功\"\n        except Exception as e:\n            # 回滚所有更改\n            self.con.rollback()\n            return \"操作出现错误\"\n\n\n"
  },
  {
    "path": "utils/time_util.py",
    "content": "from datetime import datetime\nimport random\nimport time\n\ndef deal_time(sj):\n    if \"小时\" in sj or \"分钟\" in sj or \"刚刚\" in sj:\n        return datetime.time.strftime(\"%Y-%m-%d\", time.localtime(time.time()))\n    if len(sj) == 5:\n        return '2023-' + sj\n    return sj;\n\n\ndef random_sleep(start=1, end=5):\n    # 生成随机的睡眠时间，范围为1到5秒\n    sleep_time = random.randint(start, end)\n    # print(\"休眠时间\" +str(sleep_time))\n    # 进行睡眠操作\n    time.sleep(sleep_time)\n\n\n\n\nif __name__ == '__main__':\n    print(datetime.now())\n    random_sleep()\n    print(datetime.now())\n    random_sleep()\n    print(datetime.now())\n    random_sleep()\n    print(datetime.now())\n    random_sleep()\n    print(datetime.now())\n\n"
  },
  {
    "path": "utils/webdriver_util.py",
    "content": "from selenium.webdriver.support.wait import WebDriverWait\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver import ChromeOptions\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom utils import globals\n\n\n\nclass ElementUtil(object):\n    def get_element_by_xpath(bro, chains, path):\n        \"\"\"\n        获取element的通用方法\n        :param bro:\n        :param chains:\n        :param path:\n        :return:\n        \"\"\"\n        return WebDriverWait(bro, 10).until(EC.element_to_be_clickable((By.XPATH, path)))\n\n    def get_elementArr_by_xpath(bro, chains, path):\n        return WebDriverWait(bro, 10).until(EC.presence_of_all_elements_located((By.XPATH, path)))\n\n    def is_xpath_exist(bro, chains, path):\n        try:\n            WebDriverWait(bro, 5).until(EC.element_to_be_clickable((By.XPATH, path)))\n            return True\n        except:\n            return False\n\n    def wait_to_go(bro, timeout=10):\n        WebDriverWait(bro, timeout).until(EC.new_window_is_opened)\n\ndef local_driver():\n    chrome_options = webdriver.ChromeOptions()\n    # chrome_options.add_argument(\"--headless\")  # 以无头模式运行Chrome\n    chrome_options.add_argument(\"--no-sandbox\")  # 取消沙盒模式\n    chrome_options.add_argument(\"--disable-gpu\")  # 取消GPU\n    chrome_options.add_argument(\"--disable-extensions\")  # 禁用插件加载\n    chrome_options.add_argument(\"--disable-software-rasterizer\")  # 禁用软件光栅化器\n    chrome_options.add_argument('lang=zh_CN.UTF-8')\n    chrome_options.add_argument('--enable-javascript')\n    chrome_options.add_argument(\"--start-minimized\")\n    chrome_options.add_argument(\n        '--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '\n        'Chrome/115.0.5790.110 Safari/537.36')  # 替换User-Agent\n    option = ChromeOptions()\n    option.add_experimental_option('excludeSwitches', ['enable-automation'])\n    s = Service(r\"./lib/chromedriver.exe\")\n    bro = webdriver.Chrome(service=s, chrome_options=chrome_options, options=option)\n    chains = ActionChains(bro)\n    return bro, chains\n\n\ndef online_driver():\n    \"\"\"\n        初始化Selenium信息———— 此版本用于生成Cookie，所以浏览器去掉无头模式\n        :return:\n        \"\"\"\n    # 设置浏览器信息\n    chrome_options = webdriver.ChromeOptions()\n    # chrome_options.add_argument(\"--headless\")  # 以无头模式运行Chrome\n    chrome_options.add_argument(\"--no-sandbox\")  # 取消沙盒模式\n    chrome_options.add_argument(\"--disable-gpu\")  # 取消GPU\n    chrome_options.add_argument(\"--disable-software-rasterizer\")\n    # chrome_options.add_argument(\"blink-settings=imagesEnabled=false\")  # 配置不加载图片\n    chrome_options.add_argument(\"--disable-extensions\")  # 禁用插件加载\n    chrome_options.add_argument('lang=zh_CN.UTF-8')\n    chrome_options.add_argument(\n        '--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '\n        'Chrome/101.0.4951.64 Safari/537.36')  # 替换User-Agent\n    driver = webdriver.Remote(\n        command_executor=globals.selenium_url,\n        options=chrome_options\n    )\n    chains = ActionChains(driver)\n    return driver, chains\n\ndef init_webdriver():\n\n    if globals.DRIVER_VERSION == 'Local':\n        return local_driver()\n    if globals.DRIVER_VERSION == 'Online':\n        return online_driver()\n    # 默认本地驱动\n    return local_driver()"
  }
]