Full Code of mu-arch/skyfolder for AI

master 8b850699740f cached
22 files
86.8 KB
21.9k tokens
56 symbols
1 requests
Download .txt
Repository: mu-arch/skyfolder
Branch: master
Commit: 8b850699740f
Files: 22
Total size: 86.8 KB

Directory structure:
gitextract__hbgz72c/

├── .gitignore
├── Cargo.toml
├── LICENSE
├── README.md
├── askama.toml
├── assets/
│   ├── raster_spritesheet.pxd
│   ├── scripts.js
│   ├── styles.css
│   └── vector_spritesheet.pxd
├── attribution.txt
├── build.rs
├── hosted/
│   └── spritesheet.pxd
├── src/
│   ├── lib/
│   │   ├── errors.rs
│   │   ├── fs_interaction.rs
│   │   ├── helper.rs
│   │   ├── parse_cli_args.rs
│   │   ├── provision_certs.rs
│   │   ├── request_handler.rs
│   │   └── services.rs
│   └── main.rs
└── templates/
    ├── about.html
    └── directory.html

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
/target
.idea/
OUT_DIR/

================================================
FILE: Cargo.toml
================================================
[package]
name = "skyfolder"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0"
description = "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."

build = "build.rs"

[build-dependencies]
rand = "0.8.5"
minify-js = "0.5.6"

[dependencies]
tokio = { version = "1.30.0", features = ["macros","rt-multi-thread", "signal", "sync", "full"] }
tikv-jemallocator = "0.5"

axum = { version = "0.6.19", features = ["macros"]}
askama = "0.12.0"
hyper = "0.14.26"
tower = "0.4.13"
tower-http = "0.4.0"
tower-layer = "0.3.2"
tokio-util = {version = "0.7.1", features = ["io"]}
#rustls-acme = "0.7.3"

reqwest = "0.11.18"


clap = { version = "4.3.0", features = ["cargo"]}
get_if_addrs = "0.5.3"
chrono = "0.4"
bytes = "1.4.0"
#smartstring = "1.0.1" eventually use this

[profile.release]
#debug = 1
#debuginfo-level = 1
lto = true
codegen-units = 1
panic = "abort"
debug-assertions=false
opt-level=3

================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
<p align="center">
  <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">
</p>

# Skyfolder - turn any device into a file-server accessible on the web

**It's like your own personal Google Drive!**

Skyfolder 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.

No need to install anything. SkyFolder is a single portable executable file. [Take me to the download link!](#how-to-install)

Skyfolder Discord: https://discord.gg/VBMe2rcYb6

### Screenshot:

![Screenshot](screenshot.png)

### Priorities:
1. Secure
2. Auto-resume and complete transfers even in bad network conditions, broken pipes, dropped connections
3. Braindead simple

### Features:

1. Downloads & uploads (Both pausable/resumable).
2. Create, Delete, Rename directories.
3. Sort the list by multiple parameters.
4. Access Control Lists (ACL) for managing permissions on a per folder/user basis.
5. Portable - requires no installation or management of program files; everything is packaged in a single executable file.
6. No third party services or data collection. Runs completely on your system.
7. Multiple views: list view, icon view.
8. In-browser file-viewer and streamer.
9. Built in real-time search engine with fuzzy finding.
10. Low resource footprint (~10mb DRAM, files are streamed off disk in small chunks) suitable to run 24/7.
11. Static generator option: pre-compile folders and files to be stored on a CDN (not compatible with permission system)
12. Compatible with GNU/Linux, BSD, Windows, and Mac.
13. Supports TLS certificates, including a built-in automatic Let's Encrypt client that can renew certs with no user interaction.
14. Stable to run indefinitely without needing a restart.
15. Secure to expose to the open internet.
16. Management GUI that generates [Gura](https://github.com/gura-conf/gura) markup in the background (manual Gura editing is also an option).
17. Multiple download methods: HTTP GET, HTTP JS managed File System Access API, Bittorrent magnet.
18. Efficiently utilizes all CPU cores and available bandwidth across thousands of active downloaders.
19. Supports partial files (content-range) and retries.
20. Generates thumbnails for images and videos.
21. Supports directories with tens of thousands of files.
22. Produces the correct headers for streaming video to VRChat movie theater worlds ;)
23. Communicates with routers to automatically open WAN ports (UPNP)
24. QR code generation

### Roadmap

1. Bittorrent tracker and seeding client, so you can download files via your favorite client and seed to others
2. OS toast notification when someone downloads a file from you

### Help needed:

1. Mobile version
2. Dark mode
3. General testing
4. Penetration Testing
5. Unit tests
6. Implementing Bittorrent
7. Polish and improve UI, more clever thoughtfulness towards the UI is always desired
8. Your feedback (there's no such thing as a stupid/trite question/comment here)
9. Test if it works on a 32bit computer
10. Support embedded computers

### How to install:

It's not complete as of Sep 2, 2023. Expect updates soon.

## Security notice

1. 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.

2. Skyfolder has not yet been penetration tested.

3. Bittorrent Magnet links can be shared freely and used by anyone, so keep that in mind.

4. 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.

## Limitations

1. Some functionality requires Javascript to work

================================================
FILE: askama.toml
================================================
[general]
# Directories to search for templates, relative to the crate root.
dirs = ["templates"]
# Unless you add a `-` in a block, whitespace characters won't be trimmed.
whitespace = "suppress"

================================================
FILE: assets/scripts.js
================================================
'use strict';

let GLOBAL_TABLE_DATA;

function navurl(url) {
    window.location.href = url;
}

function qs(divs) {
    return document.querySelector(divs)
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

function check_if_tbody_is_empty() {
    const table = document.querySelector('#table');
    const tbody = table.querySelector('tbody');

    if (tbody.children.length === 0) {
        table.querySelector('thead tr:last-child').style = 'border-bottom: 1px solid #e5e5e5';
    }
}
function extractTableData() {
    const tbody = document.querySelector('tbody');  // get the tbody element
    const rows = tbody.querySelectorAll('tr'); // get all 'tr' elements within the tbody

    // Map each 'tr' to an array and return the result
    return Array.from(rows).map((row, index) => {
        const aTag = row.querySelector('a');  // get the 'a' tag within the current 'tr'
        return [aTag.innerText.toLowerCase(), index]; // return the array for the current 'tr', and we lowercase the inner text ready to search
    });
}

function workerSearch() {
    self.onmessage = function(event) {
        const { query, rowMatrix } = event.data;

        function fuzzysearch(needle, haystack) {
            var hlen = haystack.length;
            var nlen = needle.length;
            if (nlen > hlen) {
                return false;
            }
            if (nlen === hlen) {
                return haystack.startsWith(needle);
            }
            outer: for (var i = 0, j = 0; i < nlen; i++) {
                var nch = needle.charCodeAt(i);
                while (j < hlen) {
                    if (haystack.charCodeAt(j++) === nch) {
                        continue outer;
                    }
                }
                return false;
            }
            return true;
        }

        const matches = rowMatrix
            .map((row, index) => ({
                index: row[1],
                match: fuzzysearch(query, row[0]),
                // Save the relevance score
                relevance: row[0].includes(query) ? 0 : 1
            }))
            .filter(m => m.match !== false)
            .sort((a, b) => a.relevance - b.relevance) // Lower scores first
            .map(m => m.index);

        self.postMessage(matches);
    };
}

function marshall_search(query, rowMatrix) {
    return new Promise((resolve, reject) => {
        let workerCode = workerSearch.toString();
        workerCode = workerCode.slice(workerCode.indexOf("{") + 1, workerCode.lastIndexOf("}"));

        const workerBlob = new Blob([workerCode], { type: "text/javascript" });
        const workerURL = URL.createObjectURL(workerBlob);

        const worker = new Worker(workerURL);
        worker.onmessage = function(event) {
            resolve(event.data);
        };
        worker.onerror = function(error) {
            reject(error);
        };
        worker.postMessage({ query, rowMatrix });
    });
}






function displaySearchResults(indexes, searchTerm, limit = Infinity) {
    requestAnimationFrame(() => {
        const tbody = document.getElementById('b');
        tbody.style.display = 'none';

        const oldB2 = document.getElementById('b2');
        if (oldB2) {
            oldB2.remove();
        }

        const b2 = document.createElement('tbody');
        b2.id = 'b2';

        const limitedIndexes = indexes.slice(0, limit);

        const fragment = document.createDocumentFragment();

        for (const index of limitedIndexes) {
            const row = tbody.rows[index];
            const clonedRow = row.cloneNode(true);
            const aTag = clonedRow.querySelector('td:first-child a');
            if (aTag) {
                const textContent = aTag.innerHTML;
                const searchTermRegExp = new RegExp(`(${searchTerm})`, 'ig'); // 'i' makes it case-insensitive, 'g' is for global search
                const newTextContent = textContent.replace(searchTermRegExp, function(match) {
                    return `<span>${match}</span>`;
                });
                aTag.innerHTML = newTextContent;
            }
            fragment.appendChild(clonedRow);
        }

        b2.appendChild(fragment);

        // Add omitted results caption
        const omittedResults = indexes.length - limitedIndexes.length;
        const omittedRows = GLOBAL_TABLE_DATA.length - limitedIndexes.length;
        const resultsCaption = document.createElement('caption');
        resultsCaption.title = "Click to show all omitted matches.";
        if (omittedResults > 0) {
            resultsCaption.innerHTML = `<span><b>${omittedResults}</b> omitted matches</span> <div>-</div> <b>${omittedRows}</b> total rows excluded.`;
        } else {
            resultsCaption.innerHTML = `<b>${omittedResults}</b> omitted matches <div>-</div> <b>${omittedRows}</b> total rows excluded`;
        }

        resultsCaption.addEventListener('click', () => {
            search(searchTerm, Infinity)
        });

        b2.appendChild(resultsCaption);

        tbody.parentNode.insertBefore(b2, tbody.nextSibling);
    });
}


function cleanupSearchResults() {
    // get the original tbody
    const tbody = document.getElementById('b');
    // set the original tbody to display block (or '' to revert to default CSS value)
    tbody.style.display = '';

    // get b2
    const oldB2 = document.getElementById('b2');
    // if b2 exists, delete it
    if (oldB2) {
        oldB2.remove();
    }
}



function search(query, resultLimit) {
    marshall_search(query, GLOBAL_TABLE_DATA)
        .then(results => {
            displaySearchResults(results, query.toLowerCase(), resultLimit)
        });
}

var handleSearchInput = (function() {
    var debouncedSearch = debounce(search, 100);

    return function(event) {
        var val = event.target.value;
        if (val === "") {
            cleanupSearchResults();
        } else {
            if (GLOBAL_TABLE_DATA.length > 200) {
                debouncedSearch(val, 50);
            } else {
                search(val, 50);
            }
        }
    };
})();



//onmouseover="preloadNextPage(this)"

/*function preloadNextPage(element) {
    const anchorElement = element.querySelector('a');
    const linkHref = anchorElement.href;

    if (anchorElement && anchorElement.rel !== 'preload') {
        if (linkHref.endsWith('/') && !anchorElement.hasAttribute('data-preload')) {
            fetch(linkHref, { method: 'GET' }); // Preload the resource
            anchorElement.setAttribute('data-preload', 'true');
        }
    }
}
*/

function navigateToParentDirectory() {
    let currentURL = window.location.href;

    // Remove trailing slashes
    while (currentURL.endsWith('/')) {
        currentURL = currentURL.slice(0, -1);
    }

    const lastSlashIndex = currentURL.lastIndexOf('/');

    if (lastSlashIndex <= currentURL.indexOf('://') + 2) {
        return;
    }

    const parentURL = currentURL.substring(0, lastSlashIndex);

    window.location.href = parentURL + '/';
}

function extractPaths(url) {
    const parsedUrl = new URL(url);
     // filter(Boolean) removes any empty strings
    return parsedUrl.pathname.split('/').filter(Boolean);
}

function spawnTooltip(source, templateFn) {
    // Check if a tooltip already exists
    let tooltip = document.querySelector('.tooltip');

    // If tooltip doesn't exist, create it
    if (!tooltip) {
        tooltip = document.createElement('div');
        tooltip.classList.add('tooltip');
        document.body.appendChild(tooltip);
    }

    // Update its content
    tooltip.innerHTML = templateFn();

    source = source.getBoundingClientRect();

    tooltip.style.left = source.left -3 + 'px';
    tooltip.style.top = source.top -3 + 'px';

    document.body.appendChild(tooltip);


}

function path_selector_generator() {
    let output = "";
    let paths = extractPaths(window.location.href)

    let left_padding = 20;
    output += `<div class='pathbar_item'>FileSystem Root</div>`

    paths.forEach(path => {
        console.log(path);
        output += `<div class='pathbar_item' style='padding-left:${left_padding}px'>${path}</div>`
        left_padding += 10;
    });

    return output
}



//manifests run at pageload
function file_dir_manifest() {
    check_if_tbody_is_empty()
    GLOBAL_TABLE_DATA = extractTableData();
    qs('nav input').addEventListener('input', handleSearchInput);
    document.getElementById("fc").innerText = `${GLOBAL_TABLE_DATA.length} files`;
    qs('nav > div').addEventListener('click', navigateToParentDirectory);

    //tooltip for pathbar
    let path_selector = document.querySelector('nav div:nth-child(2)');
    path_selector.addEventListener('click', () => spawnTooltip(path_selector, path_selector_generator));

}

document.addEventListener('DOMContentLoaded', file_dir_manifest);

================================================
FILE: assets/styles.css
================================================
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}

article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

input:focus {
    outline: none;
}

a {
    color: inherit;
    text-decoration: none;
}

html {
    background-color: #fff;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
}

section {
    padding: 20px 40px;
    width: calc(100% - 350px);
}

nav {
    display: flex;
    justify-content: flex-start;
    margin: 5px 0 15px 0;
}

nav > * {
    border: 1px solid #b8b8b8;
    box-shadow: 0 2px 3px rgba(172, 172, 172, 0.17);
    border-radius: 10px;
    background: linear-gradient(to top, #f4f4f4, #fff);
    height: 35px;
    user-select: none;
    margin-right: 20px;
    cursor:pointer;
    font-size: 14px;
    font-weight: bold;
    line-height: 35px;
    padding: 0 15px;
    position: relative;
    overflow: hidden;
}

nav > *:hover {
    border: 1px solid #3478F6;
    background: linear-gradient(to top, #e7e9ef, #f0f3f8);
}


nav > div:first-child {
    border-radius: 10px 0px 0px 10px;
    padding-right: 23px;
    margin-right: 0;
    z-index: 100;
}

nav > div:first-child:before {
    content: '';
    scale: .3;
    opacity: .7;
    width: 64px;
    height: 64px;
    background: url(/v.svg) no-repeat -128px 0px;
    transform-origin: top left;
    position: absolute;
    left: 10px;
    top: 8px;
}

nav > div:nth-child(2) {
    padding-left: 40px;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border-radius: 0px 10px 10px 0px;
    border-left: 1px solid transparent;
    position: relative;
    left:-1px;
}
nav > div:nth-child(2):hover {
    z-index: 1000;
    border-left: 1px solid #3478F6;
}

nav > div:nth-child(2):before {
    content: '';
    scale: .3;
    opacity: .7;
    width: 64px;
    height: 64px;
    background: url(/v.svg) no-repeat -64px -64px;
    transform-origin: top left;
    position: absolute;
    left: 11px;
    top: 8px;
}

nav > div:nth-child(2) span {
    font-weight: 300;
    padding: 0 0 0 8px;
    color: #6c6c6c;
}

nav > div:nth-child(3) {
    flex: 1;
    margin-right: 0;
    padding: 0;
}

nav > div:nth-child(3):before {
    content: '';
    scale: .3;
    width: 64px;
    height: 64px;
    background: url(/v.svg) no-repeat 0px 0px;
    transform-origin: top left;
    position: absolute;
    left: 11px;
    top: 8px;
}

nav > div:nth-child(3) > div {
    height: 17px;
    width: 35px;
    background-color: #356eff;
    position: absolute;
    border-radius: 5px;
    right: 13px;
    top: 9px;
}

nav > div:nth-child(3) > div:nth-child(2):before {
    content: 'ADV \xE2\x86\x92';
    color: #fff;
    position: absolute;
    left: 7px;
    top: -9px;
    font-size: 6px;
}

nav > div:nth-child(3) > div:nth-child(2):after {
    content: '';
    scale: .1;
    filter: invert();
    width: 64px;
    height: 64px;
    background: url(/r.webp) no-repeat -64px -256px;
    position: absolute;
    left: -5px;
    top: -23px;
    rotate: 270deg;
}

nav input {
    width: 100%;
    background: none;
    border: none;
    font-weight: bold;
    height: 34px;
    padding-left: 43px;
    font-size: 13px;
}




table {
    width: 100%;
    table-layout: fixed;
}

thead, tbody {
    display: contents;
}

tr {
    display: grid;
    grid-template-columns: 3fr 1fr 1fr;
    border-bottom: 1px solid #e5e5e5;
    font-size: 14px;
    position: relative;
}

th, td {
    text-align: left;
    color: #6c6c6c;
}

th {
    padding: 15px 0;
    text-transform: uppercase;
    font-weight: 700;
    font-size: 10px;
    letter-spacing: 1px;
}

th:last-child {
    position: absolute;
    right: 0;
}

td {
    padding: 22px 0;
}

td:nth-child(3) span {
    padding: 2px 4px;
    background-color: #f2f1f0;
    text-transform: uppercase;
    font-weight: bold;
    font-size: 10px;
    border-radius: 2px;
    position: relative;
    top: -1px;
}

td:nth-child(1) {
    position: relative;
    color: #000;
    cursor: pointer;
    overflow: hidden;
    user-select: none;
}


td:nth-child(1) a {
    font-weight: bold;
    overflow: hidden;
    white-space: nowrap;
    margin-left: 50px;
    max-width: calc(100% - 60px);
    line-height: 1em;
}

td:nth-child(1) a span {
    background-color: yellow;
}

td:nth-child(1)::after {
    content: '';
    position: absolute;
    right: 0;
    width: 15%;
    height: 100%;
    background: linear-gradient(to right, rgba(255,255,255,0), rgba(255,255,255,1));
    pointer-events: none;
}

td:nth-child(1):hover a {
    text-decoration: underline;
}

td:nth-child(1) div {
    display: inline-block;
    background: url('/r.webp') -256px 0px;
    scale:.25;
    width: 128px;
    height: 128px;
    transform-origin: top left;
    position: absolute;
    top: 13px;
}

tbody tr::after {
    content: '';
    background: url('/v.svg') 0px -64px;
    scale: .23;
    opacity:.4;
    width: 64px;  /* width of your icon */
    height: 64px;  /* height of your icon */
    position: absolute;
    right: -15px;  /* Adjust this value to position your icon on the right */
    top: -2px;
}

table tr:last-of-type {
    border-bottom: 0;
}

caption {
    caption-side: bottom;
    text-align: center;
    margin: 20px;
    font-size: 14px;
    background: #f2f2f2;
    padding: 12px 20px;
    border-radius: 5px;
    cursor: pointer;
    user-select:none;
}

caption b {
    font-weight: bold;
}

caption:hover {
    background: #e8e8e8;
}

caption:active {
    background: #eeeeee;
}
caption div {
    padding: 0 10px;
    display: inline-block;
}

caption span {
    color: #3478F6;
}

.folder-empty {
    position: absolute;
    top: 200px;
    left: calc(50% - 260px);
    width: 250px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.folder-empty div {
    background: url('/r.webp') -128px -128px;
    scale: .5;
    width: 256px;
    height: 128px;
    transform-origin: center;
}

.folder-empty span {
    text-align: center;
    opacity: .5;
}


#pane {
    position: fixed;
    top: 0;
    right: 0;
    min-height: 100vh;
    width: 270px;
}

#pane > div:first-child {
    margin: 25px 0;
    background-color: #fbfbfb;
    width: 90%;
    overflow: hidden;
    border-radius: 10px;
    border: 1px solid #b8b8b8;
}

#pane > div:first-child > div:first-child {
    height: 37px;
    background: linear-gradient(to top, #f4f4f4, #fff);
    border-bottom: 1px solid #c4c4c4;
}

#pane > div:first-child > div:first-child > * {
    display: inline-block;
    font-weight: 500;
    color: #404040;
}

#pane h1 {
    padding: 11px;
    font-size: 14px;
    width: 165px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

#pane > div:first-child > div:first-child > *:last-child {
    padding: 6px;
    background-color: rgba(0, 0, 0, 0.24);
    color: #fff;
    letter-spacing: 1px;
    border-radius: 5px;
    margin: 7px 10px;
    float: right;
    text-transform: uppercase;
    font-size: 10px;
    font-weight: 600;
}

#pane > div:first-child > div:nth-child(2) {
    border-bottom: 1px solid #cac7c2;
}

#pane p {
    padding: 20px 10px;
    font-size: 12px;
    color: #777;
    line-height: 15px;
}

#pane > div:first-child > div:last-child {
    display: flex;
    justify-content: space-around;
    font-size: 10px;
    color: #6a6a6a;
    padding: 8px 0;
}

#pane > div:first-child > div:last-child span span {
    padding: 2px 4px;
    background-color: #ddd;
    text-transform: uppercase;
    font-weight: bold;
    font-size: 8px;
    border-radius: 2px;
    position: relative;
    top: -1px;
    color: #626262;
}

#pane > div:first-child > div:last-child > span {
    padding: 0 10px;
}

#qr {
    position: relative;
    width: 36px;
}

#qr:after {
    content: '';
    scale: .2;
    opacity: .7;
    width: 64px;
    height: 64px;
    background: url(/v.svg) no-repeat -64px 0px;
    position: absolute;
    left: 3px;
    top: -26px;
}

footer {
    display:none;
    padding: 50px 0 10px 0;
    font-size: 10px;
    letter-spacing: 1px;
    text-transform: uppercase;
}

footer a:hover {
    text-decoration: underline;
}

#pane .button-menu{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 10px;
    padding: 0 25px 0 0 ;
}

#pane button {
    border: 0;
    padding: 45px 0 10px 0;
    border-radius: 9px;
    background-color: #fff;
    text-transform: uppercase;
    font-size: 9px;
    font-weight: bold;
    position: relative;
    cursor: pointer;
}

#pane button:hover {
    background-color: #eeeeee;
}

#pane button::before {
    content: '';
    scale: .35;
    opacity: 1;
    width: 64px;
    height: 64px;
    display: block;
    margin: auto;
    position: absolute;
    top: -9px;
    left: 4px;
}

.display-btn::before {
    background: url(/v.svg) no-repeat -256px -64px;
}

.upload-btn::before {
    background: url(/v.svg) no-repeat -192px 0px;
}

.select-btn::before {
    background: url(/v.svg) no-repeat -320px 0px;
}

.tooltip {
    min-width:100px;
    position: absolute;
    z-index:9999;
    border-radius: 5px;
    border: 1px solid #b8b8b8;
    box-shadow: 0 2px 3px rgba(172, 172, 172, 0.17);
    background: linear-gradient(to top, #f4f4f4, #fff);
    padding:5px;

}

.pathbar_item {
    padding: 5px 10px;
    font-size: 12px;
    font-weight: bold;
}



================================================
FILE: attribution.txt
================================================
Ballon Model: Ekayasa.Design
Open Source Libraries: Check respective repositories
Sea Creature Water Color: rawpixel.com

================================================
FILE: build.rs
================================================
use std::env;
use std::fs;
use std::path::Path;
use rand::Rng;
use rand::distributions::Alphanumeric;
use std::fmt::Write;
use minify_js::{Session, TopLevelMode, minify};

fn main() {
    let out_dir = env::var_os("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("constants.rs");

    let build_id = generate_random_string(15);

    let raster_sprites_filename = format!("/r{}.webp", build_id);
    let vector_sprites_filename = format!("/v{}.svg", build_id);

    let mut out = String::new();

    let css_file = fs::read_to_string("assets/styles.css").unwrap();
    let css_file = css_file.replace("/r.webp", &raster_sprites_filename);
    let css_file = css_file.replace("/v.svg", &vector_sprites_filename);

    write!(out, "pub const RASTER_SPRITES_FILENAME: &str = \"{raster_sprites_filename}\";").unwrap();
    write!(out, "pub const VECTOR_SPRITES_FILENAME: &str = \"{vector_sprites_filename}\";").unwrap();
    write!(out, "pub const JS_FILENAME: &str = \"/js{}.js\";", build_id).unwrap();
    write!(out, "pub const CSS_FILENAME: &str = \"/css{}.css\";", build_id).unwrap();

    //write in the css file with our replaced filenames
    write!(out, "pub const STYLES: &[u8] = b\"{css_file}\";").unwrap();

    //minify js
    let js_file = fs::read_to_string("assets/scripts.js").unwrap();
    let session = Session::new();
    let mut minified = Vec::new();
    minify(&session, TopLevelMode::Global, js_file.as_ref(), &mut minified).unwrap();
    let js_file = String::from_utf8(Vec::from(minified.as_slice())).unwrap();

    write!(out, "pub const SCRIPTS: &[u8] = b\"{js_file}\";").unwrap();


    fs::write(
        &dest_path,
        out,
    )
        .unwrap();
}

fn generate_random_string(length: u16) -> String {
    let rand_string: String = rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(length.try_into().unwrap())
        .map(char::from)
        .collect();
    rand_string
}

================================================
FILE: src/lib/errors.rs
================================================
#[derive(Debug)]
pub enum AppErrorInternal {
    AddrParseError(std::net::AddrParseError),
    HyperError(hyper::Error),
    //AcmeError(acme_micro::Error),
    Custom(String),
}

impl From<std::net::AddrParseError> for AppErrorInternal {
    fn from(inner: std::net::AddrParseError) -> Self {
        AppErrorInternal::AddrParseError(inner)
    }
}

impl From<hyper::Error> for AppErrorInternal {
    fn from(inner: hyper::Error) -> Self {
        AppErrorInternal::HyperError(inner)
    }
}

/*
impl From<acme_micro::Error> for AppErrorInternal {
    fn from(inner: acme_micro::Error) -> Self {
        AppErrorInternal::AcmeError(inner)
    }
}

 */


use axum::http::{StatusCode};
use axum::response::{IntoResponse, Response};
use hyper::Body;

#[derive(Debug)]
pub enum AppErrorExternal {
    IoError(std::io::Error),
    AskamaError(askama::Error),
    AxumError(axum::http::Error),
    FileNotFound,
    PathTraversal
}

impl IntoResponse for AppErrorExternal {
    fn into_response(self) -> Response {
        dbg!(&self);

        let (status, error_message) = match self {
            AppErrorExternal::IoError(ref e) if e.kind() == std::io::ErrorKind::NotFound =>
                (StatusCode::NOT_FOUND, "File not found"),
            AppErrorExternal::IoError(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Internal IO Error"),
            AppErrorExternal::FileNotFound => (StatusCode::NOT_FOUND, "File not found"),
            AppErrorExternal::PathTraversal => (StatusCode::FORBIDDEN, "nice try"),
            _ => (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR")
        };

        (status, error_message).into_response()
    }
}

impl From<std::io::Error> for AppErrorExternal {
    fn from(inner: std::io::Error) -> Self {
        AppErrorExternal::IoError(inner)
    }
}

impl From<askama::Error> for AppErrorExternal {
    fn from(inner: askama::Error) -> Self {
        AppErrorExternal::AskamaError(inner)
    }
}

impl From<axum::http::Error> for AppErrorExternal {
    fn from(inner: axum::http::Error) -> Self {
        AppErrorExternal::AxumError(inner)
    }
}



================================================
FILE: src/lib/fs_interaction.rs
================================================
use std::path::{Path, PathBuf};
use axum::response::Response;
use tokio::fs;
use crate::lib::errors::{AppErrorExternal};
use chrono::DateTime;
use chrono::Utc;
use hyper::Body;
use tokio::fs::File;


#[derive(Debug)]
pub struct DirEntry {
    pub(crate) name: String,
    pub(crate) size: Option<u64>,
    pub(crate) is_dir: bool,
    pub(crate) is_symlink: bool,
    pub(crate) last_modified: Option<u64>, // Change this line
}

pub async fn list_dir_contents(dir: &Path) -> Result<Vec<DirEntry>, AppErrorExternal> {
    let mut entries = Vec::new();

    if dir.is_dir() {
        let mut dir_entries = fs::read_dir(dir).await?;

        while let Some(entry) = dir_entries.next_entry().await? {
            let path = entry.path();
            let metadata = fs::metadata(&path).await?;
            let last_modified = metadata.modified()
                .ok()
                .and_then(|system_time| {
                    system_time.duration_since(std::time::UNIX_EPOCH).ok()
                        .map(|duration| duration.as_secs())
                        .map(|secs| secs as u64)
                });
            entries.push(DirEntry {
                name: String::from(path.file_name().unwrap().to_str().unwrap()),
                size: if metadata.is_file() { Some(metadata.len()) } else { None },
                is_dir: metadata.is_dir(),
                is_symlink: entry.file_type().await?.is_symlink(),
                last_modified, // Change this line
            });
        }
    }

    Ok(entries)
}

pub async fn serve_file(path: &PathBuf) -> Result<Body, AppErrorExternal> {

    let file = File::open(path).await?;

    // Create a FramedRead using the BytesCodec
    let stream = tokio_util::io::ReaderStream::new(file);

    // Convert the stream into a hyper Body and return
    Ok(Body::wrap_stream(stream))
}

================================================
FILE: src/lib/helper.rs
================================================
use reqwest;

pub fn format_file_size_pretty(size: Option<u64>) -> Option<String> {
    let units = vec!["b", "kb", "mb", "gb", "tb"];
    let kib = 1024.0;

    let bytes = match size {
        None => return None,
        Some(v) => v as f64
    };

    if bytes == 0.0 || bytes.is_nan() {
        return None;
    }

    let base = f64::log(bytes, kib).floor() as usize;
    if base >= units.len() {
        return Some("Too Large".to_string());
    }

    let adjusted_bytes = bytes / f64::powi(kib, base as i32);
    let unit = &units[base];

    if f64::round(adjusted_bytes.fract() * 10.0) == 0.0 {
        return Some(format!("{} <span>{}</span>", adjusted_bytes.floor(), unit));
    } else {
        let formatted_adjusted_bytes = format!("{:.1}", adjusted_bytes);
        return Some(format!("{} <span>{}</span>", formatted_adjusted_bytes.trim_end_matches(".0"), unit));
    }
}

pub async fn get_public_ip() -> Result<String, reqwest::Error> {
    let url = "https://www.cloudflare.com/cdn-cgi/trace";
    let resp = reqwest::get(url).await?.text().await?;

    let ip = resp
        .lines()
        .find(|line| line.starts_with("ip="))
        .map(|line| &line[3..])
        .unwrap_or("")
        .to_string();

    Ok(ip)
}

================================================
FILE: src/lib/parse_cli_args.rs
================================================
use clap::{arg, command, value_parser, ArgAction, Command};
use std::env;
use std::path::PathBuf;
use crate::lib::errors::AppErrorInternal;

pub struct Args {
    pub path: PathBuf,
}

pub fn parse_args() -> Result<Args, AppErrorInternal> {

    let matches = command!()
        .arg(
            arg!(
                -p --path <PATH> "Sets a custom path to serve from"
            )
                // We don't have syntax yet for optional options, so manually calling `required`
                .required(false)
                .value_parser(value_parser!(PathBuf)),
        )
        .get_matches();


    let path = match matches.get_one::<PathBuf>("path") {
        None => env::current_dir().expect("Couldn't determine the current directory. The program will exit."),
        Some(v) => v.clone()
    };

    let args = Args {
        path
    };

    Ok(args)
}

================================================
FILE: src/lib/provision_certs.rs
================================================
/*

pub async fn ssl_cert_lifecycle_manager() {

    /*
        let _ = get_dns().await;
        return
     */


    //init the cache
    crate::lib::once::set_tls_cert_cache().await;

    //try downloading a suitable cert from the database to launch the application
    println!("! Blocking while waiting to download or provision TLS cert.");
    let success = download_and_set_cert_cache().await;
    //this panic only happens at start time, during future runtime we don't panic, just silently fail
    if !success {
        panic!("Cannot proceed: failed to get ssl cert to start application. Maybe try again.")
    }


    tokio::spawn(async move {

        //since we ran at the start of the program we can sleep now for a day
        sleep(Duration::from_secs(86400)).await;

        loop {
            //try to refresh our cert from db or generate a new one. if succeed wait another day, if fail retry in 20 mins
            match download_and_set_cert_cache().await {
                true => sleep(Duration::from_secs(86400)).await,
                false => sleep(Duration::from_secs(1200)).await
            }
        }
    });

}

async fn read_and_set_cert_cache(hostname: &str) -> bool {

    let v = match atomic_read_or_write_cert(hostname).await {
        Ok(v) => v,
        Err(e) => {dbg!(e); return false}
    };

    //write v to oncecell
    let mut write_guard = TLS_CERT_CACHE.get().unwrap().write().await;

    *write_guard = v;

    true
}

async fn atomic_read_or_write_cert(hostname: &str) -> Result<CertRow, AppErrorInternal> {

    //attempt to read cert value

    // if not exists provision a new one


    Ok(cert)
}




async fn request_certificate(hostname: &str) -> Result<CertRow, AppErrorInternal> {
    let url = DirectoryUrl::LetsEncrypt;

// Create a directory entrypoint.
    let dir = Directory::from_url(url)?;

// Your contact addresses, note the `mailto:`
    let contact = vec![];

// Generate a private key and register an account with your ACME provider.
    let acc = dir.register_account(contact.clone())?;

// Order a new TLS certificate for a domain.
    let mut ord_new = acc.new_order(hostname, &[])?;

    let auths = ord_new.authorizations()?;


    let ord_csr = loop {
        if let Some(ord_csr) = ord_new.confirm_validations() {
            break ord_csr;
        }

        let auths = ord_new.authorizations()?;

        let challenge = auths.get(0)
            .ok_or_else(|| Custom("Failed to access auths index".to_owned()))?
            .dns_challenge()
            .ok_or_else(|| Custom("Failed to unwrap dns challenge".to_owned()))?;

        set_dns_challenge(&challenge.dns_proof()?).await?;
        challenge.validate(Duration::from_millis(10000))?;

        ord_new.refresh()?;
    };


    let pkey_pri = create_p384_key()?;

// Submit the CSR. This causes the ACME provider to enter a
// state of "processing" that must be polled until the
// certificate is either issued or rejected. Again we poll
// for the status change.
    let ord_cert =
        ord_csr.finalize_pkey(pkey_pri, Duration::from_secs(10))?;

// Finally download the certificate.
    let cert = ord_cert.download_cert()?;


    let cert = CertRow {
        full_chain: cert.certificate().to_owned(),
        private_key: cert.private_key().to_owned(),
    };


    Ok(cert)
}

async fn set_dns_challenge(challenge: &str) -> Result<(), AppErrorInternal> {



    Ok(())

}

 */

================================================
FILE: src/lib/request_handler.rs
================================================
use std::sync::Arc;
use axum::{Extension, extract::Path};
use crate::lib::errors::{AppErrorExternal};
use askama::Template;
use axum::response::{Html, IntoResponse, Response};
use hyper::Body;
use hyper::{StatusCode};
use crate::AppState;
use crate::lib::fs_interaction::{DirEntry, list_dir_contents};
use std::ffi::OsStr;
use std::time::{SystemTime, UNIX_EPOCH};
use bytes::Bytes;
use crate::lib::helper;
use crate::VERSION;

pub enum ResponseWrapper {
    File(String),
    Html(axum::response::Html<String>),
}

impl IntoResponse for ResponseWrapper {

    fn into_response(self) -> Response {
        match self {
            ResponseWrapper::File(content) => {
                content.into_response()
            },
            ResponseWrapper::Html(content) => {
                content.into_response()
            },
        }
    }
}

//this is a special case for the root path "/" to simplify axum code
pub async fn handle_root_path(app_state: Extension<Arc<AppState>>) -> Result<ResponseWrapper, AppErrorExternal> {

    Ok(ResponseWrapper::Html(Html::from(build_dir_page(&app_state.title_name, &app_state.root_path, std::path::Path::new("")).await?)))
}


pub async fn handle_path(Path(path): Path<String>, app_state: Extension<Arc<AppState>>) -> Result<ResponseWrapper, AppErrorExternal> {

    let root_path = std::path::Path::new(&app_state.root_path);
    let relative_path = std::path::Path::new(&path);
    let canonical_root_path = root_path.canonicalize()?;

    // Construct the full path
    let full_path = root_path.join(&path);

    // Canonicalize the full path, resolving any ".." or "." segments
    let canonical_full_path = full_path.canonicalize()?;

    // If the canonical full path does not start with the canonical root path,
    // then this is a path traversal attempt, and we should not serve the file.
    if !canonical_full_path.starts_with(&canonical_root_path) {
        return Err(AppErrorExternal::PathTraversal);
    }

    // Here, you can be sure that canonical_full_path is within root_path.
    if path.as_str().chars().last() == Some('/') {
        Ok(ResponseWrapper::Html(
            Html::from(build_dir_page(&app_state.title_name, &app_state.root_path, &relative_path).await?)
        ))
    } else {
        Ok(ResponseWrapper::Html(
            axum::response::Html(format!("You requested file: {}", path))
        ))
    }
}

pub async fn build_dir_page(title_name: &Option<String>, root_path: &std::path::Path, relative_path: &std::path::Path) -> Result<String, AppErrorExternal> {

    let path = root_path.join(relative_path);

    let entries = list_dir_contents(&path).await?;

    build_template(title_name, &entries, relative_path).await
}


#[derive(Template)]
#[template(path = "directory.html")]
pub struct DirectoryTemplate<'a> {
    title: String,
    relative_path: &'a str,
    entries: &'a [DirEntry],
    current_location_name: &'a str,
    current_location_size: String,
}

pub async fn build_template(title_name: &Option<String>, entries: &[DirEntry], relative_path: &std::path::Path) -> Result<String, AppErrorExternal> {
    let title = title_name.as_deref().unwrap_or_else(|| "SkyFolder");
    let folder_name = relative_path.file_name().and_then(OsStr::to_str).unwrap_or_else(|| "Fileserver Root");
    let title = format!("{folder_name} - {title}");
    let current_location_name = folder_name;

    let relative_path_str = relative_path.to_str().unwrap_or_else(|| "");

    let mut size_sum = 0;
    for entry in entries {
        size_sum += entry.size.unwrap_or_else(|| 0);
    }

    let size_string = match helper::format_file_size_pretty(Some(size_sum)) {
        None => "Sizeless".to_string(),
        Some(v) => v
    };

    let template = DirectoryTemplate {
        title,
        relative_path: relative_path_str,
        entries,
        current_location_name,
        current_location_size: size_string,
    };

    Ok(template.render()?)
}

impl DirEntry {
    pub fn display_modified_raw(&self) -> String {
        match &self.last_modified {
            Some(date) => date.to_string(),
            None => "?".to_string(),
        }
    }
    pub fn display_size_raw(&self) -> String {
        match self.size {
            Some(size) => size.to_string(),
            None => "?".to_string(),
        }
    }
    pub fn icon_picker(&self) -> &str {
        // The `position_text` variable stores the position of the icon in the sprite sheet
        // The coordinates are assigned based on whether the item is a directory or a file with a specific extension
        let position_text = if self.is_dir {
            // If the item is a directory, its icon is located at "-128px 0px" in the sprite sheet
            "-128px 0px"
        } else {
            // If the item is not a directory, it's a file. We need to look at the file's extension
            let name = &self.name.to_lowercase();

            // We find the last occurrence of the '.' character in the name,
            // and slice the string from one character after this position to the end, to get the file extension
            match &name.rfind('.').map(|i| &name[i + 1..]) {
                // Depending on the extension, we match the appropriate icon from the sprite sheet
                Some("rs") => "0px -128px",
                Some("iso") => "-384px 0px",
                Some("json") | Some("js") => "-512px 0px",
                Some("py") => "-640px 0px",
                Some("zip") | Some("gz") | Some("rar") | Some("7z") | Some("tar") | Some("bz2") | Some("xz") => "-768px 0px",
                Some("pdf") => "-896px 0px",
                Some("jpg") | Some("jpeg") => "-512px -128px",
                Some("svg")  => "-384px -128px",
                Some("png")  => "-640px -128px",
                Some("gif")  => "-896px -128px",
                Some("ds_store")  => "-768px -128px",
                // If we can't match the extension to any of the above, we use a default icon located at "-256px 0px"
                _ => "-256px 0px"
            }
        };

        // Return the coordinates of the appropriate icon
        position_text
    }


    pub fn format_file_size(&self) -> String {
        match helper::format_file_size_pretty(self.size) {
            Some(b) => b,
            None => "-".to_string(),
        }
    }





    pub fn format_time_ago(&self) -> String {
        let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        let time_difference = match self.last_modified {
            Some(time) => current_time - time,
            None => return "Unknown".to_string(),
        };

        if time_difference < 60 {
            return "Just now".to_string();
        }

        let minutes = time_difference / 60;

        if minutes < 60 {
            return format!("{} {} ago", minutes, if minutes == 1 { "minute" } else { "minutes" });
        }

        let hours = minutes / 60;

        if hours < 24 {
            return format!("{} {} ago", hours, if hours == 1 { "hour" } else { "hours" });
        }

        let days = hours / 24;

        format!("{} {} ago", days, if days == 1 { "day" } else { "days" })
    }

}

/*
trait FormatPath {
    fn format_path(&self) -> Vec<&str>;
}

impl FormatPath for &str {
    fn format_path(&self) -> Vec<&str> {
        let mut path_parts: Vec<&str> = self.split('/').collect();
        if self.ends_with('/') {
            path_parts.pop();
        }
        path_parts
    }
}
 */





// embedding this data in the binary allows it to work without external files
static RASTER_SPRITESHEET: Bytes = Bytes::from_static(include_bytes!("../../assets/r.webp"));
static VECTOR_SPRITESHEET: Bytes = Bytes::from_static(include_bytes!("../../assets/v.svg"));


//static SCRIPTS: Bytes = Bytes::from_static(include_bytes!("../../assets/scripts.js"));
static FAVICON: Bytes = Bytes::from_static(include_bytes!("../../assets/favicon.ico"));

//serving these files with Axum rather than dynamically templated in with Askama results in better performance and memory usage
pub async fn serve_raster_spritesheet() -> Result<impl IntoResponse, AppErrorExternal> {
    Ok(
        Response::builder()
            .status(StatusCode::OK)
            .header(hyper::header::CONTENT_TYPE, "image/webp")
            .header("Cache-Control", "public, max-age=7884000")
            .body(Body::from(&*RASTER_SPRITESHEET))?
    )
}

pub async fn serve_vector_spritesheet() -> Result<impl IntoResponse, AppErrorExternal> {
    Ok(
        Response::builder()
            .status(StatusCode::OK)
            .header(hyper::header::CONTENT_TYPE, "image/svg+xml")
            .header("Cache-Control", "public, max-age=7884000")
            .body(Body::from(&*VECTOR_SPRITESHEET))?
    )
}

pub async fn serve_favicon() -> Result<impl IntoResponse, AppErrorExternal> {
    Ok(
        Response::builder()
            .status(StatusCode::OK)
            .header(hyper::header::CONTENT_TYPE, "image/x-icon")
            .header("Cache-Control", "public, max-age=7884000")
            .body(Body::from(&*FAVICON))?
    )
}


pub async fn serve_css() -> Result<impl IntoResponse, AppErrorExternal> {
    Ok(
        Response::builder()
            .status(StatusCode::OK)
            .header(hyper::header::CONTENT_TYPE, "text/css")
            .header("Cache-Control", "public, max-age=7884000")
            .body(Body::from(crate::STYLES))?
    )
}


pub async fn serve_js() -> Result<impl IntoResponse, AppErrorExternal> {
    Ok(
        Response::builder()
            .status(StatusCode::OK)
            .header(hyper::header::CONTENT_TYPE, "text/javascript")
            .header("Cache-Control", "public, max-age=7884000")
            .body(Body::from(crate::SCRIPTS))?
    )
}

#[derive(Template)]
#[template(path = "about.html")]
pub struct AboutTemplate<'a> {
    version: &'a str
}
pub async fn build_about() -> Result<Html<String>, AppErrorExternal> {

    let template = AboutTemplate {
        version: VERSION
    };

    Ok(Html::from(template.render()?))
}

//<input type="text" autocomplete="off">

================================================
FILE: src/lib/services.rs
================================================


================================================
FILE: src/main.rs
================================================
#[cfg(not(target_env = "msvc"))]
use tikv_jemallocator::Jemalloc;

#[cfg(not(target_env = "msvc"))]
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;

use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::lib::{fs_interaction, helper, parse_cli_args, request_handler};
use crate::lib::errors::AppErrorInternal;
use axum::routing::get;
use axum::{Extension, Server};

mod lib {
    pub(crate) mod errors;
    pub(crate) mod fs_interaction;
    pub(crate) mod parse_cli_args;
    pub(crate) mod request_handler;
    pub(crate) mod helper;
    pub(crate) mod services;
}

const VERSION: &str = env!("CARGO_PKG_VERSION");
include!(concat!(env!("OUT_DIR"), "/constants.rs"));

#[tokio::main]
async fn main() {

    println!("Starting up \x1B[95mSkyFolder\x1B[0m {VERSION}\n");
    println!("✅ If you need a feature or find a bug let me know in the Github issues tab.");
    println!("⭐ If you like the program please star it on Github as it helps me.");

    //start the actual application
    if let Err(e) = init().await {
        eprintln!("The program has crashed: {:?}", e)
    }

}

pub struct AppState {
    pub(crate) root_path: PathBuf,
    pub(crate) port: u16,
    pub(crate) title_name: Option<String> // the name the user gives to their server i.e. what is shown in page title tag
}

async fn init() -> Result<(), AppErrorInternal> {

    let app_state = {
        let args = parse_cli_args::parse_args()?;
        Arc::new(AppState {
            root_path: args.path,
            port: 30080,
            title_name: None
        })
    };

    println!("Serving path: {}", app_state.root_path.display());
    println!("Bound to [::]:{}, 0.0.0.0:{}", app_state.port, app_state.port);
    let ifaces = get_if_addrs::get_if_addrs().unwrap();

    println!("Available on LAN at (non-exhaustive list):");

    for iface in ifaces {
        match iface.addr {
            get_if_addrs::IfAddr::V4(addr) => {
                println!("    http://{}:{}", addr.ip, &app_state.port);
            }
            get_if_addrs::IfAddr::V6(addr) => {
                println!("    http://[{}]:{}", addr.ip, &app_state.port);
            }
        }
    }

    //todo only show this if the user has upnp mode enabled. remember to set port to whatever upnp negotiates
    println!("Available on WAN (Public internet) at:");
    println!("    http://{}:30080", helper::get_public_ip().await.unwrap_or("Failed to determine IP".to_string()));


    let app = axum::Router::new()
        .route("/", get(request_handler::handle_root_path))
        .route("/*path", get(request_handler::handle_path))
        .route("/about_skyfolder", get(request_handler::build_about))
        .layer(Extension(app_state.clone()))
        .route(RASTER_SPRITES_FILENAME, get(request_handler::serve_raster_spritesheet))
        .route(VECTOR_SPRITES_FILENAME, get(request_handler::serve_vector_spritesheet))
        .route(CSS_FILENAME, get(request_handler::serve_css))
        .route(JS_FILENAME, get(request_handler::serve_js))
        .route("/favicon.ico", get(request_handler::serve_favicon));

    Server::bind(&format!("0.0.0.0:{}", app_state.port).parse()?)
        .serve(app.into_make_service())
        .await?;

    Ok(())
}

================================================
FILE: templates/about.html
================================================
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>About - SkyFolder</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="A folder has been shared with you. Open now to browse.">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" type="text/css" href="/styles.css">
    <meta property="og:title" content="About - SkyFolder"/>
    <meta property="og:description" content="A folder has been shared with you. Open now to browse."/>
    <meta property="og:image" content="https://raw.githubusercontent.com/mu-arch/skyfolder/master/hosted/og_image.jpg"/>
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>

<body>
<style>
    .about {
        margin: auto;
        text-align: center;
    }

    img {
        max-width: 500px;
    }
    p {
        padding: 10px;
    }
    a {
        color: #0049ff;
    }
</style>

<div class="about">
    <img alt="SkyFolder Logo" src="https://raw.githubusercontent.com/mu-arch/skyfolder/master/hosted/logo.png">
    <p>Version: {{ VERSION }}</p>
    <p>Source code: <a href="https://github.com/mu-arch/skyfolder">[Github]</a></p>
    <p>License: GPLv3</p>
    <p>Crafted with love and care 💕</p>
    <p><a href="/">[Back]</a></p>
</div>

</body>
</html>

================================================
FILE: templates/directory.html
================================================
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="A folder has been shared with you. Open now to browse.">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" type="text/css" href="{{ crate::CSS_FILENAME }}">
    <meta property="og:title" content="{{ title }}"/>
    <meta property="og:description" content="A folder has been shared with you. Open now to browse."/>
    <meta property="og:image" content="https://raw.githubusercontent.com/mu-arch/skyfolder/master/hosted/og_image.jpg"/>
    <link rel="icon" type="image/x-icon" href="/favicon.ico" />
</head>

<body>
<section>
    <nav>
        <div title="Navigate up one directory."></div>
        <div title="{{ current_location_name }}">{{ current_location_name }}</div>
        <div><input contenteditable="true" placeholder="Quick search folder..."><div></div></div>
    </nav>




    <table id="table">
        <thead>
        <tr>
            <th>Name</th>
            <th>Modified</th>
            <th>Size</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody id="b">

        {% if entries.is_empty() %}
        <div class="folder-empty">
            <div></div>
            <span>This folder is empty.</span>
        </div>
        {% else %}
        {% for entry in entries %}
        <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>
            <td aria-modified="{{ entry.display_modified_raw() | safe}}">{{ entry.format_time_ago() | safe }}</td>
            <td aria-size="{{ entry.display_size_raw() | safe }}">{{ entry.format_file_size() | safe }}</td></tr>
        {% endfor %}
        {% endif %}

        </tbody>
    </table>
    <footer><a href="/about_skyfolder">SkyFolder</a></footer>

</section>

<div id="pane">
    <div>
        <div><h1>{{ current_location_name }}</h1><span>Dir</span></div>
        <div>
            <p>No description.</p>
        </div>
        <div><span id="fc"></span>|<span id="fsz">{{ current_location_size|safe }}</span>|<span id="qr">QR</span></div>
    </div>

    <div class="button-menu">
    <button class="display-btn">View Mode</button>
    <button class="select-btn">Select</button>
    <button class="upload-btn">Upload</button>
    </div>

</div>

</body>
</html>

<script src="{{ crate::JS_FILENAME }}"></script>
Download .txt
gitextract__hbgz72c/

├── .gitignore
├── Cargo.toml
├── LICENSE
├── README.md
├── askama.toml
├── assets/
│   ├── raster_spritesheet.pxd
│   ├── scripts.js
│   ├── styles.css
│   └── vector_spritesheet.pxd
├── attribution.txt
├── build.rs
├── hosted/
│   └── spritesheet.pxd
├── src/
│   ├── lib/
│   │   ├── errors.rs
│   │   ├── fs_interaction.rs
│   │   ├── helper.rs
│   │   ├── parse_cli_args.rs
│   │   ├── provision_certs.rs
│   │   ├── request_handler.rs
│   │   └── services.rs
│   └── main.rs
└── templates/
    ├── about.html
    └── directory.html
Download .txt
SYMBOL INDEX (56 symbols across 8 files)

FILE: assets/scripts.js
  constant GLOBAL_TABLE_DATA (line 3) | let GLOBAL_TABLE_DATA;
  function navurl (line 5) | function navurl(url) {
  function qs (line 9) | function qs(divs) {
  function debounce (line 13) | function debounce(func, wait) {
  function check_if_tbody_is_empty (line 25) | function check_if_tbody_is_empty() {
  function extractTableData (line 33) | function extractTableData() {
  function workerSearch (line 44) | function workerSearch() {
  function marshall_search (line 84) | function marshall_search(query, rowMatrix) {
  function displaySearchResults (line 108) | function displaySearchResults(indexes, searchTerm, limit = Infinity) {
  function cleanupSearchResults (line 164) | function cleanupSearchResults() {
  function search (line 180) | function search(query, resultLimit) {
  function navigateToParentDirectory (line 221) | function navigateToParentDirectory() {
  function extractPaths (line 240) | function extractPaths(url) {
  function spawnTooltip (line 246) | function spawnTooltip(source, templateFn) {
  function path_selector_generator (line 270) | function path_selector_generator() {
  function file_dir_manifest (line 289) | function file_dir_manifest() {

FILE: build.rs
  function main (line 9) | fn main() {
  function generate_random_string (line 49) | fn generate_random_string(length: u16) -> String {

FILE: src/lib/errors.rs
  type AppErrorInternal (line 2) | pub enum AppErrorInternal {
    method from (line 10) | fn from(inner: std::net::AddrParseError) -> Self {
    method from (line 16) | fn from(inner: hyper::Error) -> Self {
  type AppErrorExternal (line 36) | pub enum AppErrorExternal {
    method from (line 62) | fn from(inner: std::io::Error) -> Self {
    method from (line 68) | fn from(inner: askama::Error) -> Self {
    method from (line 74) | fn from(inner: axum::http::Error) -> Self {
  method into_response (line 45) | fn into_response(self) -> Response {

FILE: src/lib/fs_interaction.rs
  type DirEntry (line 12) | pub struct DirEntry {
  function list_dir_contents (line 20) | pub async fn list_dir_contents(dir: &Path) -> Result<Vec<DirEntry>, AppE...
  function serve_file (line 49) | pub async fn serve_file(path: &PathBuf) -> Result<Body, AppErrorExternal> {

FILE: src/lib/helper.rs
  function format_file_size_pretty (line 3) | pub fn format_file_size_pretty(size: Option<u64>) -> Option<String> {
  function get_public_ip (line 32) | pub async fn get_public_ip() -> Result<String, reqwest::Error> {

FILE: src/lib/parse_cli_args.rs
  type Args (line 6) | pub struct Args {
  function parse_args (line 10) | pub fn parse_args() -> Result<Args, AppErrorInternal> {

FILE: src/lib/request_handler.rs
  type ResponseWrapper (line 16) | pub enum ResponseWrapper {
  method into_response (line 23) | fn into_response(self) -> Response {
  function handle_root_path (line 36) | pub async fn handle_root_path(app_state: Extension<Arc<AppState>>) -> Re...
  function handle_path (line 42) | pub async fn handle_path(Path(path): Path<String>, app_state: Extension<...
  function build_dir_page (line 72) | pub async fn build_dir_page(title_name: &Option<String>, root_path: &std...
  type DirectoryTemplate (line 84) | pub struct DirectoryTemplate<'a> {
  function build_template (line 92) | pub async fn build_template(title_name: &Option<String>, entries: &[DirE...
  method display_modified_raw (line 122) | pub fn display_modified_raw(&self) -> String {
  method display_size_raw (line 128) | pub fn display_size_raw(&self) -> String {
  method icon_picker (line 134) | pub fn icon_picker(&self) -> &str {
  method format_file_size (line 169) | pub fn format_file_size(&self) -> String {
  method format_time_ago (line 180) | pub fn format_time_ago(&self) -> String {
  function serve_raster_spritesheet (line 239) | pub async fn serve_raster_spritesheet() -> Result<impl IntoResponse, App...
  function serve_vector_spritesheet (line 249) | pub async fn serve_vector_spritesheet() -> Result<impl IntoResponse, App...
  function serve_favicon (line 259) | pub async fn serve_favicon() -> Result<impl IntoResponse, AppErrorExtern...
  function serve_css (line 270) | pub async fn serve_css() -> Result<impl IntoResponse, AppErrorExternal> {
  function serve_js (line 281) | pub async fn serve_js() -> Result<impl IntoResponse, AppErrorExternal> {
  type AboutTemplate (line 293) | pub struct AboutTemplate<'a> {
  function build_about (line 296) | pub async fn build_about() -> Result<Html<String>, AppErrorExternal> {

FILE: src/main.rs
  constant VERSION (line 24) | const VERSION: &str = env!("CARGO_PKG_VERSION");
  function main (line 28) | async fn main() {
  type AppState (line 41) | pub struct AppState {
  function init (line 47) | async fn init() -> Result<(), AppErrorInternal> {
Condensed preview — 22 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (93K chars).
[
  {
    "path": ".gitignore",
    "chars": 23,
    "preview": "/target\n.idea/\nOUT_DIR/"
  },
  {
    "path": "Cargo.toml",
    "chars": 1163,
    "preview": "[package]\nname = \"skyfolder\"\nversion = \"0.1.0\"\nedition = \"2021\"\nlicense = \"GPL-3.0\"\ndescription = \"Skyfolder is a self-c"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 4385,
    "preview": "<p align=\"center\">\n  <img src=\"https://github.com/mu-arch/skyfolder/blob/master/hosted/logo.png\" alt=\"Skyfolder - Secure"
  },
  {
    "path": "askama.toml",
    "chars": 196,
    "preview": "[general]\n# Directories to search for templates, relative to the crate root.\ndirs = [\"templates\"]\n# Unless you add a `-`"
  },
  {
    "path": "assets/scripts.js",
    "chars": 9072,
    "preview": "'use strict';\n\nlet GLOBAL_TABLE_DATA;\n\nfunction navurl(url) {\n    window.location.href = url;\n}\n\nfunction qs(divs) {\n   "
  },
  {
    "path": "assets/styles.css",
    "chars": 10228,
    "preview": "html, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, bi"
  },
  {
    "path": "attribution.txt",
    "chars": 120,
    "preview": "Ballon Model: Ekayasa.Design\nOpen Source Libraries: Check respective repositories\nSea Creature Water Color: rawpixel.com"
  },
  {
    "path": "build.rs",
    "chars": 1940,
    "preview": "use std::env;\nuse std::fs;\nuse std::path::Path;\nuse rand::Rng;\nuse rand::distributions::Alphanumeric;\nuse std::fmt::Writ"
  },
  {
    "path": "src/lib/errors.rs",
    "chars": 2098,
    "preview": "#[derive(Debug)]\npub enum AppErrorInternal {\n    AddrParseError(std::net::AddrParseError),\n    HyperError(hyper::Error),"
  },
  {
    "path": "src/lib/fs_interaction.rs",
    "chars": 1839,
    "preview": "use std::path::{Path, PathBuf};\nuse axum::response::Response;\nuse tokio::fs;\nuse crate::lib::errors::{AppErrorExternal};"
  },
  {
    "path": "src/lib/helper.rs",
    "chars": 1240,
    "preview": "use reqwest;\n\npub fn format_file_size_pretty(size: Option<u64>) -> Option<String> {\n    let units = vec![\"b\", \"kb\", \"mb\""
  },
  {
    "path": "src/lib/parse_cli_args.rs",
    "chars": 869,
    "preview": "use clap::{arg, command, value_parser, ArgAction, Command};\nuse std::env;\nuse std::path::PathBuf;\nuse crate::lib::errors"
  },
  {
    "path": "src/lib/provision_certs.rs",
    "chars": 3421,
    "preview": "/*\n\npub async fn ssl_cert_lifecycle_manager() {\n\n    /*\n        let _ = get_dns().await;\n        return\n     */\n\n\n    //"
  },
  {
    "path": "src/lib/request_handler.rs",
    "chars": 10082,
    "preview": "use std::sync::Arc;\nuse axum::{Extension, extract::Path};\nuse crate::lib::errors::{AppErrorExternal};\nuse askama::Templa"
  },
  {
    "path": "src/lib/services.rs",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "src/main.rs",
    "chars": 3223,
    "preview": "#[cfg(not(target_env = \"msvc\"))]\nuse tikv_jemallocator::Jemalloc;\n\n#[cfg(not(target_env = \"msvc\"))]\n#[global_allocator]\n"
  },
  {
    "path": "templates/about.html",
    "chars": 1308,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>About - SkyFolder</title>\n    <meta name=\"viewport\" "
  },
  {
    "path": "templates/directory.html",
    "chars": 2569,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>{{ title }}</title>\n    <meta name=\"viewport\" conten"
  }
]

// ... and 3 more files (download for full content)

About this extraction

This page contains the full source code of the mu-arch/skyfolder GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 22 files (86.8 KB), approximately 21.9k tokens, and a symbol index with 56 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!