[
  {
    "path": ".gitignore",
    "content": "/target\n.idea/\nOUT_DIR/"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"skyfolder\"\nversion = \"0.1.0\"\nedition = \"2021\"\nlicense = \"GPL-3.0\"\ndescription = \"Skyfolder is a self-contained portable HTTP/Bittorrent server that hosts a website for immediate filesharing with friends & colleagues. Made for busy people that want to share files NOW, and don't want to remember how to configure anything. Ships with good defaults and includes a built-in management graphical interface.\"\n\nbuild = \"build.rs\"\n\n[build-dependencies]\nrand = \"0.8.5\"\nminify-js = \"0.5.6\"\n\n[dependencies]\ntokio = { version = \"1.30.0\", features = [\"macros\",\"rt-multi-thread\", \"signal\", \"sync\", \"full\"] }\ntikv-jemallocator = \"0.5\"\n\naxum = { version = \"0.6.19\", features = [\"macros\"]}\naskama = \"0.12.0\"\nhyper = \"0.14.26\"\ntower = \"0.4.13\"\ntower-http = \"0.4.0\"\ntower-layer = \"0.3.2\"\ntokio-util = {version = \"0.7.1\", features = [\"io\"]}\n#rustls-acme = \"0.7.3\"\n\nreqwest = \"0.11.18\"\n\n\nclap = { version = \"4.3.0\", features = [\"cargo\"]}\nget_if_addrs = \"0.5.3\"\nchrono = \"0.4\"\nbytes = \"1.4.0\"\n#smartstring = \"1.0.1\" eventually use this\n\n[profile.release]\n#debug = 1\n#debuginfo-level = 1\nlto = true\ncodegen-units = 1\npanic = \"abort\"\ndebug-assertions=false\nopt-level=3"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img src=\"https://github.com/mu-arch/skyfolder/blob/master/hosted/logo.png\" alt=\"Skyfolder - Securely host files onto the web directly from your PC\" title=\"SkyFolder\" width=\"250px\" height=\"250px\">\n</p>\n\n# Skyfolder - turn any device into a file-server accessible on the web\n\n**It's like your own personal Google Drive!**\n\nSkyfolder is a secure, self-contained, portable, HTTP/Bittorrent server that serves a local folder on your computer as a website and torrent for immediate file-sharing with friends, colleagues, or just yourself. Made for busy people that want to share files NOW, and don't want to remember how to configure anything. Auto-negotiates with your router to automate port-forwarding. Ships with good defaults and includes a built-in management graphical interface for permissions, etc.\n\nNo need to install anything. SkyFolder is a single portable executable file. [Take me to the download link!](#how-to-install)\n\nSkyfolder Discord: https://discord.gg/VBMe2rcYb6\n\n### Screenshot:\n\n![Screenshot](screenshot.png)\n\n### Priorities:\n1. Secure\n2. Auto-resume and complete transfers even in bad network conditions, broken pipes, dropped connections\n3. Braindead simple\n\n### Features:\n\n1. Downloads & uploads (Both pausable/resumable).\n2. Create, Delete, Rename directories.\n3. Sort the list by multiple parameters.\n4. Access Control Lists (ACL) for managing permissions on a per folder/user basis.\n5. Portable - requires no installation or management of program files; everything is packaged in a single executable file.\n6. No third party services or data collection. Runs completely on your system.\n7. Multiple views: list view, icon view.\n8. In-browser file-viewer and streamer.\n9. Built in real-time search engine with fuzzy finding.\n10. Low resource footprint (~10mb DRAM, files are streamed off disk in small chunks) suitable to run 24/7.\n11. Static generator option: pre-compile folders and files to be stored on a CDN (not compatible with permission system)\n12. Compatible with GNU/Linux, BSD, Windows, and Mac.\n13. Supports TLS certificates, including a built-in automatic Let's Encrypt client that can renew certs with no user interaction.\n14. Stable to run indefinitely without needing a restart.\n15. Secure to expose to the open internet.\n16. Management GUI that generates [Gura](https://github.com/gura-conf/gura) markup in the background (manual Gura editing is also an option).\n17. Multiple download methods: HTTP GET, HTTP JS managed File System Access API, Bittorrent magnet.\n18. Efficiently utilizes all CPU cores and available bandwidth across thousands of active downloaders.\n19. Supports partial files (content-range) and retries.\n20. Generates thumbnails for images and videos.\n21. Supports directories with tens of thousands of files.\n22. Produces the correct headers for streaming video to VRChat movie theater worlds ;)\n23. Communicates with routers to automatically open WAN ports (UPNP)\n24. QR code generation\n\n### Roadmap\n\n1. Bittorrent tracker and seeding client, so you can download files via your favorite client and seed to others\n2. OS toast notification when someone downloads a file from you\n\n### Help needed:\n\n1. Mobile version\n2. Dark mode\n3. General testing\n4. Penetration Testing\n5. Unit tests\n6. Implementing Bittorrent\n7. Polish and improve UI, more clever thoughtfulness towards the UI is always desired\n8. Your feedback (there's no such thing as a stupid/trite question/comment here)\n9. Test if it works on a 32bit computer\n10. Support embedded computers\n\n### How to install:\n\nIt's not complete as of Sep 2, 2023. Expect updates soon.\n\n## Security notice\n\n1. You should use a Transport Layer Security (TLS) certificate when using management features from outside your local area network (LAN) - such as over the internet - to avoid your management credentials from being sniff-able.\n\n2. Skyfolder has not yet been penetration tested.\n\n3. Bittorrent Magnet links can be shared freely and used by anyone, so keep that in mind.\n\n4. TLS certificates are integral for encrypting data in transit for all websites, including Skyfolder. However, it's important to understand the limitations of this setup. While TLS provides secure transmission, it does not equate to end-to-end (E2E) encryption. Specifically, Skyfolder does not utilize E2E encryption.\n\n## Limitations\n\n1. Some functionality requires Javascript to work"
  },
  {
    "path": "askama.toml",
    "content": "[general]\n# Directories to search for templates, relative to the crate root.\ndirs = [\"templates\"]\n# Unless you add a `-` in a block, whitespace characters won't be trimmed.\nwhitespace = \"suppress\""
  },
  {
    "path": "assets/scripts.js",
    "content": "'use strict';\n\nlet GLOBAL_TABLE_DATA;\n\nfunction navurl(url) {\n    window.location.href = url;\n}\n\nfunction qs(divs) {\n    return document.querySelector(divs)\n}\n\nfunction debounce(func, wait) {\n    let timeout;\n    return function executedFunction(...args) {\n        const later = () => {\n            clearTimeout(timeout);\n            func(...args);\n        };\n        clearTimeout(timeout);\n        timeout = setTimeout(later, wait);\n    };\n};\n\nfunction check_if_tbody_is_empty() {\n    const table = document.querySelector('#table');\n    const tbody = table.querySelector('tbody');\n\n    if (tbody.children.length === 0) {\n        table.querySelector('thead tr:last-child').style = 'border-bottom: 1px solid #e5e5e5';\n    }\n}\nfunction extractTableData() {\n    const tbody = document.querySelector('tbody');  // get the tbody element\n    const rows = tbody.querySelectorAll('tr'); // get all 'tr' elements within the tbody\n\n    // Map each 'tr' to an array and return the result\n    return Array.from(rows).map((row, index) => {\n        const aTag = row.querySelector('a');  // get the 'a' tag within the current 'tr'\n        return [aTag.innerText.toLowerCase(), index]; // return the array for the current 'tr', and we lowercase the inner text ready to search\n    });\n}\n\nfunction workerSearch() {\n    self.onmessage = function(event) {\n        const { query, rowMatrix } = event.data;\n\n        function fuzzysearch(needle, haystack) {\n            var hlen = haystack.length;\n            var nlen = needle.length;\n            if (nlen > hlen) {\n                return false;\n            }\n            if (nlen === hlen) {\n                return haystack.startsWith(needle);\n            }\n            outer: for (var i = 0, j = 0; i < nlen; i++) {\n                var nch = needle.charCodeAt(i);\n                while (j < hlen) {\n                    if (haystack.charCodeAt(j++) === nch) {\n                        continue outer;\n                    }\n                }\n                return false;\n            }\n            return true;\n        }\n\n        const matches = rowMatrix\n            .map((row, index) => ({\n                index: row[1],\n                match: fuzzysearch(query, row[0]),\n                // Save the relevance score\n                relevance: row[0].includes(query) ? 0 : 1\n            }))\n            .filter(m => m.match !== false)\n            .sort((a, b) => a.relevance - b.relevance) // Lower scores first\n            .map(m => m.index);\n\n        self.postMessage(matches);\n    };\n}\n\nfunction marshall_search(query, rowMatrix) {\n    return new Promise((resolve, reject) => {\n        let workerCode = workerSearch.toString();\n        workerCode = workerCode.slice(workerCode.indexOf(\"{\") + 1, workerCode.lastIndexOf(\"}\"));\n\n        const workerBlob = new Blob([workerCode], { type: \"text/javascript\" });\n        const workerURL = URL.createObjectURL(workerBlob);\n\n        const worker = new Worker(workerURL);\n        worker.onmessage = function(event) {\n            resolve(event.data);\n        };\n        worker.onerror = function(error) {\n            reject(error);\n        };\n        worker.postMessage({ query, rowMatrix });\n    });\n}\n\n\n\n\n\n\nfunction displaySearchResults(indexes, searchTerm, limit = Infinity) {\n    requestAnimationFrame(() => {\n        const tbody = document.getElementById('b');\n        tbody.style.display = 'none';\n\n        const oldB2 = document.getElementById('b2');\n        if (oldB2) {\n            oldB2.remove();\n        }\n\n        const b2 = document.createElement('tbody');\n        b2.id = 'b2';\n\n        const limitedIndexes = indexes.slice(0, limit);\n\n        const fragment = document.createDocumentFragment();\n\n        for (const index of limitedIndexes) {\n            const row = tbody.rows[index];\n            const clonedRow = row.cloneNode(true);\n            const aTag = clonedRow.querySelector('td:first-child a');\n            if (aTag) {\n                const textContent = aTag.innerHTML;\n                const searchTermRegExp = new RegExp(`(${searchTerm})`, 'ig'); // 'i' makes it case-insensitive, 'g' is for global search\n                const newTextContent = textContent.replace(searchTermRegExp, function(match) {\n                    return `<span>${match}</span>`;\n                });\n                aTag.innerHTML = newTextContent;\n            }\n            fragment.appendChild(clonedRow);\n        }\n\n        b2.appendChild(fragment);\n\n        // Add omitted results caption\n        const omittedResults = indexes.length - limitedIndexes.length;\n        const omittedRows = GLOBAL_TABLE_DATA.length - limitedIndexes.length;\n        const resultsCaption = document.createElement('caption');\n        resultsCaption.title = \"Click to show all omitted matches.\";\n        if (omittedResults > 0) {\n            resultsCaption.innerHTML = `<span><b>${omittedResults}</b> omitted matches</span> <div>-</div> <b>${omittedRows}</b> total rows excluded.`;\n        } else {\n            resultsCaption.innerHTML = `<b>${omittedResults}</b> omitted matches <div>-</div> <b>${omittedRows}</b> total rows excluded`;\n        }\n\n        resultsCaption.addEventListener('click', () => {\n            search(searchTerm, Infinity)\n        });\n\n        b2.appendChild(resultsCaption);\n\n        tbody.parentNode.insertBefore(b2, tbody.nextSibling);\n    });\n}\n\n\nfunction cleanupSearchResults() {\n    // get the original tbody\n    const tbody = document.getElementById('b');\n    // set the original tbody to display block (or '' to revert to default CSS value)\n    tbody.style.display = '';\n\n    // get b2\n    const oldB2 = document.getElementById('b2');\n    // if b2 exists, delete it\n    if (oldB2) {\n        oldB2.remove();\n    }\n}\n\n\n\nfunction search(query, resultLimit) {\n    marshall_search(query, GLOBAL_TABLE_DATA)\n        .then(results => {\n            displaySearchResults(results, query.toLowerCase(), resultLimit)\n        });\n}\n\nvar handleSearchInput = (function() {\n    var debouncedSearch = debounce(search, 100);\n\n    return function(event) {\n        var val = event.target.value;\n        if (val === \"\") {\n            cleanupSearchResults();\n        } else {\n            if (GLOBAL_TABLE_DATA.length > 200) {\n                debouncedSearch(val, 50);\n            } else {\n                search(val, 50);\n            }\n        }\n    };\n})();\n\n\n\n//onmouseover=\"preloadNextPage(this)\"\n\n/*function preloadNextPage(element) {\n    const anchorElement = element.querySelector('a');\n    const linkHref = anchorElement.href;\n\n    if (anchorElement && anchorElement.rel !== 'preload') {\n        if (linkHref.endsWith('/') && !anchorElement.hasAttribute('data-preload')) {\n            fetch(linkHref, { method: 'GET' }); // Preload the resource\n            anchorElement.setAttribute('data-preload', 'true');\n        }\n    }\n}\n*/\n\nfunction navigateToParentDirectory() {\n    let currentURL = window.location.href;\n\n    // Remove trailing slashes\n    while (currentURL.endsWith('/')) {\n        currentURL = currentURL.slice(0, -1);\n    }\n\n    const lastSlashIndex = currentURL.lastIndexOf('/');\n\n    if (lastSlashIndex <= currentURL.indexOf('://') + 2) {\n        return;\n    }\n\n    const parentURL = currentURL.substring(0, lastSlashIndex);\n\n    window.location.href = parentURL + '/';\n}\n\nfunction extractPaths(url) {\n    const parsedUrl = new URL(url);\n     // filter(Boolean) removes any empty strings\n    return parsedUrl.pathname.split('/').filter(Boolean);\n}\n\nfunction spawnTooltip(source, templateFn) {\n    // Check if a tooltip already exists\n    let tooltip = document.querySelector('.tooltip');\n\n    // If tooltip doesn't exist, create it\n    if (!tooltip) {\n        tooltip = document.createElement('div');\n        tooltip.classList.add('tooltip');\n        document.body.appendChild(tooltip);\n    }\n\n    // Update its content\n    tooltip.innerHTML = templateFn();\n\n    source = source.getBoundingClientRect();\n\n    tooltip.style.left = source.left -3 + 'px';\n    tooltip.style.top = source.top -3 + 'px';\n\n    document.body.appendChild(tooltip);\n\n\n}\n\nfunction path_selector_generator() {\n    let output = \"\";\n    let paths = extractPaths(window.location.href)\n\n    let left_padding = 20;\n    output += `<div class='pathbar_item'>FileSystem Root</div>`\n\n    paths.forEach(path => {\n        console.log(path);\n        output += `<div class='pathbar_item' style='padding-left:${left_padding}px'>${path}</div>`\n        left_padding += 10;\n    });\n\n    return output\n}\n\n\n\n//manifests run at pageload\nfunction file_dir_manifest() {\n    check_if_tbody_is_empty()\n    GLOBAL_TABLE_DATA = extractTableData();\n    qs('nav input').addEventListener('input', handleSearchInput);\n    document.getElementById(\"fc\").innerText = `${GLOBAL_TABLE_DATA.length} files`;\n    qs('nav > div').addEventListener('click', navigateToParentDirectory);\n\n    //tooltip for pathbar\n    let path_selector = document.querySelector('nav div:nth-child(2)');\n    path_selector.addEventListener('click', () => spawnTooltip(path_selector, path_selector_generator));\n\n}\n\ndocument.addEventListener('DOMContentLoaded', file_dir_manifest);"
  },
  {
    "path": "assets/styles.css",
    "content": "html, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\nb, u, i, center,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, canvas, details, embed,\nfigure, figcaption, footer, header, hgroup,\nmenu, nav, output, ruby, section, summary,\ntime, mark, audio, video {\n    margin: 0;\n    padding: 0;\n    border: 0;\n    font-size: 100%;\n    font: inherit;\n    vertical-align: baseline;\n}\n\narticle, aside, details, figcaption, figure,\nfooter, header, hgroup, menu, nav, section {\n    display: block;\n}\nbody {\n    line-height: 1;\n}\nol, ul {\n    list-style: none;\n}\nblockquote, q {\n    quotes: none;\n}\nblockquote:before, blockquote:after,\nq:before, q:after {\n    content: '';\n    content: none;\n}\ntable {\n    border-collapse: collapse;\n    border-spacing: 0;\n}\n\ninput:focus {\n    outline: none;\n}\n\na {\n    color: inherit;\n    text-decoration: none;\n}\n\nhtml {\n    background-color: #fff;\n    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', Arial, sans-serif;\n}\n\nsection {\n    padding: 20px 40px;\n    width: calc(100% - 350px);\n}\n\nnav {\n    display: flex;\n    justify-content: flex-start;\n    margin: 5px 0 15px 0;\n}\n\nnav > * {\n    border: 1px solid #b8b8b8;\n    box-shadow: 0 2px 3px rgba(172, 172, 172, 0.17);\n    border-radius: 10px;\n    background: linear-gradient(to top, #f4f4f4, #fff);\n    height: 35px;\n    user-select: none;\n    margin-right: 20px;\n    cursor:pointer;\n    font-size: 14px;\n    font-weight: bold;\n    line-height: 35px;\n    padding: 0 15px;\n    position: relative;\n    overflow: hidden;\n}\n\nnav > *:hover {\n    border: 1px solid #3478F6;\n    background: linear-gradient(to top, #e7e9ef, #f0f3f8);\n}\n\n\nnav > div:first-child {\n    border-radius: 10px 0px 0px 10px;\n    padding-right: 23px;\n    margin-right: 0;\n    z-index: 100;\n}\n\nnav > div:first-child:before {\n    content: '';\n    scale: .3;\n    opacity: .7;\n    width: 64px;\n    height: 64px;\n    background: url(/v.svg) no-repeat -128px 0px;\n    transform-origin: top left;\n    position: absolute;\n    left: 10px;\n    top: 8px;\n}\n\nnav > div:nth-child(2) {\n    padding-left: 40px;\n    max-width: 200px;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    border-radius: 0px 10px 10px 0px;\n    border-left: 1px solid transparent;\n    position: relative;\n    left:-1px;\n}\nnav > div:nth-child(2):hover {\n    z-index: 1000;\n    border-left: 1px solid #3478F6;\n}\n\nnav > div:nth-child(2):before {\n    content: '';\n    scale: .3;\n    opacity: .7;\n    width: 64px;\n    height: 64px;\n    background: url(/v.svg) no-repeat -64px -64px;\n    transform-origin: top left;\n    position: absolute;\n    left: 11px;\n    top: 8px;\n}\n\nnav > div:nth-child(2) span {\n    font-weight: 300;\n    padding: 0 0 0 8px;\n    color: #6c6c6c;\n}\n\nnav > div:nth-child(3) {\n    flex: 1;\n    margin-right: 0;\n    padding: 0;\n}\n\nnav > div:nth-child(3):before {\n    content: '';\n    scale: .3;\n    width: 64px;\n    height: 64px;\n    background: url(/v.svg) no-repeat 0px 0px;\n    transform-origin: top left;\n    position: absolute;\n    left: 11px;\n    top: 8px;\n}\n\nnav > div:nth-child(3) > div {\n    height: 17px;\n    width: 35px;\n    background-color: #356eff;\n    position: absolute;\n    border-radius: 5px;\n    right: 13px;\n    top: 9px;\n}\n\nnav > div:nth-child(3) > div:nth-child(2):before {\n    content: 'ADV \\xE2\\x86\\x92';\n    color: #fff;\n    position: absolute;\n    left: 7px;\n    top: -9px;\n    font-size: 6px;\n}\n\nnav > div:nth-child(3) > div:nth-child(2):after {\n    content: '';\n    scale: .1;\n    filter: invert();\n    width: 64px;\n    height: 64px;\n    background: url(/r.webp) no-repeat -64px -256px;\n    position: absolute;\n    left: -5px;\n    top: -23px;\n    rotate: 270deg;\n}\n\nnav input {\n    width: 100%;\n    background: none;\n    border: none;\n    font-weight: bold;\n    height: 34px;\n    padding-left: 43px;\n    font-size: 13px;\n}\n\n\n\n\ntable {\n    width: 100%;\n    table-layout: fixed;\n}\n\nthead, tbody {\n    display: contents;\n}\n\ntr {\n    display: grid;\n    grid-template-columns: 3fr 1fr 1fr;\n    border-bottom: 1px solid #e5e5e5;\n    font-size: 14px;\n    position: relative;\n}\n\nth, td {\n    text-align: left;\n    color: #6c6c6c;\n}\n\nth {\n    padding: 15px 0;\n    text-transform: uppercase;\n    font-weight: 700;\n    font-size: 10px;\n    letter-spacing: 1px;\n}\n\nth:last-child {\n    position: absolute;\n    right: 0;\n}\n\ntd {\n    padding: 22px 0;\n}\n\ntd:nth-child(3) span {\n    padding: 2px 4px;\n    background-color: #f2f1f0;\n    text-transform: uppercase;\n    font-weight: bold;\n    font-size: 10px;\n    border-radius: 2px;\n    position: relative;\n    top: -1px;\n}\n\ntd:nth-child(1) {\n    position: relative;\n    color: #000;\n    cursor: pointer;\n    overflow: hidden;\n    user-select: none;\n}\n\n\ntd:nth-child(1) a {\n    font-weight: bold;\n    overflow: hidden;\n    white-space: nowrap;\n    margin-left: 50px;\n    max-width: calc(100% - 60px);\n    line-height: 1em;\n}\n\ntd:nth-child(1) a span {\n    background-color: yellow;\n}\n\ntd:nth-child(1)::after {\n    content: '';\n    position: absolute;\n    right: 0;\n    width: 15%;\n    height: 100%;\n    background: linear-gradient(to right, rgba(255,255,255,0), rgba(255,255,255,1));\n    pointer-events: none;\n}\n\ntd:nth-child(1):hover a {\n    text-decoration: underline;\n}\n\ntd:nth-child(1) div {\n    display: inline-block;\n    background: url('/r.webp') -256px 0px;\n    scale:.25;\n    width: 128px;\n    height: 128px;\n    transform-origin: top left;\n    position: absolute;\n    top: 13px;\n}\n\ntbody tr::after {\n    content: '';\n    background: url('/v.svg') 0px -64px;\n    scale: .23;\n    opacity:.4;\n    width: 64px;  /* width of your icon */\n    height: 64px;  /* height of your icon */\n    position: absolute;\n    right: -15px;  /* Adjust this value to position your icon on the right */\n    top: -2px;\n}\n\ntable tr:last-of-type {\n    border-bottom: 0;\n}\n\ncaption {\n    caption-side: bottom;\n    text-align: center;\n    margin: 20px;\n    font-size: 14px;\n    background: #f2f2f2;\n    padding: 12px 20px;\n    border-radius: 5px;\n    cursor: pointer;\n    user-select:none;\n}\n\ncaption b {\n    font-weight: bold;\n}\n\ncaption:hover {\n    background: #e8e8e8;\n}\n\ncaption:active {\n    background: #eeeeee;\n}\ncaption div {\n    padding: 0 10px;\n    display: inline-block;\n}\n\ncaption span {\n    color: #3478F6;\n}\n\n.folder-empty {\n    position: absolute;\n    top: 200px;\n    left: calc(50% - 260px);\n    width: 250px;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n}\n\n.folder-empty div {\n    background: url('/r.webp') -128px -128px;\n    scale: .5;\n    width: 256px;\n    height: 128px;\n    transform-origin: center;\n}\n\n.folder-empty span {\n    text-align: center;\n    opacity: .5;\n}\n\n\n#pane {\n    position: fixed;\n    top: 0;\n    right: 0;\n    min-height: 100vh;\n    width: 270px;\n}\n\n#pane > div:first-child {\n    margin: 25px 0;\n    background-color: #fbfbfb;\n    width: 90%;\n    overflow: hidden;\n    border-radius: 10px;\n    border: 1px solid #b8b8b8;\n}\n\n#pane > div:first-child > div:first-child {\n    height: 37px;\n    background: linear-gradient(to top, #f4f4f4, #fff);\n    border-bottom: 1px solid #c4c4c4;\n}\n\n#pane > div:first-child > div:first-child > * {\n    display: inline-block;\n    font-weight: 500;\n    color: #404040;\n}\n\n#pane h1 {\n    padding: 11px;\n    font-size: 14px;\n    width: 165px;\n    text-overflow: ellipsis;\n    overflow: hidden;\n    white-space: nowrap;\n}\n\n#pane > div:first-child > div:first-child > *:last-child {\n    padding: 6px;\n    background-color: rgba(0, 0, 0, 0.24);\n    color: #fff;\n    letter-spacing: 1px;\n    border-radius: 5px;\n    margin: 7px 10px;\n    float: right;\n    text-transform: uppercase;\n    font-size: 10px;\n    font-weight: 600;\n}\n\n#pane > div:first-child > div:nth-child(2) {\n    border-bottom: 1px solid #cac7c2;\n}\n\n#pane p {\n    padding: 20px 10px;\n    font-size: 12px;\n    color: #777;\n    line-height: 15px;\n}\n\n#pane > div:first-child > div:last-child {\n    display: flex;\n    justify-content: space-around;\n    font-size: 10px;\n    color: #6a6a6a;\n    padding: 8px 0;\n}\n\n#pane > div:first-child > div:last-child span span {\n    padding: 2px 4px;\n    background-color: #ddd;\n    text-transform: uppercase;\n    font-weight: bold;\n    font-size: 8px;\n    border-radius: 2px;\n    position: relative;\n    top: -1px;\n    color: #626262;\n}\n\n#pane > div:first-child > div:last-child > span {\n    padding: 0 10px;\n}\n\n#qr {\n    position: relative;\n    width: 36px;\n}\n\n#qr:after {\n    content: '';\n    scale: .2;\n    opacity: .7;\n    width: 64px;\n    height: 64px;\n    background: url(/v.svg) no-repeat -64px 0px;\n    position: absolute;\n    left: 3px;\n    top: -26px;\n}\n\nfooter {\n    display:none;\n    padding: 50px 0 10px 0;\n    font-size: 10px;\n    letter-spacing: 1px;\n    text-transform: uppercase;\n}\n\nfooter a:hover {\n    text-decoration: underline;\n}\n\n#pane .button-menu{\n    display: grid;\n    grid-template-columns: 1fr 1fr 1fr;\n    gap: 10px;\n    padding: 0 25px 0 0 ;\n}\n\n#pane button {\n    border: 0;\n    padding: 45px 0 10px 0;\n    border-radius: 9px;\n    background-color: #fff;\n    text-transform: uppercase;\n    font-size: 9px;\n    font-weight: bold;\n    position: relative;\n    cursor: pointer;\n}\n\n#pane button:hover {\n    background-color: #eeeeee;\n}\n\n#pane button::before {\n    content: '';\n    scale: .35;\n    opacity: 1;\n    width: 64px;\n    height: 64px;\n    display: block;\n    margin: auto;\n    position: absolute;\n    top: -9px;\n    left: 4px;\n}\n\n.display-btn::before {\n    background: url(/v.svg) no-repeat -256px -64px;\n}\n\n.upload-btn::before {\n    background: url(/v.svg) no-repeat -192px 0px;\n}\n\n.select-btn::before {\n    background: url(/v.svg) no-repeat -320px 0px;\n}\n\n.tooltip {\n    min-width:100px;\n    position: absolute;\n    z-index:9999;\n    border-radius: 5px;\n    border: 1px solid #b8b8b8;\n    box-shadow: 0 2px 3px rgba(172, 172, 172, 0.17);\n    background: linear-gradient(to top, #f4f4f4, #fff);\n    padding:5px;\n\n}\n\n.pathbar_item {\n    padding: 5px 10px;\n    font-size: 12px;\n    font-weight: bold;\n}\n\n"
  },
  {
    "path": "attribution.txt",
    "content": "Ballon Model: Ekayasa.Design\nOpen Source Libraries: Check respective repositories\nSea Creature Water Color: rawpixel.com"
  },
  {
    "path": "build.rs",
    "content": "use std::env;\nuse std::fs;\nuse std::path::Path;\nuse rand::Rng;\nuse rand::distributions::Alphanumeric;\nuse std::fmt::Write;\nuse minify_js::{Session, TopLevelMode, minify};\n\nfn main() {\n    let out_dir = env::var_os(\"OUT_DIR\").unwrap();\n    let dest_path = Path::new(&out_dir).join(\"constants.rs\");\n\n    let build_id = generate_random_string(15);\n\n    let raster_sprites_filename = format!(\"/r{}.webp\", build_id);\n    let vector_sprites_filename = format!(\"/v{}.svg\", build_id);\n\n    let mut out = String::new();\n\n    let css_file = fs::read_to_string(\"assets/styles.css\").unwrap();\n    let css_file = css_file.replace(\"/r.webp\", &raster_sprites_filename);\n    let css_file = css_file.replace(\"/v.svg\", &vector_sprites_filename);\n\n    write!(out, \"pub const RASTER_SPRITES_FILENAME: &str = \\\"{raster_sprites_filename}\\\";\").unwrap();\n    write!(out, \"pub const VECTOR_SPRITES_FILENAME: &str = \\\"{vector_sprites_filename}\\\";\").unwrap();\n    write!(out, \"pub const JS_FILENAME: &str = \\\"/js{}.js\\\";\", build_id).unwrap();\n    write!(out, \"pub const CSS_FILENAME: &str = \\\"/css{}.css\\\";\", build_id).unwrap();\n\n    //write in the css file with our replaced filenames\n    write!(out, \"pub const STYLES: &[u8] = b\\\"{css_file}\\\";\").unwrap();\n\n    //minify js\n    let js_file = fs::read_to_string(\"assets/scripts.js\").unwrap();\n    let session = Session::new();\n    let mut minified = Vec::new();\n    minify(&session, TopLevelMode::Global, js_file.as_ref(), &mut minified).unwrap();\n    let js_file = String::from_utf8(Vec::from(minified.as_slice())).unwrap();\n\n    write!(out, \"pub const SCRIPTS: &[u8] = b\\\"{js_file}\\\";\").unwrap();\n\n\n    fs::write(\n        &dest_path,\n        out,\n    )\n        .unwrap();\n}\n\nfn generate_random_string(length: u16) -> String {\n    let rand_string: String = rand::thread_rng()\n        .sample_iter(&Alphanumeric)\n        .take(length.try_into().unwrap())\n        .map(char::from)\n        .collect();\n    rand_string\n}"
  },
  {
    "path": "src/lib/errors.rs",
    "content": "#[derive(Debug)]\npub enum AppErrorInternal {\n    AddrParseError(std::net::AddrParseError),\n    HyperError(hyper::Error),\n    //AcmeError(acme_micro::Error),\n    Custom(String),\n}\n\nimpl From<std::net::AddrParseError> for AppErrorInternal {\n    fn from(inner: std::net::AddrParseError) -> Self {\n        AppErrorInternal::AddrParseError(inner)\n    }\n}\n\nimpl From<hyper::Error> for AppErrorInternal {\n    fn from(inner: hyper::Error) -> Self {\n        AppErrorInternal::HyperError(inner)\n    }\n}\n\n/*\nimpl From<acme_micro::Error> for AppErrorInternal {\n    fn from(inner: acme_micro::Error) -> Self {\n        AppErrorInternal::AcmeError(inner)\n    }\n}\n\n */\n\n\nuse axum::http::{StatusCode};\nuse axum::response::{IntoResponse, Response};\nuse hyper::Body;\n\n#[derive(Debug)]\npub enum AppErrorExternal {\n    IoError(std::io::Error),\n    AskamaError(askama::Error),\n    AxumError(axum::http::Error),\n    FileNotFound,\n    PathTraversal\n}\n\nimpl IntoResponse for AppErrorExternal {\n    fn into_response(self) -> Response {\n        dbg!(&self);\n\n        let (status, error_message) = match self {\n            AppErrorExternal::IoError(ref e) if e.kind() == std::io::ErrorKind::NotFound =>\n                (StatusCode::NOT_FOUND, \"File not found\"),\n            AppErrorExternal::IoError(_) => (StatusCode::INTERNAL_SERVER_ERROR, \"Internal IO Error\"),\n            AppErrorExternal::FileNotFound => (StatusCode::NOT_FOUND, \"File not found\"),\n            AppErrorExternal::PathTraversal => (StatusCode::FORBIDDEN, \"nice try\"),\n            _ => (StatusCode::INTERNAL_SERVER_ERROR, \"INTERNAL_SERVER_ERROR\")\n        };\n\n        (status, error_message).into_response()\n    }\n}\n\nimpl From<std::io::Error> for AppErrorExternal {\n    fn from(inner: std::io::Error) -> Self {\n        AppErrorExternal::IoError(inner)\n    }\n}\n\nimpl From<askama::Error> for AppErrorExternal {\n    fn from(inner: askama::Error) -> Self {\n        AppErrorExternal::AskamaError(inner)\n    }\n}\n\nimpl From<axum::http::Error> for AppErrorExternal {\n    fn from(inner: axum::http::Error) -> Self {\n        AppErrorExternal::AxumError(inner)\n    }\n}\n\n"
  },
  {
    "path": "src/lib/fs_interaction.rs",
    "content": "use std::path::{Path, PathBuf};\nuse axum::response::Response;\nuse tokio::fs;\nuse crate::lib::errors::{AppErrorExternal};\nuse chrono::DateTime;\nuse chrono::Utc;\nuse hyper::Body;\nuse tokio::fs::File;\n\n\n#[derive(Debug)]\npub struct DirEntry {\n    pub(crate) name: String,\n    pub(crate) size: Option<u64>,\n    pub(crate) is_dir: bool,\n    pub(crate) is_symlink: bool,\n    pub(crate) last_modified: Option<u64>, // Change this line\n}\n\npub async fn list_dir_contents(dir: &Path) -> Result<Vec<DirEntry>, AppErrorExternal> {\n    let mut entries = Vec::new();\n\n    if dir.is_dir() {\n        let mut dir_entries = fs::read_dir(dir).await?;\n\n        while let Some(entry) = dir_entries.next_entry().await? {\n            let path = entry.path();\n            let metadata = fs::metadata(&path).await?;\n            let last_modified = metadata.modified()\n                .ok()\n                .and_then(|system_time| {\n                    system_time.duration_since(std::time::UNIX_EPOCH).ok()\n                        .map(|duration| duration.as_secs())\n                        .map(|secs| secs as u64)\n                });\n            entries.push(DirEntry {\n                name: String::from(path.file_name().unwrap().to_str().unwrap()),\n                size: if metadata.is_file() { Some(metadata.len()) } else { None },\n                is_dir: metadata.is_dir(),\n                is_symlink: entry.file_type().await?.is_symlink(),\n                last_modified, // Change this line\n            });\n        }\n    }\n\n    Ok(entries)\n}\n\npub async fn serve_file(path: &PathBuf) -> Result<Body, AppErrorExternal> {\n\n    let file = File::open(path).await?;\n\n    // Create a FramedRead using the BytesCodec\n    let stream = tokio_util::io::ReaderStream::new(file);\n\n    // Convert the stream into a hyper Body and return\n    Ok(Body::wrap_stream(stream))\n}"
  },
  {
    "path": "src/lib/helper.rs",
    "content": "use reqwest;\n\npub fn format_file_size_pretty(size: Option<u64>) -> Option<String> {\n    let units = vec![\"b\", \"kb\", \"mb\", \"gb\", \"tb\"];\n    let kib = 1024.0;\n\n    let bytes = match size {\n        None => return None,\n        Some(v) => v as f64\n    };\n\n    if bytes == 0.0 || bytes.is_nan() {\n        return None;\n    }\n\n    let base = f64::log(bytes, kib).floor() as usize;\n    if base >= units.len() {\n        return Some(\"Too Large\".to_string());\n    }\n\n    let adjusted_bytes = bytes / f64::powi(kib, base as i32);\n    let unit = &units[base];\n\n    if f64::round(adjusted_bytes.fract() * 10.0) == 0.0 {\n        return Some(format!(\"{} <span>{}</span>\", adjusted_bytes.floor(), unit));\n    } else {\n        let formatted_adjusted_bytes = format!(\"{:.1}\", adjusted_bytes);\n        return Some(format!(\"{} <span>{}</span>\", formatted_adjusted_bytes.trim_end_matches(\".0\"), unit));\n    }\n}\n\npub async fn get_public_ip() -> Result<String, reqwest::Error> {\n    let url = \"https://www.cloudflare.com/cdn-cgi/trace\";\n    let resp = reqwest::get(url).await?.text().await?;\n\n    let ip = resp\n        .lines()\n        .find(|line| line.starts_with(\"ip=\"))\n        .map(|line| &line[3..])\n        .unwrap_or(\"\")\n        .to_string();\n\n    Ok(ip)\n}"
  },
  {
    "path": "src/lib/parse_cli_args.rs",
    "content": "use clap::{arg, command, value_parser, ArgAction, Command};\nuse std::env;\nuse std::path::PathBuf;\nuse crate::lib::errors::AppErrorInternal;\n\npub struct Args {\n    pub path: PathBuf,\n}\n\npub fn parse_args() -> Result<Args, AppErrorInternal> {\n\n    let matches = command!()\n        .arg(\n            arg!(\n                -p --path <PATH> \"Sets a custom path to serve from\"\n            )\n                // We don't have syntax yet for optional options, so manually calling `required`\n                .required(false)\n                .value_parser(value_parser!(PathBuf)),\n        )\n        .get_matches();\n\n\n    let path = match matches.get_one::<PathBuf>(\"path\") {\n        None => env::current_dir().expect(\"Couldn't determine the current directory. The program will exit.\"),\n        Some(v) => v.clone()\n    };\n\n    let args = Args {\n        path\n    };\n\n    Ok(args)\n}"
  },
  {
    "path": "src/lib/provision_certs.rs",
    "content": "/*\n\npub async fn ssl_cert_lifecycle_manager() {\n\n    /*\n        let _ = get_dns().await;\n        return\n     */\n\n\n    //init the cache\n    crate::lib::once::set_tls_cert_cache().await;\n\n    //try downloading a suitable cert from the database to launch the application\n    println!(\"! Blocking while waiting to download or provision TLS cert.\");\n    let success = download_and_set_cert_cache().await;\n    //this panic only happens at start time, during future runtime we don't panic, just silently fail\n    if !success {\n        panic!(\"Cannot proceed: failed to get ssl cert to start application. Maybe try again.\")\n    }\n\n\n    tokio::spawn(async move {\n\n        //since we ran at the start of the program we can sleep now for a day\n        sleep(Duration::from_secs(86400)).await;\n\n        loop {\n            //try to refresh our cert from db or generate a new one. if succeed wait another day, if fail retry in 20 mins\n            match download_and_set_cert_cache().await {\n                true => sleep(Duration::from_secs(86400)).await,\n                false => sleep(Duration::from_secs(1200)).await\n            }\n        }\n    });\n\n}\n\nasync fn read_and_set_cert_cache(hostname: &str) -> bool {\n\n    let v = match atomic_read_or_write_cert(hostname).await {\n        Ok(v) => v,\n        Err(e) => {dbg!(e); return false}\n    };\n\n    //write v to oncecell\n    let mut write_guard = TLS_CERT_CACHE.get().unwrap().write().await;\n\n    *write_guard = v;\n\n    true\n}\n\nasync fn atomic_read_or_write_cert(hostname: &str) -> Result<CertRow, AppErrorInternal> {\n\n    //attempt to read cert value\n\n    // if not exists provision a new one\n\n\n    Ok(cert)\n}\n\n\n\n\nasync fn request_certificate(hostname: &str) -> Result<CertRow, AppErrorInternal> {\n    let url = DirectoryUrl::LetsEncrypt;\n\n// Create a directory entrypoint.\n    let dir = Directory::from_url(url)?;\n\n// Your contact addresses, note the `mailto:`\n    let contact = vec![];\n\n// Generate a private key and register an account with your ACME provider.\n    let acc = dir.register_account(contact.clone())?;\n\n// Order a new TLS certificate for a domain.\n    let mut ord_new = acc.new_order(hostname, &[])?;\n\n    let auths = ord_new.authorizations()?;\n\n\n    let ord_csr = loop {\n        if let Some(ord_csr) = ord_new.confirm_validations() {\n            break ord_csr;\n        }\n\n        let auths = ord_new.authorizations()?;\n\n        let challenge = auths.get(0)\n            .ok_or_else(|| Custom(\"Failed to access auths index\".to_owned()))?\n            .dns_challenge()\n            .ok_or_else(|| Custom(\"Failed to unwrap dns challenge\".to_owned()))?;\n\n        set_dns_challenge(&challenge.dns_proof()?).await?;\n        challenge.validate(Duration::from_millis(10000))?;\n\n        ord_new.refresh()?;\n    };\n\n\n    let pkey_pri = create_p384_key()?;\n\n// Submit the CSR. This causes the ACME provider to enter a\n// state of \"processing\" that must be polled until the\n// certificate is either issued or rejected. Again we poll\n// for the status change.\n    let ord_cert =\n        ord_csr.finalize_pkey(pkey_pri, Duration::from_secs(10))?;\n\n// Finally download the certificate.\n    let cert = ord_cert.download_cert()?;\n\n\n    let cert = CertRow {\n        full_chain: cert.certificate().to_owned(),\n        private_key: cert.private_key().to_owned(),\n    };\n\n\n    Ok(cert)\n}\n\nasync fn set_dns_challenge(challenge: &str) -> Result<(), AppErrorInternal> {\n\n\n\n    Ok(())\n\n}\n\n */"
  },
  {
    "path": "src/lib/request_handler.rs",
    "content": "use std::sync::Arc;\nuse axum::{Extension, extract::Path};\nuse crate::lib::errors::{AppErrorExternal};\nuse askama::Template;\nuse axum::response::{Html, IntoResponse, Response};\nuse hyper::Body;\nuse hyper::{StatusCode};\nuse crate::AppState;\nuse crate::lib::fs_interaction::{DirEntry, list_dir_contents};\nuse std::ffi::OsStr;\nuse std::time::{SystemTime, UNIX_EPOCH};\nuse bytes::Bytes;\nuse crate::lib::helper;\nuse crate::VERSION;\n\npub enum ResponseWrapper {\n    File(String),\n    Html(axum::response::Html<String>),\n}\n\nimpl IntoResponse for ResponseWrapper {\n\n    fn into_response(self) -> Response {\n        match self {\n            ResponseWrapper::File(content) => {\n                content.into_response()\n            },\n            ResponseWrapper::Html(content) => {\n                content.into_response()\n            },\n        }\n    }\n}\n\n//this is a special case for the root path \"/\" to simplify axum code\npub async fn handle_root_path(app_state: Extension<Arc<AppState>>) -> Result<ResponseWrapper, AppErrorExternal> {\n\n    Ok(ResponseWrapper::Html(Html::from(build_dir_page(&app_state.title_name, &app_state.root_path, std::path::Path::new(\"\")).await?)))\n}\n\n\npub async fn handle_path(Path(path): Path<String>, app_state: Extension<Arc<AppState>>) -> Result<ResponseWrapper, AppErrorExternal> {\n\n    let root_path = std::path::Path::new(&app_state.root_path);\n    let relative_path = std::path::Path::new(&path);\n    let canonical_root_path = root_path.canonicalize()?;\n\n    // Construct the full path\n    let full_path = root_path.join(&path);\n\n    // Canonicalize the full path, resolving any \"..\" or \".\" segments\n    let canonical_full_path = full_path.canonicalize()?;\n\n    // If the canonical full path does not start with the canonical root path,\n    // then this is a path traversal attempt, and we should not serve the file.\n    if !canonical_full_path.starts_with(&canonical_root_path) {\n        return Err(AppErrorExternal::PathTraversal);\n    }\n\n    // Here, you can be sure that canonical_full_path is within root_path.\n    if path.as_str().chars().last() == Some('/') {\n        Ok(ResponseWrapper::Html(\n            Html::from(build_dir_page(&app_state.title_name, &app_state.root_path, &relative_path).await?)\n        ))\n    } else {\n        Ok(ResponseWrapper::Html(\n            axum::response::Html(format!(\"You requested file: {}\", path))\n        ))\n    }\n}\n\npub async fn build_dir_page(title_name: &Option<String>, root_path: &std::path::Path, relative_path: &std::path::Path) -> Result<String, AppErrorExternal> {\n\n    let path = root_path.join(relative_path);\n\n    let entries = list_dir_contents(&path).await?;\n\n    build_template(title_name, &entries, relative_path).await\n}\n\n\n#[derive(Template)]\n#[template(path = \"directory.html\")]\npub struct DirectoryTemplate<'a> {\n    title: String,\n    relative_path: &'a str,\n    entries: &'a [DirEntry],\n    current_location_name: &'a str,\n    current_location_size: String,\n}\n\npub async fn build_template(title_name: &Option<String>, entries: &[DirEntry], relative_path: &std::path::Path) -> Result<String, AppErrorExternal> {\n    let title = title_name.as_deref().unwrap_or_else(|| \"SkyFolder\");\n    let folder_name = relative_path.file_name().and_then(OsStr::to_str).unwrap_or_else(|| \"Fileserver Root\");\n    let title = format!(\"{folder_name} - {title}\");\n    let current_location_name = folder_name;\n\n    let relative_path_str = relative_path.to_str().unwrap_or_else(|| \"\");\n\n    let mut size_sum = 0;\n    for entry in entries {\n        size_sum += entry.size.unwrap_or_else(|| 0);\n    }\n\n    let size_string = match helper::format_file_size_pretty(Some(size_sum)) {\n        None => \"Sizeless\".to_string(),\n        Some(v) => v\n    };\n\n    let template = DirectoryTemplate {\n        title,\n        relative_path: relative_path_str,\n        entries,\n        current_location_name,\n        current_location_size: size_string,\n    };\n\n    Ok(template.render()?)\n}\n\nimpl DirEntry {\n    pub fn display_modified_raw(&self) -> String {\n        match &self.last_modified {\n            Some(date) => date.to_string(),\n            None => \"?\".to_string(),\n        }\n    }\n    pub fn display_size_raw(&self) -> String {\n        match self.size {\n            Some(size) => size.to_string(),\n            None => \"?\".to_string(),\n        }\n    }\n    pub fn icon_picker(&self) -> &str {\n        // The `position_text` variable stores the position of the icon in the sprite sheet\n        // The coordinates are assigned based on whether the item is a directory or a file with a specific extension\n        let position_text = if self.is_dir {\n            // If the item is a directory, its icon is located at \"-128px 0px\" in the sprite sheet\n            \"-128px 0px\"\n        } else {\n            // If the item is not a directory, it's a file. We need to look at the file's extension\n            let name = &self.name.to_lowercase();\n\n            // We find the last occurrence of the '.' character in the name,\n            // and slice the string from one character after this position to the end, to get the file extension\n            match &name.rfind('.').map(|i| &name[i + 1..]) {\n                // Depending on the extension, we match the appropriate icon from the sprite sheet\n                Some(\"rs\") => \"0px -128px\",\n                Some(\"iso\") => \"-384px 0px\",\n                Some(\"json\") | Some(\"js\") => \"-512px 0px\",\n                Some(\"py\") => \"-640px 0px\",\n                Some(\"zip\") | Some(\"gz\") | Some(\"rar\") | Some(\"7z\") | Some(\"tar\") | Some(\"bz2\") | Some(\"xz\") => \"-768px 0px\",\n                Some(\"pdf\") => \"-896px 0px\",\n                Some(\"jpg\") | Some(\"jpeg\") => \"-512px -128px\",\n                Some(\"svg\")  => \"-384px -128px\",\n                Some(\"png\")  => \"-640px -128px\",\n                Some(\"gif\")  => \"-896px -128px\",\n                Some(\"ds_store\")  => \"-768px -128px\",\n                // If we can't match the extension to any of the above, we use a default icon located at \"-256px 0px\"\n                _ => \"-256px 0px\"\n            }\n        };\n\n        // Return the coordinates of the appropriate icon\n        position_text\n    }\n\n\n    pub fn format_file_size(&self) -> String {\n        match helper::format_file_size_pretty(self.size) {\n            Some(b) => b,\n            None => \"-\".to_string(),\n        }\n    }\n\n\n\n\n\n    pub fn format_time_ago(&self) -> String {\n        let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();\n        let time_difference = match self.last_modified {\n            Some(time) => current_time - time,\n            None => return \"Unknown\".to_string(),\n        };\n\n        if time_difference < 60 {\n            return \"Just now\".to_string();\n        }\n\n        let minutes = time_difference / 60;\n\n        if minutes < 60 {\n            return format!(\"{} {} ago\", minutes, if minutes == 1 { \"minute\" } else { \"minutes\" });\n        }\n\n        let hours = minutes / 60;\n\n        if hours < 24 {\n            return format!(\"{} {} ago\", hours, if hours == 1 { \"hour\" } else { \"hours\" });\n        }\n\n        let days = hours / 24;\n\n        format!(\"{} {} ago\", days, if days == 1 { \"day\" } else { \"days\" })\n    }\n\n}\n\n/*\ntrait FormatPath {\n    fn format_path(&self) -> Vec<&str>;\n}\n\nimpl FormatPath for &str {\n    fn format_path(&self) -> Vec<&str> {\n        let mut path_parts: Vec<&str> = self.split('/').collect();\n        if self.ends_with('/') {\n            path_parts.pop();\n        }\n        path_parts\n    }\n}\n */\n\n\n\n\n\n// embedding this data in the binary allows it to work without external files\nstatic RASTER_SPRITESHEET: Bytes = Bytes::from_static(include_bytes!(\"../../assets/r.webp\"));\nstatic VECTOR_SPRITESHEET: Bytes = Bytes::from_static(include_bytes!(\"../../assets/v.svg\"));\n\n\n//static SCRIPTS: Bytes = Bytes::from_static(include_bytes!(\"../../assets/scripts.js\"));\nstatic FAVICON: Bytes = Bytes::from_static(include_bytes!(\"../../assets/favicon.ico\"));\n\n//serving these files with Axum rather than dynamically templated in with Askama results in better performance and memory usage\npub async fn serve_raster_spritesheet() -> Result<impl IntoResponse, AppErrorExternal> {\n    Ok(\n        Response::builder()\n            .status(StatusCode::OK)\n            .header(hyper::header::CONTENT_TYPE, \"image/webp\")\n            .header(\"Cache-Control\", \"public, max-age=7884000\")\n            .body(Body::from(&*RASTER_SPRITESHEET))?\n    )\n}\n\npub async fn serve_vector_spritesheet() -> Result<impl IntoResponse, AppErrorExternal> {\n    Ok(\n        Response::builder()\n            .status(StatusCode::OK)\n            .header(hyper::header::CONTENT_TYPE, \"image/svg+xml\")\n            .header(\"Cache-Control\", \"public, max-age=7884000\")\n            .body(Body::from(&*VECTOR_SPRITESHEET))?\n    )\n}\n\npub async fn serve_favicon() -> Result<impl IntoResponse, AppErrorExternal> {\n    Ok(\n        Response::builder()\n            .status(StatusCode::OK)\n            .header(hyper::header::CONTENT_TYPE, \"image/x-icon\")\n            .header(\"Cache-Control\", \"public, max-age=7884000\")\n            .body(Body::from(&*FAVICON))?\n    )\n}\n\n\npub async fn serve_css() -> Result<impl IntoResponse, AppErrorExternal> {\n    Ok(\n        Response::builder()\n            .status(StatusCode::OK)\n            .header(hyper::header::CONTENT_TYPE, \"text/css\")\n            .header(\"Cache-Control\", \"public, max-age=7884000\")\n            .body(Body::from(crate::STYLES))?\n    )\n}\n\n\npub async fn serve_js() -> Result<impl IntoResponse, AppErrorExternal> {\n    Ok(\n        Response::builder()\n            .status(StatusCode::OK)\n            .header(hyper::header::CONTENT_TYPE, \"text/javascript\")\n            .header(\"Cache-Control\", \"public, max-age=7884000\")\n            .body(Body::from(crate::SCRIPTS))?\n    )\n}\n\n#[derive(Template)]\n#[template(path = \"about.html\")]\npub struct AboutTemplate<'a> {\n    version: &'a str\n}\npub async fn build_about() -> Result<Html<String>, AppErrorExternal> {\n\n    let template = AboutTemplate {\n        version: VERSION\n    };\n\n    Ok(Html::from(template.render()?))\n}\n\n//<input type=\"text\" autocomplete=\"off\">"
  },
  {
    "path": "src/lib/services.rs",
    "content": ""
  },
  {
    "path": "src/main.rs",
    "content": "#[cfg(not(target_env = \"msvc\"))]\nuse tikv_jemallocator::Jemalloc;\n\n#[cfg(not(target_env = \"msvc\"))]\n#[global_allocator]\nstatic GLOBAL: Jemalloc = Jemalloc;\n\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\nuse crate::lib::{fs_interaction, helper, parse_cli_args, request_handler};\nuse crate::lib::errors::AppErrorInternal;\nuse axum::routing::get;\nuse axum::{Extension, Server};\n\nmod lib {\n    pub(crate) mod errors;\n    pub(crate) mod fs_interaction;\n    pub(crate) mod parse_cli_args;\n    pub(crate) mod request_handler;\n    pub(crate) mod helper;\n    pub(crate) mod services;\n}\n\nconst VERSION: &str = env!(\"CARGO_PKG_VERSION\");\ninclude!(concat!(env!(\"OUT_DIR\"), \"/constants.rs\"));\n\n#[tokio::main]\nasync fn main() {\n\n    println!(\"Starting up \\x1B[95mSkyFolder\\x1B[0m {VERSION}\\n\");\n    println!(\"✅ If you need a feature or find a bug let me know in the Github issues tab.\");\n    println!(\"⭐ If you like the program please star it on Github as it helps me.\");\n\n    //start the actual application\n    if let Err(e) = init().await {\n        eprintln!(\"The program has crashed: {:?}\", e)\n    }\n\n}\n\npub struct AppState {\n    pub(crate) root_path: PathBuf,\n    pub(crate) port: u16,\n    pub(crate) title_name: Option<String> // the name the user gives to their server i.e. what is shown in page title tag\n}\n\nasync fn init() -> Result<(), AppErrorInternal> {\n\n    let app_state = {\n        let args = parse_cli_args::parse_args()?;\n        Arc::new(AppState {\n            root_path: args.path,\n            port: 30080,\n            title_name: None\n        })\n    };\n\n    println!(\"Serving path: {}\", app_state.root_path.display());\n    println!(\"Bound to [::]:{}, 0.0.0.0:{}\", app_state.port, app_state.port);\n    let ifaces = get_if_addrs::get_if_addrs().unwrap();\n\n    println!(\"Available on LAN at (non-exhaustive list):\");\n\n    for iface in ifaces {\n        match iface.addr {\n            get_if_addrs::IfAddr::V4(addr) => {\n                println!(\"    http://{}:{}\", addr.ip, &app_state.port);\n            }\n            get_if_addrs::IfAddr::V6(addr) => {\n                println!(\"    http://[{}]:{}\", addr.ip, &app_state.port);\n            }\n        }\n    }\n\n    //todo only show this if the user has upnp mode enabled. remember to set port to whatever upnp negotiates\n    println!(\"Available on WAN (Public internet) at:\");\n    println!(\"    http://{}:30080\", helper::get_public_ip().await.unwrap_or(\"Failed to determine IP\".to_string()));\n\n\n    let app = axum::Router::new()\n        .route(\"/\", get(request_handler::handle_root_path))\n        .route(\"/*path\", get(request_handler::handle_path))\n        .route(\"/about_skyfolder\", get(request_handler::build_about))\n        .layer(Extension(app_state.clone()))\n        .route(RASTER_SPRITES_FILENAME, get(request_handler::serve_raster_spritesheet))\n        .route(VECTOR_SPRITES_FILENAME, get(request_handler::serve_vector_spritesheet))\n        .route(CSS_FILENAME, get(request_handler::serve_css))\n        .route(JS_FILENAME, get(request_handler::serve_js))\n        .route(\"/favicon.ico\", get(request_handler::serve_favicon));\n\n    Server::bind(&format!(\"0.0.0.0:{}\", app_state.port).parse()?)\n        .serve(app.into_make_service())\n        .await?;\n\n    Ok(())\n}"
  },
  {
    "path": "templates/about.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>About - SkyFolder</title>\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <meta name=\"description\" content=\"A folder has been shared with you. Open now to browse.\">\n    <link rel=\"icon\" href=\"/favicon.ico\">\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"/styles.css\">\n    <meta property=\"og:title\" content=\"About - SkyFolder\"/>\n    <meta property=\"og:description\" content=\"A folder has been shared with you. Open now to browse.\"/>\n    <meta property=\"og:image\" content=\"https://raw.githubusercontent.com/mu-arch/skyfolder/master/hosted/og_image.jpg\"/>\n    <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\" />\n</head>\n\n<body>\n<style>\n    .about {\n        margin: auto;\n        text-align: center;\n    }\n\n    img {\n        max-width: 500px;\n    }\n    p {\n        padding: 10px;\n    }\n    a {\n        color: #0049ff;\n    }\n</style>\n\n<div class=\"about\">\n    <img alt=\"SkyFolder Logo\" src=\"https://raw.githubusercontent.com/mu-arch/skyfolder/master/hosted/logo.png\">\n    <p>Version: {{ VERSION }}</p>\n    <p>Source code: <a href=\"https://github.com/mu-arch/skyfolder\">[Github]</a></p>\n    <p>License: GPLv3</p>\n    <p>Crafted with love and care 💕</p>\n    <p><a href=\"/\">[Back]</a></p>\n</div>\n\n</body>\n</html>"
  },
  {
    "path": "templates/directory.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>{{ title }}</title>\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <meta name=\"description\" content=\"A folder has been shared with you. Open now to browse.\">\n    <link rel=\"icon\" href=\"/favicon.ico\">\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ crate::CSS_FILENAME }}\">\n    <meta property=\"og:title\" content=\"{{ title }}\"/>\n    <meta property=\"og:description\" content=\"A folder has been shared with you. Open now to browse.\"/>\n    <meta property=\"og:image\" content=\"https://raw.githubusercontent.com/mu-arch/skyfolder/master/hosted/og_image.jpg\"/>\n    <link rel=\"icon\" type=\"image/x-icon\" href=\"/favicon.ico\" />\n</head>\n\n<body>\n<section>\n    <nav>\n        <div title=\"Navigate up one directory.\"></div>\n        <div title=\"{{ current_location_name }}\">{{ current_location_name }}</div>\n        <div><input contenteditable=\"true\" placeholder=\"Quick search folder...\"><div></div></div>\n    </nav>\n\n\n\n\n    <table id=\"table\">\n        <thead>\n        <tr>\n            <th>Name</th>\n            <th>Modified</th>\n            <th>Size</th>\n            <th>Action</th>\n        </tr>\n        </thead>\n        <tbody id=\"b\">\n\n        {% if entries.is_empty() %}\n        <div class=\"folder-empty\">\n            <div></div>\n            <span>This folder is empty.</span>\n        </div>\n        {% else %}\n        {% for entry in entries %}\n        <tr><td><div style=\"background-position: {{ entry.icon_picker() | safe}}\"></div><a href=\"{{ entry.name }}{% if entry.is_dir %}/{% endif %}\">{{ entry.name }}{% if entry.is_dir %}/{% endif %}</a></td>\n            <td aria-modified=\"{{ entry.display_modified_raw() | safe}}\">{{ entry.format_time_ago() | safe }}</td>\n            <td aria-size=\"{{ entry.display_size_raw() | safe }}\">{{ entry.format_file_size() | safe }}</td></tr>\n        {% endfor %}\n        {% endif %}\n\n        </tbody>\n    </table>\n    <footer><a href=\"/about_skyfolder\">SkyFolder</a></footer>\n\n</section>\n\n<div id=\"pane\">\n    <div>\n        <div><h1>{{ current_location_name }}</h1><span>Dir</span></div>\n        <div>\n            <p>No description.</p>\n        </div>\n        <div><span id=\"fc\"></span>|<span id=\"fsz\">{{ current_location_size|safe }}</span>|<span id=\"qr\">QR</span></div>\n    </div>\n\n    <div class=\"button-menu\">\n    <button class=\"display-btn\">View Mode</button>\n    <button class=\"select-btn\">Select</button>\n    <button class=\"upload-btn\">Upload</button>\n    </div>\n\n</div>\n\n</body>\n</html>\n\n<script src=\"{{ crate::JS_FILENAME }}\"></script>"
  }
]