[
  {
    "path": ".gitignore",
    "content": "node_modules\n*.mp3\nmp3/\n"
  },
  {
    "path": ".jshintrc",
    "content": "{\n    \"esnext\": true\n}\n"
  },
  {
    "path": ".npmignore",
    "content": "mp3/\ntest/\ntest.js\n"
  },
  {
    "path": ".prettierrc.json",
    "content": "{\n  \"trailingComma\": \"all\",\n  \"tabWidth\": 2,\n  \"semi\": true,\n  \"singleQuote\": true,\n  \"arrowParens\": \"always\",\n  \"bracketSpacing\": true,\n  \"printWidth\": 120\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 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 Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\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,\nour General Public Licenses are 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.\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  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\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 Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\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 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 work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be 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 Affero 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 Affero 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 Affero 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 Affero General Public License as published\n    by 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\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 AGPL, see\n<http://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# alltomp3 [![CircleCI Status](https://circleci.com/gh/AllToMP3/alltomp3.svg?style=shield&circle-token=:circle-token)](https://circleci.com/gh/AllToMP3/alltomp3)\nDownload and convert an online video in MP3 with tags.\n\nProvide several useful methods to get information about a song or to guess the track matching a YouTube video.\n\n## Requirements\n- ffmpeg >= 2.8 with lamemp3;\n- node-acoutstid requirements (https://github.com/parshap/node-acoustid#installation - https://acoustid.org/chromaprint);\n- eyeD3 >= 0.7.10.\n\n## Installation\n```\nnpm install alltomp3\n```\n\n```js\nconst alltomp3 = require('alltomp3');\n\nconst dl = alltomp3.findAndDownload(\"imagine dragons on top of the world\", \"./\", (infos) => {\n  console.log(\"It's finished: \", infos);\n});\n\n// {\n//   infos: {\n//     title: 'On Top Of The World',\n//     artistName: 'Imagine Dragons',\n//     deezerId: 63510362,\n//     itunesId: 555694746,\n//     position: 5,\n//     duration: 192,\n//     deezerAlbum: 6240279,\n//     discNumber: 1,\n//     album: 'Night Visions',\n//     releaseDate: '2012-01-01',\n//     nbTracks: 13,\n//     genreId: 132,\n//     cover: 'http://e-cdn-images.deezer.com/images/cover/7e8314f4280cffde363547a495a260bc/600x600-000000-80-0-0.jpg',\n//     genre: 'Pop'\n//   },\n//   file: './Imagine Dragons - On Top Of The World.mp3'\n// }\n```\n\n## Methods\n\nEach time a `trackInfos` object is referred, it corresponds to a JavaScript object with the following fields:\n- `title`\n- `artistName`\n- (optional) `album`: name of the album\n- (optional) `cover`: URL of an image for the cover\n- (optional) `position`: position of the track on the album\n- (optional) `nbTracks`: number of tracks on the album\n- (optional) `releaseDate`: format YYYY-MM-YY\n- (optional) `discNumber`: number of the disc where the track is\n- (optional) `genre`: name of the genre\n- (optional) `duration`: duration in second\n- (optional) `deezerId`: ID of the track on Deezer (http://developers.deezer.com/api/track)\n- (optional) `itunesId`: ID of the track on iTunes (https://itunes.apple.com/lookup?id=)\n- (optional) `deezerAlbum`: ID of the album on Deezer (http://developers.deezer.com/api/album)\n- (optional) `genreId`: ID of the genre on Deezer (http://developers.deezer.com/api/genre)\n\n\n### downloadAndTagSingleURL(url, outputFolder, callback, title, verbose)\nDownload, convert and tag the video from `url`. Does not work with playlists, only with single videos.\nThe callback function takes one argument, an object containing the following fields:\n- `file`: the name of the output file\n- `infos`: a `trackInfos` object\n\nIf you are looking for specific query and you think `url` correspond to the song you want, you can help the identification and tags with the `title` argument.\n\n#### Emit\n##### 'download': the download is in progress\nThis event is emitted during the download, with an object containing:\n- `progress`: the percentage of the download\n\n##### 'download-end': the download end\n\n##### 'convert': the conversion is in progress\nThis event is emitted during the conversion, with an object containing:\n- `progress`: the percentage of the conversion\n\n##### 'infos': infos about the track\nThis event is emitted every time new information about the track are found, with a `trackInfos` object.\n\n##### 'end': everything is finished\nThis event is emitted at the end (when the file has been downloaded, converted and tagged) with an object containing the following fields:\n- `file`: the name of the output file\n- `infos`: a `trackInfos` object\n\n### findAndDownload(query, outputFolder, callback, verbose)\nFind a YouTube music video matching the query, download and tag it.\nThe callback function takes two arguments, first is an object containing the following fields:\n- `file`: the name of the output file\n- `infos`: a `trackInfos` object\n\nAnd second is fill with an error message if any.\n\n#### Emit\n##### 'search-end': the search end\n\n##### 'download': the download is in progress\nThis event is emitted during the download, with an object containing:\n- `progress`: the percentage of the download\n\n##### 'download-end': the download end\n\n##### 'convert': the conversion is in progress\nThis event is emitted during the conversion, with an object containing:\n- `progress`: the percentage of the conversion\n\n##### 'infos': infos about the track\nThis event is emitted every time new information about the track are found, with a `trackInfos` object.\n\n```js\nconst alltomp3 = require('alltomp3');\n\nconst dl = alltomp3.findAndDownload(\"imagine dragons on top of the world\", (infos) => {\n  console.log(\"It's finished: \", infos);\n});\ndl.on('search-end', () => {\n  console.log('Search end');\n});\ndl.on('download', (infos) => {\n  process.stdout.cursorTo(0);\n  process.stdout.clearLine(1);\n  process.stdout.write(infos.progress + '%');\n});\ndl.on('download-end', () => {\n  console.log('', 'Download end');\n});\ndl.on('convert', (infos) => {\n  process.stdout.cursorTo(0);\n  process.stdout.clearLine(1);\n  process.stdout.write(infos.progress + '%');\n});\ndl.on('convert-end', () => {\n  console.log('', 'Convert end');\n});\ndl.on('infos', (infos) => {\n  console.log('New infos received: ', infos);\n});\n```\n\n### findVideo(query, verbose)\nSearch on YouTube the video which should have an audio corresponding to the `query`. It works best if the query contains the artist and the title of the track.\n\nReturns a **Promise** which is resolved with an ordered array of objects containing:\n- `id`: YouTube videoId\n- `url`: URL of the video\n- `title`: title of the video\n- `hd` (boolean): `true` if the quality >= 720p\n- `duration`: duration in seconds\n- `views`: number of views\n- `score`: a high score indicate a high probability of matching with the query. Can be negative\n\n```js\nconst alltomp3 = require('alltomp3');\n\nalltomp3.findVideo(\"imagine dragons on top of the world\").then((results) => {\n  console.log(results);\n});\n\n// [ { id: 'g8PrTzLaLHc',\n//     url: 'https://www.youtube.com/watch?v=g8PrTzLaLHc',\n//     title: 'Imagine Dragons - On Top of the World -',\n//     hd: false,\n//     duration: 191,\n//     views: '24255381',\n//     score: -42.113922489729575 },\n//   { id: 'e74VMNgARvY',\n//     url: 'https://www.youtube.com/watch?v=e74VMNgARvY',\n//     title: 'Imagine Dragons - On Top of the World',\n//     hd: true,\n//     duration: 196,\n//     views: '1695902',\n//     score: -62.604333945991385 },\n//     ....\n// ]\n\n```\n\n### retrieveTrackInformations(title, artistName, exact, verbose)\nRetrieve information on the track corresponding to `title` and `artistName`. `exact` is a boolean indicating if the terms can change a little (`true` by default).\n\nReturns a **Promise** with a `trackInfos` object.\n\n\n### guessTrackFromString(query)\nTry to find a title and an artist matching the `query`. Works especially well with YouTube video names.\n\nReturns a **Promise** with an object containing:\n- `title`\n- `artistName`\n\n```js\nconst alltomp3 = require('alltomp3');\n\nconst l = (infos) => {\n  console.log(infos);\n};\n\nalltomp3.guessTrackFromString('Imagine Dragons - On Top of the World - Lyrics').then(l);\nalltomp3.guessTrackFromString('C2C - Happy Ft. D.Martin').then(l);\nalltomp3.guessTrackFromString('David Guetta - Bang My Head (Official Video) feat Sia & Fetty Wap').then(l);\nalltomp3.guessTrackFromString('David Guetta - Hey Mama (Official Video) ft Nicki Minaj, Bebe Rexha & Afrojack').then(l);\nalltomp3.guessTrackFromString('hans zimmer no time for caution').then(l);\n\n// { title: 'On Top Of The World', artistName: 'Imagine Dragons' }\n// { title: 'Happy', artistName: 'C2C' }\n// { title: 'Bang my Head (feat. Sia & Fetty Wap)', artistName: 'David Guetta' }\n// { title: 'Hey Mama', artistName: 'David Guetta' }\n// { title: 'No Time for Caution', artistName: 'Hans Zimmer' }\n```\n\n\n### findLyrics(title, artistName)\nSearch lyrics for a song.\n\nReturns a **Promise** with a `string`.\n\n```js\nconst alltomp3 = require('alltomp3');\n\nalltomp3.findLyrics('Radioactive', 'Imagine Dragons').then((lyrics) => {\n  console.log(lyrics);\n}).catch(() => {\n  console.log('No lyrics');\n});\n```\n\n\n### downloadPlaylistWithURLs(url, outputFolder, callback, maxSimultaneous)\nDownload the playlist `url` containing URLs (aka YouTube or SoundCloud playlist), convert and tag it in `outputFolder`. `maxSimultaneous` is the maximum number of parallel conversions (default to 1).\n\n#### Emit\n#### 'list': the playlist description has been received\nThis event is emitted when information about the playlist has been received, with an `array(objects)` with the following keys:\n- `url`: URL of the video/track\n- `title`: title of the video/track\n- `image`: image of the video/track\n- `progress`: object with:\n  - `download`: progression of the download\n  - `convert`: progression of the conversion\n- `infos`: `trackInfos` object\n- `file`: path to the final MP3\n\n**This array is updated as the process progress.**\n\n#### 'begin-url': a new item is processed\nThis event is emitted when a new item is now processed, with an integer `index` indicating the corresponding track.\n\n##### 'download': the download of an item is in progress\nThis event is emitted during the download, with an integer `index` indicating the corresponding track.\n\n##### 'download-end': the download end\nThis event is emitted when the download of an item end, with an integer `index` indicating the corresponding track.\n\n##### 'convert': the conversion is in progress\nThis event is emitted during the conversion, with an integer `index` indicating the corresponding track.\n\n##### 'infos': infos about the track\nThis event is emitted every time new information about a track is received, with an integer `index` indicating the corresponding track.\n\n#### 'end-url': the processing of an item is finished\nThis event is emitted when the processing of an item is finished, with an integer `index` indicating the corresponding track.\n\n##### 'end': everything is finished\nThis event is emitted at the end, when all items have been processed, with the `list` array.\n\n\n### downloadPlaylistWithTitles(url, outputFolder, callback, maxSimultaneous)\nDownload the playlist `url` containing titles (aka Deezer Playlist or Deezer Album), find best matching video on YouTube, convert and tag it in `outputFolder`. `maxSimultaneous` is the maximum number of parallel conversions (default to 1).\n\n#### Emit\n#### 'list': the playlist description has been received\nThis event is emitted when information about the playlist has been received, with an `array(objects)` with the following keys:\n- `title`: title of the track\n- `artistName`: artist of the track\n- `cover`: cover of the track\n- `progress`: object with:\n  - `download`: progression of the download\n  - `convert`: progression of the conversion\n- `infos`: `trackInfos` object\n- `file`: path to the final MP3\n\n**This array is updated as the process progress.**\n\n#### 'begin-url': a new item is processed\nThis event is emitted when a new item is now processed, with an integer `index` indicating the corresponding track.\n\n### 'search-end': the search end\nThis event is emitted when the search of YouTube videos for an item (based on the title) end, with an integer `index` indicating the corresponding track.\n\n##### 'download': the download of an item is in progress\nThis event is emitted during the download, with an integer `index` indicating the corresponding track.\n\n##### 'download-end': the download end\nThis event is emitted when the download of an item end, with an integer `index` indicating the corresponding track.\n\n##### 'convert': the conversion is in progress\nThis event is emitted during the conversion, with an integer `index` indicating the corresponding track.\n\n##### 'infos': infos about the track\nThis event is emitted every time new information about a track is received, with an integer `index` indicating the corresponding track.\n\n#### 'end-url': the processing of an item is finished\nThis event is emitted when the processing of an item is finished, with an integer `index` indicating the corresponding track.\n\n##### 'end': everything is finished\nThis event is emitted at the end, when all items have been processed, with the `list` array.\n"
  },
  {
    "path": "circle.yml",
    "content": "machine:\n  node:\n    version: 7.2.0\n\ndependencies:\n  pre:\n    - sudo apt-get update; sudo apt-get install ffmpeg libchromaprint-tools eyeD3 lame\n    - npm install --global mocha\n"
  },
  {
    "path": "index.js",
    "content": "const ytdl = require('ytdl-core');\nconst ffmpeg = require('fluent-ffmpeg');\nconst path = require('path');\nconst fs = require('fs-extra');\nconst EventEmitter = require('events');\nconst request = require('request-promise');\nconst requestNoPromise = require('request');\nconst _ = require('lodash');\nconst acoustid = require('acoustid');\nconst EyeD3 = require('eyed3');\nlet eyed3 = new EyeD3({ eyed3_path: 'eyeD3' });\neyed3.metaHook = (m) => m;\nconst levenshtein = require('fast-levenshtein');\nconst randomstring = require('randomstring');\nconst cheerio = require('cheerio');\nconst Promise = require('bluebird');\nconst sharp = require('sharp');\nconst smartcrop = require('smartcrop-sharp');\nconst ytsr = require('ytsr');\nconst ytpl = require('ytpl');\nconst lcs = require('longest-common-substring');\n\n// API keys\nconst API_ACOUSTID = 'lm59lNN597';\nconst API_SOUNDCLOUD = 'dba290d84e6ca924414c91ac12fc3c8f';\nconst API_SPOTIFY = 'ODNiZjMzMmQ4MDI1NGNlNzhkNjNkOWM2ZWM2N2M5ZTU6Mzg4OTIxY2M0ZjEyNGEwYWFjM2NiMzIzYTNiZGVlYmU=';\n\nconst at3 = {};\n\n// ISO 3166-1 alpha-2 country code of the user (ex: US, FR)\nat3.regionCode;\n\n// ISO 639-1 two-letter language code of the user (ex: en, fr)\nat3.relevanceLanguage;\n\n// Folder for temporary files\nat3.tempFolder = null;\n\n// Fix for renameSync failing on Windows when cropping cover images\n// See https://github.com/lovell/sharp/issues/415\nsharp.cache(false);\n\nat3.configEyeD3 = (eyeD3Path, eyeD3PathPythonPath, metaHook) => {\n  process.env.PYTHONPATH = eyeD3PathPythonPath;\n  eyed3 = new EyeD3({ eyed3_path: eyeD3Path });\n  if (!metaHook) {\n    metaHook = (m) => m;\n  }\n  eyed3.metaHook = metaHook;\n};\n\nat3.FPCALC_PATH = 'fpcalc';\nat3.setFpcalcPath = (fpcalcPath) => {\n  at3.FPCALC_PATH = fpcalcPath;\n};\n\nat3.setFfmpegPaths = (ffmpegPath, ffprobePath) => {\n  if (ffmpegPath) {\n    at3.FFMPEG_PATH = ffmpegPath;\n  }\n  if (ffprobePath) {\n    at3.FFPROBE_PATH = ffprobePath;\n  }\n};\n\n/**\n * Find lyrics for a song\n * @param title string\n * @param artistName string\n * @return Promise\n */\nat3.findLyrics = (title, artistName) => {\n  let promises = [];\n\n  const textln = (html) => {\n    html.find('br').replaceWith('\\n');\n    html.find('script').replaceWith('');\n    html.find('#video-musictory').replaceWith('');\n    html.find('strong').replaceWith('');\n    html = _.trim(html.text());\n    html = html.replace(/\\r\\n\\n/g, '\\n');\n    html = html.replace(/\\t/g, '');\n    html = html.replace(/\\n\\r\\n/g, '\\n');\n    html = html.replace(/ +/g, ' ');\n    html = html.replace(/\\n /g, '\\n');\n    return html;\n  };\n\n  const lyricsUrl = (title) => {\n    return _.kebabCase(_.trim(_.toLower(_.deburr(title))));\n  };\n  const lyricsManiaUrl = (title) => {\n    return _.snakeCase(_.trim(_.toLower(_.deburr(title))));\n  };\n  const lyricsManiaUrlAlt = (title) => {\n    title = _.trim(_.toLower(title));\n    title = title.replace(\"'\", '');\n    title = title.replace(' ', '_');\n    title = title.replace(/_+/g, '_');\n    return title;\n  };\n\n  const reqWikia = request({\n    uri: 'http://lyrics.wikia.com/wiki/' + encodeURIComponent(artistName) + ':' + encodeURIComponent(title),\n    transform: (body) => {\n      return cheerio.load(body);\n    },\n  }).then(($) => {\n    return textln($('.lyricbox'));\n  });\n\n  const reqParolesNet = request({\n    uri: 'http://www.paroles.net/' + lyricsUrl(artistName) + '/paroles-' + lyricsUrl(title),\n    transform: (body) => {\n      return cheerio.load(body);\n    },\n  }).then(($) => {\n    if ($('.song-text').length === 0) {\n      return Promise.reject();\n    }\n    return textln($('.song-text'));\n  });\n\n  const reqLyricsMania1 = request({\n    uri: 'http://www.lyricsmania.com/' + lyricsManiaUrl(title) + '_lyrics_' + lyricsManiaUrl(artistName) + '.html',\n    transform: (body) => {\n      return cheerio.load(body);\n    },\n  }).then(($) => {\n    if ($('.lyrics-body').length === 0) {\n      return Promise.reject();\n    }\n    return textln($('.lyrics-body'));\n  });\n\n  const reqLyricsMania2 = request({\n    uri: 'http://www.lyricsmania.com/' + lyricsManiaUrl(title) + '_' + lyricsManiaUrl(artistName) + '.html',\n    transform: (body) => {\n      return cheerio.load(body);\n    },\n  }).then(($) => {\n    if ($('.lyrics-body').length === 0) {\n      return Promise.reject();\n    }\n    return textln($('.lyrics-body'));\n  });\n\n  const reqLyricsMania3 = request({\n    uri:\n      'http://www.lyricsmania.com/' +\n      lyricsManiaUrlAlt(title) +\n      '_lyrics_' +\n      encodeURIComponent(lyricsManiaUrlAlt(artistName)) +\n      '.html',\n    transform: (body) => {\n      return cheerio.load(body);\n    },\n  }).then(($) => {\n    if ($('.lyrics-body').length === 0) {\n      return Promise.reject();\n    }\n    return textln($('.lyrics-body'));\n  });\n\n  const reqSweetLyrics = request({\n    method: 'POST',\n    uri: 'http://www.sweetslyrics.com/search.php',\n    form: {\n      search: 'title',\n      searchtext: title,\n    },\n    transform: (body) => {\n      return cheerio.load(body);\n    },\n  })\n    .then(($) => {\n      let closestLink,\n        closestScore = -1;\n      _.forEach($('.search_results_row_color'), (e) => {\n        let artist = $(e)\n          .text()\n          .replace(/ - .+$/, '');\n        let currentScore = levenshtein.get(artistName, artist);\n        if (closestScore === -1 || currentScore < closestScore) {\n          closestScore = currentScore;\n          closestLink = $(e).find('a').last().attr('href');\n        }\n      });\n      if (!closestLink) {\n        return Promise.reject();\n      }\n      return request({\n        uri: 'http://www.sweetslyrics.com/' + closestLink,\n        transform: (body) => {\n          return cheerio.load(body);\n        },\n      });\n    })\n    .then(($) => {\n      return textln($('.lyric_full_text'));\n    });\n\n  if (/\\(.*\\)/.test(title) || /\\[.*\\]/.test(title)) {\n    promises.push(at3.findLyrics(title.replace(/\\(.*\\)/g, '').replace(/\\[.*\\]/g, ''), artistName));\n  }\n\n  promises.push(reqWikia);\n  promises.push(reqParolesNet);\n  promises.push(reqLyricsMania1);\n  promises.push(reqLyricsMania2);\n  promises.push(reqLyricsMania3);\n  promises.push(reqSweetLyrics);\n\n  return Promise.any(promises).then((lyrics) => {\n    return lyrics;\n  });\n};\n\n/**\n * Returns true if the query corresponds\n * to an URL, else false\n * @param query string\n * @return boolean\n */\nat3.isURL = (query) => {\n  return /^http(s?):\\/\\//.test(query);\n};\n\n/**\n * Get a fresh access token from Spotify API\n * @return {Promise}\n */\nat3.spotifyToken = () => {\n  return request\n    .post({\n      uri: 'https://accounts.spotify.com/api/token',\n      headers: {\n        Authorization: 'Basic ' + API_SPOTIFY,\n      },\n      form: {\n        grant_type: 'client_credentials',\n      },\n      json: true,\n    })\n    .then((r) => {\n      return r.access_token;\n    });\n};\n\n/**\n * Perform a GET request to the Spotify API `url` endpoint\n * @param {String} url URL of Spotify API endpoint to get\n * @return {Promise} The request\n */\nat3.requestSpotify = (url) => {\n  return at3.spotifyToken().then((token) => {\n    return request({\n      uri: url,\n      json: true,\n      headers: {\n        Authorization: 'Bearer ' + token,\n      },\n    });\n  });\n};\n\n/**\n * Download a single video\n * @param url\n * @param outputFile\n * @return Event\n */\nat3.downloadWithYoutubeDl = (url, outputFile) => {\n  const download = ytdl(url, { quality: 'highestaudio' });\n  download.pipe(fs.createWriteStream(outputFile));\n  const downloadEmitter = new EventEmitter();\n  let aborted = false;\n\n  const onProgress = (_chunk, nbDownloaded, nbTotal) => {\n    const percent = ((nbDownloaded / nbTotal) * 100).toFixed(2);\n    downloadEmitter.emit('download-progress', {\n      progress: percent,\n    });\n  };\n\n  download.on('progress', onProgress);\n\n  download.once('end', () => {\n    if (aborted) {\n      return;\n    }\n    download.removeListener('progress', onProgress);\n    downloadEmitter.emit('download-end');\n  });\n\n  download.once('error', (error) => {\n    download.removeListener('progress', onProgress);\n    downloadEmitter.emit('error', new Error(error));\n  });\n\n  const abort = () => {\n    aborted = true;\n    download.abort();\n    if (fs.existsSync(outputFile)) {\n      fs.unlinkSync(outputFile);\n    }\n  };\n\n  downloadEmitter.once('abort', abort);\n\n  return downloadEmitter;\n};\n\n/**\n * Convert a outputFile in MP3\n * @param inputFile\n * @param outputFile\n * @param bitrate string\n * @return Event\n */\nat3.convertInMP3 = (inputFile, outputFile, bitrate) => {\n  const convertEmitter = new EventEmitter();\n  let aborted = false;\n  let started = false;\n\n  let convert = ffmpeg(inputFile);\n  if (at3.FFMPEG_PATH) {\n    convert.setFfmpegPath(at3.FFMPEG_PATH);\n  }\n  if (at3.FFPROBE_PATH) {\n    convert.setFfprobePath(at3.FFPROBE_PATH);\n  }\n\n  const onProgress = (progress) => {\n    convertEmitter.emit('convert-progress', {\n      progress: progress.percent,\n    });\n  };\n\n  convert\n    .audioBitrate(bitrate)\n    .audioCodec('libmp3lame')\n    .once('codecData', (_data) => {\n      convertEmitter.emit('convert-start');\n    })\n    .on('progress', onProgress)\n    .once('end', () => {\n      convert.removeListener('progress', onProgress);\n      fs.unlinkSync(inputFile);\n      convertEmitter.emit('convert-end');\n    })\n    .once('error', (e) => {\n      convert.removeListener('progress', onProgress);\n      if (!aborted) {\n        convertEmitter.emit('error', e);\n      } else {\n        if (fs.existsSync(inputFile)) {\n          fs.unlink(inputFile, () => {});\n        }\n        if (fs.existsSync(outputFile)) {\n          fs.unlink(outputFile, () => {});\n        }\n      }\n    })\n    .once('start', () => {\n      started = true;\n      if (aborted) {\n        abort();\n      }\n    })\n    .save(outputFile);\n\n  const abort = () => {\n    aborted = true;\n    if (started) {\n      convert.kill();\n    }\n  };\n\n  convertEmitter.once('abort', abort);\n\n  return convertEmitter;\n};\n\n/**\n * Get infos about an online video\n * @param url\n * @return Promise\n */\nat3.getInfosWithYoutubeDl = (url) => {\n  return ytdl.getBasicInfo(url).then((infos) => {\n    const thumbnails = infos.player_response.videoDetails.thumbnail.thumbnails;\n\n    return {\n      title: infos.videoDetails.title,\n      author: infos.videoDetails.author.name,\n      picture: thumbnails[thumbnails.length - 1].url,\n    };\n  });\n\n  //   youtubedl.getInfo(url, ['--no-check-certificate'], (err, infos) => {\n  //     if (err || infos === undefined) {\n  //       reject();\n  //     } else {\n  //       resolve({\n  //         title: infos.title,\n  //         author: infos.uploader,\n  //         picture: infos.thumbnail,\n  //       });\n  //     }\n  //   });\n  // });\n};\n\n/**\n * Download a single URL in MP3\n * @param url\n * @param outputFile\n * @param bitrate\n * @return Event\n */\nat3.downloadSingleURL = (url, outputFile, bitrate) => {\n  const progressEmitter = new EventEmitter();\n  let tempFile = outputFile + '.video';\n  let downloadEnded = false;\n  let convert;\n\n  const dl = at3.downloadWithYoutubeDl(url, tempFile);\n  const onDlProgress = (infos) => {\n    progressEmitter.emit('download', {\n      progress: infos.progress,\n    });\n  };\n\n  dl.once('download-start', () => {\n    progressEmitter.emit('start');\n  });\n  dl.on('download-progress', onDlProgress);\n\n  dl.once('download-end', () => {\n    downloadEnded = true;\n    dl.removeListener('download-progress', onDlProgress);\n    progressEmitter.emit('download-end');\n\n    convert = at3.convertInMP3(tempFile, outputFile, bitrate);\n    const onConvertProgress = (infos) => {\n      progressEmitter.emit('convert', {\n        progress: infos.progress,\n      });\n    };\n    convert.on('convert-progress', onConvertProgress);\n    convert.once('convert-end', () => {\n      convert.removeListener('convert-progress', onConvertProgress);\n      progressEmitter.emit('end');\n    });\n    convert.once('error', (error) => {\n      progressEmitter.emit('error', error);\n    });\n  });\n\n  dl.once('error', (error) => {\n    dl.removeListener('download-progress', onDlProgress);\n    progressEmitter.emit('error', new Error(error));\n  });\n\n  progressEmitter.once('abort', () => {\n    if (!downloadEnded) {\n      dl.emit('abort');\n    } else {\n      convert.emit('abort');\n    }\n  });\n\n  return progressEmitter;\n};\n\n/**\n * Try to find to title and artist from a string\n * (example: a YouTube video title)\n * @param query string\n * @param exact boolean Can the query be modified or not\n * @param last boolean Last call\n * @param v boolean Verbose\n * @return Promise\n */\nat3.guessTrackFromString = (query, exact, last, v) => {\n  // [TODO] Replace exact by a level of strictness\n  // 0: no change at all\n  // 4: remove every thing useless\n  if (exact === undefined) {\n    exact = false;\n  }\n  if (last === undefined) {\n    last = false;\n  }\n  if (v === undefined) {\n    v = false;\n  }\n\n  if (v) {\n    console.log('Query: ', query);\n  }\n\n  let searchq = query;\n  if (!exact) {\n    searchq = searchq.replace(/\\(.*\\)/g, '');\n    searchq = searchq.replace(/\\[.*\\]/g, '');\n    searchq = searchq.replace(/lyric(s?)|parole(s?)/gi, '');\n    searchq = searchq.replace(/^'/, '');\n    searchq = searchq.replace(/ '/g, ' ');\n    searchq = searchq.replace(/' /g, ' ');\n    searchq = searchq.replace(/Original Motion Picture Soundtrack/i, '');\n    searchq = searchq.replace(/bande originale/i, '');\n  }\n\n  const requests = [];\n  const infos = {\n    title: null,\n    artistName: null,\n  };\n\n  // We search on Deezer and iTunes\n  // [TODO] Adding Spotify\n\n  // Deezer\n  const requestDeezer = request({\n    url: 'https://api.deezer.com/2.0/search?q=' + encodeURIComponent(searchq),\n    json: true,\n  }).then((body) => {\n    let title, artistName, tempTitle;\n    _.forEach(body.data, (s) => {\n      if (!title) {\n        if (vsimpleName(searchq, exact).replace(new RegExp(vsimpleName(s.artist.name), 'ig'))) {\n          if (\n            delArtist(s.artist.name, searchq, exact).match(new RegExp(vsimpleName(s.title_short), 'ig')) ||\n            vsimpleName(s.title_short).match(new RegExp(delArtist(s.artist.name, searchq, exact), 'ig'))\n          ) {\n            artistName = s.artist.name;\n            title = s.title;\n          } else if (!artistName) {\n            artistName = s.artist.name;\n            tempTitle = s.title;\n          }\n        }\n      }\n    });\n    if (title && artistName) {\n      infos.title = title;\n      infos.artistName = artistName;\n    }\n    if (v) {\n      console.log('Deezer answer: ', title, '-', artistName);\n    }\n  });\n\n  // iTunes\n  const requestiTunes = request({\n    url: 'https://itunes.apple.com/search?media=music&term=' + encodeURIComponent(searchq),\n    json: true,\n  }).then((body) => {\n    let title, artistName, tempTitle;\n    _.forEach(body.results, (s) => {\n      if (!title) {\n        if (vsimpleName(searchq, exact).match(new RegExp(vsimpleName(s.artistName), 'gi'))) {\n          if (delArtist(s.artistName, searchq, exact).match(new RegExp(vsimpleName(s.trackCensoredName), 'gi'))) {\n            artistName = s.artistName;\n            title = s.trackCensoredName;\n          } else if (delArtist(s.artistName, searchq, exact).match(new RegExp(vsimpleName(s.trackName), 'gi'))) {\n            artistName = s.artistName;\n            title = s.trackName;\n          } else if (!artistName) {\n            artistName = s.artistName;\n            temp_title = s.trackName;\n          }\n        }\n      }\n    });\n    if (title && artistName) {\n      infos.title = title;\n      infos.artistName = artistName;\n    }\n    if (v) {\n      console.log('iTunes answer: ', title, '-', artistName);\n    }\n  });\n\n  requests.push(requestDeezer);\n  requests.push(requestiTunes);\n\n  return Promise.all(requests).then(() => {\n    if (!last && (!infos.title || !infos.artistName)) {\n      searchq = searchq.replace(/f(ea)?t(\\.)? [^-]+/gi, ' ');\n      return at3.guessTrackFromString(searchq, false, true, v);\n    }\n    return infos;\n  });\n};\n\n/**\n * Try to guess title and artist from mp3 file\n * @param file\n * @return Promise\n */\nat3.guessTrackFromFile = (file) => {\n  return new Promise((resolve, _reject) => {\n    acoustid(file, { key: API_ACOUSTID, fpcalc: { command: at3.FPCALC_PATH } }, (err, results) => {\n      if (\n        err ||\n        results.length === 0 ||\n        !results[0].recordings ||\n        results[0].recordings.length === 0 ||\n        !results[0].recordings[0].artists ||\n        results[0].recordings[0].artists.length === 0\n      ) {\n        resolve({});\n        return;\n      }\n      resolve({\n        title: results[0].recordings[0].title,\n        artistName: results[0].recordings[0].artists[0].name,\n      });\n    });\n  });\n};\n\n/**\n * Retrieve informations about a track from artist and title\n * @param title\n * @param artistName\n * @param exact boolean Exact search or not\n * @param v boolean Verbose\n * @return Promise\n */\nat3.retrieveTrackInformations = (title, artistName, exact, v) => {\n  if (exact === undefined) {\n    exact = false;\n  }\n  if (v === undefined) {\n    v = false;\n  }\n\n  if (!exact) {\n    title = title.replace(/((\\[)|(\\())?radio edit((\\])|(\\)))?/gi, '');\n  }\n\n  const infos = {\n    title: title,\n    artistName: artistName,\n  };\n\n  const requests = [];\n\n  const requestDeezer = request({\n    url: 'https://api.deezer.com/2.0/search?q=' + encodeURIComponent(artistName + ' ' + title),\n    json: true,\n  }).then((body) => {\n    let deezerInfos;\n    _.forEach(body.data, (s) => {\n      if (\n        !infos.deezerId &&\n        imatch(vsimpleName(title), vsimpleName(s.title)) &&\n        imatch(vsimpleName(artistName), vsimpleName(s.artist.name))\n      ) {\n        infos.deezerId = s.id;\n        deezerInfos = _.clone(s);\n      }\n    });\n    if (infos.deezerId) {\n      infos.artistName = deezerInfos.artist.name;\n      infos.title = deezerInfos.title;\n\n      return at3\n        .getDeezerTrackInfos(infos.deezerId, v)\n        .then((deezerInfos) => {\n          infos = deezerInfos;\n        })\n        .catch(() => {});\n    }\n  });\n\n  const requestiTunes = request({\n    url: 'https://itunes.apple.com/search?media=music&term=' + encodeURIComponent(artistName + ' ' + title),\n    json: true,\n  }).then((body) => {\n    let itunesInfos;\n    _.forEach(body.results, (s) => {\n      if (\n        !infos.itunesId &&\n        (imatch(vsimpleName(title), vsimpleName(s.trackName)) ||\n          imatch(vsimpleName(title), vsimpleName(s.trackCensoredName))) &&\n        imatch(vsimpleName(artistName), vsimpleName(s.artistName))\n      ) {\n        infos.itunesId = s.trackId;\n        itunesInfos = _.clone(s);\n      }\n    });\n    if (!infos.deezerId && itunesInfos) {\n      infos.artistName = itunesInfos.artistName;\n      if (imatch(vsimpleName(infos.title), vsimpleName(itunesInfos.trackName))) {\n        infos.title = itunesInfos.trackName;\n      } else {\n        infos.title = itunesInfos.trackCensoredName;\n      }\n      infos.itunesAlbum = itunesInfos.collectionId;\n      infos.position = itunesInfos.trackNumber;\n      infos.nbTracks = itunesInfos.trackCount;\n      infos.album = itunesInfos.collectionName;\n      infos.releaseDate = itunesInfos.releaseDate.replace(/T.+/, '');\n      infos.cover = itunesInfos.artworkUrl100.replace('100x100', '200x200');\n      infos.genre = itunesInfos.primaryGenreName;\n      infos.discNumber = itunesInfos.discNumber;\n      infos.duration = itunesInfos.trackTimeMillis / 1000;\n    }\n\n    if (v) {\n      console.log('iTunes infos: ', itunesInfos);\n    }\n  });\n\n  requests.push(requestDeezer);\n  requests.push(requestiTunes);\n\n  return Promise.all(requests).then(() => infos);\n};\n\n/**\n * Retrieve detailed infos about a Deezer Track\n * @param trackId\n * @param v boolean Verbosity\n * @return Promise(trackInfos)\n */\nat3.getDeezerTrackInfos = (trackId, v) => {\n  const infos = {\n    deezerId: trackId,\n  };\n\n  return request({\n    url: 'https://api.deezer.com/2.0/track/' + infos.deezerId,\n    json: true,\n  })\n    .then((trackInfos) => {\n      if (trackInfos.error) {\n        return Promise.reject();\n      }\n\n      infos.title = trackInfos.title;\n      infos.artistName = trackInfos.artist.name;\n      infos.position = trackInfos.track_position;\n      infos.duration = trackInfos.duration;\n      infos.deezerAlbum = trackInfos.album.id;\n      infos.discNumber = trackInfos.disk_number;\n\n      return request({\n        url: 'https://api.deezer.com/2.0/album/' + infos.deezerAlbum,\n        json: true,\n      });\n    })\n    .then((albumInfos) => {\n      infos.album = albumInfos.title;\n      infos.releaseDate = albumInfos.release_date;\n      infos.nbTracks = albumInfos.tracks.data.length;\n      infos.genreId = albumInfos.genre_id;\n      infos.cover = albumInfos.cover_big;\n\n      return request({\n        url: 'https://api.deezer.com/2.0/genre/' + infos.genreId,\n        json: true,\n      });\n    })\n    .then((genreInfos) => {\n      infos.genre = genreInfos.name;\n\n      if (v) {\n        console.log('Deezer infos: ', infos);\n      }\n\n      return infos;\n    });\n};\n\n/**\n * Get complete information (title, artist, release date, genre, album name...)\n * for a Spotify track\n * @param {trackId} string The Spotify track id\n * @param {v} boolean The verbosity\n * @return Promise\n */\nat3.getSpotifyTrackInfos = (trackId, v) => {\n  const infos = {\n    spotifyId: trackId,\n  };\n\n  return at3\n    .requestSpotify('https://api.spotify.com/v1/tracks/' + trackId)\n    .then((trackInfos) => {\n      infos.title = trackInfos.name;\n      infos.artistName = trackInfos.artists[0].name;\n      infos.duration = Math.ceil(trackInfos.duration_ms / 1000);\n      infos.position = trackInfos.track_number;\n      infos.discNumber = trackInfos.disc_number;\n      infos.spotifyAlbum = trackInfos.album.id;\n\n      return at3.requestSpotify('https://api.spotify.com/v1/albums/' + trackInfos.album.id);\n    })\n    .then((albumInfos) => {\n      infos.album = albumInfos.name;\n      infos.cover = albumInfos.images[0].url;\n      infos.genre = albumInfos.genres[0] || '';\n      infos.nbTracks = albumInfos.tracks.total;\n      infos.releaseDate = albumInfos.release_date;\n\n      return infos;\n    });\n};\n\n/**\n * Add tags to MP3 file\n * @param file\n * @param infos\n * @return Promise\n */\nat3.tagFile = (file, infos) => {\n  const meta = {\n    title: infos.title,\n    artist: infos.artistName,\n  };\n\n  if (infos.album) {\n    meta.album = infos.album;\n  }\n  if (infos.position) {\n    meta.track = infos.position;\n  }\n  if (infos.nbTracks) {\n    meta.trackTotal = infos.nbTracks;\n  }\n  if (infos.discNumber) {\n    meta.disc = infos.discNumber;\n  }\n  if (infos.lyrics) {\n    meta.lyrics = infos.lyrics;\n  }\n  if (infos.releaseDate) {\n    meta.year = /[0-9]{4}/.exec(infos.releaseDate)[0];\n  }\n  if (infos.genre) {\n    meta.genre = infos.genre.replace(/\\/.+/g, '');\n  }\n\n  return new Promise((resolve, reject) => {\n    eyed3.updateMeta(file, eyed3.metaHook(meta), (err) => {\n      if (err) {\n        return reject(err);\n      }\n      if (infos.cover) {\n        let coverPath = file + '.cover.jpg';\n\n        requestNoPromise(infos.cover, () => {\n          // Check that the cover is a square\n          const coverFile = sharp(coverPath);\n          coverFile\n            .metadata()\n            .then((metadata) => {\n              if (metadata.width != metadata.height) {\n                // In that case we will crop the cover to get a square\n                const tempCoverPath = file + '.cover.resized.jpg';\n                return smartcrop\n                  .crop(coverPath, { width: 100, height: 100 })\n                  .then((result) => {\n                    let crop = result.topCrop;\n                    return coverFile\n                      .extract({\n                        width: crop.width,\n                        height: crop.height,\n                        left: crop.x,\n                        top: crop.y,\n                      })\n                      .toFile(tempCoverPath);\n                  })\n                  .then(() => {\n                    fs.renameSync(tempCoverPath, coverPath);\n                  });\n              }\n            })\n            .then(() => {\n              eyed3.updateMeta(file, eyed3.metaHook({ image: coverPath }), (err) => {\n                fs.unlinkSync(coverPath);\n\n                if (err) {\n                  return reject(err);\n                }\n\n                resolve();\n              });\n            });\n        }).pipe(fs.createWriteStream(coverPath));\n      } else {\n        resolve();\n      }\n    });\n  });\n};\n\n/**\n * Search and return complete information about a single video url\n * @param url\n * @param v boolean Verbosity\n * @return Promise(object)\n */\nat3.getCompleteInfosFromURL = (url, v) => {\n  let infosFromString;\n  // Try to find information based on video title\n  return at3\n    .getInfosWithYoutubeDl(url)\n    .then((videoInfos) => {\n      infosFromString = {\n        title: videoInfos.title,\n        artistName: videoInfos.author,\n        cover: videoInfos.picture.replace('hqdefault', 'mqdefault'), // [TODO]: getting a better resolution and removing the black borders\n        originalTitle: videoInfos.title,\n      };\n\n      if (v) {\n        console.log('Video infos: ', infosFromString);\n      }\n\n      // progressEmitter.emit('infos', _.clone(infosFromString));\n\n      return at3.guessTrackFromString(videoInfos.title, false, false, v);\n    })\n    .then((guessStringInfos) => {\n      if (guessStringInfos.title && guessStringInfos.artistName) {\n        return at3.retrieveTrackInformations(guessStringInfos.title, guessStringInfos.artistName, false, v);\n      } else {\n        return Promise.resolve();\n      }\n    })\n    .then((guessStringInfos) => {\n      if (guessStringInfos) {\n        guessStringInfos.originalTitle = infosFromString.originalTitle;\n        infosFromString = guessStringInfos;\n        // progressEmitter.emit('infos', _.clone(infosFromString));\n        if (v) {\n          console.log('guessStringInfos: ', guessStringInfos);\n        }\n      } else {\n        if (v) {\n          console.log('Cannot retrieve detailed information from video title');\n        }\n      }\n\n      return infosFromString;\n    })\n    .then((guessStringInfos) => {\n      if (guessStringInfos.deezerId) {\n        return at3.getDeezerTrackInfos(guessStringInfos.deezerId, v);\n      } else if (guessStringInfos.spotifyId) {\n        return at3.getSpotifyTrackInfos(guessStringInfos.spotifyId, v);\n      } else {\n        return guessStringInfos;\n      }\n    })\n    .catch((_error) => {\n      // The download must have failed to, and emit an error\n    });\n};\n\n/**\n * Identify the song from a file and then search complete information about it\n * @param file string\n * @param v boolean Verbosity\n * @return Promise(object)\n */\nat3.getCompleteInfosFromFile = (file, v) => {\n  return at3\n    .guessTrackFromFile(file)\n    .then((guessFileInfos) => {\n      if (guessFileInfos.title && guessFileInfos.artistName) {\n        return at3.retrieveTrackInformations(guessFileInfos.title, guessFileInfos.artistName, false, v);\n      } else {\n        return Promise.resolve();\n      }\n    })\n    .then((guessFileInfos) => {\n      if (guessFileInfos) {\n        if (v) {\n          console.log('guessFileInfos: ', guessFileInfos);\n        }\n        return guessFileInfos;\n      } else {\n        if (v) {\n          console.log('Cannot retrieve detailed information from MP3 file');\n        }\n      }\n    });\n};\n\n/**\n * Simplify a string so it works well as a filename\n * @param {String} string\n * @return {String}\n */\nat3.escapeForFilename = (string) => {\n  return _.startCase(_.toLower(_.deburr(string)))\n    .replace(/^\\.+/, '')\n    .replace(/\\.+$/, '');\n};\n\n/**\n * Return a correctly formatted filename for a song.\n * Example: \"02 - On Top Of The World\"\n * @param title string Title of the song\n * @param artist string Artist\n * @param position int Position on the disk\n * @return string\n */\nat3.formatSongFilename = (title, artist, position) => {\n  let filename = at3.escapeForFilename(artist) + ' - ';\n  if (position) {\n    if (position < 10) {\n      filename += '0';\n    }\n    filename += position + ' - ';\n  }\n\n  filename += at3.escapeForFilename(title);\n\n  return filename;\n};\n\n/**\n * Create necessary folders for a subpath\n * @param baseFolder {string} The path of the outputfolder\n * @param subPathFormat {string} The subPath format: {artist}/{title}/\n * @param title {string} Title\n * @param artist {string} Artist\n * @return {String} The complete path\n */\nat3.createSubPath = (baseFolder, subPathFormat, title, artist) => {\n  subPathFormat = subPathFormat.replace(/\\{artist\\}/g, at3.escapeForFilename(artist));\n  subPathFormat = subPathFormat.replace(/\\{title\\}/g, at3.escapeForFilename(title));\n\n  let p = path.join(baseFolder, subPathFormat);\n  if (p.charAt(p.length - 1) != path.sep) {\n    p += path.sep;\n  }\n\n  const folders = subPathFormat.split(path.sep);\n  let currentFolder = baseFolder;\n  folders.forEach((f) => {\n    currentFolder = path.join(currentFolder, f);\n    if (!fs.existsSync(currentFolder)) {\n      fs.mkdirSync(currentFolder);\n    }\n  });\n\n  return p;\n};\n\n/**\n * Download and convert a single URL,\n * retrieve and add tags to the MP3 file\n * @param url\n * @param outputFolder\n * @param callback Callback function\n * @param title string Optional requested title\n * @param infos object Basic infos to tag the file\n * @param v boolean Verbosity\n * @param options object { bitrate: '256k' } output audio bitrate\n * @return Event\n */\nat3.downloadAndTagSingleURL = (url, outputFolder, callback, title, v, infos, options = {}) => {\n  if (v === undefined) {\n    v = false;\n  }\n  if (callback === undefined) {\n    callback = () => {};\n  }\n  if (outputFolder.charAt(outputFolder.length - 1) !== path.sep) {\n    outputFolder += path.sep;\n  }\n  title = title || '';\n  const bitrate = options.bitrate || '256k';\n\n  const progressEmitter = new EventEmitter();\n\n  const tempFile = (at3.tempFolder || outputFolder) + randomstring.generate(10) + '.mp3';\n\n  // Download and convert file\n  const dl = at3.downloadSingleURL(url, tempFile, bitrate);\n  const onDownload = (infos) => {\n    progressEmitter.emit('download', infos);\n  };\n  const onConvert = (infos) => {\n    progressEmitter.emit('convert', infos, infos);\n  };\n  dl.on('download', onDownload);\n  dl.once('download-end', () => {\n    dl.removeListener('download', onDownload);\n    progressEmitter.emit('download-end');\n  });\n  dl.on('convert', onConvert);\n  dl.once('error', (error) => {\n    dl.removeListener('download', onDownload);\n    dl.removeListener('convert', onConvert);\n    callback(null, 'error');\n    progressEmitter.emit('error', new Error(error));\n  });\n  progressEmitter.once('abort', () => {\n    dl.emit('abort');\n  });\n\n  let infosFromString,\n    infosFromFile,\n    infosRequests = [];\n\n  if (infos && infos.deezerId) {\n    // If deezer track id is provided, with fetch more information\n    let getMoreInfos = at3\n      .getDeezerTrackInfos(infos.deezerId, v)\n      .then((inf) => {\n        infosFromString = inf;\n      })\n      .catch(() => {\n        infosFromString = {\n          title: infos.title,\n          artistName: infos.artistName,\n        };\n      });\n\n    infosRequests.push(getMoreInfos);\n  } else if (infos && infos.spotifyId) {\n    // If spotify track id is provided, with fetch more information\n    let getMoreInfos = at3\n      .getSpotifyTrackInfos(infos.spotifyId, v)\n      .then((inf) => {\n        infosFromString = inf;\n      })\n      .catch(() => {\n        infosFromString = {\n          title: infos.title,\n          artistName: infos.artistName,\n        };\n      });\n    infosRequests.push(getMoreInfos);\n  } else {\n    // Try to find information based on video title\n    let getStringInfos = at3\n      .getCompleteInfosFromURL(url, v)\n      .then((inf) => {\n        if (title === undefined) {\n          title = inf.originalTitle;\n        }\n        infosFromString = inf;\n        progressEmitter.emit('infos', _.clone(infosFromString));\n      })\n      .catch(() => {\n        // The download must have failed to, and emit an error\n      });\n\n    infosRequests.push(getStringInfos);\n  }\n\n  // Try to find information based on MP3 file when dl is finished\n  dl.once('end', () => {\n    dl.removeListener('convert', onConvert);\n    progressEmitter.emit('convert-end');\n\n    if (!infos || (!infos.deezerId && !infos.spotifyId)) {\n      let getFileInfos = at3.getCompleteInfosFromFile(tempFile, v).then((inf) => {\n        infosFromFile = inf;\n        if (infosFromFile && infosFromFile.title && infosFromFile.artistName) {\n          progressEmitter.emit('infos', _.clone(infosFromFile));\n        }\n      });\n\n      infosRequests.push(getFileInfos);\n    }\n\n    // [TODO] Improve network issue resistance\n    Promise.all(infosRequests).then(() => {\n      // ça on peut garder\n      let infos = infosFromString;\n      if (infosFromFile) {\n        let scoreFromFile = Math.min(\n          levenshtein.get(simpleName(infosFromFile.title + ' ' + infosFromFile.artistName), simpleName(title)),\n          levenshtein.get(simpleName(infosFromFile.artistName + ' ' + infosFromFile.title), simpleName(title)),\n        );\n        let scoreFromString = Math.min(\n          levenshtein.get(simpleName(infosFromString.title + ' ' + infosFromString.artistName), simpleName(title)),\n          levenshtein.get(simpleName(infosFromString.artistName + ' ' + infosFromString.title), simpleName(title)),\n        );\n\n        if (v) {\n          console.log('Infos from file score: ', scoreFromFile);\n          console.log('Infos from string score: ', scoreFromString);\n        }\n\n        if (infosFromFile.cover && scoreFromFile < scoreFromString + Math.ceil(simpleName(title).length / 10.0)) {\n          infos = infosFromFile;\n        }\n      }\n\n      progressEmitter.emit('infos', _.clone(infos));\n\n      if (v) {\n        console.log('Final infos: ', infos);\n      }\n\n      at3\n        .findLyrics(infos.title, infos.artistName)\n        .then((lyrics) => {\n          return new Promise((resolve, reject) => {\n            fs.writeFile(tempFile + '.lyrics', lyrics, (error) => {\n              if (error) {\n                reject(error);\n              } else {\n                resolve();\n              }\n            });\n          });\n        })\n        .then(() => {\n          infos.lyrics = tempFile + '.lyrics';\n        })\n        .catch(() => {\n          // no lyrics\n        })\n        .finally(() => {\n          return at3.tagFile(tempFile, infos);\n        })\n        .then(() => {\n          let finalFile = outputFolder;\n          finalFile += at3.formatSongFilename(infos.title, infos.artistName, infos.position) + '.mp3';\n          fs.moveSync(tempFile, finalFile, { overwrite: true });\n          if (infos.lyrics) {\n            fs.unlinkSync(tempFile + '.lyrics');\n          }\n          const finalInfos = {\n            infos: infos,\n            file: finalFile,\n          };\n          progressEmitter.emit('end', finalInfos);\n          callback(finalInfos);\n        })\n        .catch((err) => {\n          progressEmitter.emit('error', err);\n        });\n    });\n  });\n\n  return progressEmitter;\n};\n\n/**\n * Search a query on YouTube and return the detailed results\n * @param query string\n * @param regionCode string ISO 3166-1 alpha-2 country code (ex: FR, US)\n * @param relevanceLanguage string ISO 639-1 two-letter language code (ex: en: fr)\n * @param v boolean Verbosity\n * @return Promise\n */\nat3.searchOnYoutube = (query, regionCode, relevanceLanguage, v) => {\n  if (v === undefined) {\n    v = false;\n  }\n\n  /**\n   * Remove useless information in the title\n   * like (audio only), (lyrics)...\n   * @param title string\n   * @return string\n   */\n  const improveTitle = (title) => {\n    let useless = [\n      'audio only',\n      'audio',\n      'paroles/lyrics',\n      'lyrics/paroles',\n      'with lyrics',\n      'w/lyrics',\n      'w / lyrics',\n      'avec paroles',\n      'avec les paroles',\n      'avec parole',\n      'lyrics',\n      'paroles',\n      'parole',\n      'radio edit.',\n      'radio edit',\n      'radio-edit',\n      'shazam version',\n      'shazam v...',\n      'music video',\n      'clip officiel',\n      'officiel',\n      'new song',\n      'official video',\n      'official',\n    ];\n\n    _.forEach(useless, (u) => {\n      title = title.replace(new RegExp('((\\\\(|\\\\[)?)( ?)' + u + '( ?)((\\\\)|\\\\])?)', 'gi'), '');\n    });\n\n    title = title.replace(new RegExp('(\\\\(|\\\\[)( ?)hd( ?)(\\\\)|\\\\])', 'gi'), '');\n    title = title.replace(new RegExp('hd', 'gi'), '');\n    title = _.trim(title);\n\n    return title;\n  };\n\n  // We simply search on YouTube\n  return ytsr(query, { limit: 20 }).then(({ items }) => {\n    const videos = items.filter((item) => item.type === 'video');\n\n    if (videos.length === 0) {\n      return Promise.reject();\n    }\n\n    return Promise.all(\n      videos.map(async (video) => {\n        const infos = await ytdl.getInfo(video.link);\n\n        let ratio = 1.0;\n        if (infos.dislikes > 0) {\n          ratio = infos.likes / infos.dislikes;\n        }\n        if (ratio === 0) {\n          ratio = 1;\n        }\n        const realLike = (infos.likes - infos.dislikes) * ratio;\n\n        return {\n          id: infos.video_id,\n          url: video.link,\n          title: improveTitle(infos.title),\n          hd: infos.formats.some(\n            ({ qualityLabel }) => qualityLabel && (qualityLabel.startsWith('720p') || qualityLabel.startsWith('1080p')),\n          ),\n          duration: parseInt(infos.length_seconds, 10),\n          views: video.views,\n          realLike,\n        };\n      }),\n    );\n  });\n};\n\n/**\n * @param song Object Searched song\n * @param videos Array List of videos\n * @param v boolean Verbosity\n */\nat3.findBestVideo = (song, videos, v) => {\n  if (v === undefined) {\n    v = false;\n  }\n\n  /**\n   * Returns the score of a video, comparing to the request\n   * @param song Object Searched song\n   * @param video object\n   * @param largestRealLike\n   * @param largestViews\n   * @return Object\n   */\n  const score = (song, video, largestRealLike, largestViews) => {\n    // weight of each argument\n    let weights = {\n      title: 30,\n      hd: 0.3,\n      duration: 20,\n      views: 10,\n      realLike: 15,\n    };\n\n    let duration = song.duration || video.duration;\n\n    // Score for title\n    let videoTitle = ' ' + _.lowerCase(video.title) + ' ';\n    let songTitle = ' ' + _.lowerCase(song.title) + ' '; // we add spaces to help longest-common-substring\n    let songArtist = ' ' + _.lowerCase(song.artistName) + ' '; // (example: the artist \"M\")\n\n    // for longest-common-substring, which works with arrays\n    let videoTitlea = videoTitle.split('');\n    let songTitlea = songTitle.split('');\n    let songArtista = songArtist.split('');\n\n    const videoSongTitle = lcs(videoTitlea, songTitlea);\n    if (\n      videoSongTitle.length > 0 &&\n      videoSongTitle.startString2 === 0 &&\n      videoTitle[videoSongTitle.startString1 + videoSongTitle.length - 1] === ' '\n    ) {\n      // The substring must start at the beginning of the song title, and the next char in the video title must be a space\n      videoTitle =\n        videoTitle.substring(0, videoSongTitle.startString1) +\n        ' ' +\n        videoTitle.substring(videoSongTitle.startString1 + videoSongTitle.length);\n      videoTitlea = videoTitle.split('');\n    }\n    const videoSongArtist = lcs(videoTitlea, songArtista);\n    if (\n      videoSongArtist.length > 0 &&\n      videoSongArtist.startString2 === 0 &&\n      videoTitle[videoSongArtist.startString1 + videoSongArtist.length - 1] === ' '\n    ) {\n      // The substring must start at the beginning of the song title, and the next char in the video title must be a space\n      videoTitle =\n        videoTitle.substring(0, videoSongArtist.startString1) +\n        videoTitle.substring(videoSongArtist.startString1 + videoSongArtist.length);\n    }\n\n    videoTitle = _.lowerCase(videoTitle);\n    const sTitle =\n      videoTitle.length + (songTitle.length - videoSongTitle.length) + (songArtist.length - videoSongArtist.length);\n\n    const videoScore = {\n      title: sTitle * weights.title,\n      hd: video.hd * weights.hd,\n      duration: Math.sqrt(Math.abs(video.duration - duration)) * weights.duration,\n      views: (video.views / largestViews) * weights.views,\n      realLike: (video.realLike / largestRealLike) * weights.realLike || -50, // video.realLike is NaN when the likes has been deactivated, which is a very bad sign\n    };\n    video.videoScore = videoScore;\n\n    let preVideoScore = videoScore.views + videoScore.realLike - videoScore.title - videoScore.duration;\n    preVideoScore = preVideoScore + Math.abs(preVideoScore) * videoScore.hd;\n\n    return preVideoScore;\n  };\n\n  const largestRealLike = _.reduce(\n    videos,\n    (v, r) => {\n      if (r.realLike > v) {\n        return r.realLike;\n      }\n      return v;\n    },\n    0,\n  );\n  const largestViews = _.reduce(\n    videos,\n    (v, r) => {\n      if (r.views > v) {\n        return r.views;\n      }\n      return v;\n    },\n    0,\n  );\n\n  _.forEach(videos, (r) => {\n    r.score = score(song, r, largestRealLike, largestViews);\n  });\n\n  return _.reverse(_.sortBy(videos, 'score'));\n};\n\n/**\n * Try to find the best video matching a song\n * @param song Object Searched song\n * @param v boolean Verbosity\n * @return Promise\n */\nat3.findVideoForSong = (song, v) => {\n  if (v === undefined) {\n    v = false;\n  }\n\n  let query = song.title + ' - ' + song.artistName;\n  return at3.searchOnYoutube(query, at3.regionCode, at3.relevanceLanguage, v).then((youtubeResults) => {\n    return at3.findBestVideo(song, youtubeResults, v);\n  });\n};\n\n// [TODO] we could also add a method that just take the first youtube video and download it\n/**\n * Try to find the best video matching a song request\n * @param query string\n * @param v boolean Verbosity\n * @return Promise\n */\nat3.findVideo = (query, v) => {\n  if (v === undefined) {\n    v = false;\n  }\n\n  // We try to find the song\n  return at3\n    .guessTrackFromString(query, true, false, v)\n    .then((guessStringInfos) => {\n      if (guessStringInfos.title && guessStringInfos.artistName) {\n        return at3.retrieveTrackInformations(guessStringInfos.title, guessStringInfos.artistName, true, v);\n      } else {\n        return Promise.reject({ error: 'No song corresponds to your query' });\n      }\n    })\n    .then((song) => {\n      return at3.findVideoForSong(song, v);\n    });\n};\n\n/**\n * Find a song from a query, then download the corresponding video,\n * convert and tag it\n * @param query string\n * @param outputFolder\n * @param callback Callback function\n * @param v boolean Verbosity\n * @return Event\n */\nat3.findAndDownload = (query, outputFolder, callback, v) => {\n  if (v === undefined) {\n    v = false;\n  }\n  const progressEmitter = new EventEmitter();\n\n  at3\n    .findVideo(query, v)\n    .then((results) => {\n      if (results.length === 0) {\n        progressEmitter.emit('error', new Error('Cannot find any video matching'));\n        return callback(null, 'Cannot find any video matching');\n      }\n      let i = 0;\n      progressEmitter.emit('search-end');\n      let dl = at3.downloadAndTagSingleURL(results[i].url, outputFolder, callback, query);\n\n      const onDownload = (infos) => {\n        progressEmitter.emit('download', infos);\n      };\n      const onConvert = (infos) => {\n        progressEmitter.emit('convert', infos);\n      };\n      const onInfos = (infos) => {\n        progressEmitter.emit('infos', infos);\n      };\n\n      dl.on('download', onDownload);\n      dl.once('download-end', () => {\n        dl.removeListener('download', onDownload);\n        progressEmitter.emit('download-end');\n      });\n      dl.on('convert', onConvert);\n      dl.once('convert-end', () => {\n        dl.removeListener('convert', onConvert);\n        progressEmitter.emit('convert-end');\n      });\n      dl.on('infos', onInfos);\n      dl.once('error', (error) => {\n        dl.removeListener('download', onDownload);\n        dl.removeListener('convert', onConvert);\n        dl.removeListener('infos', onInfos);\n        // [TODO]: try to download the next video, in case of ytdl error only\n        // if (i < results.length) {\n        //     dl = at3.downloadAndTagSingleURL(results[i++].url, outputFolder, callback, query);\n        // } else {\n        progressEmitter.emit('error', new Error(error));\n        // }\n      });\n      dl.once('end', () => {\n        dl.removeListener('infos', onInfos);\n      });\n    })\n    .catch(() => {\n      progressEmitter.emit('error', new Error('Cannot find any video matching'));\n      return callback(null, 'Cannot find any video matching');\n    });\n\n  return progressEmitter;\n};\n\n/**\n * Find videos for a track, and download it\n * @param track trackInfos\n * @param outputFolder\n * @param callback Callback function\n * @param v boolean Verbosity\n * @return Event\n */\nat3.downloadTrack = (track, outputFolder, callback, v) => {\n  if (v === undefined) {\n    v = false;\n  }\n  const progressEmitter = new EventEmitter();\n  let aborted = false;\n\n  at3\n    .findVideoForSong(track, v)\n    .then((results) => {\n      if (aborted) {\n        return;\n      }\n      if (results.length === 0) {\n        progressEmitter.emit('error', new Error('Cannot find any video matching'));\n        return callback(null, 'Cannot find any video matching');\n      }\n      let i = 0;\n      progressEmitter.emit('search-end');\n      const dlNext = () => {\n        if (i >= results.length) {\n          progressEmitter.emit('error', new Error('Cannot find any video matching'));\n          return;\n        }\n        if (v) {\n          console.log('Will be downloaded:', results[i].url);\n        }\n        let aborted = false;\n        let dl = at3.downloadAndTagSingleURL(results[i].url, outputFolder, callback, '', v, track);\n        const onDownload = (infos) => {\n          progressEmitter.emit('download', infos);\n        };\n        const onConvert = (infos) => {\n          progressEmitter.emit('convert', infos);\n        };\n        const onInfos = (infos) => {\n          progressEmitter.emit('infos', infos);\n        };\n        dl.on('download', onDownload);\n        dl.once('download-end', () => {\n          dl.removeListener('download', onDownload);\n          progressEmitter.emit('download-end');\n        });\n        dl.on('convert', onConvert);\n        dl.once('convert-end', () => {\n          dl.removeListener('convert', onConvert);\n          progressEmitter.emit('convert-end');\n        });\n        dl.on('infos', onInfos);\n        dl.once('end', (finalInfos) => {\n          dl.removeListener('infos', onInfos);\n          progressEmitter.emit('end', finalInfos);\n        });\n        dl.once('error', (_error) => {\n          dl.removeListener('download', onDownload);\n          dl.removeListener('convert', onConvert);\n          dl.removeListener('infos', onInfos);\n          i += 1;\n          aborted = true;\n          dlNext();\n        });\n        progressEmitter.once('abort', () => {\n          if (!aborted) {\n            dl.emit('abort');\n          }\n        });\n      };\n      dlNext();\n    })\n    .catch(() => {\n      progressEmitter.emit('error', new Error('Cannot find any video matching'));\n      return callback(null, 'Cannot find any video matching');\n    });\n\n  progressEmitter.on('abort', () => {\n    aborted = true;\n  });\n\n  return progressEmitter;\n};\n\n/**\n * Return URLs contained in a playlist (YouTube or SoundCloud)\n * @param url\n * @return Promise(object)\n */\nat3.getPlaylistURLsInfos = (url) => {\n  let type = at3.guessURLType(url);\n\n  if (type === 'youtube') {\n    let playlistId = url.match(/list=([0-9a-zA-Z_-]+)/);\n    playlistId = playlistId[1];\n    return ytpl(playlistId).then((playlist) => {\n      return {\n        title: playlist.title,\n        cover: playlist.author.avatar,\n        artistName: playlist.author.name,\n        items: playlist.items.map((item) => {\n          return {\n            url: item.url_simple,\n            title: item.title,\n            cover: item.thumbnail,\n          };\n        }),\n      };\n    });\n  } else if (type === 'soundcloud') {\n    return request({\n      url: 'http://api.soundcloud.com/resolve?client_id=' + API_SOUNDCLOUD + '&url=' + url,\n      json: true,\n    }).then((playlistDetails) => {\n      let playlistInfos = {\n        title: playlistDetails.title,\n        artistName: playlistDetails.user.username,\n        cover: playlistDetails.artwork_url,\n      };\n      let items = [];\n\n      _.forEach(playlistDetails.tracks, (track) => {\n        items.push({\n          url: track.permalink_url,\n          title: track.title,\n          cover: track.artwork_url,\n          artistName: track.user.username,\n        });\n      });\n\n      playlistInfos.items = items;\n\n      return playlistInfos;\n    });\n  }\n};\n\n/**\n * Returns info (title, cover, songs) about a playlist (Deezer or Spotify)\n * @param url\n * @return Promise(object)\n */\nat3.getPlaylistTitlesInfos = (url) => {\n  // Deezer Playlist\n  // Deezer Album\n  // Deezer Loved Tracks [TODO]\n  // Spotify playlist\n  // Spotify Album\n  const type = at3.guessURLType(url);\n\n  const regDeezerPlaylist = /playlist\\/([0-9]+)/;\n  const regDeezerAlbum = /album\\/([0-9]+)/;\n\n  const regSpotifyPlaylist = /playlist\\/([0-9a-zA-Z]+)/;\n  const regSpotifyAlbum = /album\\/([0-9a-zA-Z]+)/;\n\n  if (type === 'deezer') {\n    // Deezer Playlist\n    if (regDeezerPlaylist.test(url)) {\n      const playlistId = url.match(regDeezerPlaylist)[1];\n\n      return request({\n        url: 'https://api.deezer.com/playlist/' + playlistId,\n        json: true,\n      }).then((playlistDetails) => {\n        const playlist = {};\n        const items = [];\n\n        playlist.title = playlistDetails.title;\n        playlist.artistName = playlistDetails.creator.name;\n        playlist.cover = playlistDetails.picture_big;\n\n        _.forEach(playlistDetails.tracks.data, (track) => {\n          items.push({\n            title: track.title,\n            artistName: track.artist.name,\n            deezerId: track.id,\n            album: track.album.title,\n            cover: track.album.cover,\n          });\n        });\n\n        playlist.items = items;\n\n        return playlist;\n      });\n    } else if (regDeezerAlbum.test(url)) {\n      // Deezer Album\n      let albumId = url.match(regDeezerAlbum)[1];\n      let albumInfos = {};\n\n      return request({\n        url: 'https://api.deezer.com/album/' + albumId,\n        json: true,\n      })\n        .then((ralbumInfos) => {\n          albumInfos.cover = ralbumInfos.cover_big;\n          albumInfos.title = ralbumInfos.title;\n          albumInfos.artistName = ralbumInfos.artist.name;\n\n          return request({\n            url: 'https://api.deezer.com/album/' + albumId + '/tracks',\n            json: true,\n          });\n        })\n        .then((albumTracks) => {\n          let items = [];\n\n          _.forEach(albumTracks.data, (track) => {\n            items.push({\n              title: track.title,\n              artistName: track.artist.name,\n              deezerId: track.id,\n              album: albumInfos.title,\n              cover: albumInfos.cover,\n              duration: track.duration,\n            });\n          });\n\n          albumInfos.items = items;\n\n          return albumInfos;\n        });\n    }\n  } else if (type === 'spotify') {\n    // Spotify Playlist\n    if (regSpotifyPlaylist.test(url)) {\n      const playlistId = url.match(regSpotifyPlaylist)[1];\n\n      return at3.requestSpotify('https://api.spotify.com/v1/playlists/' + playlistId).then((playlistDetails) => {\n        const playlist = {};\n        const items = [];\n\n        playlist.title = playlistDetails.name;\n        playlist.artistName = playlistDetails.owner.id;\n        playlist.cover = playlistDetails.images[0].url;\n\n        playlist.items = items;\n\n        const processSpotifyPage = (page) => {\n          page.items.forEach((t) => {\n            let track = t.track;\n            items.push({\n              title: track.name,\n              artistName: track.artists[0].name,\n              spotifyId: track.id,\n              album: track.album.name,\n              cover: track.album.images[0] ? track.album.images[0].url : undefined,\n              duration: Math.ceil(track.duration_ms / 1000),\n            });\n          });\n\n          if (page.next) {\n            return at3.requestSpotify(page.next).then(processSpotifyPage);\n          } else {\n            return playlist;\n          }\n        };\n\n        return processSpotifyPage(playlistDetails.tracks);\n      });\n    } else if (regSpotifyAlbum.test(url)) {\n      // Spotify Album\n      let albumId = url.match(regSpotifyAlbum)[1];\n      let albumInfos = {};\n\n      return at3.requestSpotify('https://api.spotify.com/v1/albums/' + albumId).then((ralbumInfos) => {\n        albumInfos.title = ralbumInfos.name;\n        albumInfos.artistName = ralbumInfos.artists[0].name;\n        albumInfos.cover = ralbumInfos.images[0].url;\n\n        let items = [];\n\n        ralbumInfos.tracks.items.forEach((track) => {\n          items.push({\n            title: track.name,\n            artistName: track.artists[0].name,\n            spotifyId: track.id,\n            album: albumInfos.title,\n            cover: albumInfos.cover,\n            duration: Math.ceil(track.duration_ms / 1000),\n          });\n        });\n\n        albumInfos.items = items;\n\n        return albumInfos;\n      });\n    }\n  }\n};\n\n/**\n * Download a playlist containing URLs\n * @param url {string}\n * @param outputFolder {string}\n * @param callback {Function}\n * @param maxSimultaneous {number} Maximum number of simultaneous track processing\n * @param subPathFormat {string} The format of the subfolder: {artist}/{title}/\n * @return {Event}\n */\nat3.downloadPlaylistWithURLs = (url, outputFolder, callback, maxSimultaneous, subPathFormat) => {\n  if (maxSimultaneous === undefined) {\n    maxSimultaneous = 1;\n  }\n  if (subPathFormat === undefined) {\n    subPathFormat = '';\n  }\n\n  const emitter = new EventEmitter();\n  let running = 0;\n  let lastIndex = 0;\n  let aborted = false;\n\n  at3.getPlaylistURLsInfos(url).then((playlistInfos) => {\n    if (aborted) {\n      return;\n    }\n\n    outputFolder = at3.createSubPath(outputFolder, subPathFormat, playlistInfos.title, playlistInfos.artistName);\n\n    emitter.emit('playlist-infos', playlistInfos);\n\n    for (let i = 0; i < maxSimultaneous; i += 1) {\n      downloadNext(playlistInfos.items, i);\n    }\n  });\n\n  const downloadNext = (urls, currentIndex) => {\n    if (aborted) {\n      return;\n    }\n    if (urls.length === currentIndex) {\n      if (running === 0) {\n        emitter.emit('end');\n        callback(urls);\n      }\n      return;\n    }\n    running += 1;\n    if (currentIndex > lastIndex) {\n      lastIndex = currentIndex;\n    }\n\n    const currentUrl = urls[currentIndex];\n\n    currentUrl.progress = {};\n\n    emitter.emit('begin-url', currentIndex);\n\n    const dl = at3.downloadAndTagSingleURL(currentUrl.url, outputFolder, (infos, _error) => {\n      if (infos) {\n        currentUrl.file = infos.file;\n        currentUrl.infos = infos.infos;\n      }\n      running -= 1;\n\n      emitter.emit('end-url', currentIndex);\n\n      if (running < maxSimultaneous) {\n        downloadNext(urls, lastIndex + 1);\n      }\n    });\n\n    emitter.once('abort', () => {\n      aborted = true;\n      dl.emit('abort');\n    });\n\n    const onDownload = (infos) => {\n      currentUrl.progress.download = infos;\n      emitter.emit('download', currentIndex);\n    };\n    const onConvert = (infos) => {\n      currentUrl.progress.convert = infos;\n      emitter.emit('convert', currentIndex);\n    };\n    const onInfos = (infos) => {\n      currentUrl.infos = infos;\n      emitter.emit('infos', currentIndex);\n    };\n\n    dl.on('download', onDownload);\n    dl.once('download-end', () => {\n      dl.removeListener('download', onDownload);\n      emitter.emit('download-end', currentIndex);\n      if (running < maxSimultaneous) {\n        downloadNext(urls, lastIndex + 1);\n      }\n    });\n    dl.on('convert', onConvert);\n    dl.once('convert-end', () => {\n      dl.removeListener('convert', onConvert);\n      emitter.emit('convert-end', currentIndex);\n    });\n    dl.on('infos', onInfos);\n    dl.once('error', () => {\n      dl.removeListener('download', onDownload);\n      dl.removeListener('convert', onConvert);\n      dl.removeListener('infos', onInfos);\n      emitter.emit('error', new Error(currentIndex));\n      if (running < maxSimultaneous) {\n        downloadNext(urls, lastIndex + 1);\n      }\n    });\n    dl.once('end', () => {\n      dl.removeListener('infos', onInfos);\n    });\n  };\n\n  emitter.once('abort', () => {\n    aborted = true;\n  });\n\n  return emitter;\n};\n\n/**\n * Download a playlist containing titles\n * @param url {string}\n * @param outputFolder {string}\n * @param callback {Function}\n * @param maxSimultaneous {number} Maximum number of simultaneous track processing\n * @param subPathFormat {string} The format of the subfolder: {artist}/{title}/\n * @return {Event}\n */\nat3.downloadPlaylistWithTitles = (url, outputFolder, callback, maxSimultaneous, subPathFormat) => {\n  if (maxSimultaneous === undefined) {\n    maxSimultaneous = 1;\n  }\n  if (subPathFormat === undefined) {\n    subPathFormat = '';\n  }\n\n  const emitter = new EventEmitter();\n  let running = 0;\n  let lastIndex = 0;\n  let aborted = false;\n\n  at3.getPlaylistTitlesInfos(url).then((playlistInfos) => {\n    if (aborted) {\n      return;\n    }\n\n    outputFolder = at3.createSubPath(outputFolder, subPathFormat, playlistInfos.title, playlistInfos.artistName);\n\n    emitter.emit('playlist-infos', playlistInfos);\n\n    for (let i = 0; i < maxSimultaneous; i += 1) {\n      downloadNext(playlistInfos.items, i);\n    }\n  });\n\n  const downloadNext = (urls, currentIndex) => {\n    if (aborted) {\n      return;\n    }\n    if (urls.length === currentIndex) {\n      if (running === 0) {\n        emitter.emit('end');\n        callback(urls);\n      }\n      return;\n    }\n    running += 1;\n    if (currentIndex > lastIndex) {\n      lastIndex = currentIndex;\n    }\n\n    let currentTrack = urls[currentIndex];\n\n    currentTrack.progress = {};\n\n    emitter.emit('begin-url', currentIndex);\n\n    at3\n      .findVideoForSong(currentTrack)\n      .then((videos) => {\n        if (aborted) {\n          return;\n        }\n        emitter.emit('search-end', currentIndex);\n\n        const downloadFinished = (infos, error) => {\n          if (!infos || error) {\n            return;\n          }\n          currentTrack.file = infos.file;\n          currentTrack.infos = infos.infos;\n          running -= 1;\n\n          emitter.emit('end-url', currentIndex);\n\n          if (running < maxSimultaneous) {\n            downloadNext(urls, lastIndex + 1);\n          }\n        };\n\n        let i = 0;\n\n        const handleDl = (dl) => {\n          const onDownload = (infos) => {\n            currentTrack.progress.download = infos;\n            emitter.emit('download', currentIndex);\n          };\n          const onConvert = (infos) => {\n            currentTrack.progress.convert = infos;\n            emitter.emit('convert', currentIndex);\n          };\n          const onInfos = (infos) => {\n            currentTrack.infos = infos;\n            emitter.emit('infos', currentIndex);\n          };\n\n          dl.on('download', onDownload);\n          dl.once('download-end', () => {\n            dl.removeListener('download', onDownload);\n            emitter.emit('download-end', currentIndex);\n            if (running < maxSimultaneous) {\n              downloadNext(urls, lastIndex + 1);\n            }\n          });\n          dl.on('convert', onConvert);\n          dl.once('convert-end', () => {\n            dl.removeListener('convert', onConvert);\n            emitter.emit('convert-end', currentIndex);\n          });\n          dl.on('infos', onInfos);\n          dl.once('end', () => {\n            dl.removeListener('infos', onInfos);\n          });\n          dl.once('error', () => {\n            dl.removeListener('download', onDownload);\n            dl.removeListener('convert', onConvert);\n            if (i < videos.length - 1) {\n              i += 1;\n              handleDl(\n                at3.downloadAndTagSingleURL(\n                  videos[i].url,\n                  outputFolder,\n                  downloadFinished,\n                  undefined,\n                  false,\n                  currentTrack,\n                ),\n              );\n            } else {\n              emitter.emit('error', new Error(currentIndex));\n              if (running < maxSimultaneous) {\n                downloadNext(urls, lastIndex + 1);\n              }\n            }\n          });\n          emitter.once('abort', () => {\n            aborted = true;\n            dl.emit('abort');\n          });\n        };\n\n        handleDl(\n          at3.downloadAndTagSingleURL(videos[i].url, outputFolder, downloadFinished, undefined, false, currentTrack),\n        );\n      })\n      .catch(() => {\n        emitter.emit('error', new Error(currentIndex));\n        if (running < maxSimultaneous) {\n          downloadNext(urls, lastIndex + 1);\n        }\n      });\n  };\n\n  emitter.once('abort', () => {\n    aborted = true;\n  });\n\n  return emitter;\n};\n\n/**\n * Download a playlist containing urls or titles\n * @param url {string}\n * @param outputFolder {string}\n * @param callback {Function}\n * @param maxSimultaneous {number} Maximum number of simultaneous track processing\n * @return {Event}\n */\nat3.downloadPlaylist = (url, outputFolder, callback, maxSimultaneous, subPathFormat) => {\n  const type = at3.guessURLType(url);\n  const sitesTitles = ['deezer', 'spotify'];\n  const sitesURLs = ['youtube', 'soundcloud'];\n\n  if (sitesTitles.indexOf(type) >= 0) {\n    return at3.downloadPlaylistWithTitles(url, outputFolder, callback, maxSimultaneous, subPathFormat);\n  } else if (sitesURLs.indexOf(type) >= 0) {\n    return at3.downloadPlaylistWithURLs(url, outputFolder, callback, maxSimultaneous, subPathFormat);\n  } else {\n    callback(null, 'Website not supported yet');\n    return new EventEmitter().emit('error', new Error('Website not supported yet'));\n  }\n};\n\n/**\n * Download a track from an URL\n * @param url\n * @param outputFolder\n * @param callback\n * @param v boolean Verbose\n * @return Event\n */\nat3.downloadTrackURL = (url, outputFolder, callback, v) => {\n  if (v === undefined) {\n    v = false;\n  }\n  const type = at3.guessURLType(url);\n  const emitter = new EventEmitter();\n\n  if (type === 'spotify') {\n    const trackId = url.match(/\\/track\\/([0-9a-zA-Z]+)/)[1];\n    at3.requestSpotify('https://api.spotify.com/v1/tracks/' + trackId).then((trackInfos) => {\n      const track = {\n        title: trackInfos.name,\n        artistName: trackInfos.artists[0].name,\n        duration: Math.ceil(trackInfos.duration_ms / 1000),\n        spotifyId: trackId,\n        cover: trackInfos.album.images[0].url,\n      };\n      const e = at3.downloadTrack(track, outputFolder, callback, v);\n\n      at3.forwardEvents(e, emitter);\n    });\n  } else if (type === 'deezer') {\n    const trackId = url.match(/\\/track\\/([0-9]+)/)[1];\n    at3.getDeezerTrackInfos(trackId, v).then((trackInfos) => {\n      const e = at3.downloadTrack(trackInfos, outputFolder, callback, v);\n\n      at3.forwardEvents(e, emitter);\n    });\n  }\n\n  return emitter;\n};\n\n/**\n * Forward any classical event from e1 to e2, and abort from e2 to e1\n * @param e1 Event The source\n * @param e2 Event the destination\n * @return e2\n */\nat3.forwardEvents = (e1, e2) => {\n  const events = [\n    'download',\n    'download-end',\n    'convert',\n    'convert-end',\n    'infos',\n    'error',\n    'playlist-infos',\n    'begin-url',\n    'end-url',\n    'end',\n    'search-end',\n  ];\n  events.forEach((e) => {\n    e1.on(e, (data) => {\n      e2.emit(e, data);\n    });\n  });\n  e2.once('abort', () => {\n    e1.emit('abort');\n  });\n  return e2;\n};\n\n/**\n * Return the suggested songs for the query\n * @param query string\n * @param limit number\n * @return Promise<array<trackInfos>> Array of potential songs\n */\nat3.suggestedSongs = (query, limit) => {\n  if (!limit) {\n    limit = 5;\n  }\n\n  return request({\n    uri: 'https://api.deezer.com/search?limit=' + limit + '&q=' + encodeURIComponent(query),\n    json: true,\n  }).then((results) => {\n    return _.map(results.data, (r) => {\n      return {\n        title: r.title,\n        artistName: r.artist.name,\n        duration: r.duration,\n        cover: r.album.cover_medium,\n        deezerId: r.id,\n      };\n    });\n  });\n};\n\n/**\n * Return the suggested albums for the query\n * @param query string\n * @param limit number\n * @return Promise<array<Object>> Array of potential albums\n */\nat3.suggestedAlbums = (query, limit) => {\n  if (!limit) {\n    limit = 5;\n  }\n\n  return request({\n    uri: 'https://api.deezer.com/search/album?limit=' + limit + '&q=' + encodeURIComponent(query),\n    json: true,\n  }).then((results) => {\n    return _.map(results.data, (r) => {\n      return {\n        title: r.title,\n        artistName: r.artist.name,\n        cover: r.cover_medium,\n        deezerId: r.id,\n        link: r.link,\n        nbTracks: r.nb_tracks,\n      };\n    });\n  });\n};\n\n/**\n * Return the type of the query\n * @param query string\n * @return string: text, single-url, playlist-url, track-url, not-supported\n */\nat3.typeOfQuery = (query) => {\n  if (!at3.isURL(query)) {\n    return 'text';\n  }\n  const type = at3.guessURLType(query);\n  if (!type) {\n    return 'not-supported';\n  }\n\n  if (type === 'youtube' && /list=([0-9a-zA-Z_-]+)/.test(query)) {\n    return 'playlist-url';\n  } else if (type === 'deezer') {\n    if (/\\/(playlist|album)\\//.test(query)) {\n      return 'playlist-url';\n    } else if (/\\/track\\//.test(query)) {\n      return 'track-url';\n    }\n    return 'not-supported';\n  } else if (type === 'soundcloud' && /\\/sets\\//.test(query)) {\n    return 'playlist-url';\n  } else if (type === 'spotify') {\n    if (/\\/(playlist|album)\\//.test(query)) {\n      return 'playlist-url';\n    } else if (/\\/track\\//.test(query)) {\n      return 'track-url';\n    }\n    return 'not-supported';\n  }\n\n  return 'single-url';\n};\n\n/**\n * Return URL type\n * @param url\n * @return string\n */\nat3.guessURLType = (url) => {\n  if (/^(https?:\\/\\/)?((www|m)\\.)?((youtube\\.([a-z]{2,4}))|(youtu\\.be))/.test(url)) {\n    return 'youtube';\n  } else if (/^(https?:\\/\\/)?(((www)|(m))\\.)?(soundcloud\\.([a-z]{2,4}))/.test(url)) {\n    return 'soundcloud';\n  } else if (/^(https?:\\/\\/)?(www\\.)?(deezer\\.([a-z]{2,4}))\\//.test(url)) {\n    return 'deezer';\n  } else if (/^(https?:\\/\\/)?((open|play)\\.)?spotify\\.([a-z]{2,4})/.test(url)) {\n    return 'spotify';\n  }\n};\n\nconst imatch = (textSearched, text) => {\n  // [TODO] Improve this function (use .test and espace special caracters + use it everywhere else)\n  return text.match(new RegExp(textSearched, 'gi'));\n};\nconst vsimpleName = (text, exact) => {\n  if (exact === undefined) {\n    exact = false;\n  }\n  text = text.toLowerCase();\n  if (!exact) {\n    // text = text.replace('feat', '');\n  }\n  text = text.replace(/((\\[)|(\\())?radio edit((\\])|(\\)))?/gi, '');\n  text = text.replace(/[^a-zA-Z0-9]/gi, '');\n  return text;\n};\nconst delArtist = (artist, text, exact) => {\n  if (exact === undefined) {\n    exact = false;\n  }\n  if (vsimpleName(artist).length <= 2) {\n    // Artist with a very short name (Mathieu Chedid - M)\n    return vsimpleName(text, exact);\n  } else {\n    // [TODO] Improve, escape regex special caracters in vsimpleName(artist)\n    return vsimpleName(text, exact).replace(new RegExp(vsimpleName(artist), 'ig'), '');\n  }\n};\nconst simpleName = (text) => {\n  return text.replace(/\\(.+\\)/g, '');\n};\n\nmodule.exports = at3;\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"alltomp3\",\n  \"version\": \"0.4.5\",\n  \"description\": \"Download and convert in MP3 with tags online videos\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"mocha\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/AllToMP3/alltomp3.git\"\n  },\n  \"keywords\": [\n    \"youtube\",\n    \"mp3\",\n    \"vimeo\",\n    \"convert\",\n    \"lyrics\",\n    \"deezer\",\n    \"itunes\",\n    \"tags\",\n    \"music\",\n    \"video\"\n  ],\n  \"author\": \"Basile Bruneau <basilebruneau@gmail.com>\",\n  \"license\": \"AGPL-3.0\",\n  \"bugs\": {\n    \"url\": \"https://github.com/AllToMP3/alltomp3/issues\"\n  },\n  \"homepage\": \"https://github.com/AllToMP3/alltomp3#readme\",\n  \"dependencies\": {\n    \"acoustid\": \"^1.2.1\",\n    \"bluebird\": \"^3.5.2\",\n    \"chai\": \"^3.5.0\",\n    \"cheerio\": \"^0.20.0\",\n    \"eyed3\": \"git+https://github.com/AllToMP3/node-eyed3.git#b545986\",\n    \"fast-levenshtein\": \"^1.1.3\",\n    \"fluent-ffmpeg\": \"git+https://github.com/fluent-ffmpeg/node-fluent-ffmpeg.git#21f701430f98ae4fd53e12881e4328f1c165b45d\",\n    \"fs-extra\": \"^2.1.2\",\n    \"lodash\": \"^4.17.10\",\n    \"longest-common-substring\": \"^0.0.1\",\n    \"randomstring\": \"^1.1.5\",\n    \"request\": \"^2.88.0\",\n    \"request-promise\": \"^2.0.1\",\n    \"sharp\": \"^0.20.8\",\n    \"smartcrop-sharp\": \"git+https://github.com/AllToMP3/smartcrop-sharp.git#9d65314\",\n    \"ytdl-core\": \"latest\",\n    \"ytpl\": \"^1.0.1\",\n    \"ytsr\": \"^1.0.4\"\n  },\n  \"devDependencies\": {\n    \"prettier\": \"^2.0.5\"\n  }\n}\n"
  },
  {
    "path": "test/findLyrics.js",
    "content": "const expect = require('chai').expect;\nconst alltomp3 = require('..');\nconst _ = require('lodash');\n\n/**\n * Lyrics uses 5 or 6 different websites,\n * and the first to answer is the one chosen.\n * So it is absolutely non determinist, and\n * these tests are repeated 5 times.\n * Moreover lyrics varies depending on the website,\n * and can sometimes be wrong...\n*/\n\ndescribe('findLyrics', () => {\n\n  for (let i = 0; i < 5; i += 1) {\n    it('should find lyrics for Imagine Dragons - On Top of the World', (done) => {\n      alltomp3.findLyrics('On Top of the World', 'Imagine Dragons').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/^if-you-love-somebody-better-tell-them-while-theyre-here/);\n        expect(lyrics).to.match(/(when-you-hit-the-ground-get-up-now-get-up-get-up-now)|(i-can-been-dreaming-of-this-since-a-child-im-on-top-of-the-world)$/);\n        done();\n      });\n    });\n    it('should find lyrics for Pauline Croze - T\\'es Beau', (done) => {\n      alltomp3.findLyrics('T\\'es beau', 'Pauline Croze').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/tes-beau-parce-que-tes-courageux-de-regarder-dans-le-fond-des-yeux-celui-qui-te-defie-detre-heureux/);\n        expect(lyrics).to.match(/jai-peur-doublier-jai-peur-daccepter-jai-peur-des-vivants-a-present-tes-beau$/);\n        done();\n      });\n    });\n    it('should find lyrics for M - Mama Sam', (done) => {\n      alltomp3.findLyrics('Mama Sam', 'M').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/^quand-je-te-revois-mama-sam-je-retrouve-les-vraies-valeurs/);\n        expect(lyrics).to.match(/non-je-ne-connais-pas-l-afrique-aigrie-est-ma-couleur-de-peau-la-vie-est-une-machine-a-fric-ou-les-affreux-non(t?)-pas-dafro$/);\n        done();\n      });\n    });\n    it('should find lyrics for Coldplay - Viva la Vida', (done) => {\n      alltomp3.findLyrics('Viva la Vida', 'Coldplay').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/^i-used-to-rule-the-world-seas-would-rise-when-i-gave-the-word/);\n        expect(lyrics).to.match(/for-some-reason-i-cant-explain-i-know-saint-peter-wont-call-my-name-never-an-honest-word-but-that-was-when-i-ruled-the-world/);\n        done();\n      });\n    });\n    it('should find lyrics for HYPHEN HYPHEN - Cause I Got A Chance', (done) => {\n      alltomp3.findLyrics('Cause I Got A Chance', 'HYPHEN HYPHEN').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/^tonight-i-dont-wanna-cry-tonight-i-want-you-to-dance-with-me-tonight/);\n        expect(lyrics).to.match(/ive-been-waiting-for-so-long-knew-you-always-thought-about-always-thought-about-me$/);\n        done();\n      });\n    });\n    it('should find lyrics for Calvin Harris - The Rain', (done) => {\n      alltomp3.findLyrics('The Rain', 'Calvin Harris').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/^shes-the-type-of-girl-that-makes-you-feel-better/);\n        expect(lyrics).to.match(/these-are-the-good-times-in-your-life-so-put-on-a-smile-and-itll-be-((alright)|(all-right))/);\n        done();\n      });\n    });\n    it('should find lyrics for Sam Smith - Writing\\'s on the Wall', (done) => {\n      alltomp3.findLyrics('Writing\\'s on the Wall', 'Sam Smith').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/^ive-been-here-before-but-always-hit-the-floor-ive-spent-a-lifetime-running-and-i-always-get-away/);\n        expect(lyrics).to.match(/where-i-give-it-all-up-for-you-i-have-to-risk-it-all-cause-the-writings-on-the-wall$/);\n        done();\n      });\n    });\n    it('should find lyrics for C2C - Down The Road', (done) => {\n      alltomp3.findLyrics('Down The Road', 'C2C').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/have-no-place-to-go-have-no-place-to-go-darling/);\n        expect(lyrics).to.match(/when-that-train-rolls-up-and-i-come-walking-out/);\n        done();\n      });\n    });\n    it('should find lyrics for Galantis - Runaway (U & I)', (done) => {\n      alltomp3.findLyrics('Runaway (U & I)', 'Galantis').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/think-i-can-fly-think-i-can-fly-when-im-with-u/);\n        expect(lyrics).to.match(/i-know-that-im-rich-enough-for-pride-i-see-a-billion-dollars-in-your-eyes-even-if-were-strangers/);\n        done();\n      });\n    });\n    it('should find lyrics for Mika - Elle me dit', (done) => {\n      alltomp3.findLyrics('Elle me dit', 'Mika').then((lyrics) => {\n        lyrics = _.kebabCase(lyrics);\n\n        expect(lyrics).to.match(/elle-me-dit-ecris-une-chanson-contente-pas-une-chanson-deprimante-une-chanson-que-tout-l((e-)?)monde-aime/);\n        expect(lyrics).to.match(/pourquoi-tu-gaches-ta-vie-pourquoi-tu-gaches-ta-vie/);\n        expect(lyrics).to.match(/regarde-un-peu-tes-amis-quest-c((e-)?)quils-vont-faire-de-leur-vie/);\n        done();\n      });\n    });\n  }\n});\n"
  },
  {
    "path": "test/findVideo.js",
    "content": "const expect = require('chai').expect;\nconst alltomp3 = require('..');\nconst _ = require('lodash');\n\nfunction testTracks(tracks, artistName) {\n  let queries = [];\n  _.forEach(tracks, t => {\n    t.song.artistName = artistName;\n    let q = alltomp3.findVideoForSong(t.song).then(v => {\n      if (t.videos.indexOf(v[0].url) === -1) {\n        console.log(t.song.title, v);\n      }\n      expect(t.videos).to.include(v[0].url);\n    });\n    queries.push(q);\n  });\n\n  return Promise.all(queries);\n}\n\ndescribe('findVideo', function() {\n  it('should find YouTube videos for Broken Back by Broken Back', function () {\n    this.timeout(20000);\n    let artistName = \"Broken Back\";\n    let tracks = [\n      {\n        song: {\n          title: \"Excuses\",\n          duration: 224\n        },\n        videos: ['https://www.youtube.com/watch?v=aBp7s6BpmrM', 'https://www.youtube.com/watch?v=Ogsfvvwu-wU', 'https://www.youtube.com/watch?v=upUWTD6x3dw']\n      },\n      {\n        song: {\n          title: \"Halcyon Birds (Radio Edit)\",\n          duration: 197\n        },\n        videos: ['https://www.youtube.com/watch?v=xWlXEGIol9E', 'https://www.youtube.com/watch?v=EGSqjTixIyk', 'https://www.youtube.com/watch?v=gzZ43IEJ8S0', 'https://www.youtube.com/watch?v=2Ggu0m0a8WA', 'https://www.youtube.com/watch?v=5eS1WxW4GM4']\n      },\n      {\n        song: {\n          title: \"Better Run\",\n          duration: 176\n        },\n        videos: ['https://www.youtube.com/watch?v=oEugd8BV_Bs', 'https://www.youtube.com/watch?v=5QP8K42-wA8'],\n      },\n      {\n        song: {\n          title: \"Happiest Man on Earth (Radio Edit)\",\n          duration: 183\n        },\n        videos: ['https://www.youtube.com/watch?v=j01T8N7wVK0', 'https://www.youtube.com/watch?v=TqpM_0_H6Qc'],\n      },\n      {\n        song: {\n          title: \"Got to Go\",\n          duration: 218\n        },\n        videos: ['https://www.youtube.com/watch?v=A2iBEZBxT3s', 'https://www.youtube.com/watch?v=MXABmCs5Fkc']\n      },\n      // This last one is currently too hard\n      // {\n      //     title: \"Young Souls (Album Edit) - Broken Back\",\n      //     videos: ['https://www.youtube.com/watch?v=LT9kwbunzWc']\n      // }\n    ];\n\n    return testTracks(tracks, artistName);\n  });\n\n  it('should find YouTube videos for Night Visions by Imagine Dragons', function () {\n    this.timeout(20000);\n    let artistName = \"Imagine Dragons\";\n\n    let tracks = [\n      {\n        \"song\": {\n          \"title\": \"Radioactive\",\n          \"duration\": 186\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=ktvTqknDobU', 'https://www.youtube.com/watch?v=iO_WxYC34eM', 'https://www.youtube.com/watch?v=Thbsg9i2mZ0', 'https://www.youtube.com/watch?v=y_8Mgn30xRU']\n      },\n      {\n        \"song\": {\n          \"title\": \"Tiptoe\",\n          \"duration\": 194\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=ajjj4pLnjz8', 'https://www.youtube.com/watch?v=UB96k1arlTk', 'https://www.youtube.com/watch?v=211bk6ctXM4', 'https://www.youtube.com/watch?v=zmKv2Aok1Mw']\n      },\n      {\n        \"song\": {\n          \"title\": \"It's Time\",\n          \"duration\": 240\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=sENM2wA_FTg', 'https://www.youtube.com/watch?v=IOatp-OCw3E', 'https://www.youtube.com/watch?v=qFqMy0ewYFQ']\n      },\n      {\n        \"song\": {\n          \"title\": \"Demons\",\n          \"duration\": 177\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=mWRsgZuwf_8', 'https://www.youtube.com/watch?v=GFQYaoiIFh8', 'https://www.youtube.com/watch?v=LqI78S14Wgg', 'https://www.youtube.com/watch?v=lxUXvOUKM_Q']\n      },\n      {\n        \"song\": {\n          \"title\": \"On Top Of The World\",\n          \"duration\": 192\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=w5tWYmIOWGk', 'https://www.youtube.com/watch?v=g8PrTzLaLHc', 'https://www.youtube.com/watch?v=Nwvil057g-g', 'https://www.youtube.com/watch?v=e74VMNgARvY']\n      },\n      {\n        \"song\": {\n          \"title\": \"Amsterdam\",\n          \"duration\": 241\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=TKtPXO5iEnA', 'https://www.youtube.com/watch?v=s6Nc4qEI3k4', 'https://www.youtube.com/watch?v=dboQYGddEC8', 'https://www.youtube.com/watch?v=j-tfNaBcyes']\n      },\n      {\n        \"song\": {\n          \"title\": \"Hear Me\",\n          \"duration\": 235\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=1Yr683VLxes', 'https://www.youtube.com/watch?v=EkB2eJfF3W8', 'https://www.youtube.com/watch?v=u0Q3r4ywA34']\n      },\n      {\n        \"song\": {\n          \"title\": \"Every Night\",\n          \"duration\": 217\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=6RVxzeBiBJU', 'https://www.youtube.com/watch?v=kuijhOvKyYg', 'https://www.youtube.com/watch?v=f6CQ3ATP_6Y', 'https://www.youtube.com/watch?v=k4ESylzBW4M']\n      },\n      {\n        \"song\": {\n          \"title\": \"Bleeding Out\",\n          \"duration\": 223\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=jNFgynmVmx0', 'https://www.youtube.com/watch?v=gJEoxeW7JvQ', 'https://www.youtube.com/watch?v=Hq6kn87NpKw', 'https://www.youtube.com/watch?v=Tyjt1Ff4m7k']\n      },\n      {\n        \"song\": {\n          \"title\": \"Underdog\",\n          \"duration\": 209\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=JCUV43T7HZ0', 'https://www.youtube.com/watch?v=USeEyhodZqk', 'https://www.youtube.com/watch?v=KoX80w5b8ps', 'https://www.youtube.com/watch?v=m4SBGLtJvPo', 'https://www.youtube.com/watch?v=2RQRoTvXXiw']\n      },\n      {\n        \"song\": {\n          \"title\": \"Nothing Left To Say / Rocks (Medley)\",\n          \"duration\": 537\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=Bn7eYibzmTs', 'https://www.youtube.com/watch?v=bSBkYqbdOKc', 'https://www.youtube.com/watch?v=B4z7loNm_kw', 'https://www.youtube.com/watch?v=Q6zqH6qKaTU', 'https://www.youtube.com/watch?v=zCqHNBleR6M']\n      },\n      {\n        \"song\": {\n          \"title\": \"Cha-Ching (Till We Grow Older)\",\n          \"duration\": 249\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=rmqyXQf8jkU', 'https://www.youtube.com/watch?v=vhSvfxtlUQc', 'https://www.youtube.com/watch?v=wO0ohGn-x3E', 'https://www.youtube.com/watch?v=IgC8yZpMRqc', 'https://www.youtube.com/watch?v=zTingWDAAts']\n      },\n      {\n        \"song\": {\n          \"title\": \"Working Man\",\n          \"duration\": 235\n        },\n        \"videos\": ['https://www.youtube.com/watch?v=m4SBGLtJvPo', 'https://www.youtube.com/watch?v=2d-GIw-pBMs', 'https://www.youtube.com/watch?v=NARf6QW3KYA', 'https://www.youtube.com/watch?v=31YTMhD4NYs', 'https://www.youtube.com/watch?v=mhXoXYbmCz4', 'https://www.youtube.com/watch?v=2d-GIw-pBMs', 'https://www.youtube.com/watch?v=aW8_7M8e5CQ']\n      }\n    ];\n\n    return testTracks(tracks, artistName);\n  });\n\n  // Failed, but the videos it finds are unavailable\n  // Should update testTracks() so it checks if the video is available or not\n  // it('should find YouTube videos for Night Shift (Original Mix) by Overwerk', function () {\n  //   this.timeout(10000);\n  //\n  //   let artistName = \"Overwerk\";\n  //   let tracks = [\n  //     {\n  //       song: {\n  //         title: \"Night Shift (Original Mix)\",\n  //         duration: 541\n  //       },\n  //       videos: ['https://www.youtube.com/watch?v=SI2wnEvrepM', 'https://www.youtube.com/watch?v=87bCbQHez9k', 'https://www.youtube.com/watch?v=dtq9NNLa1O8']\n  //     },\n  //     {\n  //       song: {\n  //         title: \"Last Call (Original Mix)\",\n  //         duration: 600\n  //       },\n  //       videos: ['https://www.youtube.com/watch?v=4C9LACMJFT4', 'https://www.youtube.com/watch?v=eQMXBaB0Ehs', 'https://www.youtube.com/watch?v=RzKCHDgQZ9g']\n  //     }\n  //   ];\n  //\n  //   return testTracks(tracks, artistName);\n  // });\n\n  it('should find YouTube videos for single letter artist M', function () {\n    this.timeout(10000);\n\n    // It's a French song\n    alltomp3.regionCode = 'FR';\n\n    let artistName = \"M\";\n    let tracks = [\n      {\n        song: {\n          title: \"Je dis aime\",\n          duration: 236\n        },\n        videos: ['https://www.youtube.com/watch?v=6hV-UnrC9tU', 'https://www.youtube.com/watch?v=QYWV67qgHvg', 'https://www.youtube.com/watch?v=ORam68OtcmY']\n      },\n      {\n        song: {\n          title: \"Mama Sam\",\n          duration: 195\n        },\n        videos: ['https://www.youtube.com/watch?v=avZTCTR6e9k', 'https://www.youtube.com/watch?v=HRez3YiXxJw']\n      }\n    ];\n\n    return testTracks(tracks, artistName);\n  });\n});\n"
  },
  {
    "path": "test/guessTrackFromString.js",
    "content": "const expect = require('chai').expect;\nconst alltomp3 = require('..');\nconst _ = require('lodash');\n\ndescribe('guessTrackFromString', function() {\n  it('should guess the right track', function () {\n    this.timeout(20000);\n    let queries = [\n      {\n        q: \"Kungs vs Cookin’ on 3 Burners - This Girl\",\n        title: \"This Girl (Kungs Vs. Cookin' On 3 Burners)\",\n        a: \"Kungs\"\n      },\n      {\n        q: \"'City of Stars' (Duet ft. Ryan Gosling, Emma Stone) - La La Land Original Motion Picture Soundtrack\",\n        t: \"City of Stars\",\n        a: \"Piano Dreamers\"\n      },\n      {\n        q: \"Imagine Dragons - On Top Of The World (Official Music Video)\",\n        t: \"On Top Of The World\",\n        a: \"Imagine Dragons\"\n      },\n      {\n        q: \"Mika - Elle Me Dit (clip officiel)\",\n        t: \"Elle Me Dit\",\n        a: \"Mika\"\n      }\n    ];\n    let promises = [];\n    _.forEach(queries, q => {\n      let p = alltomp3.guessTrackFromString(q.q).then(a => {\n        expect(a.title).to.be(q.t);\n        expect(a.artistName).to.be(q.a);\n      });\n      promises.push(p);\n    });\n    return promises;\n  });\n});\n"
  },
  {
    "path": "test.js",
    "content": "const alltomp3 = require('.');\nconst util = require('util');\n\n// alltomp3.spotifyToken().then(o => console.log(o)).catch(e => console.log(e));\n\n// alltomp3.getPlaylistTitlesInfos('https://open.spotify.com/user/spotify_france/playlist/1h4ZB3lW7lD5RmfE6DIRRI').then(d => console.log(util.inspect(d, {depth: 2})));\n\n// alltomp3.getSpotifyTrackInfos('1NOPjzkLIEUM6mwGxCm2mM').then(i => console.log(i));\n\n// alltomp3.configEyeD3('/Users/ntag/Projets/alltomp3/alltomp3-app/bin/eyeD3/bin/eyeD3', '/Users/ntag/Projets/alltomp3/alltomp3-app/bin/eyeD3/build/lib');\n// alltomp3.getInfosWithYoutubeDl('https://soundcloud.com/taylorythm/coda', function(infos) {\n//     console.log(infos);\n// });\n// alltomp3.getInfosWithYoutubeDl('https://www.youtube.com/watch?v=e74VMNgARvY', function(infos) {\n//     console.log(infos);\n// });\n// not working URL https://www.youtube.com/watch?v=yzi-7G2u89g\n// var dl = alltomp3.findAndDownload(\"mika elle me dit\", \"./\", () => {}, true);\n// dl.on(\"download\", function (infos) {\n//   process.stdout.cursorTo(0);\n//   process.stdout.clearLine(1);\n//   process.stdout.write(infos.progress + \"%\");\n// });\n// dl.on(\"download-end\", function () {\n//   console.log(\"Download end\");\n// });\n// dl.on(\"convert\", function (infos) {\n//   process.stdout.cursorTo(0);\n//   process.stdout.clearLine(1);\n//   process.stdout.write(infos.progress + \"%\");\n// });\n// dl.on(\"error\", function (e) {\n//   console.log(\"Error la la\", util.inspect(e));\n// });\n\n// alltomp3.getInfosWithYoutubeDl('https://www.youtube.com/watch?v=sX9s-bSOYxk').then(console.log);\n\n// const dl = alltomp3.downloadWithYoutubeDl('https://www.youtube.com/watch?v=sX9s-bSOYxk', 'test.mp3');\n// dl.on('download-progress', console.log);\n// dl.once('download-end', console.log);\n// dl.on('error', console.error);\n\n// alltomp3.guessTrackFromString('Imagine Dragons - On Top of the World - Lyrics', false, false, true);\n// alltomp3.guessTrackFromString('C2C - Happy Ft. D.Martin', false, false, true);\n// alltomp3.guessTrackFromString('David Guetta - Bang My Head (Official Video) feat Sia & Fetty Wap', false, false, true);\n// alltomp3.guessTrackFromString('David Guetta - Hey Mama (Official Video) ft Nicki Minaj, Bebe Rexha & Afrojack', false, false, true);\n// alltomp3.retrieveTrackInformations('On Top of the World', 'Imagine Dragons').then(function (infos) {\n//     console.log(\"Infos: \", infos);\n// });\n\n// alltomp3.guessTrackFromFile('./test.mp3').then(function (infos) {\n//     return alltomp3.retrieveTrackInformations(infos.title, infos.artistName);\n// }).then(function (infos) {\n//     console.log(infos);\n//     alltomp3.tagFile('./test.mp3', infos);\n// });\n\n// alltomp3.downloadAndTagSingleURL(\n//   'https://www.youtube.com/watch?v=sX9s-bSOYxk',\n//   './',\n//   function (infos) {\n//     console.log(infos);\n//   },\n//   undefined,\n//   true,\n// );\n\n// var title = \"hide and seek imogen heap\";\n// alltomp3.findVideo(title).then(function(results) {\n//     var dl = alltomp3.downloadAndTagSingleURL(results[0].url, function(infos) {\n//         console.log(\"FINI \", infos);\n//     }, title);\n//     dl.on('download', function(infos) {\n//         process.stdout.cursorTo(0);\n//         process.stdout.clearLine(1);\n//         process.stdout.write(infos.progress + '%');\n//     });\n//     dl.on('download-end', function() {\n//         console.log('Download end');\n//     });\n//     dl.on('convert', function(infos) {\n//         process.stdout.cursorTo(0);\n//         process.stdout.clearLine(1);\n//         process.stdout.write(infos.progress + '%');\n//     });\n//     dl.on('convert-end', function() {\n//         console.log('Convert end');\n//     });\n//     dl.on('infos', function(infos) {\n//         console.log('Got infos: ', infos);\n//     });\n// });\n\n// var dl = alltomp3.downloadAndTagSingleURL(\"https://soundcloud.com/user-523607375/sets/john-legend-start-a-fire-la-la\", 'mp3/', function(infos) {\n//     console.log(\"FINI \", infos);\n// });\n// dl.on('download', function(infos) {\n//     process.stdout.cursorTo(0);\n//     process.stdout.clearLine(1);\n//     process.stdout.write(infos.progress + '%');\n// });\n// dl.on('download-end', function() {\n//     console.log('Download end');\n// });\n// dl.on('convert', function(infos) {\n//     process.stdout.cursorTo(0);\n//     process.stdout.clearLine(1);\n//     process.stdout.write(infos.progress + '%');\n// });\n// dl.on('convert-end', function() {\n//     console.log('Convert end');\n// });\n// dl.on('infos', function(infos) {\n//     console.log('Got infos: ', infos);\n// });\n\nvar dl = alltomp3.findAndDownload('imagine dragons on top of the world', './mp3/', function (infos) {\n  console.log(\"It's finished: \", infos);\n});\ndl.on('search-end', function () {\n  console.log('Search end');\n});\ndl.on('download', function (infos) {\n  process.stdout.cursorTo(0);\n  process.stdout.clearLine(1);\n  process.stdout.write(infos.progress + '%');\n});\ndl.on('download-end', function () {\n  console.log('', 'Download end');\n});\ndl.on('convert', function (infos) {\n  process.stdout.cursorTo(0);\n  process.stdout.clearLine(1);\n  process.stdout.write(infos.progress + '%');\n});\ndl.on('convert-end', function () {\n  console.log('', 'Convert end');\n});\ndl.on('infos', function (infos) {\n  console.log('New infos received: ', infos);\n});\n\n// alltomp3.guessTrackFromString('Imagine Dragons - On Top of the World - Lyrics').then(function(infos) {\n//     console.log(infos);\n// });\n// alltomp3.guessTrackFromString('C2C - Happy Ft. D.Martin').then(function(infos) {\n//     console.log(infos);\n// });\n// alltomp3.guessTrackFromString('David Guetta - Bang My Head (Official Video) feat Sia & Fetty Wap').then(function(infos) {\n//     console.log(infos);\n// });\n// alltomp3.guessTrackFromString('David Guetta - Hey Mama (Official Video) ft Nicki Minaj, Bebe Rexha & Afrojack').then(function(infos) {\n//     console.log(infos);\n// });\n// alltomp3.guessTrackFromString('hans zimmer no time for caution').then(function(infos) {\n//     console.log(infos);\n// });\n\n// alltomp3.findLyrics('Radioactive', 'Imagine Dragons').then(function (lyrics) {\n//         console.log(lyrics);\n// }).catch(function() {\n//     console.log('No lyrics');\n// });\n\n// alltomp3.getURLsInPlaylist('https://soundcloud.com/20syl/sets/20syl-remixes-2016').then(function(items) {\n//     console.log(items);\n// });\n\n// alltomp3.getTracksInPlaylist('http://www.deezer.com/album/11111444').then(function(items) {\n//     console.log(items);\n// });\n\n// var urls;\n// var dl = alltomp3.downloadPlaylist(\"https://open.spotify.com/album/2tVnLYqhc0iGdSCLxoaLjD\", \"./mp3/\", function (urls) {\n//     console.log(\"It's finished: \", urls);\n// }, 8);\n// dl.on('search-end', function() {\n//     console.log('Search end');\n// });\n// dl.on('download', function(index) {\n//     process.stdout.cursorTo(0);\n//     process.stdout.clearLine(1);\n//     process.stdout.write(urls.items[index].progress.download.progress + '%');\n// });\n// dl.on('download-end', function() {\n//     console.log('', 'Download end');\n// });\n// dl.on('convert', function(index) {\n//     process.stdout.cursorTo(0);\n//     process.stdout.clearLine(1);\n//     process.stdout.write(urls.items[index].progress.convert.progress + '%');\n// });\n// dl.on('convert-end', function(index) {\n//     console.log('', 'Convert end');\n// });\n// dl.on('error', function(index) {\n//     console.log('', 'Error with ' + index);\n// });\n// dl.on('infos', function(index) {\n//     // console.log('New infos received: ', infos);\n// });\n// dl.on('playlist-infos', function(urlss) {\n//     urls = urlss;\n//     console.log('URLs received: ', urlss);\n// });\n// dl.on('begin-url', function(index) {\n//     console.log('Begin: ', index);\n// });\n// dl.on('end-url', function(index) {\n//     console.log('End: ', index);\n// });\n"
  }
]