[
  {
    "path": ".babelrc",
    "content": "{\n\t\"presets\": [\n\t\t[\n\t\t\t\"env\",\n\t\t\t{\n\t\t\t\t\"targets\": {\n\t\t\t\t\t\"browsers\": [\n\t\t\t\t\t\t\"last 5 Chrome version\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t}\n\t\t]\n\t],\n\t\"plugins\": [\n\t\t[\n\t\t\t\"transform-runtime\",\n\t\t\t{\n\t\t\t\t\"polyfill\": false,\n\t\t\t\t\"regenerator\": true\n\t\t\t}\n\t\t],\n\t\t[\n\t\t\t\"import\",\n\t\t\t{\n\t\t\t\t\"libraryName\": \"vant\",\n\t\t\t\t\"libraryDirectory\": \"es\",\n\t\t\t\t\"style\": true\n\t\t\t}\n\t\t]\n\t]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\ndist\nbuild\n.cache\n.DS_Store\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": "background.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>背景页</title>\n\t<meta charset=\"utf-8\"/>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n</head>\n<body id='body'>\n\t<script type=\"text/javascript\" src=\"static/background.js\"></script>\n</body>\n</html>"
  },
  {
    "path": "components/App.vue",
    "content": "<template>\n<div class='contents'>\n    <van-tabs v-model=\"activeTabName\" sticky>\n        <van-tab title=\"任务列表\" name=\"taskpanel\">\n            <taskpanel :taskId=\"runtime.taskId\" :taskPercentage=\"taskPercentage\" :applidActivityNum=\"saveinfo.applidActivityNum\" @execute=\"execute\"></taskpanel>\n        </van-tab>\n        <van-tab title=\"任务设置\" name=\"settings\">\n            <settings></settings>\n        </van-tab>\n        <van-tab title=\"商品列表\" name=\"activityItems\" :badge=\"activeSqlActivityItems.length\">\n\n            <itemList :list=\"activeSqlActivityItems\" @filter=\"filterSqlActivityItems\">\n                <template #actions=\"props\">\n                    <van-button v-if=\"props.item.status== ACTIVITY_STATUS.APPLIED\" disabled plain hairline size=\"small\" type=\"info\">已申请</van-button>\n                    <van-button v-else-if=\"runtime.applyingActivityIds.indexOf(props.item.id) >=0\" loading plain hairline size=\"small\" type=\"info\" loading-text=\"申请\" class=\"\"></van-button>\n                    <van-button v-else @click=\"activityApply(props.item)\" plain hairline size=\"small\" type=\"info\" class=\"\">申请</van-button>\n                    <van-button @click=\"deleteActivityItem(props.item)\" plain hairline size=\"small\" type=\"info\" class=\"\"> 删除 </van-button>\n                </template>\n            </itemList>\n\n        </van-tab>\n        <van-tab title=\"成功列表\" name=\"successActivityItems\" :badge=\"activeSuccessActivityItems.length\">\n\n            <itemList :list=\"activeSuccessActivityItems\" @filter=\"filterSuccessActivityItems\" :default_day=14>\n                <template #actions=\"props\">\n                    <van-button @click=\"deleteSuccessActivityItem(props.item)\" plain hairline size=\"small\" type=\"info\" class=\"\"> 删除 </van-button>\n                </template>\n            </itemList>\n\n        </van-tab>\n    </van-tabs>\n    <van-tabbar>\n        <van-tabbar-item :title=\"descriptionWithTime\" v-tippy @click=\"checkLoginStatus\">\n            <!-- TODO 这里应该是三个状态 -->\n            <span :class=\"loginStatus.status===USER_STATUS.LOGIN?'login':'not-login'\">{{loginStatus.shortDescription}}</span>\n            <template #icon>\n                <img :src=\"loginStatus.status===USER_STATUS.LOGIN?'../img/user-active.png':'../img/user-inactive.png'\" />\n            </template>\n        </van-tabbar-item>\n        <van-tabbar-item :title=\"`当前关注了${saveinfo.followVenderNum}个店铺。用户关注店铺上限为500个。每日最多增加300个关注店铺，请按时清理。`\" v-tippy icon=\"like-o\" :badge=\"saveinfo.followVenderNum\">\n            关注\n        </van-tabbar-item>\n        <van-tabbar-item title=\"点击查看本插件的全部代码\" v-tippy icon=\"../img/github.png\" @click=\"openGithub\">\n\t\t\t源代码{{currentVersion}}\n        </van-tabbar-item>\n    </van-tabbar>\n</div>\n</template>\n\n<script>\nimport {\n    getActivityItems,\n    getSuccessActivityItems,\n    deleteItems\n} from '../static/db'\nimport {\n    storage\n} from '../static/utils'\nimport {\n    Toast,\n} from 'vant';\n\nimport itemList from './itemList'\nimport settings from './settings'\nimport taskpanel from './taskpanel'\nimport {\n    ACTIVITY_STATUS,\n    USER_STATUS\n} from '../static/config'\nimport {\n    readableTime\n} from '../static/utils'\nimport {\n    updateTaskInfo, TASK_ID\n} from '../static/tasks'\n\nconst bg = chrome.extension.getBackgroundPage()\n\nexport default {\n    name: 'App',\n    components: {\n        settings,\n        itemList,\n        taskpanel\n    },\n    data() {\n        return {\n            activeTabName: 'taskpanel',\n            activity: {\n                sql: {\n                    items: [],\n                    day: 1,\n                    filter: ''\n\n                },\n                success: {\n                    items: [],\n                    day: 14,\n                    filter: ''\n                }\n            },\n            loginStatus: bg.loginStatus,\n            runtime: bg.runtime,\n            saveinfo: bg.saveinfo,\n            USER_STATUS: USER_STATUS,\n\t\t\tACTIVITY_STATUS: ACTIVITY_STATUS,\n\t\t\tcurrentVersion:\"{{version}}\"\n        }\n    },\n    destroyed() {\n        //因为 loginStatus 这些参数是 window 生命周期的，如果不手动释放的话会导致内存泄露\n        bg.loginStatus = Object.assign({}, bg.loginStatus)\n        bg.runtime = Object.assign({}, bg.runtime)\n        bg.saveinfo = Object.assign({}, bg.saveinfo)\n    },\n    mounted() {\n        chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {\n            switch (message.action) {\n                case \"popup_update_activity\":\n                    Toast('刷新商品列表')\n                    this.renderSqlActivityItems()\n                    break;\n                case \"popup_update_success_activity\":\n                    Toast('有新的成功的项目')\n                    this.renderSuccessActivityItems();\n                    break;\n                case \"popup_update_activity_status\":\n                    this.updateACTIVITY_STATUS(message.activityId, message.status);\n                    break;\n                default:\n                    break;\n            }\n        })\n\n        this.renderSqlActivityItems()\n        this.renderSuccessActivityItems()\n        if (this.loginStatus.status === USER_STATUS.UNKNOWN\n\t\t\t// ||this.loginStatus.status === USER_STATUS.LOGOUT\n\t\t\t) {\n            bg.joinTaskInQueue(TASK_ID.CHECK_OR_DO_LOGIN_OPT, true)\n        }\n    },\n    computed: {\n        descriptionWithTime() {\n\t\t\tif(this.loginStatus.timestamp){\n\t\t\t\treturn `${this.loginStatus.description} | 检查时间：${readableTime(this.loginStatus.timestamp)}`\n\t\t\t}\n\t\t\treturn this.loginStatus.description\n        },\n        disable_event: function () {\n            if (this.loginStatus.status !== this.USER_STATUS.LOGIN) {\n                Toast('未登录')\n                return true\n            }\n            if (this.runtime.taskId !== -1) {\n                Toast('已有任务正在进行')\n                return true\n            }\n            return false\n        },\n        activeSqlActivityItems: function () {\n            return this.activity.sql.items.filter(item => {\n                const filter = this.activity.sql.filter\n                if (filter) {\n                    return item.name.indexOf(filter) >= 0\n                }\n                return true\n            })\n        },\n        activeSuccessActivityItems: function () {\n            return this.activity.success.items.filter(item => {\n                const filter = this.activity.success.filter\n                if (filter) {\n                    return item.name.indexOf(filter) >= 0\n                }\n                return true\n            })\n        },\n        taskPercentage() {\n            if (this.runtime.totalTask === 0) {\n                return 100\n            }\n            return (100 * this.runtime.doneTask / this.runtime.totalTask).toFixed(0)\n        }\n\n    },\n    methods: {\n        activityApply(activity) {\n\t\t\tToast(`即将执行 ${activity.id} 任务`)\n\t\t\tbg.joinTaskInQueue(TASK_ID.ACTIVITY_APPLY, true, {activity:[activity]})\n        },\n        deleteActivityItem(activityItem) {\n            this.activity.sql.items = this.activity.sql.items.filter(item => item.id !== activityItem.id)\n            deleteItems({\n                database: 'activity',\n                id: activityItem.id\n            })\n        },\n        deleteSuccessActivityItem(activityItem) {\n            this.activity.success.items = this.activity.success.items.filter(item => item.id !== activityItem.id)\n            deleteItems({\n                database: 'success',\n                id: activityItem.id\n            })\n        },\n        updateACTIVITY_STATUS(activityId, status) {\n            for (let item of this.activeSqlActivityItems) {\n                if (item.id === activityId) {\n                    item.status = status ? ACTIVITY_STATUS.APPLIED : ACTIVITY_STATUS.APPLY\n                    break\n                }\n            }\n        },\n        renderSqlActivityItems() {\n            getActivityItems(this.activity.sql.day).then(res => {\n                this.activity.sql.items = res\n            })\n        },\n        renderSuccessActivityItems() {\n            getSuccessActivityItems(this.activity.success.day).then(res => {\n                this.activity.success.items = res\n            })\n        },\n        filterSqlActivityItems(msg) {\n            console.log(\"filter\", msg)\n            if (this.activity.sql.filter !== msg.filter) {\n                this.activity.sql.filter = msg.filter\n            }\n            if (msg.day !== this.activity.sql.day) {\n                this.activity.sql.day = msg.day\n                this.renderSqlActivityItems()\n            }\n        },\n        filterSuccessActivityItems(msg) {\n            console.log(`success ${msg.day} ${msg.filter}`)\n            if (this.activity.success.filter !== msg.filter) {\n                this.activity.success.filter = msg.filter\n            }\n            if (msg.day !== this.activity.success.day) {\n                this.activity.success.day = msg.day\n                this.renderSqlActivityItems()\n            }\n        },\n        checkLoginStatus() {\n            switch (this.loginStatus.status) {\n                case this.USER_STATUS.UNKNOWN:\n                    bg.joinTaskInQueue(TASK_ID.CHECK_OR_DO_LOGIN_OPT, true)\n                    break\n                case this.USER_STATUS.LOGOUT:\n                    chrome.tabs.create({\n                        url: 'https://passport.jd.com/new/login.aspx',\n                        active: true\n                    })\n                    break\n            }\n        },\n        openGithub() {\n            chrome.tabs.create({\n                url: 'https://github.com/ZCY01/jdtry',\n                active: true\n            })\n        },\n        execute(task) {\n            // if (this.loginStatus.status === USER_STATUS.WARMING) {\n            //     Toast('正在检查登录状态，请稍后')\n            //     return\n            // }\n            // if (this.loginStatus.status === USER_STATUS.LOGOUT) {\n            //     Toast('未登录！请手动登录！')\n            //     return\n            // }\n            if (this.runtime.taskId !== -1){\n                Toast(`${task.title} 已加入任务队列`)\n\t\t\t}\n\t\t\tbg.joinTaskInQueue(task, true)\n        }\n    }\n}\n</script>"
  },
  {
    "path": "components/itemList.vue",
    "content": "<template>\n<van-list v-model=\"loading\" :finished=\"finished\" finished-text=\"没有更多了\" @load=\"onLoad\">\n    <van-sticky offset-top=\"44\">\n        <div class=\"search-tool-bar\">\n            <div title=\"搜索未来多少天内结束的商品\" v-tippy class=\"time-title\">\n                时间：\n            </div>\n            <div>\n                <van-stepper v-model=\"day\" style=\"width:100px\" min=\"1\" max=\"24\"></van-stepper>\n            </div>\n            <div>\n                <van-search v-model=\"filter\" placeholder=\"请输入搜索关键词\" style=\"padding:5px\" @clear=\"clear\" @search=\"search\"></van-search>\n            </div>\n            <div>\n                <van-button plain hairline size=\"small\" type=\"info\" @click=\"search\"> 搜索 </van-button>\n            </div>\n        </div>\n    </van-sticky>\n\n    <van-cell v-for=\"item of loadingList\" :key=\"item.id\" center>\n        <img slot=\"icon\" :src=\"item.pic_url\" alt class=\"item-img\" />\n        <template #title>\n            <div>\n                <a class=\"item-name\" :href=\"item.url\" target=\"_blank\">{{item.name}}</a>\n                <div>\n                    <div class=\"item-info\">\n                        <div class=\"van-cell__label item-info__bd\">{{item.detail}}</div>\n                        <div class=\"van-cell__label item-info__bd\">京东价：{{item.price}}</div>\n                        <div class=\"van-cell__label item-info__bd\">结束时间：{{readableTime(item.timestamp)}}</div>\n                    </div>\n                    <div class=\"item-actions\">\n                        <slot name=\"actions\" :item=\"item\"></slot>\n                    </div>\n                </div>\n            </div>\n        </template>\n    </van-cell>\n</van-list>\n</template>\n\n<script>\nconst PAGE_SIZE=20\nimport {readableTime} from '../static/utils.js'\nexport default {\n    name: \"itemsList\",\n    props: {\n        list: Array,\n        default_day: {\n\t\t\ttype:Number,\n\t\t\tdefault:1\n        }\n\t},\n    data() {\n        return {\n            loading: false,\n\t\t\tfinished: false,\n\t\t\tday:this.default_day,\n\t\t\tfilter: \"\",\n\t\t\tpage:1\n        };\n\t},\n\tcomputed:{\n\t\tloadingList(){\n\t\t\tconst listLength = this.list.length\n\t\t\tconst pageLength = this.page * PAGE_SIZE\n\t\t\tconst minLength = listLength > pageLength? pageLength:listLength\n\t\t\tif(pageLength >= listLength){\n\t\t\t\tthis.finished = true\n\t\t\t}\n\t\t\treturn this.list.slice(0,minLength)\n\t\t}\n\t},\n    methods: {\n        onLoad() {\n\t\t\tthis.page ++\n\t\t\tthis.loading=false\n\t\t},\n\t\tclear(){\n\t\t\tthis.filter=''\n\t\t\tthis.search()\n\t\t},\n        search() {\n            this.$emit('filter', {\n                day: this.day,\n                filter: this.filter.replace(/^\\s*|\\s*$/g, \"\")\n\t\t\t})\n\t\t\tthis.finished = false\n\t\t\tthis.page = 1\n\t\t},\n\t\treadableTime:readableTime\n    }\n\n};\n</script>\n\n<style scoped>\n.item-img {\n    height: 60px;\n\twidth: 60px;\n\tmargin-right: 10px;\n}\n\n.item-info {\n    font-size: 12px;\n    float: left;\n}\n\n.item-info__bd {\n    margin: 0px;\n}\n\n.item-actions {\n    float: right;\n    margin-top: 12px;\n}\n\n.search-tool-bar {\n    width: 100%;\n    height: 44px;\n    background-color: #fff;\n    /* display: flex;\n    flex-direction: row;\n    justify-content: center;\n\talign-items: center; */\n\n    display: flex;\n    justify-content: center;\n    align-items: center;\n\n}\n\n.time-title {\n    color: #323233;\n    font-size: 14px;\n    margin-right: 3px;\n}\n</style>\n"
  },
  {
    "path": "components/settings.vue",
    "content": "<template>\n<van-list>\n\n    <van-cell v-for=\"item in settings\" :key=\"item.name\" :title=\"item.text\">\n        <template #label>\n            <span v-for=\"btn of item.btns\" :key=\"btn.value\">\n                <van-button :type=\"btn.selected?'info':'default'\" @click=\"selected(btn)\" class=\"settings-btn\" size=\"small\">\n                    {{btn.text}}\n                </van-button>\n            </span>\n        </template>\n    </van-cell>\n    <van-cell title=\"屏蔽关键字\" center>\n        <template #label>\n            <van-tag v-for=\"tag in keywordMasks\" :key=\"tag\" closeable size=\"medium\" type=\"primary\" @close=\"close(tag)\" class=\"tag\">{{tag}} </van-tag>\n        </template>\n        <div>\n            <van-search v-model=\"inputTag\" placeholder=\"回车确认\" style=\"padding:0px\" left-icon=\"\" @clear=\"clear\" @search=\"addMask\"></van-search>\n        </div>\n    </van-cell>\n    <van-cell title=\"最低价格(含)\" center>\n        <van-search v-model=\"minPrice\" placeholder=\"回车确认\" style=\"padding:0px\" left-icon=\"\" @search=\"updateMinPrice\"></van-search>\n    </van-cell>\n    <van-cell title=\"高级设置\" center>\n        <van-button plain hairline size=\"small\" type=\"info\" @click=\"clearSqlActivitys\"> 清空商品列表 </van-button>\n        <van-button plain hairline size=\"small\" type=\"info\" @click=\"reset\"> 复位 </van-button>\n    </van-cell>\n    <van-cell title=\"自动登录\" center>\n        <van-switch v-model=\"autoLogin\" @change=\"switchStatusChange('login')\"></van-switch>\n    </van-cell>\n\n</van-list>\n</template>\n\n<script>\nimport {\n    storage\n} from \"../static/utils\"\nimport {\n    Toast,\n    Dialog\n} from 'vant'\n\nexport default {\n    name: \"settings\",\n    data() {\n        return {\n            settings: [],\n            autoLogin: false,\n            keywordMasks: [],\n            inputTag: \"\",\n            minPrice: \"0\"\n        };\n    },\n    mounted: function () {\n        storage.get({\n            minPrice: 0\n        }).then(res => this.minPrice = res.minPrice.toString())\n        storage.get({\n            keywordMasks: []\n        }).then(res => this.keywordMasks = res.keywordMasks)\n        storage.get({\n            settings: []\n        }).then(res => this.settings = res.settings)\n\n        storage.get({\n            autoLogin: false\n        }).then(res => {\n            this.autoLogin = res.autoLogin\n            if (this.autoLogin)\n                storage.get({\n                    account: {\n                        username: '',\n                        password: ''\n                    }\n                })\n                .then(res => {\n                    if (!res.account.username || !res.account.password)\n                        Toast('自动登录：未保存账号')\n                })\n        })\n    },\n    methods: {\n        selected(btn) {\n            btn.selected = btn.selected ? false : true\n            storage.set({\n                settings: this.settings\n            });\n        },\n        switchStatusChange(key) {\n            storage.set({\n                autoLogin: this.autoLogin\n            })\n            if (key === 'login' && this.autoLogin) {\n                Toast('即将跳转登录界面，请点击保存')\n                setTimeout(() => {\n                    chrome.tabs.create({\n                        url: 'https://passport.jd.com/new/login.aspx',\n                        active: true\n                    })\n                }, 2000)\n            }\n        },\n        clearSqlActivitys() {\n            Dialog.confirm({\n                title: '是否要清空商品列表？'\n            }).then(() => {\n                sendMessage({\n                    action: \"bg_clear_sql_activitys\",\n                })\n            }).catch(() => {})\n        },\n        close(tag) {\n            this.keywordMasks = this.keywordMasks.filter(t => {\n                return t !== tag\n            })\n            storage.set({\n                keywordMasks: this.keywordMasks\n            }).then(() => {\n                sendMessage({\n                    action: \"popup_update_activity\",\n                })\n            })\n        },\n        addMask(tag) {\n            tag = tag.trim()\n            if (this.keywordMasks.indexOf(tag) < 0) {\n                this.keywordMasks.push(tag)\n                storage.set({\n                    keywordMasks: this.keywordMasks\n                }).then(() => {\n                    sendMessage({\n                        action: \"popup_update_activity\",\n                    })\n                })\n            }\n            this.inputTag = \"\"\n        },\n        clear() {\n            this.inputTag = \"\"\n        },\n        updateMinPrice() {\n            this.minPrice.trim()\n            if (this.minPrice === '') {\n                this.minPrice = '0'\n            }\n            let price = parseFloat(this.minPrice)\n            if (isNaN(price)) {\n                Toast(`最小价格格式错误：${this.minPrice}`)\n                storage.get({\n                    minPrice: 0\n                }).then(res => this.minPrice = res.minPrice.toString())\n                return\n            }\n            storage.set({\n                minPrice: price\n            }).then(() => {\n                sendMessage({\n                    action: \"popup_update_activity\",\n                })\n            })\n        },\n        reset() {\n            Dialog.confirm({\n\t\t\t\ttitle: '是否要复位？',\n\t\t\t\tmessage: '复原所有的配置'\n            }).then(() => {\n                sendMessage({\n                    action: 'reset'\n                })\n            }).catch(() => {})\n        }\n    }\n};\n</script>\n\n<style scoped>\n.settings-btn {\n    margin: 3px;\n    width: 74px;\n    height: 34px;\n    font-size: 13px;\n}\n</style>\n"
  },
  {
    "path": "components/taskpanel.vue",
    "content": "<template>\n<div class=\"task-panel\" style=\"background-color:#fff\">\n    <van-popup v-model=\"showAutoSetting\">\n        <van-form @submit=\"onSubmit\">\n\n            <van-field name=\"run\" label=\"自动运行\">\n                <template #input>\n                    <van-switch v-model=\"auto.run\"></van-switch>\n                </template>\n            </van-field>\n            <van-field name=\"when\" label=\"时间/24H\">\n                <template #input>\n                    <van-stepper v-model=\"auto.when\" min=\"0\" max=\"23\" />\n                </template>\n            </van-field>\n\n            <div style=\"margin: 16px;\">\n                <van-button round block type=\"info\" native-type=\"submit\"> 保存 </van-button>\n            </div>\n        </van-form>\n    </van-popup>\n    <van-cell-group>\n\n        <van-cell v-for=\"(task,index) of tasks\" :key=\"task.id\" center :label=\"autoTaskInfo(task)\">\n            <template #title>\n                <div :title=\"task.description\" v-tippy>\n                    {{task.title}}\n                </div>\n            </template>\n            <div>\n                <van-button v-if=\"taskId !== task.id\" plain hairline size=\"small\" type=\"info\" @click=\"emit(task)\" :title='readableTime(task.last_run_at)' v-tippy> 执行 </van-button>\n                <van-button v-else loading plain hairline size=\"small\" type=\"info\" loading-text=\"正在执行\"></van-button>\n                <van-icon name=\"info-o\" :color=\"`${task.auto.run?'#007DFF':''}`\" @click='showAutoSettingPanel(index)' style='margin-left:15px;top:6px' size=\"20px\" title=\"任务设置\" v-tippy></van-icon>\n            </div>\n        </van-cell>\n\n        <van-cell center>\n            <template #title>\n                <div title=\"每日最多可申请300个试用商品\" v-tippy>\n                    每日份额\n                </div>\n            </template>\n            <van-circle v-model=\"rate\" :text=\"text\" size=\"80\" layer-color=\"#ebedf0\"></van-circle>\n        </van-cell>\n\n    </van-cell-group>\n\n    <div v-if=\"taskId !== -1\">\n        <van-divider>任务进度</van-divider>\n        <van-progress :percentage=\"taskPercentage\" stroke-width=\"8\" style=\"width:100%\"></van-progress>\n    </div>\n\n</div>\n</template>\n\n<script>\nimport {\n    defaultTasks,\n    getAllTasks,\n    updateTaskInfo\n} from '../static/tasks'\nimport {\n    Dialog,\n    Toast\n} from 'vant'\nimport {\n    readableTime\n} from '../static/utils'\nimport {\n    DateTime\n} from 'luxon'\n\nexport default {\n    name: \"taskpanel\",\n    props: [\"taskId\", \"taskPercentage\", \"applidActivityNum\"],\n    data() {\n        return {\n            tasks: defaultTasks,\n            showAutoSetting: false,\n            auto: {\n                run: false,\n                when: 0\n            }\n        }\n    },\n    async mounted() {\n        this.tasks = await getAllTasks()\n    },\n    computed: {\n        rate: {\n            set() {},\n            get() {\n                return 100 * this.applidActivityNum / 300\n            }\n        },\n        text() {\n            return this.applidActivityNum + '/300'\n\t\t},\n    },\n    methods: {\n        autoTaskInfo(task) {\n            if (task.auto.run !== true) {\n                return ''\n            }\n            let now = DateTime.local()\n            if (now.hour >= task.auto.when) {\n                now = now.plus({\n                    day: 1\n                })\n            }\n            now = now.set({\n                hour: task.auto.when,\n                minute: 0,\n                second: 0,\n            })\n            return `将运行于：${readableTime(now)}`\n        },\n        emit(task) {\n            Dialog.confirm({\n                title: task.title,\n                message: task.description\n            }).then(() => {\n                this.$emit('execute', task)\n            }).catch(() => {})\n        },\n        readableTime(time) {\n            if (time <= 0) {\n                return ''\n            }\n            return `上次运行：${readableTime(time)}`\n        },\n        onSubmit(values) {\n            sendMessage({\n                action: \"bg_scheduled_task\",\n            })\n            Object.assign(this.tasks[this.taskIndex].auto, values)\n            // this.tasks[this.taskIndex].last_run_at = DateTime.local().plus({\n            //     day: -1\n\t\t\t// }).valueOf()\n            updateTaskInfo(this.tasks[this.taskIndex])\n            Toast({\n                message: '保存成功',\n                duration: 1000\n            })\n        },\n        showAutoSettingPanel(index) {\n            this.taskIndex = index\n            this.auto = Object.assign(this.auto, this.tasks[this.taskIndex].auto)\n            this.showAutoSetting = true\n        }\n    }\n};\n</script>\n"
  },
  {
    "path": "gulpfile.js",
    "content": "const gulp = require('gulp')\nconst watch = require('gulp-watch')\nconst Bundler = require('parcel-bundler')\nconst Path = require('path')\nconst cleanCss = require('gulp-clean-css')\nconst concat = require('gulp-concat')\nconst replace = require('gulp-replace')\nprocess.env.VERSION = process.env.VERSION || \"1.0.0\"\n\n\nfunction watchFile() {\n\t// watch many files\n\twatch([\n\t\t'manifest.json', '*.html', 'static/*.js', './components/*.vue', './style/*.css'\n\t], function () {\n\t\texports.default()\n\t});\n}\n\nasync function bundleBuild(fileName) {\n\tlet file = Path.join(__dirname, `./${fileName}`)\n\tlet options = {\n\t\toutDir: './dist', // 将生成的文件放入输出目录下，默认为 dist\n\t\toutFile: fileName, // 输出文件的名称\n\t\tpublicUrl: './static', // 静态资源的 url ，默认为 dist\n\t\twatch: false, // 是否需要监听文件并在发生改变时重新编译它们，默认为 process.env.NODE_ENV !== 'production'\n\t\tcache: true, // 启用或禁用缓存，默认为 true\n\t\tcacheDir: '.cache', // 存放缓存的目录，默认为 .cache\n\t\tminify: (process.env.NODE_ENV === 'production'), // 压缩文件，当 时，会启用\n\t\ttarget: 'browser', // 浏览器/node/electron, 默认为 browser\n\t\thttps: false, // 服务器文件使用 https 或者 http，默认为 false\n\t\tlogLevel: (process.env.NODE_ENV === 'production') ? 1 : 3, // 3 = 输出所有内容，2 = 输出警告和错误, 1 = 输出错误\n\t\tsourceMaps: (process.env.NODE_ENV != 'production'),\n\t\thmrHostname: '', // 热模块重载的主机名，默认为 ''\n\t\tdetailedReport: true // 打印 bundles、资源、文件大小和使用时间的详细报告，默认为 false，只有在禁用监听状态时才打印报告\n\t}\n\tlet bundler = new Bundler(file, options)\n\tawait bundler.bundle()\n}\n\nasync function buildContentScript() {\n\tawait bundleBuild('static/content-script.js')\n\tgulp.src([\n\t\t'dist/content-script.js',\n\t])\n\t\t.pipe(gulp.dest('build/static'))\n\treturn gulp.src([\n\t\t'dist/content-script.css',\n\t\t'style/content-script.css',\n\t])\n\t\t.pipe(concat('content-script.css'))\n\t\t.pipe(cleanCss())\n\t\t.pipe(gulp.dest('build/style'))\n\n}\n\nasync function buildPopupScript() {\n\tawait bundleBuild('static/popup.js')\n\tgulp.src([\n\t\t'dist/popup.js',\n\t])\n\t\t.pipe(replace('{{version}}', process.env.VERSION))\n\t\t.pipe(gulp.dest('build/static'))\n\treturn gulp.src([\n\t\t'dist/popup.css',\n\t\t'style/popup.css',\n\t])\n\t\t.pipe(concat('popup.css'))\n\t\t.pipe(cleanCss())\n\t\t.pipe(gulp.dest('build/style'))\n}\n\nasync function buildBackgroupScript() {\n\tawait bundleBuild('static/background.js')\n\treturn gulp.src([\n\t\t'dist/background.js',\n\t])\n\t\t.pipe(gulp.dest('build/static'))\n}\n\n\nasync function moveConfigFile() {\n\tgulp.src([\n\t\t'manifest.json', '*.html'\n\t])\n\t\t.pipe(replace('{{version}}', process.env.VERSION))\n\t\t.pipe(gulp.dest('build'))\n\treturn gulp.src([\n\t\t'img/*'\n\t])\n\t\t.pipe(gulp.dest('build/img'));\n}\n\n\nexports.default = gulp.series(moveConfigFile, buildContentScript, buildPopupScript, buildBackgroupScript)\n\nexports.dev = gulp.series(watchFile);\n"
  },
  {
    "path": "manifest.json",
    "content": "{\n\t// 清单文件的版本，这个必须写，而且必须是2\n\t\"manifest_version\": 2,\n\t\"name\": \"jdtry\",\n\t\"version\": \"{{version}}\",\n\t\"description\": \"jd try\",\n\t\"icons\": {\n\t\t\"16\": \"img/icon.png\",\n\t\t\"48\": \"img/icon.png\",\n\t\t\"128\": \"img/icon.png\"\n\t},\n\t\"background\": {\n\t\t\"page\": \"background.html\",\n\t\t\"persistent\": true\n\t},\n\t\"content_scripts\": [{\n\t\t\"matches\": [\"*://*.jd.com/*\"],\n\t\t\"js\": [\"static/content-script.js\"],\n\t\t\"css\": [\"style/content-script.css\"],\n\t\t\"run_at\": \"document_end\",\n\t\t\"all_frames\": true\n\t}],\n\t\"browser_action\": {\n\t\t\"default_icon\": \"img/icon.png\",\n\t\t\"default_popup\": \"popup.html\",\n\t\t\"default_title\": \"京试\"\n\t},\n\t// 权限申请\n\t\"permissions\": [\n\t\t\"*://*.jd.com/*\",\n\t\t\"notifications\",\n\t\t\"storage\",\n\t\t\"alarms\"\n\t]\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"jdtry\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.js\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"build\": \"NODE_ENV=production node_modules/.bin/gulp\",\n    \"dev\": \"node_modules/.bin/gulp dev\"\n  },\n  \"dependencies\": {\n    \"@vant/touch-emulator\": \"^1.2.0\",\n    \"babel-plugin-transform-runtime\": \"^6.23.0\",\n    \"dexie\": \"^2.0.4\",\n    \"gulp\": \"^4.0.2\",\n    \"gulp-clean-css\": \"^4.3.0\",\n    \"gulp-concat\": \"^2.6.1\",\n    \"gulp-replace\": \"^1.0.0\",\n    \"gulp-watch\": \"^5.0.1\",\n    \"luxon\": \"^1.23.0\",\n    \"parcel-bundler\": \"^1.12.4\",\n    \"tippy.js\": \"^6.1.0\",\n    \"vant\": \"^2.5.8\",\n    \"vue\": \">=2.6.0\"\n  },\n  \"devDependencies\": {\n    \"@vue/component-compiler-utils\": \"^3.1.1\",\n    \"babel-core\": \"^6.26.3\",\n    \"babel-plugin-import\": \"^1.13.0\",\n    \"babel-preset-env\": \"^1.7.0\",\n    \"stylus\": \"^0.54.7\",\n    \"vue-template-compiler\": \">=2.6.0\"\n  }\n}\n"
  },
  {
    "path": "popup.html",
    "content": "<!DOCTYPE html>\n<html>\n\n<head>\n\t<title>京东试用</title>\n\t<meta charset=\"utf-8\"/>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\t<link rel=\"stylesheet\" href=\"style/popup.css\">\n</head>\n\n<body>\n\t<div id=\"app\"></div>\n\t<!-- body 最后 -->\n\t<script src=\"static/popup.js\"></script>\n</body>\n\n</html>"
  },
  {
    "path": "readme.md",
    "content": "# 京东试用 Chrome 拓展\n本拓展自动获取所有可申请的商品，并可一键申请指定的试用商品。<br>\n请注意：本拓展仅可用于研究测试使用，不可用于其他用途。使用于其他用途，后果自负。<br>\n\n<h3>欢迎 Star！👏</h3>\n\n## 界面截图\n![界面](https://github.com/ZCY01/img/raw/master/interface1.jpg)\n\n## 主要功能\n* 获取关注商铺数量\n* 清空关注商铺\n* 搜索京东试用所有商品\n* 检索是否有成功申请试用的商品\n* 一键申请试用商品\n* 自动执行任务\n* 自动登录\n\n## 安装\n```js\n# 安装依赖\nyarn\n# 生成拓展文件\nyarn build\n# chrome 打开开发者模式加载拓展（位于build文件）\n# 或者直接下载 release 里已编译好的 crx 进行解压安装\n```\n\n## 使用方法\n1. 打开网页登录京东账号\n2. 点击 **搜索商品** 搜索并导入试用商品（可在任务设置里设置搜索范围）\n3. 点击 **一键申请** 即可申请所有试用商品\n\n## 自动运行说明\n1. 自动运行任务顺序为:\n* 获取关注数量\n* 清空关注列表\n* 搜索商品\n* 检索成功\n* 一键申请\n\n2. 当`一键申请`任务执行后，不再自动执行`清空关注列表`任务\n\n3. 如果自动执行时刻无法执行，一小时后重试\n\n\n## 其他\n* 每人每天可申请的试用商品上限为300个\n* 每人可关注的店铺上限为500个\n* 自动登录保存的账号存放在 `chrome.storage.local`，仅用于登录。\n* 使用者多的时候再考虑加入谷歌商店\n"
  },
  {
    "path": "static/background.js",
    "content": "import { storage, emitter, openByIframeAndWaitForClose, TIMEOUT_ERROR, notifications, openByIframe, waitEventWithPromise, IFRAME_LIFETIME, setNotificationLevel, NOTIFICATION_LEVEL } from './utils'\nimport { addActivityItems, updateActivityItemsStatus, addSuccessActivityList, getActivityItems, getSuccessActivityItems, clearActivityItems } from './db'\nimport { settingConfig, USER_STATUS, ACTIVITY_STATUS, INIT_KEYWORD_MASKS } from './config'\nimport { updateTaskInfo, defaultTasks, getAllTasks, commonTasks, TASK_ID} from './tasks'\nimport { DateTime } from 'luxon'\n\n\nwindow.runtime = {\n\ttaskId: -1,\n\tdoneTask: 0,\n\ttotalTask: 0,\n\tapplyingActivityIds: [],\n\ttaskQueue:[],\n\ttaskIdStack :[]\n}\nwindow.loginStatus = {\n\tstatus: USER_STATUS.UNKNOWN,\n\tdescription: '正在获取登录状态',\n\tshortDescription: '正在检查',\n\ttimestamp: 0,\n}\nwindow.saveinfo = { //reset every day\n\tfollowVenderNum: -1,\n\tapplidActivityNum: 0,\n\tfulfilled: false,\n\tnoMoreVender: false,\n\tday: -1\n}\nfunction savePersistentData() {\n\tstorage.set({ loginStatus: loginStatus })\n\tstorage.set({ saveinfo: saveinfo })\n}\nfunction reset() {\n\t// console.log('reset now')\n\t// chrome.storage.local.clear()\n\tstorage.set({ keywordMasks: INIT_KEYWORD_MASKS })\n\tstorage.set({ settings: settingConfig })\n\tfor (let task of defaultTasks) {\n\t\tupdateTaskInfo(task)\n\t}\n}\nchrome.runtime.onInstalled.addListener(function (object) {\n\treset()\n})\nchrome.alarms.onAlarm.addListener(function (alarm) {\n\tswitch (true) {\n\t\tcase alarm.name === 'daily':\n\t\t\tcheckAndResetDailyInfo()\n\t\t\tsavePersistentData()\n\t\t\tbreak\n\t\tcase alarm.name.startsWith('scheduled_'):\n\t\t\tconsole.log(alarm.name)\n\t\t\tconst when = alarm.name.split('_')[1]\n\t\t\tgetAutoTasks(when).then(runTask)\n\t\t\tbreak\n\t\tcase alarm.name === 'leak_filling':\n\t\t\truntime.taskQueue.push(()=>{setNotificationLevel(NOTIFICATION_LEVEL.INFO)})\n\t\t\tjoinTaskInQueue(TASK_ID.ACTIVITY_APPLY)\n\t\t\truntime.taskQueue.push(()=>{setNotificationLevel(NOTIFICATION_LEVEL.NORMAL)})\n\t\t\trunTask()\n\t\t\tbreak\n\t\tdefault:\n\t\t\t// console.warn(`unknown alarm:${alarm.name}`)\n\t\t\tbreak\n\t}\n})\n\nchrome.notifications.onClicked.addListener(function (notificationId) {\n\tif (!notificationId || notificationId.split('_').length < 0) {\n\t\treturn\n\t}\n\tconst action = notificationId.split('_')[1]\n\tswitch (action) {\n\t\tcase 'login-fail':\n\t\t\tchrome.tabs.create({\n\t\t\t\turl: \"https://passport.jd.com/new/login.aspx\",\n\t\t\t\tactive: true\n\t\t\t})\n\t\t\tbreak\n\t\tdefault:\n\t\t\t// console.warn(`unknown notificationId:${notificationId}`)\n\t\t\tbreak\n\t}\n})\n\n// 消息处理\nfunction backgroundMessageListener(msg, sender, sendResponse) {\n\tswitch (msg.action) {\n\t\t//from content-script\n\t\tcase 'bg_update_saveinfo':\n\t\t\tsaveinfo = Object.assign(saveinfo, msg.data)  //should check key?\n\t\t\tif (saveinfo.fulfilled) {\n\t\t\t\tsaveinfo.applidActivityNum = 300\n\t\t\t}\n\t\t\tif (saveinfo.noMoreVender) {\n\t\t\t\tsaveinfo.followVenderNum = 500\n\t\t\t}\n\t\t\tbreak\n\t\tcase 'bg_activity_applied':\n\t\t\tif (msg.status) {\n\t\t\t\tupdateActivityItemsStatus(msg.activityId, { status: ACTIVITY_STATUS.APPLIED })\n\t\t\t}\n\t\t\tif (msg.success) {\n\t\t\t\tsaveinfo.applidActivityNum++\n\t\t\t}\n\t\t\temitter.emit(`${msg.activityId}_activity_applied_event`)\n\t\t\tsendMessage({\n\t\t\t\taction: \"popup_update_activity_status\",\n\t\t\t\tactivityId: msg.activityId,\n\t\t\t\tstatus: msg.status\n\t\t\t})\n\t\t\tbreak\n\t\tcase 'bg_login_status_retrieval':\n\t\t\tloginStatus = Object.assign(loginStatus, msg.loginStatus)\n\t\t\temitter.emit('login_status_retrieval_event', { login: msg.status })\n\t\t\tupdateBrowserAction()\n\t\t\tbreak\n\n\t\tcase 'bg_new_activity_retrieval':\n\t\t\tif (msg.activityList.length) {\n\t\t\t\taddActivityItems(msg.activityList)\n\t\t\t}\n\t\t\temitter.emit(msg.href + '_new_activity_retrieval_event', {pageNum:msg.pageNum})\n\t\t\tbreak\n\n\t\tcase 'success_activity_retrieval':\n\t\t\tif (msg.successActivityList.length !== 0) {\n\t\t\t\taddSuccessActivityList(msg.successActivityList)\n\t\t\t}\n\t\t\temitter.emit(msg.href + '_success_activity_retrieval_event', {pageNum:msg.pageNum})\n\t\t\tbreak\n\t\tcase 'bg_follow_vender_num_retrieval':\n\t\t\tif (saveinfo.noMoreVender && msg.followVenderNum < saveinfo.followVenderNum) {\n\t\t\t\tsaveinfo.noMoreVender = false   //update info\n\t\t\t}\n\t\t\tsaveinfo.followVenderNum = msg.followVenderNum\n\t\t\temitter.emit('bg_follow_vender_num_retrieval_event')\n\n\t\t\tif (runtime.taskId === TASK_ID.EMPTY_FOLLOW_VENDER_LIST) { //清空关注列表\n\t\t\t\truntime.doneTask = runtime.totalTask - saveinfo.followVenderNum\n\t\t\t\tif (saveinfo.followVenderNum === 0) {\n\t\t\t\t\temitter.emit('empty_follow_vender_list_event')\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase 'bg_get_login_status':\n\t\t\tsendResponse(loginStatus)\n\t\t\tbreak\n\n\t\tcase 'bg_task_opt':\n\t\t\tconst act = getTaskActionsByHref(msg.data)\n\t\t\tsendResponse(act)\n\t\t\tbreak\n\n\t\t//from popup.html\n\t\t//\n\t\tcase 'bg_scheduled_task':\n\t\t\tinitScheduledTasks()\n\t\t\tbreak\n\t\tcase 'bg_clear_sql_activitys':\n\t\t\tclearActivityItems()\n\t\t\tbreak\n\n\t\tcase 'bg_update_browser_action':\n\t\t\tupdateBrowserAction(msg.force)\n\t\t\tbreak\n\t\tcase 'reset':\n\t\t\tchrome.storage.local.clear()\n\t\t\tchrome.runtime.reload()\n\t\t\tbreak\n\t\tdefault:\n\t\t\tif (msg.action.startsWith('popup')) {\n\t\t\t\tchrome.runtime.sendMessage(msg)\n\t\t\t}\n\t\t\tbreak\n\t}\n}\nchrome.runtime.onMessage.addListener(backgroundMessageListener)\n\nfunction getTaskActionsByHref(data) {\n\n\tconst now = DateTime.local().valueOf()\n\tconst href = data.href\n\tfor (let task of defaultTasks) {\n\t\tif (task.id !== runtime.taskId) continue\n\t\tfor (let ptn of task.href_patterns) {\n\t\t\tif (href.search(ptn) >= 0) { //&& now >= task.last_run_at + task.auto.frequency){\n\t\t\t\treturn task.actions\n\t\t\t}\n\t\t}\n\t}\n\tfor (let task of commonTasks) {\n\t\tfor (let ptn of task.href_patterns) {\n\t\t\tif (href.search(ptn) >= 0) {\n\t\t\t\treturn task.actions\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined\n}\n\n\n// ---------------- 获取关注店铺数量 ----------------//\nasync function followVenderNumberRetrieval() {\n\tconsole.log(`followVenderNumberRetrieval`)\n\n\tswitchTaskId(TASK_ID.FOLLOW_VENDER_NUM_RETRIEVAL)\n\truntime.totalTask = 1\n\truntime.doneTask = 1\n\tconst url = 'https://t.jd.com/follow/vender/list.do?index=1'\n\tconst eventName = 'bg_follow_vender_num_retrieval_event'\n\tconst result = await openByIframeAndWaitForClose(url, eventName, IFRAME_LIFETIME * 2)\n\tif (result === TIMEOUT_ERROR) {\n\t\tnotifications('获取关注数量超时')\n\t}\n\telse{\n\t\tnotifications(`获取关注数量完成，一共关注了${saveinfo.followVenderNum}个店铺`)\n\t}\n\ttaskDone()\n}\n\n// ---------------- 清空关注店铺 ----------------//\nasync function emptyFollowVenderList() {\n\tswitchTaskId(TASK_ID.EMPTY_FOLLOW_VENDER_LIST)\n\truntime.doneTask = 0\n\truntime.totalTask = saveinfo.followVenderNum > 0 ? saveinfo.followVenderNum : 500\n\n\tconst url = 'https://t.jd.com/follow/vender/list.do'\n\tconst eventName = 'empty_follow_vender_list_event'\n\tawait openByIframeAndWaitForClose(url, eventName, 5 * 60 * 1000) // 保留 iframe 五分钟\n\tnotifications(`已完成清理关注店铺列表，当前关注数量为${saveinfo.followVenderNum}`)\n\ttaskDone()\n}\n\n// ---------------- 获取成功列表 ----------------//\nasync function successActivityRetrieval() {\n\n\tswitchTaskId(TASK_ID.SUCCESS_ACTIVITY_RETRIEVAL)\n\truntime.doneTask = 0\n\truntime.totalTask = 1\n\n\tfor (let i = 1; i <= runtime.totalTask; i++) {\n\t\truntime.doneTask++\n\t\tconst url = `https://try.jd.com/user/myTrial?page=${i}&selected=2`\n\t\tconst eventName = `${url}_success_activity_retrieval_event`\n\t\tlet res = await openByIframeAndWaitForClose(url, eventName)\n\t\tif(res == TIMEOUT_ERROR){\n\t\t\tcontinue\n\t\t}\n\t\truntime.totalTask = res.pageNum\n\t}\n\tnotifications('成功项目的检索完毕')\n\ttaskDone()\n}\n\n\n// ---------------- 获取试用列表 ----------------//\nasync function activityRetrieval() {\n\n\t//实际上，商品检索并不需要登录\n\t//所以这里不检查登录状态\n\n\tlet settings = {}\n\n\tawait storage.get({ 'settings': [] }).then(res => { settings = res.settings })\n\tlet cidsList = []\n\tlet activityTypeList = []\n\n\tfor (let activityBtn of settings[0].btns) { //  商品类型\n\t\tif (activityBtn.selected) {\n\t\t\tconsole.log(`即将搜索 ${activityBtn.text} 商品`)\n\t\t\tcidsList.push(activityBtn.value)\n\t\t}\n\t}\n\tfor (let applyBtn of settings[1].btns) { // 试用类型\n\t\tif (applyBtn.selected) {\n\t\t\tconsole.log(`即将搜索 ${applyBtn.text} 试用类型`)\n\t\t\tactivityTypeList.push(applyBtn.value)\n\t\t}\n\t}\n\n\tif (!cidsList.length) {\n\t\tcidsList.push(null)\n\t}\n\tif (!activityTypeList.length) {\n\t\tactivityTypeList.push(null)\n\t}\n\n\tswitchTaskId(TASK_ID.ACTIVITY_RETRIEVAL)\n\truntime.doneTask = 0\n\truntime.totalTask = cidsList.length * activityTypeList.length\n\n\n\tfor (let cids of cidsList) {\n\t\tfor (let activityType of activityTypeList) {\n\t\t\truntime.doneTask++\n\t\t\tawait activityRetrievalByCondition(cids, activityType)\n\t\t}\n\t}\n\tconsole.log('本次搜索完毕')\n\tnotifications('搜索并导入数据库完毕')\n\ttaskDone()\n}\n\n\nasync function activityRetrievalByCondition(cids, activityType) {\n\tconsole.log(`正在获取 cids:${cids} activityType:${activityType} 类型商品`)\n\tlet pageNum = 1\n\n\tfor (let i = 1; i <= pageNum; i++) {\n\t\tconst url = `https://try.jd.com/activity/getActivityList?page=${i}${cids ? '&cids=' + cids : ''}${activityType ? '&activityType=' + activityType : ''}`\n\t\tconst eventName = `${url}_new_activity_retrieval_event`\n\t\tlet res = await openByIframeAndWaitForClose(url, eventName)\n\t\tif(res === TIMEOUT_ERROR){\n\t\t\tcontinue\n\t\t}\n\t\tpageNum = res.pageNum\n\t}\n}\n\n// ---------------- 商品试用申请 ----------------//\nasync function activityApply(activity){\n\n\tif(activity === undefined){\n\t\tconst items = await getActivityItems(1)\n\t\tactivity = items.filter(item => {\n\t\t\treturn item.status === ACTIVITY_STATUS.APPLY\n\t\t})\n\t}\n\n\tconst unSatisfyCondition = ()=> {\n\t\tif (saveinfo.fulfilled) {\n\t\t\tnotifications('今日申请试用份额已满，不再进行试用申请')\n\t\t\treturn true\n\t\t}\n\t\tif (saveinfo.noMoreVender) {\n\t\t\tnotifications('关注数超过上限了哦，请及时清理')\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tif (unSatisfyCondition()) {\n\t\treturn\n\t}\n\n\tswitchTaskId(TASK_ID.ACTIVITY_APPLY)\n\truntime.doneTask = 0\n\truntime.totalTask = activity.length ? activity.length : 1\n\tconsole.log(`即将申请 ${activity.length} 个商品`)\n\n\truntime.applyingActivityIds.length = 0\n\tfor (const item of activity) {\n\t\truntime.applyingActivityIds.push(\n\t\t\titem.id\n\t\t)\n\t}\n\n\tfor (const item of activity) {\n\t\tconst eventName = `${item.id}_activity_applied_event`\n\n\t\tlet cnt = 1\n\t\tif(item.try) cnt = item.try + 1\n\t\tupdateActivityItemsStatus(item.id, {try:cnt})\n\n\t\tawait openByIframeAndWaitForClose(item.url, eventName)\n\t\truntime.applyingActivityIds.shift()\n\n\t\truntime.doneTask++\n\t\tif (unSatisfyCondition()) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tconsole.log('商品试用执行完毕')\n\tif (activity.length > 1) {\n\t\tnotifications(`申请完毕，今日已申请${saveinfo.applidActivityNum}个商品`)\n\t}\n\n\truntime.applyingActivityIds.length = 0\n\ttaskDone()\n}\n\n// ---------------- 获取登陆状态 ----------------//\nasync function loginStatusRetrieval(retry = 0) {\n\tif (retry >= 2) { // 最多重试两次\n\t\tloginStatus.description = '请检查网络状态'\n\t\tloginStatus.shortDescription = '检查超时'\n\t\tloginStatus.status = USER_STATUS.UNKNOWN\n\t\tloginStatus.timestamp = DateTime.local().valueOf()\n\t\tnotifications('检查登录状态失败，请检查网络状态后重试', 'login-fail', NOTIFICATION_LEVEL.INFO)\n\t\treturn false\n\t}\n\n\tswitchTaskId(TASK_ID.CHECK_OR_DO_LOGIN_OPT)\n\tconst url = 'https://try.jd.com/'\n\tconst eventName = `login_status_retrieval_event`\n\tconst result = await openByIframeAndWaitForClose(url, eventName, IFRAME_LIFETIME)\n\ttaskDone()\n\n\tif (result === TIMEOUT_ERROR) {\n\t\treturn loginStatusRetrieval(retry + 1)\n\t}\n\treturn result.login\n}\n\nasync function checkLoginStatusValid() {\n\tconsole.log(`checkLoginStatusValid`)\n\tif (loginStatus.status !== USER_STATUS.LOGIN\n\t\t|| DateTime.local().valueOf() > loginStatus.timestamp + 30 * 60 * 1000) {//半小时\n\n\t\tloginStatus = Object.assign(loginStatus, {\n\t\t\tstatus: USER_STATUS.WARMING,\n\t\t\tdescription: '正在获取登录状态',\n\t\t\tshortDescription: '正在检查',\n\t\t\ttimestamp: 0,\n\t\t})\n\t\treturn loginStatusRetrieval()\n\t}\n\treturn true\n}\n\nfunction checkAndResetDailyInfo() {\n\tconst day = DateTime.local().day\n\tconsole.log(`reset daily info, today:${day}, saveinfo.day:${saveinfo.day}`)\n\tif (day !== saveinfo.day) {\n\t\tsaveinfo.day = day\n\t\tsaveinfo.fulfilled = false\n\t\tsaveinfo.applidActivityNum = 0\n\t\tinitScheduledTasks()\n\t}\n\n\tchrome.alarms.clear('leak_filling')\n\tchrome.alarms.create('daily', {\n\t\twhen: DateTime.local().plus({ day: 1 }).set({\n\t\t\thour: 0,\n\t\t\tminute: 1,\n\t\t\tsecond: 0,\n\t\t}).valueOf()\n\t})\n}\nwindow.joinTaskInQueue = function(task, run=false, data={}){\n\tconsole.log(`joinTaskInQueue`)\n\tconsole.log(task)\n\tlet id = task\n\tif(typeof (task) === 'object'){\n\t\ttask.last_run_at = DateTime.local().valueOf()\n\t\tupdateTaskInfo(task)\n\t\tid = task.id\n\t}\n\tswitch (id) {\n\t\tcase TASK_ID.FOLLOW_VENDER_NUM_RETRIEVAL:\n\t\t\truntime.taskQueue.push(checkLoginStatusValid)\n\t\t\truntime.taskQueue.push(followVenderNumberRetrieval)\n\t\t\tbreak\n\t\tcase TASK_ID.EMPTY_FOLLOW_VENDER_LIST:\n\t\t\truntime.taskQueue.push(checkLoginStatusValid)\n\t\t\truntime.taskQueue.push(emptyFollowVenderList)\n\t\t\tbreak\n\t\tcase TASK_ID.ACTIVITY_RETRIEVAL:\n\t\t\truntime.taskQueue.push(activityRetrieval)\n\t\t\tbreak\n\t\tcase TASK_ID.SUCCESS_ACTIVITY_RETRIEVAL:\n\t\t\truntime.taskQueue.push(checkLoginStatusValid)\n\t\t\truntime.taskQueue.push(successActivityRetrieval)\n\t\t\tbreak\n\t\tcase TASK_ID.ACTIVITY_APPLY:\n\t\t\tif(data.activity){\n\t\t\t\truntime.taskQueue.push(async ()=>{await activityApply(data.activity)})\n\t\t\t}\n\t\t\telse{\n\t\t\t\truntime.taskQueue.push(checkLoginStatusValid)\n\t\t\t\truntime.taskQueue.push(activityApply)\n\t\t\t\truntime.taskQueue.push(followVenderNumberRetrieval)\n\t\t\t}\n\t\t\tbreak\n\t\tcase TASK_ID.CHECK_OR_DO_LOGIN_OPT:\n\t\t\truntime.taskQueue.push(checkLoginStatusValid)\n\t\tdefault:\n\t\t\tbreak\n\t}\n\tif(run){\n\t\trunTask()\n\t}\n}\n\nasync function getAutoTasks(when) {\n\t\n\truntime.taskQueue.push(loginStatusRetrieval)\n\truntime.taskQueue.push(()=>{setNotificationLevel(NOTIFICATION_LEVEL.INFO)})\n\t\n\tconst allTasks = await getAllTasks()\n\n\tconst now = DateTime.local()\n\n\tfor (let task of allTasks) {\n\t\tif (task.auto.run !== true || when != task.auto.when) { // must use !=\n\t\t\tcontinue\n\t\t}\n\t\tif (task.auto.frequency === 'daily' && now.day === DateTime.fromMillis(task.last_run_at).day) {\n\t\t\tconsole.log('当天已执行 ', task)\n\t\t\tcontinue  //已经执行过了\n\t\t}\n\t\tjoinTaskInQueue(task)\n\n\t\t// 两个半小时候后，尝试再次执行 ACTIVITY_APPLY\n\t\tif(task.id === TASK_ID.ACTIVITY_APPLY){\n\t\t\tchrome.alarms.create('leak_filling', {\n\t\t\t\twhen: DateTime.local().plus({ hour: 2, minute:30}) .valueOf()\n\t\t\t})\n\t\t}\n\n\n\t}\n\truntime.taskQueue.push(()=>{setNotificationLevel(NOTIFICATION_LEVEL.NORMAL)})\n\tconsole.log(`join all task in taskQueue`)\n}\n\nwindow.runTask = async function(){\n\tif(runtime.taskQueue.length === 0 || runtime.taskId !== -1){\n\t\tconsole.log(`runtask err, taskQueue.length:${runtime.taskQueue.length}, taskId:${runtime.taskId}`)\n\t\treturn\n\t}\n\n\tswitchTaskId(TASK_ID.RUNNING)\n\twhile(runtime.taskQueue.length !== 0){\n\t\tconst task = runtime.taskQueue.shift()\n\t\tif(await task() === false){\n\t\t\tconsole.warn(task)\n\t\t\tconsole.warn(`任务执行失败`)\n\t\t\truntime.taskQueue.length = 0\n\t\t}\n\t}\n\ttaskDone()\n}\n\nfunction switchTaskId(taskId){\n\truntime.taskIdStack.push(runtime.taskId)\n\truntime.taskId = taskId\n}\nfunction taskDone() {\n\tconsole.log(`taskid: ${runtime.taskId} done`)\n\tif(runtime.taskIdStack.length){\n\t\truntime.taskId = runtime.taskIdStack.pop()\n\t}\n\telse{\n\t\tconsole.warn(`runtime.taskIdStack empty`)\n\t\truntime.taskId = -1\n\t}\n\tsavePersistentData()\n\temitter.emit('taskDone')\n}\n\n//------------------------------------------------------------------//\n\nasync function initScheduledTasks() {\n\t//每次加载插件会执行一次\n\t//每天执行一次\n\t//每次更新自动任务执行一次\n\n\tfor (let i = 0; i < 24; i++) {\n\t\tchrome.alarms.clear(`scheduled_${i}`)\n\t}\n\n\tconst nowHour = DateTime.local().hour\n\tconst autorunat = []\n\tconst allTasks = await getAllTasks()\n\tfor (let task of allTasks) {\n\t\tif (task.auto.run !== true || nowHour >= task.auto.when) {\n\t\t\tcontinue\n\t\t}\n\t\tif (autorunat.indexOf(task.auto.when) === -1) {\n\t\t\tautorunat.push(task.auto.when)\n\t\t}\n\t}\n\tfor (let when of autorunat) {\n\t\tlet timestamp = DateTime.local().set({\n\t\t\thour: when,\n\t\t\tminute: 1,\n\t\t\tsecond: 0,\n\t\t})\n\t\tchrome.alarms.create(`scheduled_${when}`, {\n\t\t\twhen: timestamp.valueOf()\n\t\t})\n\t\tconsole.log(`scheduled_${when} auto run at ${timestamp}`)\n\t}\n\n}\n\nfunction updateBrowserAction(force = false) {\n\tconst warmMsg = \" ! \"\n\tchrome.browserAction.setBadgeBackgroundColor({\n\t\tcolor: \"#FF2800\"\n\t})\n\tswitch (loginStatus.status) {\n\t\tcase USER_STATUS.LOGOUT:\n\t\t\tchrome.browserAction.setBadgeText({\n\t\t\t\ttext: warmMsg\n\t\t\t})\n\t\t\tchrome.browserAction.setTitle({\n\t\t\t\ttitle: \"账号登录失效\"\n\t\t\t})\n\t\t\tbreak\n\t\tdefault:\n\t\t\tchrome.browserAction.getBadgeText({}, text => {\n\t\t\t\tif (!force && text !== warmMsg) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchrome.browserAction.setTitle({\n\t\t\t\t\ttitle: \"京试\"\n\t\t\t\t})\n\t\t\t\tgetSuccessActivityItems().then(list => {\n\t\t\t\t\tchrome.browserAction.setBadgeText({\n\t\t\t\t\t\ttext: list.length === 0 ? '' : list.length.toString()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t\tbreak\n\t}\n}\n\nwindow.onload = () => {\n\tconsole.log(`${DateTime.local()} background.js loading`)\n\tchrome.alarms.clearAll()\n\tstorage.get({ loginStatus: loginStatus }).then(res => { loginStatus = res.loginStatus })\n\tstorage.get({ saveinfo: saveinfo }).then(res => {\n\t\tsaveinfo = res.saveinfo\n\t\tcheckAndResetDailyInfo()\n\t})\n\tinitScheduledTasks()\n\tupdateBrowserAction(true)\n}\n\nwindow.onunload = () => {\n\tsavePersistentData()\n}\n\n// chrome.runtime.sendMessage 调用者无法接收到 调用者发的 sendMessage \n// 但是代码需要调用者收到调用者发送的 sendMessage...\n// 需要消息机制来解耦...\nwindow.sendMessage = function (msg) {\n\tbackgroundMessageListener(msg)\n}"
  },
  {
    "path": "static/config.js",
    "content": "export const settingConfig = [{\n\ttext: \"商品分类\",\n\tname: \"cids\",\n\tbtns: [{\n\t\t\ttext: \"家用电器\",\n\t\t\tvalue: \"737\",\n\t\t\tselected: true\n\t\t},\n\t\t{\n\t\t\ttext: \"手机数码\",\n\t\t\tvalue: \"652,9987\",\n\t\t\tselected: true\n\t\t},\n\t\t{\n\t\t\ttext: \"电脑办公\",\n\t\t\tvalue: \"670\",\n\t\t\tselected: true\n\t\t},\n\t\t{\n\t\t\ttext: \"家居家装\",\n\t\t\tvalue: \"1620,6728,9847,9855,6196,15248,14065\",\n\t\t\tselected: true\n\t\t},\n\t\t{\n\t\t\ttext: \"美妆护肤\",\n\t\t\tvalue: \"1316\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"服饰鞋包\",\n\t\t\tvalue: \"1315,1672,1318,11729\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"母婴玩具\",\n\t\t\tvalue: \"1319,6233\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"生鲜美食\",\n\t\t\tvalue: \"12218\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"图书音像\",\n\t\t\tvalue: \"1713,4051,4052,4053,7191,7192,5272\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"钟表奢品\",\n\t\t\tvalue: \"5025,6144\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"个人护理\",\n\t\t\tvalue: \"16750\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"家庭清洁\",\n\t\t\tvalue: \"15901\",\n\t\t\tselected: false\n\t\t},\n\t\t{\n\t\t\ttext: \"食品饮料\",\n\t\t\tvalue: \"1320,12259\",\n\t\t\tselected: false\n\t\t},\n\t\t// {\n\t\t// \ttext: \"更多惊喜\",\n\t\t// \tvalue: \"4938,13314,6994,9192,12473,6196,5272,12379,13678,15083,15126,15980\",\n\t\t// \tselected: false\n\t\t// }\n\t]\n},\n{\n\ttext: \"试用类型\",\n\tname: \"activityType\",\n\tbtns: [{\n\t\t\ttext: \"免费试用\",\n\t\t\tvalue: \"1\",\n\t\t\tselected: true\n\t\t},\n\t\t{\n\t\t\ttext: \"闪电试\",\n\t\t\tvalue: \"3\",\n\t\t\tselected: true\n\t\t},\n\t\t{\n\t\t\ttext: \"30天试用\",\n\t\t\tvalue: \"5\",\n\t\t\tselected: false\n\t\t}\n\t]\n}\n];\n\nexport const ACTIVITY_STATUS={\n\tAPPLY:0,\n\tAPPLYING:1,\n\tAPPLIED:2\n}\n\nexport const USER_STATUS={\n\tLOGIN:0,\n\tLOGOUT:1,\n\tWARMING:2,\n\tUNKNOWN:3,\n\tLOGINING:4\n}\n\nexport const INIT_KEYWORD_MASKS = [\n\t\"教程\",\n\t\"软件\",\n\t\"英语\",\n\t\"辅导\",\n\t\"培训\",\n]"
  },
  {
    "path": "static/content-script.js",
    "content": "import { suspend, mutationsPromise, simulateClick, parseActivityId, storage } from './utils'\nimport { USER_STATUS, ACTIVITY_STATUS } from './config'\nimport { Toast } from 'vant';\n\nconst task_opts = {\n\tasync auto_login() {\n\n\t\tsimulateClick(document.querySelector('.login-tab.login-tab-r a'), true)\n\n\t\tlet res = await storage.get({ autoLogin: false })\n\t\tif (!res.autoLogin) {\n\t\t\treturn\n\t\t}\n\n\t\tawait suspend(2000)\n\n\t\tres = await storage.get({ account: { username: '', password: '' } })\n\t\tif (!res.account.username || !res.account.password) {\n\t\t\treturn\n\t\t}\n\t\tdocument.querySelector(\"#loginname\").value = res.account.username\n\t\tdocument.querySelector(\"#nloginpwd\").value = res.account.password\n\n\t\tsimulateClick(document.querySelector(\".login-btn a\"), true)\n\n\t\tsetTimeout(() => {\n\t\t\tconsole.warn('自动登录失败')\n\t\t}, 3000)\n\n\t\treturn true\n\t},\n\n\tasync check_login_status(open_link_login=true) {\n\t\tif (document.querySelector(\"#ttbar-login\") === null) { // 检查不到用户登录状态\n\t\t\treturn undefined\n\t\t}\n\t\tlet loginStatus = {\n\t\t\tstatus: USER_STATUS.LOGOUT,\n\t\t\tdescription: '未检查到用户名，点击打开网页登录',\n\t\t\tshortDescription: `未登录`,\n\t\t\ttimestamp: Date.now()\n\t\t}\n\t\tif (document.querySelector(\".nickname\")\n\t\t\t&& document.querySelector(\".nickname\").innerText) {\n\n\t\t\tloginStatus.status = USER_STATUS.LOGIN\n\t\t\tloginStatus.description = `${document.querySelector('.nickname').innerText}`\n\t\t\tloginStatus.shortDescription = '已登录'\n\t\t}\n\t\telse if( open_link_login\n\t\t\t&& document.querySelector('.link-login')\n\t\t\t&& document.querySelector('.link-login') === \"你好，请登录\"){\n\n\t\t\tlet res = await storage.get({ autoLogin: false })\n\t\t\tif(res.autoLogin){\n\t\t\t\tsimulateClick(document.querySelector('.link-login'))\n\t\t\t}\n\n\t\t}\n\n\t\tconst login = loginStatus.status === USER_STATUS.LOGIN\n\t\tchrome.runtime.sendMessage({\n\t\t\taction: \"bg_login_status_retrieval\",\n\t\t\thref: window.location.href,\n\t\t\tloginStatus: loginStatus,\n\t\t\tstatus: login\n\t\t})\n\t\tconsole.log(`登录状态 ${login}`)\n\t\treturn login\n\t},\n\n\tfollow_vender_num_retrieval() {\n\t\tlet num = 0\n\t\tdocument.querySelectorAll('#categoryFilter li').forEach(li => {\n\t\t\tconst reg = /（(\\d*)）/.exec(li.innerText)\n\t\t\tif (reg) {\n\t\t\t\tnum += parseInt(reg[1])\n\t\t\t}\n\t\t})\n\t\tconsole.log(`当前用户一共关注了 ${num} 个店铺`)\n\t\tchrome.runtime.sendMessage({\n\t\t\taction: \"bg_follow_vender_num_retrieval\",\n\t\t\tfollowVenderNum: num\n\t\t})\n\t\treturn true\n\t},\n\tasync empty_follow_vender_list() {\n\t\tlet res = await emptyFollowVenderList()\n\t\tif (!res) {//要么成功自动reload, 要么失败手动reload\n\t\t\twindow.location.reload()\n\t\t}\n\t\treturn res\n\t},\n\tactivity_retrieval() {\n\t\tlet activityList = []\n\t\tdocument.querySelectorAll('.try-item').forEach(activity => {\n\t\t\tlet link = activity.querySelector('.link')\n\t\t\tif (activity.innerHTML.indexOf('已申请') < 0) {\n\t\t\t\tactivityList.push({\n\t\t\t\t\turl: link.href,\n\t\t\t\t\tid: parseInt(activity.parentElement.getAttribute('activity_id')),\n\t\t\t\t\tpic_url: activity.querySelector('img').src,\n\t\t\t\t\tname: activity.querySelector('.p-name').innerText,\n\t\t\t\t\tdetail: activity.querySelector('.p-detail').innerText,\n\t\t\t\t\tprice: parseFloat(activity.querySelector('.p-price span').innerText.substr(1)),\n\t\t\t\t\ttimestamp: parseInt(activity.parentElement.getAttribute('end_time')),\n\t\t\t\t\tstatus: ACTIVITY_STATUS.APPLY\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t\tconsole.log(`页面一共有 ${activityList.length} 个未进行的任务`)\n\t\tconst pages = document.querySelector('.page.clearfix .p-wrap .p-skip b')\n\t\tchrome.runtime.sendMessage({\n\t\t\taction: \"bg_new_activity_retrieval\",\n\t\t\tactivityList: activityList,\n\t\t\thref: window.location.href,\n\t\t\tpageNum:pages ? pages.innerText : 1,\n\t\t})\n\t\treturn true\n\t},\n\tsuccess_activity_retrieval() {\n\t\tlet activityList = document.querySelectorAll('.list-detail-item')\n\t\tif (!activityList) {\n\t\t\tconsole.warn('无法获得/没有申请成功的商品')\n\t\t\treturn false\n\t\t}\n\t\tlet successActivityList = []\n\t\tfor (let activity of activityList) {\n\t\t\tconst countDown = activity.querySelector('.re-time')\n\t\t\tif (!countDown) {//过期了\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst timestamp = parseInt(countDown.getAttribute('end_time')) + countDown.getAttribute('after_hours') * 60 * 60 * 1000\n\t\t\tsuccessActivityList.push({\n\t\t\t\turl: activity.querySelector('.p-name a').href,\n\t\t\t\tid: parseInt(activity.getAttribute('activity_id')),\n\t\t\t\tpic_url: activity.querySelector('img').src,\n\t\t\t\tname: activity.querySelector('.p-name').innerText,\n\t\t\t\tdetail: activity.querySelector('.p-detail').innerText,\n\t\t\t\tprice: parseFloat(activity.querySelector('.p-price span').innerText.substr(1)),\n\t\t\t\ttimestamp: timestamp,\n\t\t\t\tapply: true\n\t\t\t})\n\t\t}\n\t\tconst pages = document.querySelector('.page.clearfix .p-wrap .p-skip b')\n\t\tchrome.runtime.sendMessage({\n\t\t\taction: \"success_activity_retrieval\",\n\t\t\tsuccessActivityList: successActivityList,\n\t\t\thref: window.location.href,\n\t\t\tpageNum: pages ? pages.innerText : 1,\n\t\t})\n\n\t\treturn true\n\t},\n\tasync activity_apply() {\n\t\tconst activityId = parseActivityId(window.location.href)\n\n\t\tlet destoryIframeMsg = (status = false, success = false) => {\n\t\t\tchrome.runtime.sendMessage({\n\t\t\t\taction: \"bg_activity_applied\",\n\t\t\t\thref: window.location.href,\n\t\t\t\tactivityId: activityId,\n\t\t\t\tstatus: status,\n\t\t\t\tsuccess: success\n\t\t\t})\n\t\t}\n\n\t\tlet state = document.querySelector('.state')\n\t\tif (!state) {                                 // 获取不了状态，关闭\n\t\t\tconsole.log(`${window.location.href} 无法获取状态`)\n\t\t\treturn destoryIframeMsg(false) // window.location.reload()\n\t\t}\n\t\tif (state.innerText.startsWith('您已提交申请')) { // 已申请，关闭并更新状态\n\t\t\tconsole.log(`${window.location.href} ${state.innerText}`)\n\t\t\treturn destoryIframeMsg(true)\n\t\t}\n\t\tif (!state.innerText.startsWith('活动已开始')) { // 当前页面不是可以申请的页面，关闭\n\t\t\tconsole.log(`${window.location.href} ${state.innerText}`)\n\t\t\treturn destoryIframeMsg(false)\n\t\t}\n\n\t\tlet res = await clickApplyBtn(activityId)\n\t\tdestoryIframeMsg(res, res)\n\t\treturn res\n\t}\n}\n\nfunction insert_auto_login_btn() {\n\tsimulateClick(document.querySelector('.login-tab.login-tab-r a'), true)\n\tconst autoLoginBtn = document.createElement('p')\n\tautoLoginBtn.innerHTML = \"<span class='jdtry-login'>让京试记住密码并自动登录</span>\"\n\tdocument.querySelector('.item.item-fore5').append(autoLoginBtn)\n\tautoLoginBtn.onclick = () => {\n\t\tconst username = document.querySelector(\"#loginname\").value\n\t\tconst password = document.querySelector(\"#nloginpwd\").value\n\t\tif (!username || !password) {\n\t\t\tToast('请填写账号和密码后重试')\n\t\t\treturn\n\t\t}\n\t\tstorage.set({ account: { username: username, password: password } }).then(() => {\n\t\t\tToast('保存账号和密码成功')\n\n\t\t\tchrome.runtime.sendMessage({\n\t\t\t\taction: \"bg_get_login_status\",\n\t\t\t}, loginStatus => {\n\t\t\t\tconsole.log(loginStatus)\n\t\t\t\tif (loginStatus.status !== USER_STATUS.LOGIN) {\n\t\t\t\t\tsimulateClick(document.querySelector(\".login-btn a\"), true)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t}\n}\nasync function waitForDialog(timeout = 2500) {\n\ttry{\n\t\tawait mutationsPromise(\n\t\t\tdocument.body,\n\t\t\t{ childList: true },\n\t\t\tmutation => {\n\t\t\t\tfor (let node of mutation.addedNodes) {\n\t\t\t\t\tif (node.className.startsWith('ui-dialog')) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\ttimeout,\n\t\t\t\"获得 ui-dialog 弹窗失败\")\n\t}\n\tcatch (e) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nasync function dealWithDialogAlert(innerText) {\n\tif (innerText.indexOf('成功') >= 0) {\n\t\treturn true\n\t}\n\telse if (innerText.indexOf('已超过上限') >= 0) {\n\t\tchrome.runtime.sendMessage({\n\t\t\taction: \"bg_update_saveinfo\",\n\t\t\tdata: { fulfilled: true }\n\t\t})\n\t\tconsole.log('达到每日上限')\n\t\treturn false\n\t}\n\telse if (innerText.indexOf('关注数超过上限了哦') >= 0) {\n\t\tchrome.runtime.sendMessage({           //先将就用这个！\n\t\t\taction: \"bg_update_saveinfo\",\n\t\t\tdata: { noMoreVender: true }\n\t\t})\n\t\tconsole.log('关注数超过上限了哦～先清理下关注列表吧')\n\t\treturn false\n\t}\n\tconsole.warn(`未知DialogAlert弹窗 ${innerText}`)\n\treturn false\n}\n\nasync function clickApplyBtn(activityId) {\n\n\t// 点击试用\n\tlet applyBtn = document.querySelector('.app-btn.btn-application')\n\tif (!applyBtn\n\t\t|| applyBtn.innerText !== '申请试用'\n\t\t|| applyBtn.className.indexOf('app-btn-disabled') >= 0) {\n\t\tconsole.log(`当前页面不可操作`)\n\t\treturn false\n\t}\n\tsimulateClick(applyBtn, true)\n\n\t//检查是否需要关注以及关注状态\n\tlet needFollow = document.body.innerHTML.indexOf('需关注') !== -1\n\tif (needFollow) {\n\t\tconst followStatus = document.querySelector('.btn-def.follow-shop.J-follow-shop')\n\t\tif (followStatus && followStatus.innerText.indexOf('已关注店铺') >= 0) {\n\t\t\tneedFollow = false\n\t\t}\n\t}\n\n\tif (needFollow) {\n\n\t\tconsole.log('需要关注店铺，即将进行关注店铺操作')\n\t\tif(await waitForDialog() === false){\n\t\t\treturn false\n\t\t}\n\n\t\tconst dialog = document.querySelector('.ui-dialog')\n\t\tif (dialog.className.indexOf('tipsAlert') >= 0) {  //此时不应该出现 tipsAlert 的！\n\t\t\treturn dealWithDialogAlert(dialog.innerText)\n\t\t}\n\n\t\tconst btn = dialog.querySelector('.y')\n\t\tif (!btn || btn.innerText !== '关注并申请' || btn.className.indexOf('app-btn-disabled') >= 0) {\n\t\t\tconsole.log(`未知dialog弹窗：${dialog.innerText}`)\n\t\t\treturn false\n\t\t}\n\t\tawait suspend(1000)\n\t\tsimulateClick(btn, true)\n\t}\n\telse {\n\t\tconsole.log('不需要关注店铺，即将获取结果')\n\t}\n\n\tif(await waitForDialog() === false){\n\t\treturn false\n\t}\n\n\tlet result = document.querySelector('.ui-dialog') // 获取整个弹窗的值\n\treturn dealWithDialogAlert(result.innerText)\n}\n\nasync function emptyFollowVenderList() {\n\tconsole.log(`即将执行 emptyFollowVenderList`)\n\n\tif (document.querySelectorAll('.mf-shop-item').length === 0) {\n\t\tconsole.log('已经没有关注的店铺')\n\t\treturn true\n\t}\n\n\tconst allOptBtn = document.querySelector('.batch-box.J-batchBox a') // 批量操作按钮\n\tif (!allOptBtn || allOptBtn.innerText !== '批量操作') {\n\t\tconsole.warn('找不到批量操作按钮')\n\t\treturn false\n\t}\n\tsimulateClick(allOptBtn, true)\n\tawait suspend(1000)\n\n\tconst allCheckBtn = document.querySelector('.batch-box.J-batchBox .op-btn.u-check') // 全选按钮\n\tif (!allCheckBtn || allCheckBtn.innerText !== '全选') {\n\t\tconsole.warn('找不到全选按钮')\n\t\treturn false\n\t}\n\tsimulateClick(allCheckBtn, true)\n\tawait suspend(1000)\n\n\tconst unFollowBtn = document.querySelector('.batch-box.J-batchBox .op-btn.u-unfollow')  //取消关注\n\tif (!unFollowBtn || unFollowBtn.innerText !== '取消关注') {\n\t\tconsole.warn('找不到取消关注按钮')\n\t\treturn false\n\t}\n\tsimulateClick(unFollowBtn, true)\n\n\tif(await waitForDialog() === false){\n\t\treturn false;\n\t}\n\n\tconst dialog = document.querySelector('.ui-dialog')\n\tconst submitBtn = dialog.querySelector('.ui-dialog-btn-submit')\n\tif (!submitBtn || submitBtn.innerText !== '确定') {\n\t\tconsole.warn(`找不到确定关注按钮 ${dialog.innerText}`)\n\t\treturn false\n\t}\n\tsimulateClick(submitBtn, true)\n\n\tawait waitForDialog(10 * 1000)\n\treturn false\n}\n\nasync function do_actions(actions){\n\tif(actions === undefined){\n\t\treturn\n\t}\n\tfor(let act of actions){\n\t\tif(act in task_opts){\n\t\t\tconsole.log(`do ${act} action`)\n\t\t\tif(await task_opts[act]() === false){\n\t\t\t\tconsole.log(`do ${act} action fail`)\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tconsole.warn(`unknown ${act} action`)\n\t\t\tbreak\n\t\t}\n\t}\n}\nwindow.onload = () => {\n\tconsole.log(`${window.location.href} loading`)\n\n\tconst openByBrowser = self === top // 用于标示 是浏览器打开还是脚本使用iframe打开\n\tif (openByBrowser) {\n\t\tif (document.querySelector('.login-tab.login-tab-r')) {\n\t\t\tinsert_auto_login_btn()\n\t\t}\n\t\ttask_opts.check_login_status(false)\n\t\treturn\n\t}\n\n\tsetTimeout(() => {\n\t\tchrome.runtime.sendMessage({\n\t\t\taction: \"bg_task_opt\",\n\t\t\tdata: { href: window.location.href }\n\t\t},actions=>{\n\t\t\tdo_actions(actions)\n\t\t})\n\n\t}, 4000)\n\n}\nwindow.onbeforeunload = () => {\n\tconsole.log(`${window.location.href} unloading`)\n}"
  },
  {
    "path": "static/db.js",
    "content": "import Dexie from 'dexie'\nimport { notifications, NOTIFICATION_LEVEL, storage } from './utils'\n\n\n//\n// Declare Database\n//\n\n// Dexie.delete('JDTryDatabase');\n\nconst db = new Dexie(\"JDTryDatabase\")\ndb.version(1).stores({\n\tactivityItems: \",timestamp,price\",\n\tsuccessActivityItems: \",timestamp\"\n})\n\nexport async function addActivityItems(items) {\n\tlet keys = []\n\tlet newSuccess = true\n\tfor (const item of items) {\n\t\tkeys.push(item.id)\n\t}\n\ttry {\n\t\tawait db.activityItems.bulkAdd(items, keys)\n\t} catch (e) {\n\t\t// console.log(`activityItems add error:${e}`)\n\t\tnewSuccess = e.failures.length !== items.length\n\t}\n\tif (newSuccess) {\n\t\tsendMessage({\n\t\t\taction: \"popup_update_activity\",\n\t\t})\n\t}\n}\n\nexport async function getActivityItems(days = 20) {\n\tconst now = Date.now()\n\tconst endTimeOnFurture = now + 60 * 60 * 1000 * 24 * days\n\tawait db.activityItems.where('timestamp').below(now).delete()\n\n\tlet minPrice\n\tlet keywordMasks\n\tawait storage.get({\n\t\tkeywordMasks: []\n\t}).then(res => keywordMasks = res.keywordMasks)\n\tawait storage.get({\n\t\tminPrice: 0\n\t}).then(res => minPrice = res.minPrice)\n\n\tlet items = await db.activityItems.where('timestamp')\n\t\t.below(endTimeOnFurture)\n\t\t.and(item => {\n\t\t\t// let num = parseInt(/提供(.*)份/.exec(item.detail)[1])\n\t\t\tif (item.deleted) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let mask of keywordMasks) {\n\t\t\t\tif (item.name.indexOf(mask) >= 0) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(item.try) return item.try<3\n\t\t\treturn item.price >= minPrice\n\t\t})\n\t\t.sortBy('price')\n\treturn items.reverse()\n}\n\n// export async function updateActivityItems(items){\n// \treturn db.activityItems.update(items)\n// }\n\nexport async function addSuccessActivityList(items) {\n\tlet keys = []\n\tlet newSuccess = true\n\tfor (const item of items) {\n\t\tkeys.push(item.id)\n\t}\n\ttry {\n\t\tawait db.successActivityItems.bulkAdd(items, keys)\n\t\t//notify 有新的成功的项目\n\t} catch (e) {\n\t\t// console.log(`successActivityItems update error:${e}`)\n\t\tnewSuccess = e.failures.length !== items.length\n\t}\n\tif (newSuccess) {\n\t\tsendMessage({\n\t\t\taction: \"popup_update_success_activity\",\n\t\t})\n\t\tnotifications('恭喜！发现新的成功的商品！', null, NOTIFICATION_LEVEL.INFO)\n\t\tsendMessage({\n\t\t\taction: \"bg_update_browser_action\",\n\t\t\tforce: true\n\t\t})\n\t}\n}\n\nexport async function getSuccessActivityItems(days = 15) {\n\tconst now = Date.now()\n\tconst endTime = now + 60 * 60 * 1000 * 24 * days\n\tawait db.successActivityItems.where('timestamp')\n\t\t.below(now)\n\t\t.delete()\n\t\t.then(deleted => {\n\t\t\tif (deleted) {\n\t\t\t\tsendMessage({\n\t\t\t\t\taction: \"bg_update_browser_action\",\n\t\t\t\t\tforce: true\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\tlet items = await db.successActivityItems.where('timestamp')\n\t\t.below(endTime)\n\t\t.and(item => {\n\t\t\treturn !item.deleted\n\t\t})\n\t\t.sortBy('timestamp')\n\treturn items.reverse()\n}\nexport function deleteItems(option) {\n\tif (option.database === 'activity') {\n\t\tdb.activityItems.update(option.id, { deleted: true })\n\t}\n\telse { //success\n\t\tdb.successActivityItems.update(option.id, { deleted: true })\n\t\tsendMessage({\n\t\t\taction: \"bg_update_browser_action\",\n\t\t\tforce: true\n\t\t})\n\t}\n}\n\nexport function updateActivityItemsStatus(activityId, data) {\n\tdb.activityItems.update(activityId, data).then(function (updated) {\n\t\tif (!updated && typeof (activityId) !== 'number') {\n\t\t\tconsole.warn(`can not find ${activityId} activity, remember that id is Number, ${typeof (activityId)}`);\n\t\t}\n\t})\n}\n\nexport function clearActivityItems() {\n\tdb.activityItems.clear().then(() => {\n\t\tsendMessage({\n\t\t\taction: \"popup_update_activity\",\n\t\t})\n\t})\n}"
  },
  {
    "path": "static/popup.js",
    "content": "import Vue from 'vue'\nimport App from '../components/App.vue'\nimport { Tab, Tabs } from 'vant'\nimport { List } from 'vant'\nimport { Cell, CellGroup } from 'vant';\nimport { Button } from 'vant';\nimport { Field } from 'vant';\nimport { Tag } from 'vant';\nimport { Tabbar, TabbarItem } from 'vant';\n\nimport tippy from 'tippy.js';\nimport 'tippy.js/dist/tippy.css';\nimport { Icon } from 'vant';\nimport { Sticky } from 'vant';\nimport { Stepper } from 'vant';\nimport { Col, Row } from 'vant';\nimport { Search } from 'vant';\nimport '@vant/touch-emulator';\nimport { Toast } from 'vant';\nimport { Dialog } from 'vant';\nimport { Loading } from 'vant';\nimport { Progress } from 'vant';\n\nimport { Switch } from 'vant';\nimport { Divider } from 'vant';\nimport { Circle } from 'vant';\nimport { Popup } from 'vant';\nimport { Form } from 'vant';\n\nVue.use(Form);\n\nVue.use(Popup);\n\nVue.use(Circle);\n\nVue.use(Divider);\n\nVue.use(Switch);\nVue.use(Progress);\n\nVue.use(Loading);\n\nVue.use(Dialog);\n\nVue.use(Toast);\n\n\nVue.use(Search);\n\nVue.use(Col);\nVue.use(Row);\n\nVue.use(Stepper);\n\nVue.use(Sticky);\n\nVue.use(Icon);\n\nfunction tippyElement(el) {\n\tsetTimeout(() => {\n\t\tlet title = el.getAttribute(\"title\");\n\t\tif (title) {\n\t\t\tif (el._tippy) {\n\t\t\t\tel._tippy.setContent(title)\n\t\t\t} else {\n\t\t\t\ttippy(el, {\n\t\t\t\t\tcontent: title,\n\t\t\t\t\tarrow: false\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}, 50);\n}\n\nVue.directive(\"tippy\", {\n\tcomponentUpdated: tippyElement,\n\tinserted: tippyElement\n});\n\nVue.use(Tabbar);\nVue.use(TabbarItem);\n\nVue.use(Tag);\n\nVue.use(Field);\nVue.use(Button);\nVue.use(Cell);\nVue.use(CellGroup);\nVue.use(Tab)\nVue.use(Tabs)\nVue.use(List);\nlet popup = new Vue({\n\tel: '#app',\n\trender: h => h(App),\n\tcomponents: {\n\t\tApp\n\t}\n})\n\n//手动注销，缺一不可\nwindow.onunload = ()=>{\n\tpopup.$destroy()\n\tpopup = null\n}\n\nwindow.sendMessage = function(msg){\n\tchrome.runtime.sendMessage(msg)\n}"
  },
  {
    "path": "static/tasks.js",
    "content": "import { storage } from './utils'\nconst NO_LIMIT = 0\nconst ONE_HOUR = 60 * 60 * 1000\nconst HALF_HOUR = 30 * 60 * 1000\nconst TEN_MINUTE = 10 * 60 * 1000\nexport const TASK_ID = {\n\tFOLLOW_VENDER_NUM_RETRIEVAL:0,\n\tEMPTY_FOLLOW_VENDER_LIST:1,\n\tACTIVITY_RETRIEVAL:2,\n\tSUCCESS_ACTIVITY_RETRIEVAL:3,\n\tACTIVITY_APPLY:4,\n\tCHECK_OR_DO_LOGIN_OPT:5,\n\n\tRUNNING:6978\n}\n\nexport const commonTasks = [\n\t{\n\t\tactions: [\"auto_login\"],\n\t\thref_patterns: [/https:\\/\\/passport.jd.com/]\n\t},\n\t{\n\t\tactions: [\"check_login_status\"],\n\t\thref_patterns: [/https:\\/\\/try.jd.com/]\n\t},\n\t{\n\t\tactions: [\"check_login_status\", \"follow_vender_num_retrieval\"],\n\t\thref_patterns: [\"https://t.jd.com/vender/followVenderList.action*\", \"https://t.jd.com/follow/vender/list.do*\"]\n\t},\n\t{\n\t\tactions: [\"check_login_status\", \"success_activity_retrieval\"],\n\t\thref_patterns: [/https:\\/\\/try.jd.com\\/user\\/myTrial\\?page=\\d*&selected=2/]\n\t}\n]\nexport const defaultTasks = [\n\t{\n\t\tid: TASK_ID.FOLLOW_VENDER_NUM_RETRIEVAL,\n\t\ttitle: \"获取关注数量\",\n\t\tdescription: \"获取关注店铺的数量，请及时清理\",\n\t\tlast_run_at: 0,\n\t\tauto: {\n\t\t\trun: false,\n\t\t\twhen: 11,\n\t\t\tfrequency: NO_LIMIT,\n\t\t},\n\t\tactions: [\"check_login_status\", \"follow_vender_num_retrieval\"],\n\t\thref_patterns: [\"https://t.jd.com/vender/followVenderList.action*\", \"https://t.jd.com/follow/vender/list.do*\"]\n\t},\n\t{\n\t\tid: TASK_ID.EMPTY_FOLLOW_VENDER_LIST,\n\t\ttitle: \"清空关注列表\",\n\t\tdescription: \"取关所有已关注的店铺\",\n\t\tlast_run_at: 0,\n\t\tauto: {\n\t\t\trun: false,\n\t\t\twhen: 11,\n\t\t\tfrequency: NO_LIMIT,\n\t\t},\n\t\tactions: [\"check_login_status\", \"follow_vender_num_retrieval\", \"empty_follow_vender_list\"],\n\t\thref_patterns: [\"https://t.jd.com/vender/followVenderList.action*\", \"https://t.jd.com/follow/vender/list.do*\"]\n\t},\n\t{\n\t\tid: TASK_ID.ACTIVITY_RETRIEVAL,\n\t\ttitle: \"搜索商品\",\n\t\tdescription: \"搜索并入库指定条件下的京东试用商品列表\",\n\t\tlast_run_at: 0,\n\t\tauto: {\n\t\t\trun: false,\n\t\t\twhen: 11,\n\t\t\tfrequency: NO_LIMIT\n\t\t},\n\t\tactions: [\"activity_retrieval\"],\n\t\thref_patterns: [\"https://try.jd.com/activity/getActivityList*\"]\n\t},\n\t{\n\t\tid: TASK_ID.SUCCESS_ACTIVITY_RETRIEVAL,\n\t\ttitle: \"检索成功\",\n\t\tdescription: \"检查是否有新申请成功的项目\",\n\t\tlast_run_at: 0,\n\t\tauto: {\n\t\t\trun: false,\n\t\t\twhen: 11,\n\t\t\tfrequency: NO_LIMIT,\n\t\t},\n\t\tactions: [\"check_login_status\", \"success_activity_retrieval\"],\n\t\thref_patterns: [/https:\\/\\/try.jd.com\\/user\\/myTrial\\?page=\\d*&selected=2/]\n\t},\n\t{\n\t\tid: TASK_ID.ACTIVITY_APPLY,\n\t\ttitle: \"一键申请\",\n\t\tdescription: \"立即执行申请试用商品任务\",\n\t\tlast_run_at: 0,\n\t\tauto: {\n\t\t\trun: false,\n\t\t\twhen: 11,\n\t\t\tfrequency: NO_LIMIT\n\t\t},\n\t\tactions: [\"check_login_status\", \"activity_apply\"],\n\t\thref_patterns: [/https:\\/\\/try.jd.com\\/\\d*\\.html/]\n\t},\n]\n\nexport function updateTaskInfo(task) {\n\tif(typeof (activityId) === 'number'){\n\t\treturn\n\t}\n\tconst taskKey = `task_${task.id}`\n\tstorage.set({ [taskKey]: task })\n}\n\nexport async function getAllTasks() {\n\tconst allTasks = []\n\tconst allPromiseList = []\n\tfor (let task of defaultTasks) {\n\t\tconst taskKey = `task_${task.id}`\n\t\tallPromiseList.push(storage.get(taskKey))\n\t}\n\tawait Promise.all(allPromiseList).then(values => {\n\t\tfor (let value of values) {\n\t\t\tfor (let key in value) {\n\t\t\t\tif (key.startsWith('task_')) {\n\t\t\t\t\tallTasks.push(value[key])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\treturn allTasks\n}"
  },
  {
    "path": "static/utils.js",
    "content": "import { DateTime } from 'luxon'\n\nexport function parseActivityId(href) {\n\tlet activityIdReg = /http[s]:\\/\\/try.jd.com\\/(\\d*)\\.html/\n\tlet activityId = activityIdReg.exec(href)\n\tif (!activityId) {\n\t\treturn null\n\t}\n\treturn parseInt(activityId[1])\n}\n\nexport function mutationsPromise(element, observerConfig, callback, rejectTime = 0, rejectMsg = \"\") {\n\treturn new Promise((resolve, reject) => {\n\t\tlet t\n\t\tconst observer = new MutationObserver((mutations) => {\n\t\t\tfor (let mutation of mutations) {\n\t\t\t\tif (callback(mutation)) {\n\t\t\t\t\tif (t) {\n\t\t\t\t\t\tclearTimeout(t)\n\t\t\t\t\t}\n\t\t\t\t\tobserver.disconnect()\n\t\t\t\t\tresolve(mutation)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tobserver.observe(element, observerConfig)\n\t\tif (rejectTime > 0) {\n\t\t\tt = setTimeout(() => {\n\t\t\t\tobserver.disconnect()\n\t\t\t\treject(rejectMsg)\n\t\t\t}, rejectTime)\n\t\t}\n\t})\n}\n\nexport function suspend(time) {\n\treturn new Promise((resolve, reject) => {\n\t\tsetTimeout(() => resolve(), time)\n\t})\n}\n\nexport function rand(start, end) {\n\treturn (Math.floor(Math.random() * (end - start) + start))\n}\n\n// 如果只是单纯的 element.click() 只会触发 click 事件\n// 按理来说，还需要 mousemove 事件。但是太复杂了\nasync function mockClick(element) {\n\tlet dispatchMouseEvent = function (type, bubbles, cancelable) {\n\t\tlet e = document.createEvent(\"MouseEvents\")\n\t\te.initEvent(type, bubbles, cancelable)\n\t\telement.dispatchEvent(e)\n\t}\n\tif (element) {\n\t\tdispatchMouseEvent('mouseover', true, true)\n\t\tawait suspend(rand(100, 200))\n\t\tdispatchMouseEvent('mousedown', true, true)\n\t\tawait suspend(rand(100, 200))\n\t\tdispatchMouseEvent('mouseup', true, true)\n\t\tawait suspend(rand(100, 200))\n\t\tdispatchMouseEvent('click', true, true)\n\t\tawait suspend(rand(100, 200))\n\t\tdispatchMouseEvent('mouseout', true, true)\n\t}\n}\n\nexport function simulateClick(domNode, mouseEvent) {\n\tif (!domNode) {\n\t\tconsole.warn(`domNode 节点不存在！！！`)\n\t\treturn\n\t}\n\treturn mockClick(domNode)\n\t// if (mouseEvent && domNode) {\n\t// \treturn mockClick(domNode)\n\t// }\n\t// try {\n\t// \tdomNode.trigger(\"tap\")\n\t// \tdomNode.trigger(\"click\")\n\t// } catch (error) {\n\t// \ttry {\n\t// \t\tmockClick(domNode)\n\t// \t} catch (err) {\n\t// \t\tconsole.log('fullback to mockClick', err)\n\t// \t}\n\t// }\n}\n\n\nexport const storage = {\n\tget: function (object) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tchrome.storage.local.get(object, function (items) {\n\t\t\t\tresolve(items)\n\t\t\t})\n\t\t})\n\t},\n\tset: function (object) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tchrome.storage.local.set(object, function () {\n\t\t\t\tresolve()\n\t\t\t})\n\t\t})\n\t}\n}\n\nimport Events from 'events'\nexport const emitter = new Events.EventEmitter()\nexport const IFRAME_LIFETIME = 20 * 1000\nexport const TIMEOUT_ERROR = 'timeout'\nwindow.emitter = emitter  //TODO\n\nexport function waitEventWithPromise(eventName, timeout = IFRAME_LIFETIME) {\n\treturn new Promise((resolve, reject) => {\n\t\tlet t\n\t\tconst listener = (arg) => {\n\t\t\tif (t) {\n\t\t\t\tclearTimeout(t)\n\t\t\t}\n\t\t\tresolve(arg)\n\t\t}\n\t\temitter.once(eventName, listener)\n\t\tif (timeout > 0) {\n\t\t\tt = setTimeout(() => {\n\t\t\t\t// console.warn(`${eventName} 超时`)\n\t\t\t\temitter.removeListener(eventName, listener)\n\t\t\t\treject(TIMEOUT_ERROR)\n\t\t\t}, timeout)\n\t\t}\n\t})\n}\n\nexport async function openByIframeAndWaitForClose(url, eventName, timeout = IFRAME_LIFETIME) {\n\ttry {\n\t\tlet iframe = openByIframe(url, null, timeout)\n\t\tconst result = await waitEventWithPromise(eventName, timeout)\n\t\tsetTimeout(() => { iframe.remove() }, 2000)\n\t\t// iframe.remove()\n\t\treturn result\n\t} catch (e) {\n\t\treturn e\n\t}\n}\nexport function openByIframe(src, iframeid, lifetime = -1) {\n\tlet iframe = document.createElement('iframe')\n\tif (iframeid) {\n\t\tiframe.setAttribute('id', iframeid)\n\t}\n\tiframe.setAttribute('src', src)\n\tdocument.body.appendChild(iframe)\n\tif (lifetime > 0) {\n\t\tsetTimeout(() => {\n\t\t\tiframe.remove()\n\t\t}, lifetime)\n\t}\n\tconsole.log(`create Iframe for ${src}`)\n\treturn iframe\n}\n\nexport const NOTIFICATION_LEVEL={\n\tALL:0,\n\tNORMAL:1,\n\tINFO:2,\n\tNONE:3\n}\nlet notificationLevel = NOTIFICATION_LEVEL.NORMAL\nexport function setNotificationLevel(level) {\n\tnotificationLevel = level\n}\nexport function notifications(msg, id = null, level = NOTIFICATION_LEVEL.NORMAL) {\n\tif(level<notificationLevel){\n\t\treturn\n\t}\n\tif (id) {\n\t\tid = `${Date.now()}_${id}`\n\t}\n\tchrome.notifications.create(id, {\n\t\ttype: 'basic',\n\t\ticonUrl: '../img/icon.png',\n\t\ttitle: '京东试用',\n\t\tmessage: msg\n\t})\n}\n\nexport function readableTime(dateTime, withSeconds = false) {\n\tif (typeof dateTime === 'number') {\n\t\tdateTime = DateTime.fromMillis(dateTime)\n\t}\n\tconst mode = withSeconds ? DateTime.TIME_24_WITH_SECONDS : DateTime.TIME_SIMPLE\n\tif (DateTime.local().hasSame(dateTime, 'day')) {\n\t\treturn '今天 ' + dateTime.setLocale('zh-cn').toLocaleString(mode)\n\t}\n\tif (DateTime.local().hasSame(dateTime.plus({ days: 1 }), 'day')) {\n\t\treturn '昨天 ' + dateTime.setLocale('zh-cn').toLocaleString(mode)\n\t}\n\tif (DateTime.local().hasSame(dateTime.plus({ days: -1 }), 'day')) {\n\t\treturn '明天 ' + dateTime.setLocale('zh-cn').toLocaleString(mode)\n\t}\n\treturn dateTime.setLocale('zh-cn').toFormat('f')\n}"
  },
  {
    "path": "style/content-script.css",
    "content": ".jdtry-login{\n\tcursor: pointer;\n\tmargin-top: 5px;\n\tmargin-bottom: 5px;\n    background: #0b85c3;\n    border: 1px solid #0b85c3;\n    display: block;\n    width: 96%;\n    height: 31px;\n    line-height: 31px;\n    color: #fff;\n    padding: 4px 2%;\n    font-size: 16px;\n    text-align: center;\n}\n"
  },
  {
    "path": "style/popup.css",
    "content": "a {\n\tcolor: #0b85c3;\n}\n\n.contents {\n\twidth: 432px;\n\theight: 600px;\n\n\tbackground: #fafafa;\n}\n\n.login {}\n\n.not-login {\n\tcolor: #646566\n}\n\n.tabbar__loading {\n\theight: 18px;\n\twidth: 18px;\n}\n.tabbar__loading__text{\n\tcolor:#1989fa\n}\n\n.tag{\n\tmargin-right: 2px;\n\tmargin-bottom: 2px;\n}"
  }
]