[
  {
    "path": ".editorconfig",
    "content": "root=true\n\n[*]\ncharset=utf8\nindent_style=space\nindent_size=4\n\n"
  },
  {
    "path": ".gitignore",
    "content": "# Mac OSX\n*.DS_Store\n\n# Built application files\n*.apk\n*.ap_\n\n# Files for the ART/Dalvik VM\n*.dex\n\n# Java class files\n*.class\n\n# Generated files\nbin/\ngen/\nout/\n\n# Gradle files\n.gradle/\nbuild/\n\n# Local configuration file (sdk path, etc)\nlocal.properties\n\n# Proguard folder generated by Eclipse\nproguard/\n\n# Log Files\n*.log\n\n# Android Studio Navigation editor temp files\n.navigation/\n\n# Android Studio captures folder\ncaptures/\n\n# Intellij\n*.iml\n.idea/\n\n# Keystore files\n*.jks\n\n# External native build folder generated in Android Studio 2.2 and later\n.externalNativeBuild\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "## 0.1.1\n- remove update checks\n- fix search in FDroid version\n\n## 0.1.0\n- first release\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://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 album 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 <http://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<http://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<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n \n"
  },
  {
    "path": "README.md",
    "content": "# Funkytunes\n\n[![BuddyBuild](https://dashboard.buddybuild.com/api/statusImage?appID=5922904f63d69200012069fa&branch=master&build=latest)](https://dashboard.buddybuild.com/apps/5922904f63d69200012069fa/build/latest?branch=master)\n\n![Screenshots](screenshots.png)\n\nFunkytunes is a BitTorrent-based music app for Android, like Spotify or\nPandora. You can stream any music for free. The app is completely\nopen-source.\n\n[![Download](download.png)](https://github.com/funkyg/funkytunes/releases/latest)\n\n[Gitlab Mirror](https://gitlab.com/funkydev/funkytunes)\n\n# How does it work?\n\nThe initial album list is simply fetched from the\n[iTunes Album Charts](https://www.apple.com/itunes/charts/albums/).\n\nThe search functionality uses the [Discogs SearchAPI](https://www.discogs.com/).\n\nAfter clicking an album, the app searches for `artist album` on\n[ThePirateProxy](https://theproxypirate.pw) (limited to music). It then takes\nthe magnet link from the first search result, and downloads the torrent file.\nFinally, the first mp3 file in the torrent is downloaded and played as soon\nas its ready. Additional songs are downloaded on demand.\n\n# Building\n\nFunkytunes uses a standard Android build. Just install Android Studio and\nAndroid SDK, import the project, and that's it!\n\n# License\n\nFunkytunes is licensed under [GPLv3](LICENSE)\n"
  },
  {
    "path": "app/.gitignore",
    "content": "/build\n"
  },
  {
    "path": "app/build.gradle",
    "content": "apply plugin: 'com.android.application'\napply plugin: 'kotlin-android'\napply plugin: 'com.github.ben-manes.versions'\napply plugin: \"kotlin-kapt\"\n\nandroid {\n    compileSdkVersion 25\n    buildToolsVersion \"25.0.2\"\n    dataBinding.enabled = true\n    defaultConfig {\n        applicationId \"com.github.funkyg.funkytunes\"\n        minSdkVersion 17\n        targetSdkVersion 25\n        versionCode 6\n        versionName \"0.2.0\"\n    }\n    sourceSets {\n        main.java.srcDirs += 'src/main/kotlin'\n    }\n    applicationVariants.all { variant ->\n        variant.outputs.each { output ->\n            def apkName = 'funkytunes-' + variant.versionName + '.apk';\n            output.outputFile = new File(output.outputFile.parentFile, apkName)\n        }\n    }\n}\n\ndependencies {\n    compile \"com.android.support:appcompat-v7:$support_version\"\n    compile \"com.android.support:design:$support_version\"\n    compile \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\"\n    compile 'com.github.salomonbrys.kotson:kotson:2.5.0'\n    kapt \"com.android.databinding:compiler:$build_tools_version\"\n    compile 'com.github.nitrico.lastadapter:lastadapter:2.2.2'\n    compile 'com.google.guava:guava:20.0'\n    compile 'com.github.bumptech.glide:glide:3.7.0'\n    compile 'org.jsoup:jsoup:1.10.3'\n    compile 'com.android.volley:volley:1.0.0'\n    compile \"com.frostwire:jlibtorrent:$jlibtorrent_version\"\n    compile \"com.frostwire:jlibtorrent-android-arm:$jlibtorrent_version\"\n    compile \"com.frostwire:jlibtorrent-android-x86:$jlibtorrent_version\"\n    compile 'com.google.dagger:dagger:2.11'\n    kapt 'com.google.dagger:dagger-compiler:2.11'\n\tcompile 'com.github.lzyzsd:circleprogress:1.2.1'\n}\n\nkapt.generateStubs = true\n\nrepositories {\n    mavenCentral()\n\tmaven { url \"https://jitpack.io\" }\n}\n"
  },
  {
    "path": "app/lint.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<lint>\n    <issue id=\"GoogleAppIndexingWarning\" severity=\"ignore\"/>\n    <issue id=\"MissingTranslation\" severity=\"ignore\"/>\n</lint>\n"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.github.funkyg.funkytunes\">\n\n    <uses-permission android:name=\"android.permission.INTERNET\" />\n\n    <application\n        android:allowBackup=\"false\"\n        android:icon=\"@drawable/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/AppTheme\"\n        android:name=\".FunkyApplication\">\n        <activity android:name=\".activities.LicenseActivity\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n        <activity android:name=\".activities.MainActivity\"\n            android:launchMode=\"singleTop\" />\n        <activity android:name=\".activities.PlayingQueueActivity\"\n            android:label=\"@string/play_queue\"\n            android:launchMode=\"singleTop\"\n            android:parentActivityName=\".activities.MainActivity\"/>\n        <activity android:name=\".activities.SettingsActivity\"\n            android:label=\"@string/settings\"\n            android:parentActivityName=\".activities.MainActivity\"/>\n        <service android:name=\".service.MusicService\" />\n    </application>\n\n</manifest>\n"
  },
  {
    "path": "app/src/main/java/com/github/funkyg/funkytunes/Util.java",
    "content": "package com.github.funkyg.funkytunes;\n\nimport android.databinding.BindingAdapter;\nimport android.widget.ImageView;\n\nimport com.bumptech.glide.Glide;\n\npublic class Util {\n\n    @BindingAdapter(\"url\")\n    public static void setUrl(ImageView view, String url) {\n        Glide.with(view.getContext()).load(url).into(view);\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/DaggerComponent.kt",
    "content": "package com.github.funkyg.funkytunes\n\nimport com.github.funkyg.funkytunes.activities.MainActivity\nimport com.github.funkyg.funkytunes.network.ChartsFetcher\nimport com.github.funkyg.funkytunes.network.UpdateChecker\nimport com.github.funkyg.funkytunes.network.SearchHandler\nimport com.github.funkyg.funkytunes.network.PirateBayAdapter\nimport com.github.funkyg.funkytunes.network.SkyTorrentsAdapter\nimport com.github.funkyg.funkytunes.service.MusicService\nimport com.github.funkyg.funkytunes.service.NotificationHandler\nimport com.github.funkyg.funkytunes.service.TorrentManager\nimport dagger.Component\nimport javax.inject.Singleton\n\n@Singleton\n@Component(modules = arrayOf(FunkyModule::class))\ninterface DaggerComponent {\n\n    fun inject(app: FunkyApplication)\n    fun inject(chartsFetcher: ChartsFetcher)\n    fun inject(searchHandler: SearchHandler)\n    fun inject(pirateBayAdapter: PirateBayAdapter)\n    fun inject(skyTorrentsAdapter: SkyTorrentsAdapter)\n    fun inject(updateChecker: UpdateChecker)\n    fun inject(musicService: MusicService)\n    fun inject(notificationHandler: NotificationHandler)\n    fun inject(mainActivity: MainActivity)\n    fun inject(torrentManager: TorrentManager)\n\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/FunkyApplication.kt",
    "content": "package com.github.funkyg.funkytunes\n\nimport android.app.Application\nimport javax.inject.Inject\n\n/**\n * Performs initialization for various libraries and HTTP cache.\n */\nclass FunkyApplication : Application() {\n\n    @Inject lateinit var component: DaggerComponent\n\n    override fun onCreate() {\n        super.onCreate()\n\n        DaggerDaggerComponent.builder()\n                .funkyModule(FunkyModule(this))\n                .build()\n                .inject(this)\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/FunkyModule.kt",
    "content": "package com.github.funkyg.funkytunes\n\nimport android.support.v4.app.NotificationManagerCompat\nimport com.android.volley.RequestQueue\nimport com.android.volley.toolbox.Volley\nimport com.github.funkyg.funkytunes.network.*\nimport com.github.funkyg.funkytunes.service.NotificationHandler\nimport com.github.funkyg.funkytunes.service.TorrentManager\nimport dagger.Module\nimport dagger.Provides\nimport javax.inject.Singleton\n\n@Module\nclass FunkyModule(private val app: FunkyApplication) {\n\n    @Provides\n    @Singleton\n    fun getVolleyQueue() = Volley.newRequestQueue(app)\n\n    @Provides\n    @Singleton\n    fun getTorrentManager() = TorrentManager(app)\n\n    @Provides\n    @Singleton\n    fun getNotificationManager() =  NotificationManagerCompat.from(app)\n\n    @Provides\n    fun getChartsFetcher() = ChartsFetcher(app)\n\n    @Provides\n    fun getUpdateChecker() = UpdateChecker(app)\n\n    @Provides\n    fun getSearchHandler() = SearchHandler(app)\n\n    @Provides\n    fun getPirateBayAdapter() = PirateBayAdapter(app)\n\n    @Provides\n    fun getSkyTorrentsAdapter() = SkyTorrentsAdapter(app)\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/Model.kt",
    "content": "package com.github.funkyg.funkytunes\n\nimport android.view.View\n\ndata class Album(val title: String, val artist: String, val year: Int?, val image: Image) {\n    fun getQuery(): String {\n        // Exclude additions like \"(Original Motion Picture Soundtrack)\" or \"(Deluxe Edition)\" from\n        // the query.\n        val name = title.split('(', '[', limit = 2)[0]\n        val yearFormat = year?.toString() ?: \"\"\n        return \"$artist $name $yearFormat\"\n    }\n}\n\ndata class Song(var name: String, var artist: String?, val image: Image, var duration: Int?, val indexInTorrent: Int, var isPlaying: Boolean = false, var isQueued: Boolean = false, var progress: Int = 0) {\n    var isPaused: Boolean = false\n    val songPausedVisible: Int\n        get() = if (isPlaying && !isQueued && isPaused) View.VISIBLE else View.GONE\n    val songPlayingVisible: Int\n        get() = if (isPlaying && !isQueued && !isPaused) View.VISIBLE else View.GONE\n    val songProgressVisible: Int\n        get() = if (isQueued && !isPlaying && progress > 0) View.VISIBLE else View.GONE\n    val songLoadingVisible: Int\n        get() = if (isQueued && !isPlaying && progress <= 0) View.VISIBLE else View.GONE\n    val stringProgress: String\n        get() = progress.toString()\n}\n\ndata class Image(val url: String)\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/activities/BaseActivity.kt",
    "content": "package com.github.funkyg.funkytunes.activities\n\nimport android.content.ComponentName\nimport android.content.Context\nimport android.content.Intent\nimport android.content.ServiceConnection\nimport android.media.AudioManager\nimport android.os.Bundle\nimport android.os.IBinder\nimport android.support.v7.app.AppCompatActivity\nimport com.github.funkyg.funkytunes.service.MusicService\n\nabstract class BaseActivity : AppCompatActivity() {\n\n    protected var service: MusicService? = null\n\n    private val serviceConnection: ServiceConnection = object : ServiceConnection {\n        override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {\n            service = (binder as MusicService.MusicBinder).service\n            onServiceConnected()\n        }\n        override fun onServiceDisconnected(name: ComponentName?) {\n            service = null\n        }\n    }\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        volumeControlStream = AudioManager.STREAM_MUSIC\n        val intent = Intent(this, MusicService::class.java)\n        startService(intent)\n        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)\n    }\n\n    override fun onDestroy() {\n        super.onDestroy()\n        unbindService(serviceConnection)\n    }\n\n    protected open fun onServiceConnected() {\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/activities/LicenseActivity.kt",
    "content": "package com.github.funkyg.funkytunes.activities\n\nimport android.content.Intent\nimport android.databinding.DataBindingUtil\nimport android.graphics.PorterDuff\nimport android.os.Bundle\nimport android.preference.PreferenceManager\nimport android.support.v4.content.ContextCompat\nimport android.support.v7.app.AppCompatActivity\nimport com.github.funkyg.funkytunes.R\nimport com.github.funkyg.funkytunes.databinding.ActivityLicenseBinding\n\n\nclass LicenseActivity : AppCompatActivity() {\n\n    private val PREF_LICENSE_ACCEPTED = \"license_accepted\"\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n\n        val pref = PreferenceManager.getDefaultSharedPreferences(this)\n        if (pref.getBoolean(PREF_LICENSE_ACCEPTED, false)) {\n            startActivity(Intent(this, MainActivity::class.java))\n            finish()\n        }\n\n        val binding =\n                DataBindingUtil.setContentView<ActivityLicenseBinding>(this, R.layout.activity_license)\n        val accentColor = ContextCompat.getColor(this, R.color.colorAccent)\n        binding.accept.background.setColorFilter(accentColor, PorterDuff.Mode.MULTIPLY);\n        binding.leave.background.setColorFilter(accentColor, PorterDuff.Mode.MULTIPLY);\n        binding.accept.setOnClickListener {\n            pref.edit().putBoolean(PREF_LICENSE_ACCEPTED, true).apply()\n            startActivity(Intent(this, MainActivity::class.java))\n            finish()\n        }\n        binding.leave.setOnClickListener { finish() }\n    }\n}"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/activities/MainActivity.kt",
    "content": "package com.github.funkyg.funkytunes.activities\n\nimport android.Manifest\nimport android.app.AlertDialog\nimport android.content.Intent\nimport android.content.pm.PackageManager\nimport android.databinding.DataBindingUtil\nimport android.net.Uri\nimport android.os.Bundle\nimport android.os.Handler\nimport android.support.v4.content.ContextCompat\nimport android.support.v4.app.ActivityCompat\nimport android.support.v4.view.MenuItemCompat\nimport android.support.v7.widget.LinearLayoutManager\nimport android.support.v7.widget.SearchView\nimport android.view.Menu\nimport android.view.MenuItem\nimport android.view.View\nimport android.util.Log\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.BR\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.github.funkyg.funkytunes.R\nimport com.github.funkyg.funkytunes.databinding.ActivityMainBinding\nimport com.github.funkyg.funkytunes.databinding.ItemMainBinding\nimport com.github.funkyg.funkytunes.network.ChartsFetcher\nimport com.github.funkyg.funkytunes.network.SearchHandler\nimport com.github.funkyg.funkytunes.network.UpdateChecker\nimport com.github.funkyg.funkytunes.service.MusicService\nimport com.github.nitrico.lastadapter.Holder\nimport com.github.nitrico.lastadapter.ItemType\nimport com.github.nitrico.lastadapter.LastAdapter\nimport javax.inject.Inject\n\nclass MainActivity : BaseActivity(), SearchView.OnQueryTextListener {\n\n    @Inject lateinit var chartsFetcher: ChartsFetcher\n    @Inject lateinit var updateChecker: UpdateChecker\n    @Inject lateinit var searchHandler: SearchHandler\n    private lateinit var binding: ActivityMainBinding\n\tprivate lateinit var searchDebounceHandler: Handler\n\tprivate lateinit var searchDebounceRunnable: Runnable\n\tprivate var oldSearchText = \"\"\n\tprivate var searchText = \"\"\n    private var searchView: SearchView? = null\n\tprivate val Tag = \"MainActivity\"\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        (applicationContext as FunkyApplication).component.inject(this)\n\n        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)\n        binding.recycler.layoutManager = LinearLayoutManager(this)\n\n        chartsFetcher.fetchAppleAlbumFeed { f -> showAlbums(f) }\n        checkUpdates()\n\n\t\tsearchDebounceHandler = Handler()\n\t\tsearchDebounceRunnable = Runnable {\n\t\t\tif (searchText != oldSearchText) {\n\t\t\t\tif (!searchText.isEmpty()) {\n\t\t\t\t\tdoSearchText(searchText)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tchartsFetcher.fetchAppleAlbumFeed { f -> showAlbums(f) }\n\t\t\t\t}\n\n\t\t\t\toldSearchText = searchText\n\t\t\t}\n\t\t\tsearchDebounceHandler.postDelayed(searchDebounceRunnable, 500)\n\t\t}\n\t\tsearchDebounceHandler.postDelayed(searchDebounceRunnable, 500)\n    }\n\n    override fun onServiceConnected() {\n        binding.bottomControl.container.setMusicService(service!!)\n    }\n\n    private fun showAlbums(albums: List<Album>) {\n        val itemBinding = object : ItemType<ItemMainBinding>(R.layout.item_main) {\n            override fun onBind(holder: Holder<ItemMainBinding>) {\n                holder.itemView.setOnClickListener {\n                    service?.play(holder.binding.album)\n                    startActivity(Intent(this@MainActivity, PlayingQueueActivity::class.java))\n                }\n            }\n        }\n        LastAdapter(albums, BR.album)\n                .map<Album>(itemBinding)\n                .into(binding.recycler)\n        binding.recycler.visibility = View.VISIBLE\n        binding.progress.visibility = View.GONE\n\n    }\n\n\tprivate fun doSearchText(text: String) {\n\t\tSearchHandler(this).search(searchText, { a ->\n\t\t\tshowAlbums(a)\n\t\t})\n\t}\n\n    override fun onCreateOptionsMenu(menu: Menu?): Boolean {\n        super.onCreateOptionsMenu(menu)\n        menuInflater.inflate(R.menu.activity_main, menu)\n        val searchItem = menu!!.findItem(R.id.search)\n        searchView = MenuItemCompat.getActionView(searchItem) as SearchView\n        searchView!!.queryHint = getString(R.string.search_title)\n        searchView!!.setOnQueryTextListener(this)\n        MenuItemCompat.setOnActionExpandListener(searchItem, object : MenuItemCompat.OnActionExpandListener {\n            override fun onMenuItemActionExpand(menuItem: MenuItem): Boolean {\n                return true\n            }\n\n            override fun onMenuItemActionCollapse(menuItem: MenuItem): Boolean {\n                ChartsFetcher(this@MainActivity).fetchAppleAlbumFeed { f -> showAlbums(f) }\n                return true\n            }\n        })\n        return true\n    }\n\n    override fun onOptionsItemSelected(item: MenuItem?): Boolean {\n        when (item?.itemId) {\n            R.id.play_queue -> {\n                startActivity(Intent(this, PlayingQueueActivity::class.java))\n                return true\n            }\n            R.id.settings -> {\n                startActivity(Intent(this, SettingsActivity::class.java))\n                return true\n            }\n            R.id.exit -> {\n                stopService(Intent(this, MusicService::class.java))\n                finish()\n                return true\n            }\n            else -> return super.onOptionsItemSelected(item)\n        }\n    }\n\n    override fun onQueryTextSubmit(query: String): Boolean {\n\t\tif(!query.isEmpty()) {\n\t\t\tdoSearchText(query)\n\t\t}\n\t\treturn true\n\t}\n\n    override fun onQueryTextChange(newText: String): Boolean {\n\t\tthis.searchText = newText\n        return true\n    }\n\n    private fun checkUpdates() {\n        updateChecker.checkUpdate(object : UpdateChecker.UpdateListener {\n            override fun updateAvailable() {\n                AlertDialog.Builder(this@MainActivity)\n                        .setMessage(R.string.update_available)\n                        .setPositiveButton(R.string.download, { _, _ ->\n                            val uri = Uri.parse(getString(R.string.github_update_url))\n                            startActivity(Intent(Intent.ACTION_VIEW, uri))\n                        })\n                        .setNegativeButton(android.R.string.cancel, null)\n                        .show()\n            }\n\n            override fun repoNotFound() {\n                AlertDialog.Builder(this@MainActivity)\n                        .setMessage(R.string.github_repository_missing)\n                        .setPositiveButton(R.string.gitlab_mirror_summary, { _, _ ->\n                            val uri = Uri.parse(getString(R.string.gitlab_mirror_url))\n                            startActivity(Intent(Intent.ACTION_VIEW, uri))\n                        })\n                        .setNegativeButton(android.R.string.cancel, null)\n                        .show()\n            }\n        })\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/activities/PlayingQueueActivity.kt",
    "content": "package com.github.funkyg.funkytunes.activities\n\nimport android.databinding.DataBindingUtil\nimport android.os.Bundle\nimport android.support.v7.widget.LinearLayoutManager\nimport android.util.Log\nimport android.view.View\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.BR\nimport com.github.funkyg.funkytunes.R\nimport com.github.funkyg.funkytunes.Song\nimport com.github.funkyg.funkytunes.databinding.ActivityPlayingQueueBinding\nimport com.github.funkyg.funkytunes.databinding.ItemPlaylistBinding\nimport com.github.funkyg.funkytunes.service.PlaybackInterface\nimport com.github.lzyzsd.circleprogress.DonutProgress\nimport com.github.nitrico.lastadapter.Holder\nimport com.github.nitrico.lastadapter.ItemType\nimport com.github.nitrico.lastadapter.LastAdapter\n\n\nclass PlayingQueueActivity : BaseActivity(), PlaybackInterface {\n\n    private val Tag = \"PlayingQueueActivity\"\n\n    private lateinit var binding: ActivityPlayingQueueBinding\n\n    private var adapter: LastAdapter? = null\n    private var currentPlaylist: List<Song>? = null\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        binding = DataBindingUtil.setContentView(this, R.layout.activity_playing_queue)\n        binding.recycler.layoutManager = LinearLayoutManager(this)\n    }\n\n    override fun onServiceConnected() {\n        service!!.addPlaybackInterface(this)\n        binding.bottomControl.container.setMusicService(service!!)\n    }\n\n    override fun onDestroy() {\n        super.onDestroy()\n        service!!.removePlaybackInterface(this)\n        service?.removePlaybackInterface(binding.bottomControl.root as PlaybackInterface)\n    }\n\n    override fun onPlayAlbum(album: Album) {\n        runOnUiThread {\n            binding.recycler.visibility = View.GONE\n            binding.progress.visibility = View.VISIBLE\n            binding.empty.visibility = View.GONE\n        }\n    }\n\n    override fun onCancelAlbum() {\n        finish()\n    }\n\n    override fun onProgress(indexInTorrent: Int, progress: Int) {\n        val playlist: List<Song>? = currentPlaylist\n        if (playlist == null) {\n            Log.v(Tag, \"Progress received when playlist is null\")\n            return\n        }\n\n        val songs = playlist.filter({s -> s.indexInTorrent == indexInTorrent})\n        if (songs.size == 0) {\n            Log.v(Tag, \"Progress received for unknown file index $indexInTorrent\")\n        }\n        val song = songs[0]\n        val lastProgress = song.progress\n        if (!song.isPlaying) {\n            song.isPlaying = false\n            song.progress = progress.toInt()\n\n            Log.v(Tag, \"Progress[$indexInTorrent] = $progress song=$song (${song.name})\")\n            if(lastProgress != song.progress) {\n                runOnUiThread {\n                    binding.recycler.getAdapter().notifyDataSetChanged()\n                }\n            }\n        } else {\n            Log.v(Tag, \"Progress received when song is playing: $song\")\n        }\n    }\n\n    override fun onPlaySong(song: Song, index: Int) {\n        val playlist: List<Song>? = currentPlaylist\n        if (playlist != null) {\n            for(s in playlist) {\n                s.isPlaying = false\n                s.isPaused = false\n            }\n        } else {\n            Log.v(Tag, \"onPlaySong received when playlist is empty\")\n        }\n        song.isPlaying = true\n        song.isQueued = false\n        song.isPaused = false\n\n        runOnUiThread {\n            binding.recycler.getAdapter().notifyDataSetChanged()\n        }\n        Log.i(Tag, \"Playing track $index, adapter: $adapter\")\n    }\n\n    override fun onEnqueueTrack(index: Int) {\n        val playlist: List<Song>? = currentPlaylist\n        if (playlist != null) {\n            for(s in playlist) {\n                s.isQueued = false\n                s.isPlaying = false\n                s.isPaused = false\n            }\n        } else {\n            Log.v(Tag, \"onEnqueueTrack received when playlist is empty\")\n            return\n        }\n        val song = playlist[index]\n        song.isPlaying = false\n        song.isQueued = true\n\n        runOnUiThread {\n            binding.recycler.getAdapter().notifyDataSetChanged()\n        }\n        Log.i(Tag, \"Enqueued track $index\")\n    }\n\n    override fun onPlaylistLoaded(playlist: List<Song>) {\n        runOnUiThread {\n            currentPlaylist = playlist\n\n            val itemBinder = object : ItemType<ItemPlaylistBinding>(R.layout.item_playlist) {\n                override fun onBind(holder: Holder<ItemPlaylistBinding>) {\n                    holder.binding.root.setOnClickListener {\n                        service!!.playTrack(holder.adapterPosition)\n                    }\n                }\n            }\n\n            adapter = LastAdapter(playlist, BR.song)\n                    .map(Song::class.java, itemBinder)\n                    .into(binding.recycler)\n            binding.recycler.visibility = View.VISIBLE\n            binding.progress.visibility = View.GONE\n            binding.empty.visibility = View.GONE\n        }\n    }\n\n    override fun onPaused() {\n        val playlist: List<Song>? = currentPlaylist\n        if (playlist != null) {\n            for(s in playlist) {\n                s.isPaused = true\n            }\n        }\n        runOnUiThread {\n            binding.recycler.getAdapter().notifyDataSetChanged()\n        }\n    }\n\n    override fun onResumed() {\n        val playlist: List<Song>? = currentPlaylist\n        if (playlist != null) {\n            for(s in playlist) {\n                s.isPaused = false\n            }\n        }\n        runOnUiThread {\n            binding.recycler.getAdapter().notifyDataSetChanged()\n        }\n    }\n\n    override fun onStopped() {\n        binding.recycler.visibility = View.GONE\n        binding.progress.visibility = View.GONE\n        binding.empty.visibility = View.VISIBLE\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/activities/SettingsActivity.kt",
    "content": "package com.github.funkyg.funkytunes.activities\n\nimport android.os.Bundle\nimport android.preference.PreferenceFragment\nimport android.support.v7.app.AppCompatActivity\nimport com.github.funkyg.funkytunes.R\n\nclass SettingsActivity : AppCompatActivity() {\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n\n        fragmentManager.beginTransaction()\n                .replace(android.R.id.content, SettingsFragment())\n                .commit()\n\n    }\n\n    class SettingsFragment : PreferenceFragment() {\n\n        override fun onCreate(savedInstanceState: Bundle?) {\n            super.onCreate(savedInstanceState)\n            addPreferencesFromResource(R.xml.settings)\n            val version = findPreference(\"version\")\n            val pi = activity.packageManager.getPackageInfo(activity.packageName, 0)\n            version.summary = pi.versionName\n        }\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/network/ChartsFetcher.kt",
    "content": "package com.github.funkyg.funkytunes.network\n\nimport android.content.Context\nimport android.os.Handler\nimport android.os.Looper\nimport android.util.Log\nimport com.android.volley.Request\nimport com.android.volley.RequestQueue\nimport com.android.volley.Response\nimport com.android.volley.toolbox.StringRequest\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.github.funkyg.funkytunes.Image\nimport com.github.salomonbrys.kotson.*\nimport com.google.common.util.concurrent.FutureCallback\nimport com.google.common.util.concurrent.Futures\nimport com.google.common.util.concurrent.ListenableFutureTask\nimport com.google.gson.GsonBuilder\nimport com.google.gson.JsonParser\nimport java.lang.Exception\nimport java.text.SimpleDateFormat\nimport java.util.*\nimport javax.inject.Inject\n\nclass ChartsFetcher(context: Context) {\n\n    private val AlbumFeed = \"https://itunes.apple.com/us/rss/topalbums/limit=200/json\"\n    private val Tag = \"ChartsFetcher\"\n    private val DATE_FORMAT = SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZZZZ\")\n\n    @Inject lateinit var volleyQueue: RequestQueue\n\n    init {\n        (context.applicationContext as FunkyApplication).component.inject(this)\n    }\n\n    fun fetchAppleAlbumFeed(listener: (List<Album>) -> Unit) {\n        volleyQueue.add(StringRequest(Request.Method.GET, AlbumFeed, Response.Listener<String> { reply ->\n            val f = ListenableFutureTask.create { parseFeed(reply) }\n            Futures.addCallback(f, object : FutureCallback<List<Album>> {\n                override fun onSuccess(result: List<Album>?) { listener(result!!) }\n                override fun onFailure(t: Throwable?) {}\n            }, { command -> Handler(Looper.getMainLooper()).post(command)\n            })\n            Thread(f).start()\n        }, Response.ErrorListener { error ->\n            Log.w(Tag, error)\n        }))\n    }\n\n    private fun parseFeed(data: String): List<Album> {\n        val json = JsonParser().parse(data)[\"feed\"][\"entry\"].array\n        return Gson.fromJson<List<Album>>(json)\n    }\n\n    private val Gson = GsonBuilder()\n            .registerTypeAdapter<Album> {\n                deserialize {\n                    val year = try {\n                        val date = DATE_FORMAT.parse(it.json[\"im:releaseDate\"][\"label\"].string)\n                        val calendar = Calendar.getInstance()\n                        calendar.time = date\n                        calendar.get(Calendar.YEAR)\n                    } catch (e: Exception) {\n                        Log.w(Tag, e)\n                        null\n                    }\n\n                    Album(it.json[\"im:name\"][\"label\"].string,\n                            it.json[\"im:artist\"][\"label\"].string,\n                            year,\n                            it.context.deserialize<List<Image>>(it.json[\"im:image\"].array).last())\n                }\n            }\n            .registerTypeAdapter<Image> {\n                deserialize {\n                    Image(it.json[\"label\"].string)\n                }\n            }\n            .create()\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/network/PirateBayAdapter.kt",
    "content": "package com.github.funkyg.funkytunes.network\n\nimport android.content.Context\nimport android.util.Log\nimport com.android.volley.RequestQueue\nimport com.android.volley.Response\nimport com.android.volley.toolbox.StringRequest\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.frostwire.jlibtorrent.*\nimport com.github.funkyg.funkytunes.R\nimport java.net.URLEncoder\nimport java.text.ParseException\nimport java.text.SimpleDateFormat\nimport java.util.*\nimport javax.inject.Inject\nimport kotlin.collections.ArrayList\n\n/**\n * Parses Pirate Bay search results from HTML.\n *\n * Based on Transdroid Search\n * https://github.com/erickok/transdroid-search/blob/master/app/src/main/java/org/transdroid/search/ThePirateBay/PirateBayAdapter.java\n */\nclass PirateBayAdapter(context: Context) {\n\n    private val Tag = \"PirateBayAdapter\"\n    private val DOMAINS = arrayOf(\"https://pirateproxy.cc\", \"https://pirateportal.xyz\", \"https://thepiratebay.org\")\n    private val SORT_SEEDS = \"7\"\n    private val CATEGORY_MUSIC = \"101\"\n    private val QUERYURL = \"/search/%1\\$s/0/$SORT_SEEDS/$CATEGORY_MUSIC\"\n\n    @Inject lateinit var volleyQueue: RequestQueue\n\n    init {\n        (context.applicationContext as FunkyApplication).component.inject(this)\n    }\n\n    fun search(album: Album, resultCollector: SearchResultCollector) {\n\t\tsearch_mirror(0, album, resultCollector)\n\t}\n\n    fun search_mirror(retry: Int, album: Album, resultCollector: SearchResultCollector) {\n        // Exclude additions like \"(Original Motion Picture Soundtrack)\" or \"(Deluxe Edition)\" from\n        // the query.\n\t\tval query = album.getQuery()\n\t\tif(retry < DOMAINS.size) {\n\t\t\tval domain = DOMAINS[retry]\n\t\t\t// Build full URL string\n\t\t\tval url = String.format(domain + QUERYURL, URLEncoder.encode(query, \"UTF-8\"))\n\t\t\tLog.i(Tag, \"Trying URL: \" + url)\n\n\t\t\tval request = object : StringRequest(Method.GET, url, Response.Listener<String> Req@ { reply ->\n\t\t\t\tval parsedResults = parseHtml(reply, domain)\n\t\t\t\twhen (parsedResults.isEmpty()) {\n\t\t\t\t\tfalse -> { for(r in parsedResults) {\n\t\t\t\t\t\t\t\tresultCollector.watchRequest(r.magnetLink)\n\t\t\t\t\t\t\t\tresultCollector.addResult(r)\n\t\t\t\t\t\t\t   }   \n\t\t\t\t\t\t\t }\n\t\t\t\t}\n\t\t\t\tLog.i(Tag, \"GO()!!!!\")\n\t\t\t\tresultCollector.go()\n\t\t\t}, Response.ErrorListener { error ->\n\t\t\t\tsearch_mirror(retry + 1, album, resultCollector)\n\t\t\t}) {\n\t\t\t\toverride fun getHeaders(): MutableMap<String, String> {\n\t\t\t\t\tval headers = HashMap<String, String>()\n\t\t\t\t\t// Spoof Firefox user agent to force a result from The Pirate Bay\n\t\t\t\t\theaders.put(\"User-agent\", \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2\")\n\t\t\t\t\treturn headers\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvolleyQueue.add(request)\n\t\t} else {\n\t\t\tLog.i(Tag, \"GO()!!!! [2]\")\n\t\t\tresultCollector.go()\n\t\t}\n    }\n\n    private fun parseHtml(html: String, prefixDetails: String): List<SearchResult> {\n        // Texts to find subsequently\n        val RESULTS = \"<table id=\\\"searchResult\\\">\"\n        val TORRENT = \"<div class=\\\"detName\\\">\"\n\n        // Parse the search results from HTML by looking for the identifying texts\n        val results = ArrayList<SearchResult>()\n        val resultsStart = html.indexOf(RESULTS) + RESULTS.length\n\n        var torStart = html.indexOf(TORRENT, resultsStart)\n        while (torStart >= 0) {\n            val nextTorrentIndex = html.indexOf(TORRENT, torStart + TORRENT.length)\n            if (nextTorrentIndex >= 0) {\n                results.add(parseHtmlItem(html.substring(torStart + TORRENT.length, nextTorrentIndex), prefixDetails))\n            } else {\n                results.add(parseHtmlItem(html.substring(torStart + TORRENT.length), prefixDetails))\n            }\n            torStart = nextTorrentIndex\n        }\n        return results\n    }\n\n    private fun parseHtmlItem(htmlItem: String, prefixDetails: String): SearchResult {\n        // Texts to find subsequently\n        val DETAILS = \"<a href=\\\"\"\n        val DETAILS_END = \"\\\" class=\\\"detLink\\\"\"\n        val NAME = \"\\\">\"\n        val NAME_END = \"</a>\"\n        val MAGNET_LINK = \"<a href=\\\"\"\n        val MAGNET_LINK_END = \"\\\" title=\\\"Download this torrent using magnet\"\n        val DATE = \"detDesc\\\">Uploaded \"\n        val DATE_END = \", Size \"\n        val SIZE = \", Size \"\n        val SIZE_END = \", ULed by\"\n        val SEEDERS = \"<td align=\\\"right\\\">\"\n        val SEEDERS_END = \"</td>\"\n        val LEECHERS = \"<td align=\\\"right\\\">\"\n        val LEECHERS_END = \"</td>\"\n        val prefixYear = (Date().year + 1900).toString() + \" \" // Date.getYear() gives the current year - 1900\n        val df1 = SimpleDateFormat(\"yyyy MM-dd HH:mm\", Locale.US)\n        val df2 = SimpleDateFormat(\"MM-dd yyyy\", Locale.US)\n\n        val detailsStart = htmlItem.indexOf(DETAILS) + DETAILS.length\n        var details = htmlItem.substring(detailsStart, htmlItem.indexOf(DETAILS_END, detailsStart))\n        details = prefixDetails + details\n        val nameStart = htmlItem.indexOf(NAME, detailsStart) + NAME.length\n        val name = htmlItem.substring(nameStart, htmlItem.indexOf(NAME_END, nameStart))\n\n        // Magnet link is first\n        val magnetLinkStart = htmlItem.indexOf(MAGNET_LINK, nameStart) + MAGNET_LINK.length\n        val magnetLink = htmlItem.substring(magnetLinkStart, htmlItem.indexOf(MAGNET_LINK_END, magnetLinkStart))\n\n        val dateStart = htmlItem.indexOf(DATE, magnetLinkStart) + DATE.length\n        var dateText = htmlItem.substring(dateStart, htmlItem.indexOf(DATE_END, dateStart))\n        dateText = dateText.replace(\"&nbsp;\", \" \")\n        var date: Date? = null\n        if (dateText.startsWith(\"Today\")) {\n            date = Date()\n        } else if (dateText.startsWith(\"Y-day\")) {\n            date = Date(Date().time - 86400000L)\n        } else {\n            try {\n                date = df1.parse(prefixYear + dateText)\n            } catch (e: ParseException) {\n                try {\n                    date = df2.parse(dateText)\n                } catch (e1: ParseException) {\n                    // Not parsable at all; just leave it at null\n                }\n\n            }\n        }\n\n        val sizeStart = htmlItem.indexOf(SIZE, dateStart) + SIZE.length\n        var size = htmlItem.substring(sizeStart, htmlItem.indexOf(SIZE_END, sizeStart))\n        size = size.replace(\"&nbsp;\", \" \")\n        val seedersStart = htmlItem.indexOf(SEEDERS, sizeStart) + SEEDERS.length\n        val seedersText = htmlItem.substring(seedersStart, htmlItem.indexOf(SEEDERS_END, seedersStart))\n        val seeders = Integer.parseInt(seedersText)\n        val leechersStart = htmlItem.indexOf(LEECHERS, seedersStart) + LEECHERS.length\n        val leechersText = htmlItem.substring(leechersStart, htmlItem.indexOf(LEECHERS_END, leechersStart))\n        val leechers = Integer.parseInt(leechersText)\n\n        return SearchResult(name, magnetLink, null, details, \n\t\t\t\t\t\t\tsize, date, seeders, leechers,\n\t\t\t\t\t\t\tnull\n\t\t\t\t\t)\n    }\n\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/network/SearchHandler.kt",
    "content": "package com.github.funkyg.funkytunes.network\n\nimport android.content.Context\nimport android.net.Uri\nimport android.util.Log\nimport com.android.volley.RequestQueue\nimport com.android.volley.Response\nimport com.android.volley.toolbox.StringRequest\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.github.funkyg.funkytunes.Image\nimport com.github.salomonbrys.kotson.*\nimport com.google.gson.GsonBuilder\nimport com.google.gson.JsonParser\nimport java.util.*\nimport javax.inject.Inject\n\nclass SearchHandler(val context: Context) {\n\n    private val Tag = \"SearchHandler\"\n    private val SEARCH_URL = Uri.parse(\"https://api.discogs.com/database/search\")\n    private val DISCOGS_API_KEY = \"VDgrHCFJOTSTdUMyvCAe\"\n    private val DISCOGS_API_SECRET = \"HXHPkmfJJnrcfYmYYfBXrdlRDLAVmmuA\"\n\n    @Inject lateinit var volleyQueue: RequestQueue\n\n    private val Gson = GsonBuilder()\n            .registerTypeAdapter<Album> {\n                deserialize {\n                    // HACK: Apparently Discogs does not return artist and title seperately, so we\n                    //       have to extract them this way. Also, some results dont have a year.\n                    val year by it.json.byNullableInt(\"year\")\n                    Album(it.json[\"title\"].string.split(\" - \")[1],\n                            it.json[\"title\"].string.split(\" - \")[0],\n                            year,\n                            Image(it.json[\"thumb\"].string))\n                }\n            }\n            .create()\n\n    init {\n        (context.applicationContext as FunkyApplication).component.inject(this)\n    }\n\n    fun search(query: String, listener: (List<Album>) -> Unit) {\n        val uri = SEARCH_URL.buildUpon()\n                .appendQueryParameter(\"q\", query)\n                .appendQueryParameter(\"type\", \"release\")\n                .appendQueryParameter(\"key\", DISCOGS_API_KEY)\n                .appendQueryParameter(\"secret\", DISCOGS_API_SECRET)\n                .build()\n\n\t\tLog.i(Tag, uri.toString())\n\n        val request = object : StringRequest(Method.GET, uri.toString(), Response.Listener<String> { reply ->\n            listener(parseFeed(reply))\n        }, Response.ErrorListener { error ->\n            Log.w(Tag, error)\n        }) {\n            override fun getHeaders(): MutableMap<String, String> {\n                val headers = HashMap<String, String>()\n                headers.put(\"User-agent\", \"funkytunes\")\n                return headers\n            }\n        }\n\n        volleyQueue.add(request)\n    }\n\n    private fun parseFeed(data: String): List<Album> {\n        val json = JsonParser().parse(data)[\"results\"].array\n        val items = Gson.fromJson<List<Album>>(json)\n        // HACK: Discogs returns many duplicate releases, so we try to remove duplicates by filtering\n        //       for unique artist and title.\n        return items.distinctBy { x -> x.artist + x.title }\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/network/SearchResultCollector.kt",
    "content": "package com.github.funkyg.funkytunes.network\n\nimport android.util.Log\nimport com.android.volley.Request\nimport com.android.volley.toolbox.StringRequest\nimport com.frostwire.jlibtorrent.*\nimport com.github.funkyg.funkytunes.R\nimport java.util.*\n\n/* Torrent search result */\nclass SearchResult(val title: String, val magnetLink: String, val torrentUrl: String?, val detailsUrl: String,\n\t\t\t\t\tval size: String, val added: Date?, val seeds: Int, val leechers: Int,\n\t\t\t\t\tvar torrentInfo: TorrentInfo?) {\n\tprivate var isFlac = false\n\n\tfun score(): Int {\n\t\tval peers = seeds + leechers\n\t\tval torrentAvailableMultiplier = if(torrentInfo == null) 1 else 50\n\t\tval nonFlacMultiplier = if(isFlac) 1 else 2\n\n\t\treturn peers * torrentAvailableMultiplier * nonFlacMultiplier\n\t}\n\tfun flacDetected() {\n\t\tisFlac = true\n\t}\n}\n\n/*\n * Collects responses from torrent requests\n * Calls a callback when all results are complete\n */\n\nclass SearchResultCollector(val numAdapters: Int, val torrentListener: (TorrentInfo)->Unit, val magnetListener: (String)->Unit, val errorListener: (Int) -> Unit) {\n\tprivate val Tag = \"ResultCollector\"\n\tprivate val watchedRequests = arrayListOf<String>()\n\tprivate var failedRequests = 0\n\tprivate val searchResults = arrayListOf<SearchResult>()\n\tprivate var readyToGo = 0\n\tprivate var wasComplete = false\n\n\tfun watchRequest(req: Request<TorrentInfo>) {\n\t\twatchedRequests.add(req.getUrl())\n\t}\n\n\tfun watchRequest(req: StringRequest) {\n\t\twatchedRequests.add(req.getUrl())\n\t}\n\n\tfun watchRequest(req: String) {\n\t\twatchedRequests.add(req)\n\t}\n\n\tprivate fun getBestResult(): SearchResult {\n\t\tassert(searchResults.size > 0)\n\t\tval eligibleTorrents = searchResults\n\t\t                       .sortedByDescending {r -> r.score()}\n\t\tLog.i(Tag, \"Selecting torrent: ${eligibleTorrents[0].detailsUrl}\")\n\t\treturn eligibleTorrents[0]\n\t}\n\n\tprivate fun checkComplete(force: Boolean = false) {\n\t\tif(readyToGo < numAdapters) {\n\t\t\tLog.i(Tag, \"Not readyToGo yet. Force: $force, readyToGo: $readyToGo, all: ${watchedRequests.size}, fail $failedRequests, results ${searchResults.size}\")\n\t\t\treturn\n\t\t}\n\n\t\tif(wasComplete) {\n\t\t\tLog.i(Tag, \"checkComplete called on already completed result\")\n\t\t\treturn\n\t\t}\n\n\t\tif(watchedRequests.size <= failedRequests + searchResults.size || force) {\n\t\t\tLog.i(Tag, \"Ckecking results. Force: $force, readyToGo: $readyToGo, all: ${watchedRequests.size}, fail $failedRequests, results ${searchResults.size}\")\n\t\t\tif(searchResults.size > 0) {\n\t\t\t\t/* Success - got one or more good results */\n\t\t\t\tval bestResult = getBestResult()\n\t\t\t\tvar sent = false\n\t\t\t\tbestResult.torrentInfo?.let { ti ->\n\t\t\t\t\tLog.i(Tag, \"Starting torrent download\")\n\t\t\t\t\ttorrentListener(ti)\n\t\t\t\t\tsent = true\n\t\t\t\t}\n\t\t\t\tif(!sent) {\n\t\t\t\t\tLog.i(Tag, \"Starting manget download\")\n\t\t\t\t\tmagnetListener(bestResult.magnetLink)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif(watchedRequests.size > 0) {\n\t\t\t\t\tLog.w(Tag, \"All requests failed\")\n\t\t\t\t\terrorListener(R.string.error_no_torrent_found)\n\t\t\t\t}\n\t\t\t}\n\t\t\twasComplete = true\n\t\t} else {\n\t\t\tval totalCompleted = failedRequests + searchResults.size\n\t\t\tLog.i(Tag, \"${totalCompleted} / ${watchedRequests.size} - ${searchResults.size} usable\")\n\t\t\tfor(request in watchedRequests) {\n\t\t\t\tLog.i(Tag, \"INQUEUE: \" + request)\n\t\t\t}\n\t\t}\n\t}\n\n\tfun addFailed() {\n\t\tfailedRequests = failedRequests + 1\n\t\tcheckComplete()\n\t}\n\n\tfun addResult(result: SearchResult) {\n\t\tsearchResults.add(result)\n\t\tcheckComplete()\n\t}\n\n\t/* Additional lock - no listeners will be called before go() is called */\n\t/* Call it when all the requests have been added in the last adapter */\n\tfun go() {\n\t\treadyToGo++\n\t\tcheckComplete()\n\t}\n\n\tfun forceGo() {\n\t\treadyToGo = numAdapters\n\t\tcheckComplete(true)\n\t}\n\n\tfun notify429() {\n\t\terrorListener(R.string.error_429)\n\t}\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/network/SkyTorrentsAdapter.kt",
    "content": "package com.github.funkyg.funkytunes.network\n\nimport android.content.Context\nimport android.util.Log\nimport com.android.volley.toolbox.HttpHeaderParser\nimport com.android.volley.Request\nimport com.android.volley.RequestQueue\nimport com.android.volley.Response\nimport com.android.volley.NetworkResponse\nimport com.android.volley.VolleyError\nimport com.android.volley.toolbox.StringRequest\nimport com.frostwire.jlibtorrent.*\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.github.funkyg.funkytunes.R\nimport com.google.common.io.Files\nimport java.io.IOException\nimport java.net.URLEncoder\nimport java.text.ParseException\nimport java.text.SimpleDateFormat\nimport java.util.*\nimport javax.inject.Inject\nimport kotlin.collections.ArrayList\n\n/**\n * Parses SkyTorrents search results from HTML.\n */\nclass SkyTorrentsAdapter(context: Context) {\n\n    private val Tag = \"SkyTorrentsAdapter\"\n    private val DOMAINS = arrayOf(\"https://www.skytorrents.in\")\n    private val QUERYURL = \"/search/all/ss/1/?l=en_us&q=%s\"\n\n    @Inject lateinit var volleyQueue: RequestQueue\n\n    init {\n        (context.applicationContext as FunkyApplication).component.inject(this)\n    }\n\n    fun search(album: Album, resultCollector:SearchResultCollector) {\n\t\tsearch_mirror(0, album, resultCollector)\n\t}\n\n    fun search_mirror(retry: Int, album: Album, resultCollector: SearchResultCollector) {\n\t\tval query = album.getQuery()\n\n\t\tif(retry < DOMAINS.size) {\n\t\t\tval domain = DOMAINS[retry]\n\t\t\t// Build full URL string\n\t\t\tval url = String.format(domain + QUERYURL, URLEncoder.encode(query, \"UTF-8\"))\n\t\t\tLog.i(Tag, \"Trying URL: \" + url)\n\n\t\t\t// Get the results page \n\t\t\tval request = object : StringRequest(Method.GET, url, Response.Listener<String> { reply ->\n\t\t\t\tval parsedResults = parseHtml(reply, domain)\n\n\t\t\t\t// Fetch torrent files for results\n\t\t\t\tfor (item in parsedResults) {\n\t\t\t\t\tLog.i(Tag, \"Trying torrent URL: \" + item.torrentUrl)\n\t\t\t\t\tval torrentRequest = object : Request<TorrentInfo>(Method.GET, item.torrentUrl, Response.ErrorListener { error ->\n\t\t\t\t\t\tLog.i(Tag, \"Volley error '\" + error.message + \"' for URL: \" + item.torrentUrl)\n\t\t\t\t\t\tval lowerTitle = item.title.toLowerCase()\n\t\t\t\t\t\t// Add magnet if it has a supported file format in name\n\t\t\t\t\t\tif(lowerTitle.indexOf(\"mp3\") != -1 || lowerTitle.indexOf(\"ogg\") != -1 || lowerTitle.indexOf(\"m4a\") != -1) {\n\t\t\t\t\t\t\tresultCollector.addResult(item)\n\t\t\t\t\t\t} else if(lowerTitle.indexOf(\"flac\") != -1) {\n\t\t\t\t\t\t\titem.flacDetected()\n\t\t\t\t\t\t\tresultCollector.addResult(item)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresultCollector.addFailed()\n\t\t\t\t\t\t}\n\t\t\t\t\t}){\n\t\t\t\t\t\toverride fun parseNetworkResponse(response: NetworkResponse) : Response<TorrentInfo> {\n\t\t\t\t\t\t\tif (response.statusCode == 429) {\n\t\t\t\t\t\t\t\tresultCollector.notify429()\n\t\t\t\t\t\t\t\treturn Response.error(VolleyError(\"Error 429 getting torrent from \" + item.torrentUrl))\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tval bytes = response.data\n\t\t\t\t\t\t\t\tif (bytes != null) {\n\t\t\t\t\t\t\t\t\tval tmp = createTempFile(\"funkytunes\", \".torrent\")\n\t\t\t\t\t\t\t\t\tFiles.write(bytes, tmp)\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tval ti = TorrentInfo(tmp)\n\n\t\t\t\t\t\t\t\t\t\treturn Response.success(ti, HttpHeaderParser.parseCacheHeaders(response))\n\t\t\t\t\t\t\t\t\t} catch (e: IllegalArgumentException) {\n\t\t\t\t\t\t\t\t\t\treturn Response.error(VolleyError(\"Error \" + e.message + \" parsing torrent from \" + item.torrentUrl))\n\t\t\t\t\t\t\t\t\t} catch (e: IOException) {\n\t\t\t\t\t\t\t\t\t\treturn Response.error(VolleyError(\"Error \" + e.message + \" parsing torrent from \" + item.torrentUrl))\n\t\t\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\t\t\ttmp.delete()\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tLog.i(Tag, \"Empty bytes returned from URL: \" + item.torrentUrl)\n\t\t\t\t\t\t\t\t\treturn Response.error(VolleyError(\"Empty bytes returned from URL: \" + item.torrentUrl))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\toverride fun deliverResponse(response: TorrentInfo) {\n\t\t\t\t\t\t\tval ti = response\n\t\t\t\t\t\t\titem.torrentInfo = ti\n\n\t\t\t\t\t\t\tval origFiles = ti.origFiles()\n\t\t\t\t\t\t\tvar fileUsable = false\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tLog.i(Tag, \"Parsing torrent from URL: \" + item.torrentUrl)\n\t\t\t\t\t\t\t\tfor (fileNum in 0..origFiles.numFiles()-1) {\n\t\t\t\t\t\t\t\t\tval fileName = origFiles.filePath(fileNum)\n\t\t\t\t\t\t\t\t\tif(fileName.endsWith(\".mp3\") || fileName.endsWith(\".flac\") || fileName.endsWith(\".ogg\") || fileName.endsWith(\".m4a\")) {\n\t\t\t\t\t\t\t\t\t\tif(!fileUsable) {\n\t\t\t\t\t\t\t\t\t\t\tLog.i(Tag, \"Torrent usable: \" + item.torrentUrl)\n\t\t\t\t\t\t\t\t\t\t\tresultCollector.addResult(item)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif(fileName.endsWith(\".flac\")) {\n\t\t\t\t\t\t\t\t\t\t\titem.flacDetected()\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tfileUsable = true\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(!fileUsable) {\n\t\t\t\t\t\t\t\t\tresultCollector.addFailed()\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch (e: Exception) {\n\t\t\t\t\t\t\t\tLog.w(Tag, \"Error \" + e.message + \" parsing torrent URL: \" + item.torrentUrl)\n\t\t\t\t\t\t\t\tresultCollector.addFailed()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttorrentRequest.tag = query\n\t\t\t\t\tresultCollector.watchRequest(torrentRequest)\n\t\t\t\t\tLog.i(Tag, \"Added torrent request to watch ${item.torrentUrl}\")\n\t\t\t\t\tvolleyQueue.add(torrentRequest)\n\t\t\t\t}\n\t\t\t\tLog.i(Tag, \"GO()!!!!\")\n\t\t\t\tresultCollector.go()\n\t\t\t}, Response.ErrorListener { error ->\n\t\t\t\tLog.i(Tag, error.message ?: \"(No message from volley)\")\n\t\t\t\tsearch_mirror(retry + 1, album, resultCollector)\n\t\t\t}) {\n\t\t\t\toverride fun getHeaders(): MutableMap<String, String> {\n\t\t\t\t\tval headers = HashMap<String, String>()\n\t\t\t\t\theaders.put(\"User-agent\", \"FunkyTunes\")\n\t\t\t\t\treturn headers\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvolleyQueue.add(request)\n\t\t} else {\n\t\t\tLog.i(Tag, \"GO()!!!! [err]\")\n\t\t\tresultCollector.go()\n\t\t}\n    }\n\n    private fun parseHtml(html: String, prefixDetails: String): List<SearchResult> {\n        // Texts to find subsequently\n        val RESULTS = \"<tbody>\"\n        val TORRENT = \"<td style=\\\"word-wrap: break-word;\\\">\"\n\n        // Parse the search results from HTML by looking for the identifying texts\n        val results = ArrayList<SearchResult>()\n        val resultsStart = html.indexOf(RESULTS) + RESULTS.length\n\n        var torStart = html.indexOf(TORRENT, resultsStart)\n        while (torStart >= 0) {\n            val nextTorrentIndex = html.indexOf(TORRENT, torStart + TORRENT.length)\n            if (nextTorrentIndex >= 0) {\n                results.add(parseHtmlItem(html.substring(torStart + TORRENT.length, nextTorrentIndex), prefixDetails))\n            } else {\n                results.add(parseHtmlItem(html.substring(torStart + TORRENT.length), prefixDetails))\n            }\n            torStart = nextTorrentIndex\n        }\n        return results.slice(0..Math.min(5, results.size - 1))\n    }\n\n    private fun parseHtmlItem(htmlItem: String, prefixDetails: String): SearchResult {\n\t\t// TODO: parse XML file instead? \n        // Texts to find subsequently\n        val DETAILS = \"<a href=\\\"\"\n        val DETAILS_END = \"\\\" title=\\\"\"\n        val NAME = \"\\\">\"\n        val NAME_END = \"</a>\"\n        val MAGNET_LINK = \"<a href=\\\"\"\n        val MAGNET_LINK_END = \"\\\" rel=\\\"nofollow\\\"\"\n        val SIZE = \"<td class=\\\"is-hidden-touch\\\" >\"\n        val SIZE_END = \"</td>\"\n\t\tval NUMFILES = \"<td class=\\\"is-hidden-touch\\\" style=\\\"text-align: center;\\\" >\"\n\t\tval NUMFILES_END = \"</td>\"\n\n        val DATE = \"<td class=\\\"is-hidden-touch\\\" style=\\\"text-align: center;\\\">\"\n        val DATE_END = \"</td>\"\n        val SEEDERS = \"<td style=\\\"text-align: center;\\\">\"\n        val SEEDERS_END = \"</td>\"\n        val LEECHERS = \"<td style=\\\"text-align: center;\\\">\"\n        val LEECHERS_END = \"</td>\"\n        val prefixYear = (Calendar.getInstance().get(Calendar.YEAR)).toString() + \" \" // Date.getYear() gives the current year - 1900\n        val df1 = SimpleDateFormat(\"yyyy MM-dd HH:mm\", Locale.US)\n        val df2 = SimpleDateFormat(\"MM-dd yyyy\", Locale.US)\n\n        val detailsStart = htmlItem.indexOf(DETAILS) + DETAILS.length\n        var details = htmlItem.substring(detailsStart, htmlItem.indexOf(DETAILS_END, detailsStart))\n        details = prefixDetails + details\n        val nameStart = htmlItem.indexOf(NAME, detailsStart) + NAME.length\n        val name = htmlItem.substring(nameStart, htmlItem.indexOf(NAME_END, nameStart))\n\n        val torrentLink = \"\"\n\n        // Magnet link is second\n        val magnetLinkStart = htmlItem.indexOf(MAGNET_LINK, nameStart) + MAGNET_LINK.length\n        val magnetLink = htmlItem.substring(magnetLinkStart, htmlItem.indexOf(MAGNET_LINK_END, magnetLinkStart))\n\n        val sizeStart = htmlItem.indexOf(SIZE, magnetLinkStart) + SIZE.length\n        var size = htmlItem.substring(sizeStart, htmlItem.indexOf(SIZE_END, sizeStart))\n        size = size.replace(\"&nbsp;\", \" \")\n\n        val numFilesStart = htmlItem.indexOf(NUMFILES, sizeStart) + NUMFILES.length\n        var numFiles = htmlItem.substring(numFilesStart, htmlItem.indexOf(NUMFILES_END, numFilesStart))\n        numFiles = numFiles.replace(\"&nbsp;\", \" \")\n\n        val dateStart = htmlItem.indexOf(DATE, numFilesStart) + DATE.length\n        var dateText = htmlItem.substring(dateStart, htmlItem.indexOf(DATE_END, dateStart))\n        dateText = dateText.replace(\"&nbsp;\", \" \")\n        var date: Date? = null\n        if (dateText.startsWith(\"Today\")) {\n            date = Date()\n        } else if (dateText.startsWith(\"Y-day\")) {\n            date = Date(Date().time - 86400000L)\n        } else {\n            try {\n                date = df1.parse(prefixYear + dateText)\n            } catch (e: ParseException) {\n                try {\n                    date = df2.parse(dateText)\n                } catch (e1: ParseException) {\n                    // Not parsable at all; just leave it at null\n                }\n\n            }\n        }\n\n        val seedersStart = htmlItem.indexOf(SEEDERS, dateStart) + SEEDERS.length\n        val seedersText = htmlItem.substring(seedersStart, htmlItem.indexOf(SEEDERS_END, seedersStart))\n        val seeders = Integer.parseInt(seedersText)\n\n        val leechersStart = htmlItem.indexOf(LEECHERS, seedersStart) + LEECHERS.length\n        val leechersText = htmlItem.substring(leechersStart, htmlItem.indexOf(LEECHERS_END, leechersStart))\n        val leechers = Integer.parseInt(leechersText)\n\n        return SearchResult(name, magnetLink, torrentLink, details, \n\t\t\t\t\t\t\tsize, date, seeders, leechers, \n\t\t\t\t\t\t\tnull)\n    }\n\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/network/UpdateChecker.kt",
    "content": "package com.github.funkyg.funkytunes.network\n\nimport android.content.Context\nimport android.util.Log\nimport com.android.volley.Request\nimport com.android.volley.RequestQueue\nimport com.android.volley.Response\nimport com.android.volley.toolbox.StringRequest\nimport com.github.funkyg.funkytunes.BuildConfig\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.google.gson.Gson\nimport com.google.gson.JsonObject\nimport java.net.HttpURLConnection\nimport javax.inject.Inject\n\nclass UpdateChecker(val context: Context) {\n\n    private val TAG = \"UpdateChecker\"\n    private val UPDATE_URL = \"https://api.github.com/repos/funkyg/funkytunes/releases/latest\"\n\n    @Inject lateinit var volleyQueue: RequestQueue\n\n    interface UpdateListener {\n        fun updateAvailable()\n        fun repoNotFound()\n    }\n\n    init {\n        (context.applicationContext as FunkyApplication).component.inject(this)\n    }\n\n    fun checkUpdate(updateListener: UpdateListener) {\n        if (BuildConfig.DEBUG)\n            return\n\n        val request = StringRequest(Request.Method.GET, UPDATE_URL, Response.Listener<String> { reply ->\n            val available = Gson().fromJson(reply, JsonObject::class.java).get(\"tag_name\").asString\n            val current = context.packageManager.getPackageInfo(context.packageName, 0).versionName\n            if (available != current) {\n                updateListener.updateAvailable()\n            }\n        }, Response.ErrorListener { error ->\n            if (error.networkResponse != null &&\n                    error.networkResponse.statusCode == HttpURLConnection.HTTP_NOT_FOUND) {\n                updateListener.repoNotFound()\n            }\n            Log.w(TAG, \"Update check failed\", error)\n        })\n\n        volleyQueue.add(request)\n    }\n}"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/service/MusicService.kt",
    "content": "package com.github.funkyg.funkytunes.service\n\nimport android.app.Service\nimport android.content.BroadcastReceiver\nimport android.content.Context\nimport android.content.Intent\nimport android.content.IntentFilter\nimport android.media.AudioManager\nimport android.media.MediaMetadataRetriever\nimport android.media.MediaPlayer\nimport android.net.Uri\nimport android.os.Binder\nimport android.os.Handler\nimport android.os.Looper\nimport android.util.Log\nimport android.widget.Toast\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.github.funkyg.funkytunes.Song\nimport javax.inject.Inject\n\nclass MusicService : Service() {\n\n    private val Tag = \"MusicService\"\n    // The volume we set the media player to when we lose audio focus, but are allowed to reduce\n    // the volume instead of stopping playback.\n    private val DUCK_VOLUME = 0.1f\n\n    @Inject lateinit var torrentManager: TorrentManager\n    private val notificationHandler by lazy { NotificationHandler(this) }\n    private val audioManager by lazy {getSystemService(Context.AUDIO_SERVICE) as AudioManager}\n\n    private var mediaPlayer: MediaPlayer? = null\n    private val playbackListeners = ArrayList<PlaybackInterface>()\n    private var playedAlbum: Album? = null\n    private val playlist = ArrayList<Song>()\n    private var currentTrack: Int = 0\n    private var currentSongInfo: Song? = null\n\tprivate var noisyReceiverRegistered = false\n\n    private val becomingNoisyReceiver = object : BroadcastReceiver() {\n        override fun onReceive(context: Context?, intent: Intent?) {\n            Log.i(Tag, \"Received ACTION_AUDIO_BECOMING_NOISY intent\")\n            pause()\n        }\n    }\n    private val afChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->\n        when (focusChange) {\n            AudioManager.AUDIOFOCUS_GAIN -> {\n                Log.i(Tag, \"AUDIOFOCUS_GAIN\")\n                mediaPlayer?.setVolume(1f, 1f)\n                resume()\n            }\n            AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {\n                Log.i(Tag, \"AUDIOFOCUS_LOSS, AUDIOFOCUS_LOSS_TRANSIENT\")\n                pause()\n            }\n            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {\n                Log.i(Tag, \"AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK\")\n                mediaPlayer?.setVolume(DUCK_VOLUME, DUCK_VOLUME)\n            }\n        }\n    }\n\n    class MusicBinder(val service: MusicService) : Binder()\n\n    override fun onBind(intent: Intent?) = MusicBinder(this)\n\n    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int) =  START_STICKY\n\n    override fun onCreate() {\n        super.onCreate()\n        (applicationContext as FunkyApplication).component.inject(this)\n        addPlaybackInterface(notificationHandler)\n\n        // Delete all files, so we don't run out of space.\n        // This should be replaced by proper cache handling, to discard files only if a certain\n        // amount of storage is used, with a strategy like Least Recently Used.\n        filesDir.deleteRecursively()\n    }\n\n    override fun onDestroy() {\n        super.onDestroy()\n        torrentManager.destroy()\n        notificationHandler.stop()\n        removePlaybackInterface(notificationHandler)\n    }\n\n    fun play(album: Album) {\n        if (isPlaying()) {\n            pause()\n        }\n        playbackListeners.forEach { l -> l.onPlayAlbum(album) }\n        playlist.clear()\n        playedAlbum = album\n        currentTrack = 0\n        torrentManager.setCurrentAlbum(album, { fileList ->\n            playlist.addAll(fileList.mapIndexed { idx, f -> Song(f.first, album.artist, album.image, null, f.second) })\n            playbackListeners.forEach { l -> l.onPlaylistLoaded(playlist) }\n            playTrack()\n        }, { messageRes ->\n            Handler(Looper.getMainLooper()).post({\n                Toast.makeText(this, messageRes, Toast.LENGTH_LONG).show()\n                playbackListeners.forEach { l -> l.onCancelAlbum() }\n            })\n        })\n    }\n\n    fun pause() {\n        playbackListeners.forEach { l -> l.onPaused() }\n        mediaPlayer?.pause()\n        playbackStopped()\n    }\n\n    fun resume() {\n        playbackStarted {\n            playbackListeners.forEach { l -> l.onResumed() }\n            mediaPlayer?.start()\n        }\n    }\n\n    private fun playbackStopped() {\n\t\tif (noisyReceiverRegistered) {\n            try {\n                unregisterReceiver(becomingNoisyReceiver)\n            } catch (t: Throwable) {\n            }\n\t\t}\n        audioManager.abandonAudioFocus(afChangeListener)\n    }\n\n    private fun playbackStarted(callback: () -> Unit) {\n        val result = audioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC,\n                AudioManager.AUDIOFOCUS_GAIN)\n\n        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {\n            registerReceiver(becomingNoisyReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY))\n\t\t\tnoisyReceiverRegistered = true\n            callback()\n        }\n    }\n\n    fun isPlaying(): Boolean {\n        return mediaPlayer?.isPlaying ?: false\n    }\n\n    fun playPrevious() {\n        if (currentTrack == 0)\n            return\n\n        playbackListeners.forEach { l -> l.onPlayPrevious() }\n        pause()\n        currentTrack--\n        playTrack()\n    }\n\n    fun playNext() {\n        if (currentTrack == playlist.size)\n            return\n\n        playbackListeners.forEach { l -> l.onPlayNext() }\n        pause()\n        currentTrack++\n        playTrack()\n    }\n\n    fun stop() {\n        mediaPlayer?.stop()\n        torrentManager.stop()\n        playlist.clear()\n        currentSongInfo = null\n        playbackListeners.forEach { l -> l.onStopped() }\n        playbackStopped()\n    }\n\n    fun playTrack(index: Int) {\n        assert(index >= 0 && index <= playlist.size)\n        pause()\n        currentTrack = index\n        playTrack()\n        startService(Intent(this, MusicService::class.java))\n    }\n\n    /**\n     * Requests {@link #currentTrack} as torrent, and starts playing it on FILE_COMPLETED.\n     */\n    private fun playTrack() {\n        Handler(Looper.getMainLooper()).post({\n            playbackListeners.forEach { l ->\n                l.onEnqueueTrack(currentTrack)\n            }\n        })\n        torrentManager.requestSong(currentTrack, { file ->\n            playbackStarted {\n                Log.i(Tag, \"Playing track \" + file.name)\n                mediaPlayer = MediaPlayer.create(this, Uri.fromFile(file))\n                mediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)\n                mediaPlayer?.start()\n                mediaPlayer?.setOnCompletionListener { songCompleted() }\n\n                val mmr = MediaMetadataRetriever()\n                mmr.setDataSource(file.absolutePath)\n                val title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) ?: \"\"\n                val artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST) ?: \"\"\n                val song = playlist!![currentTrack]\n                song.name = title\n                song.artist = artist\n                song.duration = mediaPlayer?.duration?.div(1000)\n                currentSongInfo = song\n\n                Handler(Looper.getMainLooper()).post({\n                    playbackListeners.forEach { l ->\n                        l.onPlaySong(currentSongInfo!!, currentTrack)\n                        l.onResumed()\n                    }\n                })\n            }\n        }, {index: Int, progress: Int -> \n            Handler(Looper.getMainLooper()).post({\n                playbackListeners.forEach { l ->\n                    l.onProgress(index, progress)\n                }\n            })\n        })\n    }\n\n    /**\n     * Callback when the current song is over, starts the next track.\n     */\n    private fun songCompleted() {\n        if (currentTrack + 1 >= playlist.size) {\n            playbackListeners.forEach { l -> l.onPaused() }\n            playbackStopped()\n            stopSelf()\n            return\n        }\n\n        currentTrack++\n        playTrack()\n    }\n\n    fun getCurrentSong(): Song? {\n        return currentSongInfo\n    }\n\n    fun getSongProgress(): Int? {\n        return mediaPlayer?.currentPosition?.div(1000)\n    }\n\n    /**\n     * Sets callback for playlist changes, and calls it immediately with current playlist.\n     */\n    fun addPlaybackInterface(callback: PlaybackInterface) {\n        playbackListeners += callback\n        playedAlbum?.let { a -> callback.onPlayAlbum(a) }\n        if (!playlist.isEmpty()) {\n            callback.onPlaylistLoaded(playlist)\n        }\n    }\n\n    fun removePlaybackInterface(callback: PlaybackInterface) {\n        playbackListeners -= callback\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/service/NotificationHandler.kt",
    "content": "package com.github.funkyg.funkytunes.service\n\nimport android.app.PendingIntent\nimport android.content.BroadcastReceiver\nimport android.content.Context\nimport android.content.Intent\nimport android.content.IntentFilter\nimport android.os.Handler\nimport android.support.v4.app.NotificationManagerCompat\nimport android.support.v4.content.ContextCompat\nimport android.support.v7.app.NotificationCompat\nimport com.bumptech.glide.Glide\nimport com.bumptech.glide.request.target.Target\nimport com.github.funkyg.funkytunes.activities.PlayingQueueActivity\nimport java.util.concurrent.TimeUnit\nimport javax.inject.Inject\nimport android.widget.RemoteViews\nimport com.github.funkyg.funkytunes.*\n\n\nclass NotificationHandler(private val service: MusicService) : BroadcastReceiver(), PlaybackInterface {\n\n    private val NotificationId = 412\n    private val RequestCode = 100\n    private val NotificationTimeout = TimeUnit.MINUTES.toMillis(15)\n    private val ActionPause = \"com.github.funkyg.funkytunes.pause\"\n    private val ActionResume = \"com.github.funkyg.funkytunes.play\"\n    private val ActionPrev  = \"com.github.funkyg.funkytunes.prev\"\n    private val ActionNext  = \"com.github.funkyg.funkytunes.next\"\n    private val ActionStop  = \"com.github.funkyg.funkytunes.destroy\"\n\n    @Inject lateinit var torrentManager: TorrentManager\n    @Inject lateinit var notificationManager: NotificationManagerCompat\n    private var handler = Handler()\n    private var currentSong: Song? = null\n\n    init {\n        (service.applicationContext as FunkyApplication).component.inject(this)\n        val filter = IntentFilter()\n        filter.addAction(ActionNext)\n        filter.addAction(ActionPause)\n        filter.addAction(ActionResume)\n        filter.addAction(ActionPrev)\n        filter.addAction(ActionStop)\n        service.registerReceiver(this, filter)\n\n        // Cancel all notifications to handle the case where the Service was killed and\n        // restarted by the system.\n        notificationManager.cancelAll()\n    }\n\n    fun stop() {\n        service.unregisterReceiver(this)\n    }\n\n    private val StopForegroundRunnable = Runnable {\n        service.stopForeground(true)\n    }\n\n    private val UpdateLoadingNotificationRunnable = Runnable {\n        updateLoadingNotification()\n    }\n\n    /**\n     * Immediately destroy foreground and allow clearing notification. After {@link #NotificationTimeout},\n     * automatically remove the notification.\n     */\n    private fun stopNotification() {\n        service.stopForeground(false)\n        handler.postDelayed(StopForegroundRunnable, NotificationTimeout)\n    }\n\n    override fun onPlayAlbum(album: Album) = updateLoadingNotification()\n\n    private fun updateLoadingNotification() {\n        val contentIntent = PendingIntent.getActivity(service, RequestCode,\n                Intent(service, PlayingQueueActivity::class.java), PendingIntent.FLAG_CANCEL_CURRENT)\n        val notificationBuilder = NotificationCompat.Builder(service)\n                .setContentTitle(service.getString(R.string.notification_loading_title))\n                .setContentText(torrentManager.getDownloadSpeed())\n                .setContentIntent(contentIntent)\n                .setSmallIcon(R.drawable.ic_notification)\n                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)\n                .setProgress(0, 0, true)\n        service.startForeground(NotificationId, notificationBuilder.build())\n        handler.postDelayed(UpdateLoadingNotificationRunnable, 1000)\n    }\n\n    override fun onCancelAlbum() {\n        service.stopForeground(true)\n        handler.removeCallbacks(UpdateLoadingNotificationRunnable)\n    }\n\n    override fun onPlaySong(song: Song, index: Int) {\n        currentSong = song\n        updateNotification()\n    }\n\n    override fun onPaused() {\n        updateNotification()\n        stopNotification()\n    }\n\n    override fun onResumed() = updateNotification()\n\n    override fun onReceive(context: Context, intent: Intent) {\n        when (intent.action) {\n            ActionPause  -> service.pause()\n            ActionResume -> service.resume()\n            ActionPrev   -> service.playPrevious()\n            ActionNext   -> service.playNext()\n            ActionStop   -> {\n                service.stop()\n                service.stopForeground(true)\n                return\n            }\n        }\n    }\n\n    private fun updateNotification() {\n        handler.removeCallbacks(UpdateLoadingNotificationRunnable)\n        if (service.isPlaying()) {\n            handler.removeCallbacks(StopForegroundRunnable)\n        }\n\n        if (currentSong == null) {\n            return\n        }\n\n        Thread(Runnable {\n            val remoteView = RemoteViews(BuildConfig.APPLICATION_ID, R.layout.player_notification)\n            remoteView.setOnClickPendingIntent(R.id.notificationStop, createPendingIntent(ActionStop))\n            remoteView.setTextViewText(R.id.notificationArtist, currentSong!!.artist)\n            remoteView.setTextViewText(R.id.notificationSongName, currentSong!!.name)\n            val notificationBuilder = NotificationCompat.Builder(service)\n\n            notificationBuilder.addAction(R.drawable.ic_skip_previous_white_24dp,\n                    service.getString(R.string.previous), createPendingIntent(ActionPrev))\n\n            addPlayPauseAction(notificationBuilder)\n\n            notificationBuilder.addAction(R.drawable.ic_skip_next_white_24dp,\n                    service.getString(R.string.next), createPendingIntent(ActionNext))\n\n            val contentIntent = PendingIntent.getActivity(service, RequestCode,\n                    Intent(service, PlayingQueueActivity::class.java), PendingIntent.FLAG_CANCEL_CURRENT)\n\n            val icon = Glide.with(service)\n                    .load(currentSong!!.image.url)\n                    .asBitmap()\n                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)\n                    .get()\n            notificationBuilder\n                    .setStyle(NotificationCompat.DecoratedMediaCustomViewStyle())\n                    .setColor(ContextCompat.getColor(service, R.color.colorPrimary))\n                    .setSmallIcon(R.drawable.ic_notification)\n                    .setLargeIcon(icon)\n                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)\n                    .setContentIntent(contentIntent)\n                    .setShowWhen(false)\n                    .setContentTitle(currentSong!!.name)\n                    .setContentText(currentSong!!.artist)\n                    .setCustomBigContentView(remoteView)\n                    .setCustomContentView(remoteView)\n\n            service.startForeground(NotificationId, notificationBuilder.build())\n        }).start()\n    }\n\n    private fun addPlayPauseAction(builder: NotificationCompat.Builder) {\n        if (service.isPlaying()) {\n            builder.addAction(R.drawable.ic_pause_white_24dp, service.getString(R.string.pause),\n                    createPendingIntent(ActionPause))\n        } else {\n            builder.addAction(R.drawable.ic_play_arrow_white_24dp, service.getString(R.string.play),\n                    createPendingIntent(ActionResume))\n        }\n    }\n\n    private fun createPendingIntent(action: String) =\n            PendingIntent.getBroadcast(service, RequestCode,\n                    Intent(action).setPackage(service.packageName), PendingIntent.FLAG_CANCEL_CURRENT)\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/service/PlaybackInterface.kt",
    "content": "package com.github.funkyg.funkytunes.service\n\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.Song\n\ninterface PlaybackInterface {\n\n    fun onPlayAlbum(album: Album) {}\n    fun onCancelAlbum() {}\n    fun onPlaylistLoaded(playlist: List<Song>) {}\n    fun onPlaySong(song: Song, index: Int) {}\n    fun onPaused() {}\n    fun onResumed() {}\n    fun onPlayPrevious() {}\n    fun onPlayNext() {}\n\tfun onEnqueueTrack(index: Int) {}\n\tfun onProgress(index: Int, progress: Int) {}\n    fun onStopped() {}\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/service/TorrentManager.kt",
    "content": "package com.github.funkyg.funkytunes.service\n\nimport android.content.Context\nimport android.os.Handler\nimport android.util.Log\nimport com.frostwire.jlibtorrent.*\nimport com.frostwire.jlibtorrent.alerts.AddTorrentAlert\nimport com.frostwire.jlibtorrent.alerts.Alert\nimport com.frostwire.jlibtorrent.alerts.AlertType\nimport com.frostwire.jlibtorrent.alerts.BlockFinishedAlert\nimport com.frostwire.jlibtorrent.alerts.FileCompletedAlert\nimport com.github.funkyg.funkytunes.Album\nimport com.github.funkyg.funkytunes.FunkyApplication\nimport com.github.funkyg.funkytunes.R\nimport com.github.funkyg.funkytunes.network.PirateBayAdapter\nimport com.github.funkyg.funkytunes.network.SearchResultCollector\nimport com.github.funkyg.funkytunes.network.SkyTorrentsAdapter\nimport com.google.common.io.Files\nimport java.io.File\nimport javax.inject.Inject\n\nclass TorrentManager(private val context: Context) : AlertListener {\n\n    private data class FileInfo(val filename: String, val indexInTorrent: Int, val completed: Boolean, val path: File)\n\n    private val Tag = \"TorrentManager\"\n    private val MAGNET_TIMEOUT_SECONDS = 60\n\n    @Inject lateinit var pirateBayAdapter: PirateBayAdapter\n    @Inject lateinit var skyTorrentsAdapter: SkyTorrentsAdapter\n    private val sessionManager = SessionManager()\n    private var files: List<FileInfo>? = null\n    private var currentHash: Sha1Hash? = null\n    private var onTorrentAddedListener: ((List<Pair<String, Int>>) -> Unit)? = null\n    private var onFileCompletedListener: Pair<Int, (File) -> Unit>? = null\n    private var fileProgressListener: Pair<Int, (Int, Int) -> Unit>? = null\n    private var errorListener: ((Int) -> Unit)? = null\n\tprivate var lastProgressUpdate = System.currentTimeMillis()\n\tprivate lateinit var torrentTimeoutHandler: Handler\n\tprivate lateinit var torrentTimeoutRunnable: Runnable\n\n    init {\n        (context.applicationContext as FunkyApplication).component.inject(this)\n        sessionManager.start()\n        sessionManager.addListener(this)\n\n        // Disable all seeding. We should handle this more intelligently, eg seed only on wifi,\n        // and/or add a setting.\n        sessionManager.maxActiveSeeds(0)\n    }\n\n    fun stop() {\n        sessionManager.pause()\n    }\n\n    fun destroy() {\n        sessionManager.stop()\n    }\n\n    override fun types() = intArrayOf(AlertType.ADD_TORRENT.swig(), AlertType.FILE_COMPLETED.swig(), AlertType.BLOCK_FINISHED.swig())\n\n    override fun alert(alert: Alert<*>) {\n\t\ttry {\n\t\t\tval type = alert.type()\n\n\t\t\twhen (type) {\n\t\t\t\tAlertType.ADD_TORRENT -> {\n\t\t\t\t\tval handle = (alert as AddTorrentAlert).handle()\n\t\t\t\t\thandle.resume()\n\t\t\t\t\thandle.prioritizeFiles(getTorrentFiles(handle).map{ Priority.IGNORE }.toTypedArray())\n\t\t\t\t\tfiles = getTorrentFiles(handle)\n\t\t\t\t\t\t\t.withIndex()\n\t\t\t\t\t\t\t.filter { p -> (p.value.endsWith(\".mp3\") || p.value.endsWith(\".flac\") || p.value.endsWith(\".ogg\") || p.value.endsWith(\".m4a\")) }\n\t\t\t\t\t\t\t.sortedBy { f -> f.value }\n\t\t\t\t\t\t\t.map { f -> FileInfo(f.value, f.index, false, File(handle.savePath(), f.value)) }\n\t\t\t\t\tif (files!!.isEmpty()) {\n\t\t\t\t\t\terrorListener!!.invoke(R.string.error_torrent_invalid_files)\n\t\t\t\t\t\tsessionManager.remove(handle)\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcurrentHash = handle.infoHash()\n\t\t\t\t\t\tonTorrentAddedListener?.invoke(files!!.map { f -> Pair(convertToFriendlySongName(f.filename), f.indexInTorrent) })\n\t\t\t\t\t\tonTorrentAddedListener = null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tAlertType.FILE_COMPLETED -> {\n\t\t\t\t\tval position = (alert as FileCompletedAlert).index()\n\t\t\t\t\tval currentFile = files!!.find { f -> f.indexInTorrent == position }\n\n\t\t\t\t\t// For some reason we are getting this event for m3u and other file types which we\n\t\t\t\t\t// don't even download.\n\t\t\t\t\tcurrentFile ?: return\n\n\t\t\t\t\tLog.i(Tag, \"Finished downloading \" + currentFile.path.name)\n\t\t\t\t\tfiles = files!!.map { f ->\n\t\t\t\t\t\tif (f.indexInTorrent == position)\n\t\t\t\t\t\t\tf.copy(completed = true)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tf\n\t\t\t\t\t}\n\n\t\t\t\t\tif (onFileCompletedListener != null && onFileCompletedListener?.first == position) {\n\t\t\t\t\t\tonFileCompletedListener?.second?.invoke(currentFile.path)\n\t\t\t\t\t\tonFileCompletedListener = null\n\n\t\t\t\t\t\tpreloadNextTrack(position, alert.handle())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tAlertType.BLOCK_FINISHED -> {\n\t\t\t\t\t// Update progress bars when a block has finished downloading\n\t\t\t\t\tif (System.currentTimeMillis() - lastProgressUpdate > 250) {\n\t\t\t\t\t\tval finished = alert as BlockFinishedAlert\n\t\t\t\t\t\tval handle = sessionManager.find(currentHash)\n\t\t\t\t\t\tval progress = handle.fileProgress()\n\t\t\t\t\t\tval origFiles = handle.torrentFile().origFiles()\n\n                        if (fileProgressListener != null) {\n                            val i = fileProgressListener!!.first\n                            val i_progress = progress[i]\n                            val percent = 100 * i_progress / origFiles.fileSize(i)\n                            val currentFile = files!!.find { f -> f.indexInTorrent == i }\n                            if (currentFile != null) {\n                                val name = currentFile.filename\n                                Log.i(Tag, \"Progress: $name - $percent%\")\n                                fileProgressListener?.second?.invoke(i, percent.toInt())\n                            }\n                        }\n\n\t\t\t\t\t\tlastProgressUpdate = System.currentTimeMillis()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e: Exception) {\n\t\t\tLog.e(Tag, \"This error prevented the torrent file from downloading:\")\n\t\t\tLog.e(Tag, Log.getStackTraceString(e))\n\t\t\tthrow e\n\t\t}\n    }\n\n    private fun convertToFriendlySongName(name: String): String {\n        return File(name)\n                .nameWithoutExtension\n                .replace('_', ' ')\n                .replace(\"-\", \" - \")\n                .split(\" \").map { n ->\n                val stringArray = n.trim().toCharArray()\n\t\t\t\tif(stringArray.size > 0) {\n\t\t\t\t\tstringArray[0] = Character.toUpperCase(stringArray[0])\n\t\t\t\t}\n                String(stringArray)\n            }\n            .joinToString(\" \")\n    }\n\n    private fun getTorrentFiles(handle: TorrentHandle): List<String> {\n        val origFiles = handle.torrentFile().origFiles()\n        return (0..origFiles.numFiles()-1).map { i -> origFiles.filePath(i) }\n    }\n\n\tfun startTorrent(torrentInfo: TorrentInfo) {\n\t\tThread({ ->\n\t\t\tif (torrentInfo != null) {\n\t\t\t\tsessionManager.download(torrentInfo, context.filesDir)\n\t\t\t}\n\t\t}).start()\n\t}\n\n\tfun startMagnet(magnet: String) { \n\t\tThread({ ->\n\t\t\tval torrentBytes = sessionManager.fetchMagnet(magnet, MAGNET_TIMEOUT_SECONDS)\n\t\t\tif (torrentBytes != null) {\n\t\t\t\tval tmp = createTempFile(\"funkytunes\", \".torrent\")\n\t\t\t\tFiles.write(torrentBytes, tmp)\n\t\t\t\tval ti = TorrentInfo(tmp)\n\t\t\t\tsessionManager.download(ti, context.filesDir)\n\t\t\t\ttmp.delete()\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLog.w(Tag, \"Fetching torrent from magnet timed out\")\n\t\t\t\terrorListener!!.invoke(R.string.magnet_download_timeout)\n\t\t\t}\n\t\t}).start()\n\t}\n\n    fun setCurrentAlbum(album: Album, listener: (List<Pair<String, Int>>) -> Unit, errorListener: (Int) -> Unit) {\n        assert(onTorrentAddedListener == null)\n        onTorrentAddedListener = listener\n        this.errorListener = errorListener\n        if (currentHash != null) {\n            sessionManager.remove(sessionManager.find(currentHash))\n            currentHash = null\n        }\n\n\t\tval resultCollector = SearchResultCollector(\n\t\t\t\t2, // number of adapters\n\t\t\t\tthis::startTorrent,\n\t\t\t\tthis::startMagnet,\n\t\t\t\terrorListener)\n\n        skyTorrentsAdapter.search(album, resultCollector)\n        pirateBayAdapter.search(album, resultCollector)\n\n\t\t// Force harvesting results after 10s even if some requests have not finished\n\t\ttorrentTimeoutHandler = Handler()\n\t\ttorrentTimeoutRunnable = Runnable {\n\t\t\tLog.i(Tag, \"Forcing go() after 10 seconds\")\n\t\t\tresultCollector.forceGo()\n\t\t}\n\t\ttorrentTimeoutHandler.postDelayed(torrentTimeoutRunnable, 10000)\n    }\n\n    fun requestSong(position: Int, listener: (File) -> Unit, progressListener: (Int, Int) -> Unit) {\n        val fileInfo = files?.get(position)\n        val handle = sessionManager.find(currentHash)\n        if (fileInfo!!.completed) {\n            listener(fileInfo.path)\n            preloadNextTrack(position, handle)\n            return\n        }\n\n        onFileCompletedListener = Pair(fileInfo.indexInTorrent, listener)\n\t\tfileProgressListener = Pair(fileInfo.indexInTorrent, progressListener)\n\n        handle.setFilePriority(fileInfo.indexInTorrent, Priority.NORMAL)\n        Log.i(Tag, \"Starting to download \" + fileInfo.path.name)\n    }\n\n    /**\n     * Downloads the file after requestedPosition (unless it is the last file). It might download\n     * files that are not audio.\n     */\n    private fun preloadNextTrack(requestedPosition: Int, handle: TorrentHandle) {\n        if (requestedPosition < getTorrentFiles(handle).size) {\n            Log.i(Tag, \"Preloading next file\")\n            handle.setFilePriority(requestedPosition + 1, Priority.NORMAL)\n        }\n    }\n\n    /**\n     * http://stackoverflow.com/a/5599842\n     */\n    fun getDownloadSpeed(): String {\n        val rate =  sessionManager.downloadRate() / 8\n        val units = arrayOf(R.string.units_bps, R.string.units_kbps, R.string.units_mbps, R.string.units_gbps)\n\n        if (rate <= 0) {\n            return context.getString(units.first(), 0)\n        }\n\n        val digitGroups = (Math.log10(rate.toDouble())/Math.log10(1024.toDouble())).toInt()\n        val amount = rate/Math.pow(1024.toDouble(), digitGroups.toDouble())\n        return context.getString(units[digitGroups], amount.toInt())\n    }\n}\n"
  },
  {
    "path": "app/src/main/kotlin/com/github/funkyg/funkytunes/view/BottomControlView.kt",
    "content": "package com.github.funkyg.funkytunes.view\n\nimport android.content.Context\nimport android.content.Intent\nimport android.os.Handler\nimport android.os.Looper\nimport android.util.AttributeSet\nimport android.util.Log\nimport android.view.View\nimport android.widget.*\nimport com.github.funkyg.funkytunes.R\nimport com.github.funkyg.funkytunes.Song\nimport com.github.funkyg.funkytunes.Util\nimport com.github.funkyg.funkytunes.activities.PlayingQueueActivity\nimport com.github.funkyg.funkytunes.service.MusicService\nimport com.github.funkyg.funkytunes.service.PlaybackInterface\n\nclass BottomControlView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : RelativeLayout(context, attrs, defStyleAttr), PlaybackInterface {\n\n    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)\n\n    private lateinit var musicService: MusicService\n    private val logo: ImageView by lazy { findViewById(R.id.logo) as ImageView }\n    private val textHolder: View by lazy { findViewById(R.id.text_holder) }\n    private val progressBar: ProgressBar by lazy { findViewById(R.id.progress_bar) as ProgressBar }\n    private val title: TextView by lazy { findViewById(R.id.title) as TextView }\n    private val artist: TextView by lazy { findViewById(R.id.artist) as TextView }\n    private val playPause: ImageButton by lazy { findViewById(R.id.play_pause) as ImageButton }\n\n    fun setMusicService(musicService: MusicService) {\n        this.musicService = musicService\n        musicService.addPlaybackInterface(this)\n        val listener = View.OnClickListener{\n            val intent = Intent(context, PlayingQueueActivity::class.java)\n            context.startActivity(intent)\n        }\n        logo.setOnClickListener(listener)\n        textHolder.setOnClickListener(listener)\n\n        musicService.getCurrentSong()?.let { s -> onPlaySong(s, -1) }\n        if (musicService.isPlaying())\n            onResumed()\n        else\n            onPaused()\n    }\n\n    override fun onDetachedFromWindow() {\n        super.onDetachedFromWindow()\n        musicService.removePlaybackInterface(this)\n    }\n\n    override fun onPlaySong(song: Song, index: Int) {\n        visibility = View.VISIBLE\n        progressBar.progress = musicService.getSongProgress()!!\n        progressBar.max = song.duration!!\n        Util.setUrl(logo, song.image.url)\n        title.text = song.name\n        artist.text = song.artist\n        if (musicService.isPlaying())\n            incrementProgress()\n    }\n\n    private fun incrementProgress() {\n        handler?.postDelayed(incrementProgressRunnable, 1000)\n    }\n\n    private val incrementProgressRunnable: Runnable = Runnable {\n        incrementProgress()\n        progressBar.progress = musicService.getSongProgress()!!\n    }\n\n    override fun onResumed() {\n        playPause.setImageResource(R.drawable.ic_pause_accent_24dp)\n        playPause.setOnClickListener { musicService.pause() }\n    }\n\n    override fun onPaused() {\n        playPause.setImageResource(R.drawable.ic_play_arrow_accent_24dp)\n        playPause.setOnClickListener { musicService.resume() }\n        handler?.removeCallbacks(incrementProgressRunnable)\n    }\n\n    override fun onStopped() {\n        visibility = View.GONE\n\n    }\n}\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_close_white_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFFFFFF\"\n        android:pathData=\"M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_pause_accent_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFF4081\"\n        android:pathData=\"M6,19h4L10,5L6,5v14zM14,5v14h4L18,5h-4z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_pause_white_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFFFFFF\"\n        android:pathData=\"M6,19h4L10,5L6,5v14zM14,5v14h4L18,5h-4z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_play_arrow_accent_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFF4081\"\n        android:pathData=\"M8,5v14l11,-7z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_play_arrow_white_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFFFFFF\"\n        android:pathData=\"M8,5v14l11,-7z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_queue_music_white_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFFFFFF\"\n        android:pathData=\"M15,6L3,6v2h12L15,6zM15,10L3,10v2h12v-2zM3,16h8v-2L3,14v2zM17,6v8.18c-0.31,-0.11 -0.65,-0.18 -1,-0.18 -1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3L19,8h3L22,6h-5z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_search_white_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFFFFFF\"\n        android:pathData=\"M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_skip_next_white_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFFFFFF\"\n        android:pathData=\"M6,18l8.5,-6L6,6v12zM16,6v12h2V6h-2z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_skip_previous_white_24dp.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:width=\"24dp\"\n        android:height=\"24dp\"\n        android:viewportWidth=\"24.0\"\n        android:viewportHeight=\"24.0\">\n    <path\n        android:fillColor=\"#FFFFFFFF\"\n        android:pathData=\"M6,6h2v12L6,18zM9.5,12l8.5,6L18,6z\"/>\n</vector>\n"
  },
  {
    "path": "app/src/main/res/layout/activity_license.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:tools=\"http://schemas.android.com/tools\"\n    xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <ScrollView\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\">\n\n        <LinearLayout\n            android:orientation=\"vertical\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\">\n\n            <TextView\n                android:layout_width=\"wrap_content\"\n                android:layout_height=\"wrap_content\"\n                android:layout_margin=\"10dp\"\n                android:text=\"@string/license\"/>\n\n            <LinearLayout\n                android:layout_width=\"match_parent\"\n                android:layout_height=\"wrap_content\"\n                tools:ignore=\"ButtonStyle\">\n\n                <Button\n                    android:id=\"@+id/leave\"\n                    android:layout_width=\"0dp\"\n                    android:layout_weight=\"1\"\n                    android:layout_height=\"wrap_content\"\n                    android:text=\"@string/leave\"\n                    android:textColor=\"@android:color/white\"/>\n\n                <Button\n                    android:id=\"@+id/accept\"\n                    android:layout_width=\"0dp\"\n                    android:layout_weight=\"1\"\n                    android:layout_height=\"wrap_content\"\n                    android:text=\"@string/accept\"\n                    android:textColor=\"@android:color/white\"/>\n\n            </LinearLayout>\n\n        </LinearLayout>\n\n    </ScrollView>\n\n</layout>"
  },
  {
    "path": "app/src/main/res/layout/activity_main.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\">\n\n    <LinearLayout\n        android:orientation=\"vertical\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\">\n\n        <android.support.v7.widget.RecyclerView\n            android:id=\"@+id/recycler\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"0dp\"\n            android:layout_weight=\"1\"\n            android:visibility=\"gone\"/>\n\n        <ProgressBar\n            android:id=\"@+id/progress\"\n            android:layout_width=\"72dp\"\n            android:layout_height=\"0dp\"\n            android:layout_weight=\"1\"\n            android:layout_gravity=\"center\"\n            style=\"@style/Widget.AppCompat.ProgressBar\"/>\n\n        <include\n            android:id=\"@+id/bottom_control\"\n            layout=\"@layout/view_bottom_control\" />\n\n    </LinearLayout>\n\n</layout>\n"
  },
  {
    "path": "app/src/main/res/layout/activity_playing_queue.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\">\n\n    <RelativeLayout\n        android:orientation=\"vertical\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\">\n\n        <android.support.v7.widget.RecyclerView\n            android:id=\"@+id/recycler\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_alignParentTop=\"true\"\n            android:layout_above=\"@+id/bottom_control\"\n            android:visibility=\"gone\"/>\n\n        <TextView\n            android:id=\"@+id/empty\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_centerInParent=\"true\"\n            android:text=\"@string/playlist_empty\"/>\n\n        <LinearLayout\n            android:id=\"@+id/progress\"\n            android:orientation=\"vertical\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_centerInParent=\"true\"\n            android:layout_gravity=\"center_horizontal\"\n            android:gravity=\"center\"\n            android:visibility=\"gone\">\n\n            <ProgressBar\n                android:layout_width=\"72dp\"\n                android:layout_height=\"72dp\"\n                style=\"@style/Widget.AppCompat.ProgressBar\"/>\n\n            <TextView\n                android:layout_width=\"wrap_content\"\n                android:layout_height=\"wrap_content\"\n                android:layout_marginTop=\"12dp\"\n                android:text=\"@string/loading_torrent\"/>\n\n        </LinearLayout>\n\n\n        <include\n            android:id=\"@+id/bottom_control\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"55dp\"\n            android:layout_alignParentBottom=\"true\"\n            layout=\"@layout/view_bottom_control\" />\n\n    </RelativeLayout>\n\n</layout>\n"
  },
  {
    "path": "app/src/main/res/layout/item_main.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n\n    <data>\n        <variable name=\"album\" type=\"com.github.funkyg.funkytunes.Album\" />\n    </data>\n\n    <RelativeLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\">\n\n        <ImageView\n            android:id=\"@+id/image\"\n            android:layout_width=\"70dp\"\n            android:layout_height=\"70dp\"\n            android:layout_margin=\"5dp\"\n            app:url=\"@{album.image.url}\"/>\n\n        <TextView\n            android:id=\"@+id/title\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_toEndOf=\"@+id/image\"\n            android:layout_marginTop=\"5dp\"\n            android:text=\"@{album.title}\"\n            android:textColor=\"@android:color/secondary_text_light\"\n            android:textStyle=\"bold\"\n            tools:text=\"Name\"/>\n\n        <TextView\n            android:id=\"@+id/artist\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_toEndOf=\"@+id/image\"\n            android:layout_below=\"@+id/title\"\n            android:text=\"@{album.artist}\"\n            android:textColor=\"@android:color/tertiary_text_light\"\n            tools:text=\"Artist\"/>\n\n        <TextView\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:layout_toEndOf=\"@+id/image\"\n            android:layout_below=\"@+id/artist\"\n            android:layout_marginBottom=\"5dp\"\n            android:text=\"@{Integer.toString(album.year)}\"\n            android:textColor=\"@android:color/tertiary_text_light\"\n            tools:text=\"2010\"/>\n\n        <View\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"1dp\"\n            android:layout_alignParentBottom=\"true\"\n            android:background=\"@color/colorItemSeperator\" />\n\n    </RelativeLayout>\n\n</layout>\n"
  },
  {
    "path": "app/src/main/res/layout/item_playlist.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    xmlns:custom=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n\n    <data>\n        <variable name=\"song\" type=\"com.github.funkyg.funkytunes.Song\" />\n    </data>\n\n    <LinearLayout\n        android:orientation=\"vertical\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginTop=\"5dp\"\n        android:layout_marginStart=\"5dp\"\n        android:layout_marginEnd=\"5dp\">\n\n        <RelativeLayout\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\">\n\n            <LinearLayout\n                android:layout_width=\"match_parent\"\n                android:layout_height=\"wrap_content\"\n                android:orientation=\"vertical\">\n\n                <TextView\n                    android:id=\"@+id/textView\"\n                    android:layout_width=\"match_parent\"\n                    android:layout_height=\"wrap_content\"\n                    android:layout_marginTop=\"10dp\"\n                    android:text=\"@{song.artist}\"\n                    tools:text=\"Artist\" />\n\n                <TextView\n                    android:id=\"@+id/title\"\n                    android:layout_width=\"match_parent\"\n                    android:layout_height=\"wrap_content\"\n                    android:text=\"@{song.name}\"\n                    tools:text=\"Name\" />\n\n            </LinearLayout>\n\n            <ImageView\n                android:id=\"@+id/songplaying\"\n                android:layout_width=\"32dp\"\n                android:layout_height=\"32dp\"\n                android:layout_alignParentEnd=\"true\"\n                android:layout_gravity=\"right\"\n                android:layout_centerVertical=\"true\"\n                android:src=\"@drawable/ic_play_arrow_accent_24dp\"\n                android:visibility=\"@{song.songPlayingVisible}\" />\n\n            <ImageView\n                android:id=\"@+id/songpaused\"\n                android:layout_width=\"32dp\"\n                android:layout_height=\"32dp\"\n                android:layout_alignParentEnd=\"true\"\n                android:layout_gravity=\"right\"\n                android:layout_centerVertical=\"true\"\n                android:src=\"@drawable/ic_pause_accent_24dp\"\n                android:visibility=\"@{song.songPausedVisible}\" />\n\n            <ProgressBar\n                android:id=\"@+id/songloading\"\n                style=\"@style/Widget.AppCompat.ProgressBar\"\n                android:layout_width=\"32dp\"\n                android:layout_height=\"32dp\"\n                android:layout_alignParentEnd=\"true\"\n                android:layout_centerVertical=\"true\"\n                android:indeterminate=\"true\"\n                android:visibility=\"@{song.songLoadingVisible}\" />\n\n            <com.github.lzyzsd.circleprogress.DonutProgress\n                android:id=\"@+id/songprogress\"\n                android:layout_width=\"32dp\"\n                android:layout_height=\"32dp\"\n                android:layout_alignParentEnd=\"true\"\n                android:layout_centerVertical=\"true\"\n                custom:donut_finished_stroke_width=\"3dp\"\n                custom:donut_unfinished_stroke_width=\"3dp\"\n                custom:donut_text_color=\"#00000000\"\n                custom:donut_finished_color=\"#FE4083\"\n                custom:donut_progress=\"@{song.stringProgress}\"\n                android:visibility=\"@{song.songProgressVisible}\" />\n\n        </RelativeLayout>\n\n        <View\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"1dp\"\n            android:layout_marginTop=\"5dp\"\n            android:background=\"@color/colorItemSeperator\" />\n\n    </LinearLayout>\n\n</layout>\n"
  },
  {
    "path": "app/src/main/res/layout/player_notification.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\">\n\n    <LinearLayout\n        android:id=\"@+id/notificationContent\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:gravity=\"center_vertical\"\n        android:orientation=\"horizontal\"\n        tools:background=\"@android:color/holo_blue_light\">\n\n        <LinearLayout\n            android:layout_width=\"0dp\"\n            android:layout_weight=\"1\"\n            android:layout_height=\"wrap_content\"\n            android:orientation=\"vertical\">\n\n            <TextView\n                android:id=\"@+id/notificationSongName\"\n                style=\"@android:style/TextAppearance.StatusBar.EventContent.Title\"\n                android:layout_width=\"match_parent\"\n                android:layout_height=\"wrap_content\"\n                android:ellipsize=\"end\"\n                android:maxLines=\"2\"\n                android:textSize=\"14sp\"\n                tools:text=\"Insane in the Brain\"/>\n\n            <TextView\n                android:id=\"@+id/notificationArtist\"\n                style=\"@android:style/TextAppearance.StatusBar.EventContent\"\n                android:layout_width=\"match_parent\"\n                android:layout_height=\"wrap_content\"\n                android:ellipsize=\"end\"\n                android:maxLines=\"1\"\n                android:textSize=\"12sp\"\n                tools:text=\"Cypress Hill\"/>\n\n        </LinearLayout>\n\n        <ImageButton\n            android:id=\"@+id/notificationStop\"\n            android:layout_width=\"40dp\"\n            android:layout_height=\"40dp\"\n            android:background=\"@null\"\n            android:clickable=\"true\"\n            android:focusable=\"true\"\n            android:padding=\"8dp\"\n            android:src=\"@drawable/ic_close_white_24dp\"/>\n\n    </LinearLayout>\n\n</layout>"
  },
  {
    "path": "app/src/main/res/layout/view_bottom_control.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n\n    <com.github.funkyg.funkytunes.view.BottomControlView\n        android:id=\"@+id/container\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"55dp\"\n        android:layout_gravity=\"top\"\n        android:elevation=\"8dp\"\n        android:visibility=\"gone\"\n        tools:visibility=\"visible\">\n\n        <ImageView\n            android:id=\"@+id/logo\"\n            android:layout_width=\"55dp\"\n            android:layout_height=\"55dp\"\n            android:layout_alignParentStart=\"true\"\n            android:scaleType=\"centerCrop\" />\n\n        <ProgressBar\n            android:id=\"@+id/progress_bar\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"2dp\"\n            android:layout_toEndOf=\"@id/logo\"\n            android:layout_gravity=\"top\"\n            tools:progress=\"30\"\n            style=\"@style/Widget.AppCompat.ProgressBar.Horizontal\" />\n\n        <LinearLayout\n            android:id=\"@+id/text_holder\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:layout_below=\"@id/progress_bar\"\n            android:layout_alignParentBottom=\"true\"\n            android:gravity=\"center_vertical\"\n            android:layout_toEndOf=\"@id/logo\"\n            android:layout_toStartOf=\"@+id/play_pause\"\n            android:orientation=\"vertical\">\n\n            <TextView\n                android:id=\"@+id/title\"\n                android:layout_width=\"wrap_content\"\n                android:layout_height=\"wrap_content\"\n                android:layout_marginStart=\"12dp\"\n                android:layout_marginEnd=\"42dp\"\n                android:ellipsize=\"end\"\n                android:maxLines=\"1\"\n                style=\"@style/TextAppearance.AppCompat.Body1\"\n                tools:text=\"Demons\"\n                android:textSize=\"15sp\" />\n\n            <TextView\n                android:id=\"@+id/artist\"\n                style=\"@style/TextAppearance.AppCompat.Widget.ActionMode.Subtitle\"\n                android:layout_width=\"wrap_content\"\n                android:layout_height=\"wrap_content\"\n                android:layout_marginStart=\"12dp\"\n                android:ellipsize=\"end\"\n                android:maxLength=\"20\"\n                android:maxLines=\"1\"\n                tools:text=\"John Doe and Band\"\n                android:textSize=\"13sp\" />\n\n        </LinearLayout>\n\n        <ImageButton\n            android:id=\"@+id/play_pause\"\n            android:layout_width=\"32dp\"\n            android:layout_height=\"32dp\"\n            android:layout_alignParentEnd=\"true\"\n            android:layout_centerVertical=\"true\"\n            android:layout_marginEnd=\"8dp\"\n            android:background=\"?attr/selectableItemBackgroundBorderless\"\n            android:src=\"@drawable/ic_play_arrow_accent_24dp\"/>\n\n    </com.github.funkyg.funkytunes.view.BottomControlView>\n\n</layout>"
  },
  {
    "path": "app/src/main/res/menu/activity_main.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n\n    <item\n        android:id=\"@+id/search\"\n        android:title=\"@string/search_title\"\n        android:icon=\"@drawable/ic_search_white_24dp\"\n        app:showAsAction=\"ifRoom|collapseActionView\"\n        app:actionViewClass=\"android.support.v7.widget.SearchView\" />\n\n    <item\n        android:id=\"@+id/play_queue\"\n        android:title=\"@string/play_queue\"\n        android:icon=\"@drawable/ic_queue_music_white_24dp\"\n        app:showAsAction=\"ifRoom\" />\n\n    <item android:id=\"@+id/settings\"\n        android:title=\"@string/settings\" />\n\n    <item android:id=\"@+id/exit\"\n        android:title=\"@string/exit\" />\n\n</menu>\n"
  },
  {
    "path": "app/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"colorPrimary\">#3F51B5</color>\n    <color name=\"colorPrimaryDark\">#303F9F</color>\n    <color name=\"colorAccent\">#FF4081</color>\n\n    <color name=\"colorItemSeperator\">#ccc</color>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">Funkytunes</string>\n    <string name=\"play\">Play</string>\n    <string name=\"pause\">Pause</string>\n    <string name=\"previous\">Previous</string>\n    <string name=\"next\">Next</string>\n    <string name=\"play_queue\">Play Queue</string>\n    <string name=\"settings\">Settings</string>\n    <string name=\"github_repository_title\">Github Repository</string>\n    <string name=\"github_repository_summary\">Go to the Github repository</string>\n    <string name=\"github_repository_url\" translatable=\"false\">https://github.com/funkyg/funkytunes</string>\n    <string name=\"gitlab_mirror_title\">Gitlab Mirror</string>\n    <string name=\"gitlab_mirror_summary\">Open Gitlab mirror</string>\n    <string name=\"gitlab_mirror_url\" translatable=\"false\">https://gitlab.com/funkydev/funkytunes</string>\n    <string name=\"version\">Version</string>\n    <string name=\"search_title\">Search Album…</string>\n    <string name=\"notification_loading_title\">Loading torrent…</string>\n    <string name=\"license\">Your Acceptance\\n\\n\nBy using the \\'Funkytunes\\' app you signify your agreement to (1) these terms and conditions (the \\'Terms of Service\\').\\n\\n\nPrivacy Policy\\n\\n\nYou understand that by using \\' Funkytunes\\' you may encounter material that you may deem to be offensive, indecent, or objectionable, and that such content may or may not be identified as having explicit material. \\' Funkytunes\\' will have no liability to you for such material – you agree that your use of \\' Funkytunes\\' is at your sole risk.\\n\\n\nDISCLAIMERS\\n\\n\nYOU EXPRESSLY AGREE THAT YOUR USE OF \\' Funkytunes\\' IS AT YOUR SOLE RISK. \\' Funkytunes\\' AND ALL PRODUCTS ARE PROVIDED TO YOU \\'AS IS\\' WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. \\' Funkytunes\\' MAKES ABSOLUTELY NO WARRANTIES WHATSOEVER, EXPRESS OR IMPLIED. TO THE FULLEST EXTENT POSSIBLE UNDER APPLICABLE LAWS, YIFY DISCLAIMS ALL WARRANTIES, EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR OTHER VIOLATIONS OF RIGHTS.\\n\\n\nLIMITATION OF LIABILITY\\n\\n\n\\' Funkytunes\\' IS NOT RESPONSIBLE FOR ANY PROBLEMS OR TECHNICAL MALFUNCTION OF ANY WEBSITE, NETWORK, COMPUTER SYSTEMS, SERVERS, PROVIDERS, COMPUTER EQUIPMENT, OR SOFTWARE, OR FOR ANY FAILURE DUE TO TECHNICAL PROBLEMS OR TRAFFIC CONGESTION ON THE INTERNET OR \\' Funkytunes\\' OR COMBINATION THEREOF, INCLUDING ANY INJURY OR DAMAGE TO USERS OR TO ANY COMPUTER OR OTHER DEVICE ON OR THROUGH WHICH \\' Funkytunes\\' IS PROVIDED. UNDER NO CIRCUMSTANCES WILL \\' Funkytunes\\' BE LIABLE FOR ANY LOSS OR DAMAGE, INCLUDING PERSONAL INJURY OR DEATH, RESULTING FROM YOUR USE OF \\' Funkytunes\\'.\\n\\nSOURCE MATERIAL\\n\\nALL SONGS ARE NOT HOSTED IN ANY SERVER AND ARE STREAMED USING THE P2P BIT TORRENT PROTOCOL. ALL SONGS ARE PULLED IN FROM THE OPEN PUBLIC APIS. BY STREAMING A SONG WITH THIS APPLICATION YOU MIGHT BE COMMITING COPYRIGHT VIOLATIONS DEPENDING ON YOUR COUNTRY\\'S LAWS. WE DO NOT TAKE ANY RESPONSABILITIES.\\n\\n\nAbility to Accept Terms of Service\\n\\n\nBy using \\' Funkytunes\\' or accessing this site you affirm that you are either more than 18 years of age, or an emancipated minor, or possess legal parental or guardian consent, and are fully able and competent to enter into the terms, conditions, obligations, affirmations, representations, and warranties set forth in these Terms of Service, and to abide by and comply with these Terms of Service. In any case, you affirm that you are over the age of 13, as the Service is not intended for children under 13. If you are under 13 years of age, then please do not use the Service. There are lots of other great web sites for you. Talk to your parents about what sites are appropriate for you.</string>\n    <string name=\"accept\">Accept</string>\n    <string name=\"leave\">Leave</string>\n    <string name=\"error_no_torrent_found\">Error: No matching torrent found for album.</string>\n    <string name=\"error_429\">Error: The search engine asks to perform fewer requests.</string>\n    <string name=\"error_torrent_invalid_files\">Error: Torrent does not contain any mp3 files.</string>\n    <string name=\"update_available\">Update Available</string>\n    <string name=\"download\">Download</string>\n    <string name=\"github_repository_missing\">Github Repository Missing</string>\n    <string name=\"github_update_url\" translatable=\"false\">https://github.com/funkyg/funkytunes/releases/latest</string>\n    <string name=\"magnet_download_timeout\">Magnet download took too long</string>\n    <string name=\"loading_torrent\">Loading torrent</string>\n    <string name=\"playlist_empty\">Playlist is empty</string>\n    <string name=\"units_bps\">%1$d B/s</string>\n    <string name=\"units_kbps\">%1$d KB/s</string>\n    <string name=\"units_mbps\">%1$d MB/s</string>\n    <string name=\"units_gbps\">%1$d GB/s</string>\n    <string name=\"exit\">Exit</string>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n        <!-- Customize your theme here. -->\n        <item name=\"colorPrimary\">@color/colorPrimary</item>\n        <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n        <item name=\"colorAccent\">@color/colorAccent</item>\n    </style>\n\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values-ja/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">Funkytunes</string>\n    <string name=\"play\">再生</string>\n    <string name=\"pause\">一時停止</string>\n    <string name=\"previous\">前へ</string>\n    <string name=\"next\">次へ</string>\n    <string name=\"play_queue\">キューの再生</string>\n    <string name=\"settings\">設定</string>\n    <string name=\"github_repository_title\">Github リポジトリ</string>\n    <string name=\"github_repository_summary\">Github リポジトリに移動します</string>\n\n    <string name=\"gitlab_mirror_title\">Gitlab ミラー</string>\n    <string name=\"gitlab_mirror_summary\">Gitlab ミラーを開く</string>\n\n    <string name=\"version\">バージョン</string>\n    <string name=\"search_title\">アルバムを検索…</string>\n    <string name=\"notification_loading_title\">torrent のロード中…</string>\n    <string name=\"license\">同意事項\\n\\n\n\\' Funkytunes\\' アプリを使用することにより、これらの規約と条件 (\\'利用規約\\') (1) に同意することを意味します。\\n\\n\nプライバシーポリシー\\n\\n\n\\' Funkytunes\\' を使用することによって、あなたは不快、気まずい、または好ましくないと思われるコンテンツに遭遇する可能性があること、およびそのようなコンテンツが明示的に素材を有すると特定することができないことを理解します。 \\' Funkytunes\\' はそのような素材に対して責任を負いません - \\' Funkytunes\\' の使用があなた自身のリスクに基づくことに同意します。\\n\\n\n免責事項\\n\\n\nあなた自身の責任において \\' Funkytunes\\' を使用することに、あなたは明示的に同意します。 \\' Funkytunes\\' およびすべての製品は \\'あるがまま\\' に提供され、明示的にも暗黙的にも、いかなる種類の保証もありません。 \\' Funkytunes\\' は、明示的か暗示的かを問わず、いかなる保証もありません。 商用可能性、特定の目的への適合性、権利侵害、その他の権利侵害の黙示的な保証を含め、明示的にも黙示的にも、すべての保証は否認されますが、これに限定されるものではありません。\\n\\n\n責任の制限\\n\\n\n\\' Funkytunes\\' は、\\' Funkytunes\\' が提供されている間の、ウェブサイト、ネットワーク、コンピュータシステム、サーバー、プロバイダ、コンピュータ機器、ソフトウェアなどの問題や技術的不具合、または技術的問題やインターネット、\\'Funkytunes \\' またはその組み合わせ上の通信混雑に起因する不具合を、ユーザーまたはコンピュータまたはその他のデバイスへの損害または損傷を含み、責任を負いません。 いかなる状況においても、\\' Funkytunes\\'は、\\' Funkytunes\\' の使用に起因する個人の損害または損傷を含む、いかなる損失または損害に対しても責任を負わないものとします。\\n\\n\nソースの素材\\n\\n\nすべての曲はいかなるサーバーにもホストされておらず、P2P BIT TORRENT プロトコルを使用してストリーミングされています。 すべての曲は、オープンな公開 API から運ばれます。 このアプリケーションで曲をストリーミングすることは、あなたの国の法律に基づいて著作権侵害を引き起こすことがあります。 私たちはいかなる責任も負いません。\\n\\n\n利用規約に同意する能力\\n\\n\n\\' Funkytunes\\' を使用するか、このサイトにアクセスすることにより、あなたは 18 歳以上、または独立した未成年者であること、または法的な親または保護者の同意を得ていることを確認し、これらの利用規約の規約、条件 、義務、誓約、表明、および保証することが可能で、能力があり、これらの利用規約を遵守するものとします。 いずれにせよ、13 歳未満の子供向けのサービスではないので、13 歳以上であることを確認してください。あなたが 13 歳未満の場合は、このサービスを使用しないでください。 あなた向けに他のすばらしいウェブサイトがたくさんあります。 適切なサイトについてご両親に相談してください。</string>\n    <string name=\"accept\">同意</string>\n    <string name=\"leave\">やめる</string>\n    <string name=\"error_no_torrent_found\">エラー: アルバムに一致する torrent が見つかりません。</string>\n    <string name=\"error_torrent_invalid_files\">エラー: Torrent に mp3 ファイルが含まれていません。</string>\n    <string name=\"magnet_download_timeout\">Magnet ダウンロードに長時間かかり過ぎました</string>\n    <string name=\"loading_torrent\">torrent のロード中</string>\n    <string name=\"playlist_empty\">プレイリストは空です</string>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values-ru/strings.xml",
    "content": "<?xml version='1.0' encoding='UTF-8'?>\n<resources>\n    <string name=\"settings\">Настройки</string>\n    <string name=\"version\">Версия</string>\n    <string name=\"app_name\">Funkytunes</string>\n    <string name=\"github_repository_title\">Репозиторий на Github</string>\n    <string name=\"github_repository_summary\">Перейти на репозиторий на Github</string>\n    <string name=\"gitlab_mirror_title\">Зеркало на Gitlab</string>\n    <string name=\"gitlab_mirror_summary\">Открыть зеркало на Gitlab</string>\n    <string name=\"notification_loading_title\">Загрузка торрента…</string>\n    <string name=\"error_no_torrent_found\">Ошибка: не найден соответствующий альбому торрент.</string>\n    <string name=\"error_torrent_invalid_files\">Ошибка: торрент не содержит файлов mp3.</string>\n    <string name=\"update_available\">Доступно обновление</string>\n    <string name=\"github_repository_missing\">Репозиторий на Github отсутствует</string>\n    <string name=\"loading_torrent\">Загрузка торрента</string>\n    <string name=\"playlist_empty\">Плейлист пуст</string>\n    <string name=\"play_queue\">Очередь воспроизведения</string>\n    <string name=\"search_title\">Найти альбом…</string>\n    <string name=\"units_bps\">%1$d Б/с</string>\n    <string name=\"units_kbps\">%1$d КБ/с</string>\n    <string name=\"units_mbps\">%1$d МБ/с</string>\n    <string name=\"units_gbps\">%1$d ГБ/с</string>\n    <string name=\"play\">Воспроизвести</string>\n    <string name=\"pause\">Приостановить</string>\n    <string name=\"download\">Скачать</string>\n    <string name=\"magnet_download_timeout\">Загрузка Magnet заняла слишком много времени</string>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/xml/settings.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<PreferenceScreen xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <PreferenceCategory\n        android:title=\"About Funkytunes\">\n\n        <Preference\n            android:title=\"@string/github_repository_title\"\n            android:summary=\"@string/github_repository_summary\">\n            <intent\n                android:action=\"android.intent.action.VIEW\"\n                android:data=\"@string/github_repository_url\" />\n        </Preference>\n\n        <Preference\n            android:title=\"@string/gitlab_mirror_title\"\n            android:summary=\"@string/gitlab_mirror_summary\">\n            <intent\n                android:action=\"android.intent.action.VIEW\"\n                android:data=\"@string/gitlab_mirror_url\" />\n        </Preference>\n\n        <Preference\n            android:key=\"version\"\n            android:title=\"@string/version\" />\n\n    </PreferenceCategory>\n\n</PreferenceScreen>\n"
  },
  {
    "path": "build.gradle",
    "content": "buildscript {\n    ext.kotlin_version = '1.1.2'\n    ext.support_version = '25.3.1'\n    ext.build_tools_version = '2.3.2'\n    ext.jlibtorrent_version = '1.2.0.10'\n    repositories {\n        jcenter()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:2.3.3'\n        classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n        classpath 'com.github.ben-manes:gradle-versions-plugin:0.13.0'\n    }\n}\n\nallprojects {\n    repositories {\n        jcenter()\n    }\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Thu Jan 26 11:31:55 KST 2017\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-3.4.1-bin.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\norg.gradle.jvmargs=-Xmx1536m\n\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true\n"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env sh\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn ( ) {\n    echo \"$*\"\n}\n\ndie ( ) {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\n  NONSTOP* )\n    nonstop=true\n    ;;\nesac\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" -a \"$nonstop\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Escape application args\nsave ( ) {\n    for i do printf %s\\\\n \"$i\" | sed \"s/'/'\\\\\\\\''/g;1s/^/'/;\\$s/\\$/' \\\\\\\\/\" ; done\n    echo \" \"\n}\nAPP_ARGS=$(save \"$@\")\n\n# Collect all arguments for the java command, following the shell quoting and substitution rules\neval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \"\\\"-Dorg.gradle.appname=$APP_BASE_NAME\\\"\" -classpath \"\\\"$CLASSPATH\\\"\" org.gradle.wrapper.GradleWrapperMain \"$APP_ARGS\"\n\n# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong\nif [ \"$(uname)\" = \"Darwin\" ] && [ \"$HOME\" = \"$PWD\" ]; then\n  cd \"$(dirname \"$0\")\"\nfi\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@rem  Gradle startup script for Windows\r\n@rem\r\n@rem ##########################################################################\r\n\r\n@rem Set local scope for the variables with windows NT shell\r\nif \"%OS%\"==\"Windows_NT\" setlocal\r\n\r\nset DIRNAME=%~dp0\r\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\r\nset APP_BASE_NAME=%~n0\r\nset APP_HOME=%DIRNAME%\r\n\r\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r\nset DEFAULT_JVM_OPTS=\r\n\r\n@rem Find java.exe\r\nif defined JAVA_HOME goto findJavaFromJavaHome\r\n\r\nset JAVA_EXE=java.exe\r\n%JAVA_EXE% -version >NUL 2>&1\r\nif \"%ERRORLEVEL%\" == \"0\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:findJavaFromJavaHome\r\nset JAVA_HOME=%JAVA_HOME:\"=%\r\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\r\n\r\nif exist \"%JAVA_EXE%\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:init\r\n@rem Get command-line arguments, handling Windows variants\r\n\r\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\r\n\r\n:win9xME_args\r\n@rem Slurp the command line arguments.\r\nset CMD_LINE_ARGS=\r\nset _SKIP=2\r\n\r\n:win9xME_args_slurp\r\nif \"x%~1\" == \"x\" goto execute\r\n\r\nset CMD_LINE_ARGS=%*\r\n\r\n:execute\r\n@rem Setup the command line\r\n\r\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\r\n\r\n@rem Execute Gradle\r\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r\n\r\n:end\r\n@rem End local scope for the variables with windows NT shell\r\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\r\n\r\n:fail\r\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r\nrem the _cmd.exe /c_ return code!\r\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\r\nexit /b 1\r\n\r\n:mainEnd\r\nif \"%OS%\"==\"Windows_NT\" endlocal\r\n\r\n:omega\r\n"
  },
  {
    "path": "settings.gradle",
    "content": "include ':app'\n"
  }
]