Full Code of SnapDrop/snapdrop for AI

master b8b78cc22a67 cached
23 files
118.2 KB
31.0k tokens
160 symbols
1 requests
Download .txt
Repository: SnapDrop/snapdrop
Branch: master
Commit: b8b78cc22a67
Files: 23
Total size: 118.2 KB

Directory structure:
gitextract_hpr_ld_l/

├── .github/
│   └── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── client/
│   ├── images/
│   │   └── snapdrop-graphics.sketch
│   ├── index.html
│   ├── manifest.json
│   ├── scripts/
│   │   ├── clipboard.js
│   │   ├── network.js
│   │   └── ui.js
│   ├── service-worker.js
│   ├── sounds/
│   │   └── blop.ogg
│   └── styles.css
├── docker/
│   ├── nginx/
│   │   └── default.conf
│   ├── nginx-with-openssl.Dockerfile
│   └── openssl/
│       ├── create.sh
│       ├── snapdropCA.cnf
│       └── snapdropCert.cnf
├── docker-compose.yml
├── docs/
│   ├── faq.md
│   └── local-dev.md
└── server/
    ├── index.js
    └── package.json

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

================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: robinlinus
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: https://www.paypal.com/donate/?hosted_button_id=MG8GV7YCYT352


================================================
FILE: .gitignore
================================================
node_modules
.DS_Store
fqdn.env
/docker/certs

================================================
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
================================================
# Snapdrop 

[Snapdrop](https://snapdrop.net): local file sharing in your browser. Inspired by Apple's Airdrop.

## Snapdrop is now LimeWire
Dear Snapdrop community,
Snapdrop has been acquired by LimeWire, a leading file sharing platform with integrated AI tools. You can continue to share any files between devices, while benefitting from:
* sharing files between devices in the same network
* anonymous up- & downloads
* end-to-end encryption
* up to 40GB storage for free users
* integrated AI tools for signed-up users

Visit [snapdrop.net](https://snapdrop.net) or [limewire.com](https://limewire.com)

The Github repository will stay as-is and you can still go ahead and download and run the classic Snapdrop on your own infrastructure.


##  Classic Snapdrop is built with the following awesome technologies
* Vanilla HTML5 / ES6 / CSS3 frontend
* [WebRTC](http://webrtc.org/) / [WebSockets](http://www.websocket.org/)
* [NodeJS](https://nodejs.org/en/) backend
* [Progressive Web App](https://wikipedia.org/wiki/Progressive_Web_App)


Have any questions? Read our [FAQ](/docs/faq.md).

You can [host your own instance with Docker](/docs/local-dev.md).


================================================
FILE: client/index.html
================================================
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!-- Web App Config -->
    <title>Snapdrop</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#3367d6">
    <meta name="color-scheme" content="dark light">
    <meta name="apple-mobile-web-app-capable" content="no">
    <meta name="apple-mobile-web-app-title" content="Snapdrop">
    <!-- Descriptions -->
    <meta name="description" content="Instantly share images, videos, PDFs, and links with people nearby. Peer2Peer and Open Source. No Setup, No Signup.">
    <meta name="keywords" content="File, Transfer, Share, Peer2Peer">
    <meta name="author" content="RobinLinus">
    <meta property="og:title" content="Snapdrop">
    <meta property="og:type" content="article">
    <meta property="og:url" content="https://snapdrop.net/">
    <meta property="og:author" content="https://facebook.com/RobinLinus">
    <meta name="twitter:author" content="@RobinLinus">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:description" content="Instantly share images, videos, PDFs, and links with people nearby. Peer2Peer and Open Source. No Setup, No Signup.">
    <meta name="og:description" content="Instantly share images, videos, PDFs, and links with people nearby. Peer2Peer and Open Source. No Setup, No Signup.">
    <!-- Icons -->
    <link rel="icon" sizes="96x96" href="images/favicon-96x96.png">
    <link rel="shortcut icon" href="images/favicon-96x96.png">
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <meta name="msapplication-TileImage" content="images/mstile-150x150.png">
    <link rel="fluid-icon" type="image/png" href="images/android-chrome-192x192.png">
    <meta name="twitter:image" content="https://snapdrop.net/images/twitter-stream.jpg">
    <meta property="og:image" content="https://snapdrop.net/images/twitter-stream.jpg">
    <!-- Resources -->
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="manifest" href="manifest.json">
</head>

<body translate="no">
    <header class="row-reverse">
        <a href="#about" class="icon-button" title="About Snapdrop">
            <svg class="icon">
                <use xlink:href="#info-outline" />
            </svg>
        </a>
        <a href="#" id="notification" class="icon-button" title="Enable Notifications" hidden>
            <svg class="icon">
                <use xlink:href="#notifications" />
            </svg>
        </a>
        <a href="#" id="install" class="icon-button" title="Install Snapdrop" hidden>
            <svg class="icon">
                <use xlink:href="#homescreen" />
            </svg>
        </a>
    </header>
    <!-- Peers -->
    <x-peers class="center"></x-peers>
    <x-no-peers>
        <h2>Open Snapdrop on other devices to send files</h2>
    </x-no-peers>
    <x-instructions desktop="Click to send files or right click to send a message" mobile="Tap to send files or long tap to send a message"></x-instructions>
    <!-- Footer -->
    <footer class="column">
        <svg class="icon logo">
            <use xlink:href="#wifi-tethering" />
        </svg>
        <div id="displayName" placeholder="The easiest way to transfer data across devices"></div>
        <div class="font-body2">You can be discovered by everyone on this network</div>
    </footer>
    <!-- Receive Dialog -->
    <x-dialog id="receiveDialog">
        <x-background class="full center">
            <x-paper shadow="2">
                <h3>File Received</h3>
                <div class="font-subheading" id="fileName">Filename</div>
                <div class="font-body2" id="fileSize"></div>
                <div class='preview' style="visibility: hidden;">
                    <img id='img-preview' src="">
                </div>
                <div class="row">
                    <label for="autoDownload" class="grow">Ask to save each file before downloading</label>
                    <input type="checkbox" id="autoDownload" checked="">
                </div>
                <div class="row-reverse">
                    <a class="button" close id="download" title="Download File" autofocus>Save</a>
                    <button class="button" close>Ignore</button>
                </div>
            </x-paper>
        </x-background>
    </x-dialog>
    <!-- Send Text Dialog -->
    <x-dialog id="sendTextDialog">
        <form action="#">
            <x-background class="full center">
                <x-paper shadow="2">
                    <h3>Send a Message</h3>
                    <div id="textInput" class="textarea" role="textbox" placeholder="Send a message" autocomplete="off" autofocus contenteditable></div>
                    <div class="row-reverse">
                        <button class="button" type="submit" close>Send</button>
                        <a class="button" close>Cancel</a>
                    </div>
                </x-paper>
            </x-background>
        </form>
    </x-dialog>
    <!-- Receive Text Dialog -->
    <x-dialog id="receiveTextDialog">
        <x-background class="full center">
            <x-paper shadow="2">
                <h3>Message Received</h3>
                <div class="font-subheading" id="text"></div>
                <div class="row-reverse">
                    <button class="button" id="copy" close autofocus>Copy</button>
                    <button class="button" close>Close</button>
                </div>
            </x-paper>
        </x-background>
    </x-dialog>
    <!-- Toast -->
    <div class="toast-container full center">
        <x-toast class="row" shadow="1" id="toast">File Transfer Completed</x-toast>
    </div>
    <!-- About Page -->
    <x-about id="about" class="full center column">
        <section class="center column fade-in">
            <header class="row-reverse">
                <a href="#" class="close icon-button">
                    <svg class="icon">
                        <use xlink:href="#close" />
                    </svg>
                </a>
            </header>
            <svg class="icon logo">
                <use xlink:href="#wifi-tethering" />
            </svg>
            <h1>Snapdrop</h1>
            <div class="font-subheading">The easiest way to transfer files across devices</div>
            <div class="row">
                <a class="icon-button" target="_blank" href="https://github.com/RobinLinus/snapdrop" title="Snapdrop on Github" rel="noreferrer">
                    <svg class="icon">
                        <use xlink:href="#github" />
                    </svg>
                </a>
                <a class="icon-button" target="_blank" href="https://www.paypal.com/donate?hosted_button_id=FTP9DXUR7LA7Q" title="Help cover the server costs!" rel="noreferrer">
                    <svg class="icon">
                        <use xlink:href="#monetarization" />
                    </svg>
                </a>
                <a class="icon-button" target="_blank" href="https://twitter.com/intent/tweet?text=https://snapdrop.net%20by%20@robin_linus%20&" title="Tweet about Snapdrop" rel="noreferrer">
                    <svg class="icon">
                        <use xlink:href="#twitter" />
                    </svg>
                </a>
                <a class="icon-button" target="_blank" href="https://github.com/RobinLinus/snapdrop/blob/master/docs/faq.md" title="Frequently asked questions" rel="noreferrer">
                    <svg class="icon">
                        <use xlink:href="#help-outline" />
                    </svg>
                </a>
            </div>
        </section>
        <x-background></x-background>
    </x-about>
    <!-- SVG Icon Library -->
    <svg style="display: none;">
        <symbol id=wifi-tethering viewBox="0 0 24 24">
            <path d="M12 11c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 2c0-3.31-2.69-6-6-6s-6 2.69-6 6c0 2.22 1.21 4.15 3 5.19l1-1.74c-1.19-.7-2-1.97-2-3.45 0-2.21 1.79-4 4-4s4 1.79 4 4c0 1.48-.81 2.75-2 3.45l1 1.74c1.79-1.04 3-2.97 3-5.19zM12 3C6.48 3 2 7.48 2 13c0 3.7 2.01 6.92 4.99 8.65l1-1.73C5.61 18.53 4 15.96 4 13c0-4.42 3.58-8 8-8s8 3.58 8 8c0 2.96-1.61 5.53-4 6.92l1 1.73c2.99-1.73 5-4.95 5-8.65 0-5.52-4.48-10-10-10z"></path>
        </symbol>
        <symbol id=desktop-mac viewBox="0 0 24 24">
            <path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7l-2 3v1h8v-1l-2-3h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 12H3V4h18v10z"></path>
        </symbol>
        <symbol id=phone-iphone viewBox="0 0 24 24">
            <path d="M15.5 1h-8C6.12 1 5 2.12 5 3.5v17C5 21.88 6.12 23 7.5 23h8c1.38 0 2.5-1.12 2.5-2.5v-17C18 2.12 16.88 1 15.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"></path>
        </symbol>
        <symbol id=tablet-mac viewBox="0 0 24 24">
            <path d="M18.5 0h-14C3.12 0 2 1.12 2 2.5v19C2 22.88 3.12 24 4.5 24h14c1.38 0 2.5-1.12 2.5-2.5v-19C21 1.12 19.88 0 18.5 0zm-7 23c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm7.5-4H4V3h15v16z"></path>
        </symbol>
        <symbol id=info-outline viewBox="0 0 24 24">
            <path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"></path>
        </symbol>
        <symbol id=close viewBox="0 0 24 24">
            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path>
        </symbol>
        <symbol id=help-outline viewBox="0 0 24 24">
            <path d="M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z"></path>
        </symbol>
        <symbol id="twitter">
            <path d="M23.954 4.569c-.885.389-1.83.654-2.825.775 1.014-.611 1.794-1.574 2.163-2.723-.951.555-2.005.959-3.127 1.184-.896-.959-2.173-1.559-3.591-1.559-2.717 0-4.92 2.203-4.92 4.917 0 .39.045.765.127 1.124C7.691 8.094 4.066 6.13 1.64 3.161c-.427.722-.666 1.561-.666 2.475 0 1.71.87 3.213 2.188 4.096-.807-.026-1.566-.248-2.228-.616v.061c0 2.385 1.693 4.374 3.946 4.827-.413.111-.849.171-1.296.171-.314 0-.615-.03-.916-.086.631 1.953 2.445 3.377 4.604 3.417-1.68 1.319-3.809 2.105-6.102 2.105-.39 0-.779-.023-1.17-.067 2.189 1.394 4.768 2.209 7.557 2.209 9.054 0 13.999-7.496 13.999-13.986 0-.209 0-.42-.015-.63.961-.689 1.8-1.56 2.46-2.548l-.047-.02z" />
        </symbol>
        <symbol id="github">
            <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
        </symbol>
        <g id="notifications">
            <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z" />
        </g>
        <symbol id="homescreen">
            <path fill="none" d="M0 0h24v24H0V0z" />
            <path d="M18 1.01L8 1c-1.1 0-2 .9-2 2v3h2V5h10v14H8v-1H6v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM10 15h2V8H5v2h3.59L3 15.59 4.41 17 10 11.41z" />
            <path fill="none" d="M0 0h24v24H0V0z" />
        </symbol>
        <symbol id="monetarization">
            <path d="M0 0h24v24H0z" fill="none" />
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H14.3c-.05-1.11-.64-1.87-2.22-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z" />
        </symbol>
    </svg>
    <!-- Scripts -->
    <script src="scripts/network.js"></script>
    <script src="scripts/ui.js"></script>
    <script src="scripts/clipboard.js" async></script>
    <!-- Sounds -->
    <audio id="blop" autobuffer="true">
        <source src="sounds/blop.mp3" type="audio/mpeg">
        <source src="sounds/blop.ogg" type="audio/ogg">
    </audio>
    <!-- no script -->
    <noscript>
        <x-noscript class="full center column">
            <h1>Enable JavaScript</h1>
            <h3>Snapdrop works only with JavaScript</h3>
        </x-noscript>
        <style>
        x-noscript {
            background: #599cfc;
            color: white;
            z-index: 2;
        }

        a[href="#info"] {
            color: white;
        }
        </style>
    </noscript>
</body>


================================================
FILE: client/manifest.json
================================================
{
    "name": "Snapdrop",
    "short_name": "Snapdrop",
    "icons": [{
        "src": "images/android-chrome-192x192.png",
        "sizes": "192x192",
        "type": "image/png"
    },{
        "src": "images/android-chrome-512x512.png",
        "sizes": "512x512",
        "type": "image/png"
    },{
        "src": "images/android-chrome-192x192-maskable.png",
        "sizes": "192x192",
        "type": "image/png",
        "purpose": "maskable"
    },{
        "src": "images/android-chrome-512x512-maskable.png",
        "sizes": "512x512",
        "type": "image/png",
        "purpose": "maskable"
    },{
        "src": "images/favicon-96x96.png",
        "sizes": "96x96",
        "type": "image/png"
    }],
    "background_color": "#efefef",
    "display": "minimal-ui",
    "theme_color": "#3367d6",
    "share_target": {
        "method":"GET",
        "action": "/?share_target",
        "params": {
            "title": "title",
            "text": "text",
            "url": "url"
        }
    }
}

================================================
FILE: client/scripts/clipboard.js
================================================
// Polyfill for Navigator.clipboard.writeText
if (!navigator.clipboard) {
    navigator.clipboard = {
        writeText: text => {

            // A <span> contains the text to copy
            const span = document.createElement('span');
            span.textContent = text;
            span.style.whiteSpace = 'pre'; // Preserve consecutive spaces and newlines

            // Paint the span outside the viewport
            span.style.position = 'absolute';
            span.style.left = '-9999px';
            span.style.top = '-9999px';

            const win = window;
            const selection = win.getSelection();
            win.document.body.appendChild(span);

            const range = win.document.createRange();
            selection.removeAllRanges();
            range.selectNode(span);
            selection.addRange(range);

            let success = false;
            try {
                success = win.document.execCommand('copy');
            } catch (err) {
                return Promise.error();
            }

            selection.removeAllRanges();
            span.remove();

            return Promise.resolve();
        }
    }
}

================================================
FILE: client/scripts/network.js
================================================
window.URL = window.URL || window.webkitURL;
window.isRtcSupported = !!(window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection);

class ServerConnection {

    constructor() {
        this._connect();
        Events.on('beforeunload', e => this._disconnect());
        Events.on('pagehide', e => this._disconnect());
        document.addEventListener('visibilitychange', e => this._onVisibilityChange());
    }

    _connect() {
        clearTimeout(this._reconnectTimer);
        if (this._isConnected() || this._isConnecting()) return;
        const ws = new WebSocket(this._endpoint());
        ws.binaryType = 'arraybuffer';
        ws.onopen = e => console.log('WS: server connected');
        ws.onmessage = e => this._onMessage(e.data);
        ws.onclose = e => this._onDisconnect();
        ws.onerror = e => console.error(e);
        this._socket = ws;
    }

    _onMessage(msg) {
        msg = JSON.parse(msg);
        console.log('WS:', msg);
        switch (msg.type) {
            case 'peers':
                Events.fire('peers', msg.peers);
                break;
            case 'peer-joined':
                Events.fire('peer-joined', msg.peer);
                break;
            case 'peer-left':
                Events.fire('peer-left', msg.peerId);
                break;
            case 'signal':
                Events.fire('signal', msg);
                break;
            case 'ping':
                this.send({ type: 'pong' });
                break;
            case 'display-name':
                Events.fire('display-name', msg);
                break;
            default:
                console.error('WS: unkown message type', msg);
        }
    }

    send(message) {
        if (!this._isConnected()) return;
        this._socket.send(JSON.stringify(message));
    }

    _endpoint() {
        // hack to detect if deployment or development environment
        const protocol = location.protocol.startsWith('https') ? 'wss' : 'ws';
        const webrtc = window.isRtcSupported ? '/webrtc' : '/fallback';
        const url = protocol + '://' + location.host + location.pathname + 'server' + webrtc;
        return url;
    }

    _disconnect() {
        this.send({ type: 'disconnect' });
        this._socket.onclose = null;
        this._socket.close();
    }

    _onDisconnect() {
        console.log('WS: server disconnected');
        Events.fire('notify-user', 'Connection lost. Retry in 5 seconds...');
        clearTimeout(this._reconnectTimer);
        this._reconnectTimer = setTimeout(_ => this._connect(), 5000);
    }

    _onVisibilityChange() {
        if (document.hidden) return;
        this._connect();
    }

    _isConnected() {
        return this._socket && this._socket.readyState === this._socket.OPEN;
    }

    _isConnecting() {
        return this._socket && this._socket.readyState === this._socket.CONNECTING;
    }
}

class Peer {

    constructor(serverConnection, peerId) {
        this._server = serverConnection;
        this._peerId = peerId;
        this._filesQueue = [];
        this._busy = false;
    }

    sendJSON(message) {
        this._send(JSON.stringify(message));
    }

    sendFiles(files) {
        for (let i = 0; i < files.length; i++) {
            this._filesQueue.push(files[i]);
        }
        if (this._busy) return;
        this._dequeueFile();
    }

    _dequeueFile() {
        if (!this._filesQueue.length) return;
        this._busy = true;
        const file = this._filesQueue.shift();
        this._sendFile(file);
    }

    _sendFile(file) {
        this.sendJSON({
            type: 'header',
            name: file.name,
            mime: file.type,
            size: file.size
        });
        this._chunker = new FileChunker(file,
            chunk => this._send(chunk),
            offset => this._onPartitionEnd(offset));
        this._chunker.nextPartition();
    }

    _onPartitionEnd(offset) {
        this.sendJSON({ type: 'partition', offset: offset });
    }

    _onReceivedPartitionEnd(offset) {
        this.sendJSON({ type: 'partition-received', offset: offset });
    }

    _sendNextPartition() {
        if (!this._chunker || this._chunker.isFileEnd()) return;
        this._chunker.nextPartition();
    }

    _sendProgress(progress) {
        this.sendJSON({ type: 'progress', progress: progress });
    }

    _onMessage(message) {
        if (typeof message !== 'string') {
            this._onChunkReceived(message);
            return;
        }
        message = JSON.parse(message);
        console.log('RTC:', message);
        switch (message.type) {
            case 'header':
                this._onFileHeader(message);
                break;
            case 'partition':
                this._onReceivedPartitionEnd(message);
                break;
            case 'partition-received':
                this._sendNextPartition();
                break;
            case 'progress':
                this._onDownloadProgress(message.progress);
                break;
            case 'transfer-complete':
                this._onTransferCompleted();
                break;
            case 'text':
                this._onTextReceived(message);
                break;
        }
    }

    _onFileHeader(header) {
        this._lastProgress = 0;
        this._digester = new FileDigester({
            name: header.name,
            mime: header.mime,
            size: header.size
        }, file => this._onFileReceived(file));
    }

    _onChunkReceived(chunk) {
        if(!chunk.byteLength) return;
        
        this._digester.unchunk(chunk);
        const progress = this._digester.progress;
        this._onDownloadProgress(progress);

        // occasionally notify sender about our progress 
        if (progress - this._lastProgress < 0.01) return;
        this._lastProgress = progress;
        this._sendProgress(progress);
    }

    _onDownloadProgress(progress) {
        Events.fire('file-progress', { sender: this._peerId, progress: progress });
    }

    _onFileReceived(proxyFile) {
        Events.fire('file-received', proxyFile);
        this.sendJSON({ type: 'transfer-complete' });
    }

    _onTransferCompleted() {
        this._onDownloadProgress(1);
        this._reader = null;
        this._busy = false;
        this._dequeueFile();
        Events.fire('notify-user', 'File transfer completed.');
    }

    sendText(text) {
        const unescaped = btoa(unescape(encodeURIComponent(text)));
        this.sendJSON({ type: 'text', text: unescaped });
    }

    _onTextReceived(message) {
        const escaped = decodeURIComponent(escape(atob(message.text)));
        Events.fire('text-received', { text: escaped, sender: this._peerId });
    }
}

class RTCPeer extends Peer {

    constructor(serverConnection, peerId) {
        super(serverConnection, peerId);
        if (!peerId) return; // we will listen for a caller
        this._connect(peerId, true);
    }

    _connect(peerId, isCaller) {
        if (!this._conn) this._openConnection(peerId, isCaller);

        if (isCaller) {
            this._openChannel();
        } else {
            this._conn.ondatachannel = e => this._onChannelOpened(e);
        }
    }

    _openConnection(peerId, isCaller) {
        this._isCaller = isCaller;
        this._peerId = peerId;
        this._conn = new RTCPeerConnection(RTCPeer.config);
        this._conn.onicecandidate = e => this._onIceCandidate(e);
        this._conn.onconnectionstatechange = e => this._onConnectionStateChange(e);
        this._conn.oniceconnectionstatechange = e => this._onIceConnectionStateChange(e);
    }

    _openChannel() {
        const channel = this._conn.createDataChannel('data-channel', { 
            ordered: true,
            reliable: true // Obsolete. See https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/reliable
        });
        channel.onopen = e => this._onChannelOpened(e);
        this._conn.createOffer().then(d => this._onDescription(d)).catch(e => this._onError(e));
    }

    _onDescription(description) {
        // description.sdp = description.sdp.replace('b=AS:30', 'b=AS:1638400');
        this._conn.setLocalDescription(description)
            .then(_ => this._sendSignal({ sdp: description }))
            .catch(e => this._onError(e));
    }

    _onIceCandidate(event) {
        if (!event.candidate) return;
        this._sendSignal({ ice: event.candidate });
    }

    onServerMessage(message) {
        if (!this._conn) this._connect(message.sender, false);

        if (message.sdp) {
            this._conn.setRemoteDescription(new RTCSessionDescription(message.sdp))
                .then( _ => {
                    if (message.sdp.type === 'offer') {
                        return this._conn.createAnswer()
                            .then(d => this._onDescription(d));
                    }
                })
                .catch(e => this._onError(e));
        } else if (message.ice) {
            this._conn.addIceCandidate(new RTCIceCandidate(message.ice));
        }
    }

    _onChannelOpened(event) {
        console.log('RTC: channel opened with', this._peerId);
        const channel = event.channel || event.target;
        channel.binaryType = 'arraybuffer';
        channel.onmessage = e => this._onMessage(e.data);
        channel.onclose = e => this._onChannelClosed();
        this._channel = channel;
    }

    _onChannelClosed() {
        console.log('RTC: channel closed', this._peerId);
        if (!this.isCaller) return;
        this._connect(this._peerId, true); // reopen the channel
    }

    _onConnectionStateChange(e) {
        console.log('RTC: state changed:', this._conn.connectionState);
        switch (this._conn.connectionState) {
            case 'disconnected':
                this._onChannelClosed();
                break;
            case 'failed':
                this._conn = null;
                this._onChannelClosed();
                break;
        }
    }

    _onIceConnectionStateChange() {
        switch (this._conn.iceConnectionState) {
            case 'failed':
                console.error('ICE Gathering failed');
                break;
            default:
                console.log('ICE Gathering', this._conn.iceConnectionState);
        }
    }

    _onError(error) {
        console.error(error);
    }

    _send(message) {
        if (!this._channel) return this.refresh();
        this._channel.send(message);
    }

    _sendSignal(signal) {
        signal.type = 'signal';
        signal.to = this._peerId;
        this._server.send(signal);
    }

    refresh() {
        // check if channel is open. otherwise create one
        if (this._isConnected() || this._isConnecting()) return;
        this._connect(this._peerId, this._isCaller);
    }

    _isConnected() {
        return this._channel && this._channel.readyState === 'open';
    }

    _isConnecting() {
        return this._channel && this._channel.readyState === 'connecting';
    }
}

class PeersManager {

    constructor(serverConnection) {
        this.peers = {};
        this._server = serverConnection;
        Events.on('signal', e => this._onMessage(e.detail));
        Events.on('peers', e => this._onPeers(e.detail));
        Events.on('files-selected', e => this._onFilesSelected(e.detail));
        Events.on('send-text', e => this._onSendText(e.detail));
        Events.on('peer-left', e => this._onPeerLeft(e.detail));
    }

    _onMessage(message) {
        if (!this.peers[message.sender]) {
            this.peers[message.sender] = new RTCPeer(this._server);
        }
        this.peers[message.sender].onServerMessage(message);
    }

    _onPeers(peers) {
        peers.forEach(peer => {
            if (this.peers[peer.id]) {
                this.peers[peer.id].refresh();
                return;
            }
            if (window.isRtcSupported && peer.rtcSupported) {
                this.peers[peer.id] = new RTCPeer(this._server, peer.id);
            } else {
                this.peers[peer.id] = new WSPeer(this._server, peer.id);
            }
        })
    }

    sendTo(peerId, message) {
        this.peers[peerId].send(message);
    }

    _onFilesSelected(message) {
        this.peers[message.to].sendFiles(message.files);
    }

    _onSendText(message) {
        this.peers[message.to].sendText(message.text);
    }

    _onPeerLeft(peerId) {
        const peer = this.peers[peerId];
        delete this.peers[peerId];
        if (!peer || !peer._peer) return;
        peer._peer.close();
    }

}

class WSPeer {
    _send(message) {
        message.to = this._peerId;
        this._server.send(message);
    }
}

class FileChunker {

    constructor(file, onChunk, onPartitionEnd) {
        this._chunkSize = 64000; // 64 KB
        this._maxPartitionSize = 1e6; // 1 MB
        this._offset = 0;
        this._partitionSize = 0;
        this._file = file;
        this._onChunk = onChunk;
        this._onPartitionEnd = onPartitionEnd;
        this._reader = new FileReader();
        this._reader.addEventListener('load', e => this._onChunkRead(e.target.result));
    }

    nextPartition() {
        this._partitionSize = 0;
        this._readChunk();
    }

    _readChunk() {
        const chunk = this._file.slice(this._offset, this._offset + this._chunkSize);
        this._reader.readAsArrayBuffer(chunk);
    }

    _onChunkRead(chunk) {
        this._offset += chunk.byteLength;
        this._partitionSize += chunk.byteLength;
        this._onChunk(chunk);
        if (this.isFileEnd()) return;
        if (this._isPartitionEnd()) {
            this._onPartitionEnd(this._offset);
            return;
        }
        this._readChunk();
    }

    repeatPartition() {
        this._offset -= this._partitionSize;
        this._nextPartition();
    }

    _isPartitionEnd() {
        return this._partitionSize >= this._maxPartitionSize;
    }

    isFileEnd() {
        return this._offset >= this._file.size;
    }

    get progress() {
        return this._offset / this._file.size;
    }
}

class FileDigester {

    constructor(meta, callback) {
        this._buffer = [];
        this._bytesReceived = 0;
        this._size = meta.size;
        this._mime = meta.mime || 'application/octet-stream';
        this._name = meta.name;
        this._callback = callback;
    }

    unchunk(chunk) {
        this._buffer.push(chunk);
        this._bytesReceived += chunk.byteLength || chunk.size;
        const totalChunks = this._buffer.length;
        this.progress = this._bytesReceived / this._size;
        if (isNaN(this.progress)) this.progress = 1

        if (this._bytesReceived < this._size) return;
        // we are done
        let blob = new Blob(this._buffer, { type: this._mime });
        this._callback({
            name: this._name,
            mime: this._mime,
            size: this._size,
            blob: blob
        });
    }

}

class Events {
    static fire(type, detail) {
        window.dispatchEvent(new CustomEvent(type, { detail: detail }));
    }

    static on(type, callback) {
        return window.addEventListener(type, callback, false);
    }

    static off(type, callback) {
        return window.removeEventListener(type, callback, false);
    }
}


RTCPeer.config = {
    'sdpSemantics': 'unified-plan',
    'iceServers': [{
        urls: 'stun:stun.l.google.com:19302'
    }]
}


================================================
FILE: client/scripts/ui.js
================================================
const $ = query => document.getElementById(query);
const $$ = query => document.body.querySelector(query);
const isURL = text => /^((https?:\/\/|www)[^\s]+)/g.test(text.toLowerCase());
window.isDownloadSupported = (typeof document.createElement('a').download !== 'undefined');
window.isProductionEnvironment = !window.location.host.startsWith('localhost');
window.iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

// set display name
Events.on('display-name', e => {
    const me = e.detail.message;
    const $displayName = $('displayName')
    $displayName.textContent = 'You are known as ' + me.displayName;
    $displayName.title = me.deviceName;
});

class PeersUI {

    constructor() {
        Events.on('peer-joined', e => this._onPeerJoined(e.detail));
        Events.on('peer-left', e => this._onPeerLeft(e.detail));
        Events.on('peers', e => this._onPeers(e.detail));
        Events.on('file-progress', e => this._onFileProgress(e.detail));
        Events.on('paste', e => this._onPaste(e));
    }

    _onPeerJoined(peer) {
        if ($(peer.id)) return; // peer already exists
        const peerUI = new PeerUI(peer);
        $$('x-peers').appendChild(peerUI.$el);
        setTimeout(e => window.animateBackground(false), 1750); // Stop animation
    }

    _onPeers(peers) {
        this._clearPeers();
        peers.forEach(peer => this._onPeerJoined(peer));
    }

    _onPeerLeft(peerId) {
        const $peer = $(peerId);
        if (!$peer) return;
        $peer.remove();
    }

    _onFileProgress(progress) {
        const peerId = progress.sender || progress.recipient;
        const $peer = $(peerId);
        if (!$peer) return;
        $peer.ui.setProgress(progress.progress);
    }

    _clearPeers() {
        const $peers = $$('x-peers').innerHTML = '';
    }

    _onPaste(e) {
        const files = e.clipboardData.files || e.clipboardData.items
            .filter(i => i.type.indexOf('image') > -1)
            .map(i => i.getAsFile());
        const peers = document.querySelectorAll('x-peer');
        // send the pasted image content to the only peer if there is one
        // otherwise, select the peer somehow by notifying the client that
        // "image data has been pasted, click the client to which to send it"
        // not implemented
        if (files.length > 0 && peers.length === 1) {
            Events.fire('files-selected', {
                files: files,
                to: $$('x-peer').id
            });
        }
    }
}

class PeerUI {

    html() {
        return `
            <label class="column center" title="Click to send files or right click to send a text">
                <input type="file" multiple>
                <x-icon shadow="1">
                    <svg class="icon"><use xlink:href="#"/></svg>
                </x-icon>
                <div class="progress">
                  <div class="circle"></div>
                  <div class="circle right"></div>
                </div>
                <div class="name font-subheading"></div>
                <div class="device-name font-body2"></div>
                <div class="status font-body2"></div>
            </label>`
    }

    constructor(peer) {
        this._peer = peer;
        this._initDom();
        this._bindListeners(this.$el);
    }

    _initDom() {
        const el = document.createElement('x-peer');
        el.id = this._peer.id;
        el.innerHTML = this.html();
        el.ui = this;
        el.querySelector('svg use').setAttribute('xlink:href', this._icon());
        el.querySelector('.name').textContent = this._displayName();
        el.querySelector('.device-name').textContent = this._deviceName();
        this.$el = el;
        this.$progress = el.querySelector('.progress');
    }

    _bindListeners(el) {
        el.querySelector('input').addEventListener('change', e => this._onFilesSelected(e));
        el.addEventListener('drop', e => this._onDrop(e));
        el.addEventListener('dragend', e => this._onDragEnd(e));
        el.addEventListener('dragleave', e => this._onDragEnd(e));
        el.addEventListener('dragover', e => this._onDragOver(e));
        el.addEventListener('contextmenu', e => this._onRightClick(e));
        el.addEventListener('touchstart', e => this._onTouchStart(e));
        el.addEventListener('touchend', e => this._onTouchEnd(e));
        // prevent browser's default file drop behavior
        Events.on('dragover', e => e.preventDefault());
        Events.on('drop', e => e.preventDefault());
    }

    _displayName() {
        return this._peer.name.displayName;
    }

    _deviceName() {
        return this._peer.name.deviceName;
    }

    _icon() {
        const device = this._peer.name.device || this._peer.name;
        if (device.type === 'mobile') {
            return '#phone-iphone';
        }
        if (device.type === 'tablet') {
            return '#tablet-mac';
        }
        return '#desktop-mac';
    }

    _onFilesSelected(e) {
        const $input = e.target;
        const files = $input.files;
        Events.fire('files-selected', {
            files: files,
            to: this._peer.id
        });
        $input.value = null; // reset input
    }

    setProgress(progress) {
        if (progress > 0) {
            this.$el.setAttribute('transfer', '1');
        }
        if (progress > 0.5) {
            this.$progress.classList.add('over50');
        } else {
            this.$progress.classList.remove('over50');
        }
        const degrees = `rotate(${360 * progress}deg)`;
        this.$progress.style.setProperty('--progress', degrees);
        if (progress >= 1) {
            this.setProgress(0);
            this.$el.removeAttribute('transfer');
        }
    }

    _onDrop(e) {
        e.preventDefault();
        const files = e.dataTransfer.files;
        Events.fire('files-selected', {
            files: files,
            to: this._peer.id
        });
        this._onDragEnd();
    }

    _onDragOver() {
        this.$el.setAttribute('drop', 1);
    }

    _onDragEnd() {
        this.$el.removeAttribute('drop');
    }

    _onRightClick(e) {
        e.preventDefault();
        Events.fire('text-recipient', this._peer.id);
    }

    _onTouchStart(e) {
        this._touchStart = Date.now();
        this._touchTimer = setTimeout(_ => this._onTouchEnd(), 610);
    }

    _onTouchEnd(e) {
        if (Date.now() - this._touchStart < 500) {
            clearTimeout(this._touchTimer);
        } else { // this was a long tap
            if (e) e.preventDefault();
            Events.fire('text-recipient', this._peer.id);
        }
    }
}


class Dialog {
    constructor(id) {
        this.$el = $(id);
        this.$el.querySelectorAll('[close]').forEach(el => el.addEventListener('click', e => this.hide()))
        this.$autoFocus = this.$el.querySelector('[autofocus]');
    }

    show() {
        this.$el.setAttribute('show', 1);
        if (this.$autoFocus) this.$autoFocus.focus();
    }

    hide() {
        this.$el.removeAttribute('show');
        document.activeElement.blur();
        window.blur();
    }
}

class ReceiveDialog extends Dialog {

    constructor() {
        super('receiveDialog');
        Events.on('file-received', e => {
            this._nextFile(e.detail);
            window.blop.play();
        });
        this._filesQueue = [];
    }

    _nextFile(nextFile) {
        if (nextFile) this._filesQueue.push(nextFile);
        if (this._busy) return;
        this._busy = true;
        const file = this._filesQueue.shift();
        this._displayFile(file);
    }

    _dequeueFile() {
        if (!this._filesQueue.length) { // nothing to do
            this._busy = false;
            return;
        }
        // dequeue next file
        setTimeout(_ => {
            this._busy = false;
            this._nextFile();
        }, 300);
    }

    _displayFile(file) {
        const $a = this.$el.querySelector('#download');
        const url = URL.createObjectURL(file.blob);
        $a.href = url;
        $a.download = file.name;

        if(this._autoDownload()){
            $a.click()
            return
        }
        if(file.mime.split('/')[0] === 'image'){
            console.log('the file is image');
            this.$el.querySelector('.preview').style.visibility = 'inherit';
            this.$el.querySelector("#img-preview").src = url;
        }

        this.$el.querySelector('#fileName').textContent = file.name;
        this.$el.querySelector('#fileSize').textContent = this._formatFileSize(file.size);
        this.show();

        if (window.isDownloadSupported) return;
        // fallback for iOS
        $a.target = '_blank';
        const reader = new FileReader();
        reader.onload = e => $a.href = reader.result;
        reader.readAsDataURL(file.blob);
    }

    _formatFileSize(bytes) {
        if (bytes >= 1e9) {
            return (Math.round(bytes / 1e8) / 10) + ' GB';
        } else if (bytes >= 1e6) {
            return (Math.round(bytes / 1e5) / 10) + ' MB';
        } else if (bytes > 1000) {
            return Math.round(bytes / 1000) + ' KB';
        } else {
            return bytes + ' Bytes';
        }
    }

    hide() {
        this.$el.querySelector('.preview').style.visibility = 'hidden';
        this.$el.querySelector("#img-preview").src = "";
        super.hide();
        this._dequeueFile();
    }


    _autoDownload(){
        return !this.$el.querySelector('#autoDownload').checked
    }
}


class SendTextDialog extends Dialog {
    constructor() {
        super('sendTextDialog');
        Events.on('text-recipient', e => this._onRecipient(e.detail))
        this.$text = this.$el.querySelector('#textInput');
        const button = this.$el.querySelector('form');
        button.addEventListener('submit', e => this._send(e));
    }

    _onRecipient(recipient) {
        this._recipient = recipient;
        this._handleShareTargetText();
        this.show();

        const range = document.createRange();
        const sel = window.getSelection();

        range.selectNodeContents(this.$text);
        sel.removeAllRanges();
        sel.addRange(range);

    }

    _handleShareTargetText() {
        if (!window.shareTargetText) return;
        this.$text.textContent = window.shareTargetText;
        window.shareTargetText = '';
    }

    _send(e) {
        e.preventDefault();
        Events.fire('send-text', {
            to: this._recipient,
            text: this.$text.innerText
        });
    }
}

class ReceiveTextDialog extends Dialog {
    constructor() {
        super('receiveTextDialog');
        Events.on('text-received', e => this._onText(e.detail))
        this.$text = this.$el.querySelector('#text');
        const $copy = this.$el.querySelector('#copy');
        copy.addEventListener('click', _ => this._onCopy());
    }

    _onText(e) {
        this.$text.innerHTML = '';
        const text = e.text;
        if (isURL(text)) {
            const $a = document.createElement('a');
            $a.href = text;
            $a.target = '_blank';
            $a.textContent = text;
            this.$text.appendChild($a);
        } else {
            this.$text.textContent = text;
        }
        this.show();
        window.blop.play();
    }

    async _onCopy() {
        await navigator.clipboard.writeText(this.$text.textContent);
        Events.fire('notify-user', 'Copied to clipboard');
    }
}

class Toast extends Dialog {
    constructor() {
        super('toast');
        Events.on('notify-user', e => this._onNotfiy(e.detail));
    }

    _onNotfiy(message) {
        this.$el.textContent = message;
        this.show();
        setTimeout(_ => this.hide(), 3000);
    }
}


class Notifications {

    constructor() {
        // Check if the browser supports notifications
        if (!('Notification' in window)) return;

        // Check whether notification permissions have already been granted
        if (Notification.permission !== 'granted') {
            this.$button = $('notification');
            this.$button.removeAttribute('hidden');
            this.$button.addEventListener('click', e => this._requestPermission());
        }
        Events.on('text-received', e => this._messageNotification(e.detail.text));
        Events.on('file-received', e => this._downloadNotification(e.detail.name));
    }

    _requestPermission() {
        Notification.requestPermission(permission => {
            if (permission !== 'granted') {
                Events.fire('notify-user', Notifications.PERMISSION_ERROR || 'Error');
                return;
            }
            this._notify('Even more snappy sharing!');
            this.$button.setAttribute('hidden', 1);
        });
    }

    _notify(message, body) {
        const config = {
            body: body,
            icon: '/images/logo_transparent_128x128.png',
        }
        let notification;
        try {
            notification = new Notification(message, config);
        } catch (e) {
            // Android doesn't support "new Notification" if service worker is installed
            if (!serviceWorker || !serviceWorker.showNotification) return;
            notification = serviceWorker.showNotification(message, config);
        }

        // Notification is persistent on Android. We have to close it manually
        const visibilitychangeHandler = () => {                             
            if (document.visibilityState === 'visible') {    
                notification.close();
                Events.off('visibilitychange', visibilitychangeHandler);
            }                                                       
        };                                                                                
        Events.on('visibilitychange', visibilitychangeHandler);

        return notification;
    }

    _messageNotification(message) {
        if (document.visibilityState !== 'visible') {
            if (isURL(message)) {
                const notification = this._notify(message, 'Click to open link');
                this._bind(notification, e => window.open(message, '_blank', null, true));
            } else {
                const notification = this._notify(message, 'Click to copy text');
                this._bind(notification, e => this._copyText(message, notification));
            }
        }
    }

    _downloadNotification(message) {
        if (document.visibilityState !== 'visible') {
            const notification = this._notify(message, 'Click to download');
            if (!window.isDownloadSupported) return;
            this._bind(notification, e => this._download(notification));
        }
    }

    _download(notification) {
        document.querySelector('x-dialog [download]').click();
        notification.close();
    }

    _copyText(message, notification) {
        notification.close();
        if (!navigator.clipboard.writeText(message)) return;
        this._notify('Copied text to clipboard');
    }

    _bind(notification, handler) {
        if (notification.then) {
            notification.then(e => serviceWorker.getNotifications().then(notifications => {
                serviceWorker.addEventListener('notificationclick', handler);
            }));
        } else {
            notification.onclick = handler;
        }
    }
}


class NetworkStatusUI {

    constructor() {
        window.addEventListener('offline', e => this._showOfflineMessage(), false);
        window.addEventListener('online', e => this._showOnlineMessage(), false);
        if (!navigator.onLine) this._showOfflineMessage();
    }

    _showOfflineMessage() {
        Events.fire('notify-user', 'You are offline');
    }

    _showOnlineMessage() {
        Events.fire('notify-user', 'You are back online');
    }
}

class WebShareTargetUI {
    constructor() {
        const parsedUrl = new URL(window.location);
        const title = parsedUrl.searchParams.get('title');
        const text = parsedUrl.searchParams.get('text');
        const url = parsedUrl.searchParams.get('url');

        let shareTargetText = title ? title : '';
        shareTargetText += text ? shareTargetText ? ' ' + text : text : '';

        if(url) shareTargetText = url; // We share only the Link - no text. Because link-only text becomes clickable.

        if (!shareTargetText) return;
        window.shareTargetText = shareTargetText;
        history.pushState({}, 'URL Rewrite', '/');
        console.log('Shared Target Text:', '"' + shareTargetText + '"');
    }
}


class Snapdrop {
    constructor() {
        const server = new ServerConnection();
        const peers = new PeersManager(server);
        const peersUI = new PeersUI();
        Events.on('load', e => {
            const receiveDialog = new ReceiveDialog();
            const sendTextDialog = new SendTextDialog();
            const receiveTextDialog = new ReceiveTextDialog();
            const toast = new Toast();
            const notifications = new Notifications();
            const networkStatusUI = new NetworkStatusUI();
            const webShareTargetUI = new WebShareTargetUI();
        });
    }
}

const snapdrop = new Snapdrop();



if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('service-worker.js')
        .then(serviceWorker => {
            console.log('Service Worker registered');
            window.serviceWorker = serviceWorker
        });
}

window.addEventListener('beforeinstallprompt', e => {
    if (window.matchMedia('(display-mode: standalone)').matches) {
        // don't display install banner when installed
        return e.preventDefault();
    } else {
        const btn = document.querySelector('#install')
        btn.hidden = false;
        btn.onclick = _ => e.prompt();
        return e.preventDefault();
    }
});

// Background Animation
Events.on('load', () => {
    let c = document.createElement('canvas');
    document.body.appendChild(c);
    let style = c.style;
    style.width = '100%';
    style.position = 'absolute';
    style.zIndex = -1;
    style.top = 0;
    style.left = 0;
    let ctx = c.getContext('2d');
    let x0, y0, w, h, dw;

    function init() {
        w = window.innerWidth;
        h = window.innerHeight;
        c.width = w;
        c.height = h;
        let offset = h > 380 ? 100 : 65;
        offset = h > 800 ? 116 : offset;
        x0 = w / 2;
        y0 = h - offset;
        dw = Math.max(w, h, 1000) / 13;
        drawCircles();
    }
    window.onresize = init;

    function drawCircle(radius) {
        ctx.beginPath();
        let color = Math.round(197 * (1 - radius / Math.max(w, h)));
        ctx.strokeStyle = 'rgba(' + color + ',' + color + ',' + color + ',0.1)';
        ctx.arc(x0, y0, radius, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.lineWidth = 2;
    }

    let step = 0;

    function drawCircles() {
        ctx.clearRect(0, 0, w, h);
        for (let i = 0; i < 8; i++) {
            drawCircle(dw * i + step % dw);
        }
        step += 1;
    }

    let loading = true;

    function animate() {
        if (loading || step % dw < dw - 5) {
            requestAnimationFrame(function() {
                drawCircles();
                animate();
            });
        }
    }
    window.animateBackground = function(l) {
        loading = l;
        animate();
    };
    init();
    animate();
});

Notifications.PERMISSION_ERROR = `
Notifications permission has been blocked
as the user has dismissed the permission prompt several times.
This can be reset in Page Info
which can be accessed by clicking the lock icon next to the URL.`;

document.body.onclick = e => { // safari hack to fix audio
    document.body.onclick = null;
    if (!(/.*Version.*Safari.*/.test(navigator.userAgent))) return;
    blop.play();
}


================================================
FILE: client/service-worker.js
================================================
var CACHE_NAME = 'snapdrop-cache-v2';
var urlsToCache = [
  'index.html',
  './',
  'styles.css',
  'scripts/network.js',
  'scripts/ui.js',
  'scripts/clipboard.js',
  'sounds/blop.mp3',
  'images/favicon-96x96.png'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});


self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});


self.addEventListener('activate', function(event) {
  console.log('Updating Service Worker...')
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheName) {
          // Return true if you want to remove this cache,
          // but remember that caches are shared across
          // the whole origin
          return true
        }).map(function(cacheName) {
          return caches.delete(cacheName);
        })
      );
    })
  );
});


================================================
FILE: client/styles.css
================================================
/* Constants */

:root {
    --icon-size: 24px;
    --primary-color: #4285f4;
    --peer-width: 120px;
    --text-color: #333;
    --bg-color: #fafafa;
    --bg-color-secondary: #f1f3f4;
}

/* Layout */

html {
    height: 100%;
}

html,
body {
    margin: 0;
    display: flex;
    flex-direction: column;
    width: 100%;
    overflow-x: hidden;
}

body {
    flex-grow: 1;
    align-items: center;
    justify-content: center;
    overflow-y: hidden;
}

.row-reverse {
    display: flex;
    flex-direction: row-reverse;
}

.row {
    display: flex;
    flex-direction: row;
}

.column {
    display: flex;
    flex-direction: column;
}

.center {
    display: flex;
    align-items: center;
    justify-content: center;
}

.grow {
    flex-grow: 1;
}

.full {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

header {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 56px;
    align-items: center;
    padding: 16px;
    box-sizing: border-box;
}

[hidden] {
    display: none !important;
}


/* Typography */

body {
    font-family: -apple-system, BlinkMacSystemFont, Roboto, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

h1 {
    font-size: 34px;
    font-weight: 400;
    letter-spacing: -.01em;
    line-height: 40px;
    margin: 8px 0 0;
}

h2 {
    font-size: 24px;
    font-weight: 400;
    letter-spacing: -.012em;
    line-height: 32px;
}

h3 {
    font-size: 20px;
    font-weight: 500;
    margin: 16px 0;
}

.font-subheading {
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    word-break: break-all;
}

.font-body1,
body {
    font-size: 14px;
    font-weight: 400;
    line-height: 20px;
}

.font-body2 {
    font-size: 12px;
    line-height: 18px;
}

a {
    text-decoration: none;
    color: currentColor;
    cursor: pointer;
}



/* Icons */

.icon {
    width: var(--icon-size);
    height: var(--icon-size);
    fill: currentColor;
}



/* Shadows */

[shadow="1"] {
    box-shadow: 0 3px 4px 0 rgba(0, 0, 0, 0.14),
        0 1px 8px 0 rgba(0, 0, 0, 0.12),
        0 3px 3px -2px rgba(0, 0, 0, 0.4);
}

[shadow="2"] {
    box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14),
        0 1px 10px 0 rgba(0, 0, 0, 0.12),
        0 2px 4px -1px rgba(0, 0, 0, 0.4);
}




/* Animations */

@keyframes fade-in {
    0% {
        opacity: 0;
    }
}

/* Main Header */

body>header a {
    margin-left: 8px;
}

/* Peers List */

x-peers {
    width: 100%;
    overflow: hidden;
    flex-flow: row wrap;
    z-index: 2;
}

/* Empty Peers List */

x-no-peers {
    padding: 8px;
    text-align: center;
    /* prevent flickering on load */
    animation: fade-in 300ms;
    animation-delay: 500ms;
    animation-fill-mode: backwards;
}

x-no-peers h2,
x-no-peers a {
    color: var(--primary-color);
}

x-peers:not(:empty)+x-no-peers {
    display: none;
}



/* Peer */

x-peer {
    -webkit-user-select: none;
    user-select: none;
}

x-peer label {
    width: var(--peer-width);
    padding: 8px;
    cursor: pointer;
    touch-action: manipulation;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    position: relative;
}

x-peer .name {
    width: var(--peer-width);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: center;
}

input[type="file"] {
    visibility: hidden;
    position: absolute;
}

x-peer x-icon {
    --icon-size: 40px;
    width: var(--icon-size);
    padding: 12px;
    border-radius: 50%;
    background: var(--primary-color);
    color: white;
    display: flex;
    margin-bottom: 8px;
    transition: transform 150ms;
    will-change: transform;
}

x-peer:not([transfer]):hover x-icon,
x-peer:not([transfer]):focus x-icon {
    transform: scale(1.05);
}

x-peer[transfer] x-icon {
    box-shadow: none;
    opacity: 0.8;
    transform: scale(1);
}

.status,
.device-name {
    height: 18px;
    opacity: 0.7;
}

x-peer[transfer] .status:before {
    content: 'Transferring...';
}

x-peer:not([transfer]) .status,
x-peer[transfer] .device-name {
    display: none;
}

x-peer x-icon {
    animation: pop 600ms ease-out 1;
}

@keyframes pop {
    0% {
        transform: scale(0.7);
    }

    40% {
        transform: scale(1.2);
    }
}

x-peer[drop] x-icon {
    transform: scale(1.1);
}



/* Footer */

footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    align-items: center;
    padding: 0 0 16px 0;
    text-align: center;
}

footer .logo {
    --icon-size: 80px;
    margin-bottom: 8px;
    color: var(--primary-color);
}

footer .font-body2 {
    color: var(--primary-color);
}

@media (min-height: 800px) {
    footer {
        margin-bottom: 16px;
    }
}


/* Dialog */

x-dialog x-background {
    background: rgba(0, 0, 0, 0.61);
    z-index: 10;
    transition: opacity 300ms;
    will-change: opacity;
    padding: 16px;
}

x-dialog x-paper {
    z-index: 3;
    background: white;
    border-radius: 8px;
    padding: 16px 24px;
    width: 100%;
    max-width: 400px;
    box-sizing: border-box;
    transition: transform 300ms;
    will-change: transform;
}

x-dialog:not([show]) {
    pointer-events: none;
}

x-dialog:not([show]) x-paper {
    transform: scale(0.1);
}

x-dialog:not([show]) x-background {
    opacity: 0;
}

x-dialog .row-reverse>.button {
    margin-top: 16px;
    margin-left: 8px;
}

x-dialog a {
    color: var(--primary-color);
}

/* Receive Dialog */
#receiveDialog .row {
    margin-top: 24px;
    margin-bottom: 8px;
}

/* Receive Text Dialog */

#receiveTextDialog #text {
    width: 100%;
    word-break: break-all;
    max-height: 300px;
    overflow-x: hidden;
    overflow-y: auto;
    -webkit-user-select: all;
    -moz-user-select: all;
    user-select: all;
    white-space: pre-wrap;
}

#receiveTextDialog #text a {
    cursor: pointer;
}

#receiveTextDialog #text a:hover {
    text-decoration: underline;
}

#receiveTextDialog h3 {
    /* Select the received text when double-clicking the dialog */
    user-select: none;
    pointer-events: none;
}

/* Button */

.button {
    padding: 0 16px;
    box-sizing: border-box;
    min-height: 36px;
    min-width: 100px;
    font-size: 14px;
    line-height: 24px;
    font-weight: 700;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    white-space: nowrap;
    cursor: pointer;
    user-select: none;
    background: inherit;
    color: var(--primary-color);
}

.button,
.icon-button {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    touch-action: manipulation;
    border: none;
    outline: none;
}

.button:before,
.icon-button:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: currentColor;
    opacity: 0;
    transition: opacity 300ms;
}

.button:hover:before,
.icon-button:hover:before {
    opacity: 0.1;
}

.button:before {
    border-radius: 8px;
}

.button:focus:before,
.icon-button:focus:before {
    opacity: 0.2;
}



button::-moz-focus-inner {
    border: 0;
}


/* Icon Button */

.icon-button {
    width: 40px;
    height: 40px;
}

.icon-button:before {
    border-radius: 50%;
}



/* Text Input */

.textarea {
    box-sizing: border-box;
    border: none;
    outline: none;
    padding: 16px 24px;
    border-radius: 16px;
    margin: 8px 0;
    font-size: 14px;
    font-family: inherit;
    background: #f1f3f4;
    display: block;
    overflow: auto;
    resize: none;
    min-height: 40px;
    line-height: 16px;
    max-height: 300px;
}


/* Info Animation */

#about {
    color: white;
    z-index: 11;
    overflow: hidden;
    pointer-events: none;
    text-align: center;
}

#about .fade-in {
    transition: opacity 300ms;
    will-change: opacity;
    transition-delay: 300ms;
    z-index: 11;
    pointer-events: all;
}

#about:not(:target) .fade-in {
    opacity: 0;
    pointer-events: none;
    transition-delay: 0;
}

#about .logo {
    --icon-size: 96px;
}

#about x-background {
    position: absolute;
    top: calc(32px - 200px);
    right: calc(32px - 200px);
    width: 400px;
    height: 400px;
    border-radius: 50%;
    background: var(--primary-color);
    transform: scale(0);
    z-index: -1;
}

/* Hack such that initial scale(0) isn't animated */
#about x-background {
    will-change: transform;
    transition: transform 800ms cubic-bezier(0.77, 0, 0.175, 1);
}

#about:target x-background {
    transform: scale(12);
}

#about .row a {
    margin: 8px 8px -16px;
}


/* Loading Indicator */

.progress {
    width: 80px;
    height: 80px;
    position: absolute;
    top: 0px;
    clip: rect(0px, 80px, 80px, 40px);
    --progress: rotate(0deg);
    transition: transform 200ms;
}

.circle {
    width: 72px;
    height: 72px;
    border: 4px solid var(--primary-color);
    border-radius: 40px;
    position: absolute;
    clip: rect(0px, 40px, 80px, 0px);
    will-change: transform;
    transform: var(--progress);
}

.over50 {
    clip: rect(auto, auto, auto, auto);
}

.over50 .circle.right {
    transform: rotate(180deg);
}


/* Generic placeholder */
[placeholder]:empty:before {
    content: attr(placeholder);
}

/* Toast */

.toast-container {
    padding: 0 8px 24px;
    overflow: hidden;
    pointer-events: none;
}

x-toast {
    position: absolute;
    min-height: 48px;
    bottom: 24px;
    width: 100%;
    max-width: 344px;
    background-color: #323232;
    color: rgba(255, 255, 255, 0.95);
    align-items: center;
    box-sizing: border-box;
    padding: 8px 24px;
    z-index: 20;
    transition: opacity 200ms, transform 300ms ease-out;
    cursor: default;
    line-height: 24px;
    border-radius: 8px;
    pointer-events: all;
}

x-toast:not([show]):not(:hover) {
    opacity: 0;
    transform: translateY(100px);
}


/* Instructions */

x-instructions {
    position: absolute;
    top: 120px;
    opacity: 0.5;
    transition: opacity 300ms;
    z-index: -1;
    text-align: center;
}

x-instructions:before {
    content: attr(mobile);
}

x-peers:empty~x-instructions {
    opacity: 0;
}


/* Responsive Styles */

@media (min-height: 800px) {
    footer {
        margin-bottom: 16px;
    }
}

@media screen and (min-height: 800px),
screen and (min-width: 1100px) {
    x-instructions:before {
        content: attr(desktop);
    }
}

@media (max-height: 420px) {
    x-instructions {
        top: 24px;
    }

    footer .logo {
        --icon-size: 40px;
    }
}

/* 
    iOS specific styles
*/
@supports (-webkit-overflow-scrolling: touch) {

    
    html {
        position: fixed;
    }

    x-instructions:before {
        content: attr(mobile);
    }
}

/*
    Color Themes
*/

/* Default colors */
body {
    --text-color: #333;
    --bg-color: #fafafa;
    --bg-color-secondary: #f1f3f4;
}

/* Colored Elements */
body {
    color: var(--text-color);
    background-color: var(--bg-color);
    transition: background-color 0.5s ease;
}

x-dialog x-paper {
    background-color: var(--bg-color);
}

.textarea {
    color: var(--text-color);
    background-color: var(--bg-color-secondary);
}
/* Image Preview */
#img-preview{
    max-width: 100%;
    max-height: 50vh;
    margin: auto;
    display: block;
}

/* 
    Edge specific styles
*/
@supports (-ms-ime-align: auto) {

    html,
    body {
        overflow: hidden;
    }
}



================================================
FILE: docker/nginx/default.conf
================================================
server {
    listen       80;
    #server_name  your.domain;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    expires epoch;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /server {
        proxy_connect_timeout 300;
        proxy_pass http://node:3000;
        proxy_set_header Connection "upgrade";
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header X-Forwarded-for $remote_addr;
    }

    location /ca.crt {
        alias /etc/ssl/certs/snapdropCA.crt;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

server {
    listen       443 ssl http2;
    ssl_certificate /etc/ssl/certs/snapdrop-dev.crt;
    ssl_certificate_key /etc/ssl/certs/snapdrop-dev.key;

    #server_name  ;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    expires epoch;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /server {
        proxy_connect_timeout 300;
        proxy_pass http://node:3000;
        proxy_set_header Connection "upgrade";
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header X-Forwarded-for $remote_addr;
    }

    location /ca.crt {
        alias /etc/ssl/certs/snapdropCA.crt;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}



================================================
FILE: docker/nginx-with-openssl.Dockerfile
================================================
FROM nginx:alpine

RUN apk add --no-cache openssl

================================================
FILE: docker/openssl/create.sh
================================================
#!/bin/sh

cnf_dir='/mnt/openssl/'
certs_dir='/etc/ssl/certs/'
openssl req -config ${cnf_dir}snapdropCA.cnf -new -x509 -days 1 -keyout ${certs_dir}snapdropCA.key -out ${certs_dir}snapdropCA.crt
openssl req -config ${cnf_dir}snapdropCert.cnf -new -out /tmp/snapdrop-dev.csr -keyout ${certs_dir}snapdrop-dev.key
openssl x509 -req -in /tmp/snapdrop-dev.csr -CA ${certs_dir}snapdropCA.crt -CAkey ${certs_dir}snapdropCA.key -CAcreateserial -extensions req_ext -extfile ${cnf_dir}snapdropCert.cnf -sha512 -days 1 -out ${certs_dir}snapdrop-dev.crt

exec "$@"

================================================
FILE: docker/openssl/snapdropCA.cnf
================================================
[ req ]
default_bits       = 2048
default_md         = sha256
default_days       = 1
encrypt_key        = no
distinguished_name = subject
x509_extensions    = x509_ext
string_mask        = utf8only
prompt             = no

[ subject ]
organizationName = Snapdrop
OU               = CA
commonName       = snapdrop-CA

[ x509_ext ]
subjectKeyIdentifier      = hash
authorityKeyIdentifier    = keyid:always,issuer

# You only need digitalSignature below. *If* you don't allow
#   RSA Key transport (i.e., you use ephemeral cipher suites), then
#   omit keyEncipherment because that's key transport.

basicConstraints = critical, CA:TRUE, pathlen:0
keyUsage         = critical, digitalSignature, keyEncipherment, cRLSign, keyCertSign



================================================
FILE: docker/openssl/snapdropCert.cnf
================================================
[ req ]
default_bits        = 2048
default_md          = sha256
default_days        = 1
encrypt_key         = no
distinguished_name  = subject
req_extensions      = req_ext
string_mask         = utf8only
prompt              = no

[ subject ]
organizationName    = Snapdrop
OU                  = Development

# Use a friendly name here because it's presented to the user. The server's DNS
#   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
#   by both IETF and CA/Browser Forums. If you place a DNS name here, then you
#   must include the DNS name in the SAN too (otherwise, Chrome and others that
#   strictly follow the CA/Browser Baseline Requirements will fail).

commonName           = ${ENV::FQDN}

[ req_ext ]
subjectKeyIdentifier = hash
basicConstraints     = CA:FALSE
keyUsage             = digitalSignature, keyEncipherment
subjectAltName       = DNS:${ENV::FQDN}
nsComment            = "OpenSSL Generated Certificate"
extendedKeyUsage     = serverAuth

================================================
FILE: docker-compose.yml
================================================
version: "3"
services:
  node:
    image: "node:lts-alpine"
    user: "node"
    working_dir: /home/node/app
    volumes:
      - ./server/:/home/node/app
    command: ash -c "npm i && node index.js"
  nginx:
    build:
      context: ./docker/
      dockerfile: nginx-with-openssl.Dockerfile
    image: "nginx-with-openssl"
    volumes:
      - ./client:/usr/share/nginx/html
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
      - ./docker/certs:/etc/ssl/certs
      - ./docker/openssl:/mnt/openssl
    ports:
      - "8080:80"
      - "443:443"
    env_file: ./docker/fqdn.env
    entrypoint: /mnt/openssl/create.sh
    command: ["nginx", "-g", "daemon off;"]

================================================
FILE: docs/faq.md
================================================
# Frequently Asked Questions

### Instructions / Discussions
* [Video Instructions](https://www.youtube.com/watch?v=4XN02GkcHUM) (Big thanks to [TheiTeckHq](https://www.youtube.com/channel/UC_DUzWMb8gZZnAbISQjmAfQ))
* [idownloadblog](http://www.idownloadblog.com/2015/12/29/snapdrop/)
* [thenextweb](http://thenextweb.com/insider/2015/12/27/snapdrop-is-a-handy-web-based-replacement-for-apples-fiddly-airdrop-file-transfer-tool/)
* [winboard](http://www.winboard.org/artikel-ratgeber/6253-dateien-vom-desktop-pc-mit-anderen-plattformen-teilen-mit-snapdrop.html)
* [免費資源網路社群](https://free.com.tw/snapdrop/)
* [Hackernews](https://news.ycombinator.com/front?day=2020-12-24)
* [Reddit](https://www.reddit.com/r/Android/comments/et4qny/snapdrop_is_a_free_open_source_cross_platform/)
* [Producthunt](https://www.producthunt.com/posts/snapdrop)

### Help! I can't install the PWA!
if you are using a Chromium-based browser (Chrome, Edge, Brave, etc.), you can easily install Snapdrop PWA on your desktop by clicking the install button in the top-right corner while on [snapdrop.net](https://snapdrop.net) (see below).
<img src="pwa-install.png">

### What about the connection? Is it a P2P-connection directly from device to device or is there any third-party-server?
It uses a P2P connection if WebRTC is supported by the browser. WebRTC needs a Signaling Server, but it is only used to establish a connection and is not involved in the file transfer.

### What about privacy? Will files be saved on third-party-servers?
None of your files are ever sent to any server. Files are sent only between peers. Snapdrop doesn't even use a database. If you are curious have a look [at the Server](https://github.com/RobinLinus/snapdrop/blob/master/server/). Even if Snapdrop was able to view the files being transfered, WebRTC encrypts the files on transit, so the server would be unable to read them.

### What about security? Are my files encrypted while being sent between the computers?
Yes. Your files are sent using WebRTC, which encrypts them on transit.

### Why don't you implement feature xyz?
Snapdrop is a study in radical simplicity. The user interface is insanely simple. Features are chosen very carefully because complexity grows quadratically since every feature potentially interferes with each other feature. We focus very narrowly on a single use case: instant file transfer. 
We are not trying to optimize for some edge-cases. We are optimizing the user flow of the average users. Don't be sad if we decline your feature request for the sake of simplicity. 

If you want to learn more about simplicity you can read [Insanely Simple: The Obsession that Drives Apple's Success](https://www.amazon.com/Insanely-Simple-Ken-Segall-audiobook/dp/B007Z9686O) or [Thinking, Fast and Slow](https://www.amazon.com/Thinking-Fast-Slow-Daniel-Kahneman/dp/0374533555).


### Snapdrop is awesome! How can I support it? 
* [Donate via PayPal to help cover the server costs](https://www.paypal.com/donate/?hosted_button_id=FTP9DXUR7LA7Q)
* [File bugs, give feedback, submit suggestions](https://github.com/RobinLinus/snapdrop/issues)
* Share Snapdrop on your social media.
* Fix bugs and make a pull request. 
* Do security analysis and suggestions


## "Inofficial" Instances
Here's a list of other people hosting inofficial instances of Snapdrop:
- https://pairdrop.net/
- https://snapdrop.k26.ch/
- https://snapdrop.9pfs.repl.co/
- https://filedrop.codext.de/
- https://s.hoothin.com/
- https://www.wulingate.com/
- https://snapdrop.fairysoft.net/
- https://airtransferer.web.app/
- https://drop.wuyuan.dev
- https://share.jck.cx

DISCLAIMER: WE ARE NOT IN ANY WAY AFFILIATED WITH THE PEOPLE WHO RUN THESE INSTANCES. WE DO NOT KNOW THEM. WE CANNOT VERIFY THE CODE THEY ARE RUNNING!


## Third-Party Apps
Here's a list of some third-party Snapdrop apps:

1. [Snapdrop Desktop App](https://github.com/alextwothousand/snapdrop-desktop) built on top of Electron. (Thanks to [alextwothousand!](https://github.com/alextwothousand/)).

1. [Snapdrop Android App](https://github.com/fm-sys/snapdrop-android) allows you to also send files directly from other apps via the share action.

1. [Snapdrop Flutter App](https://github.com/congnguyendinh0/snapdrop_flutter)

1. [Snapdrop iOS App](https://github.com/CDsigma/Snapdrop-iOS-App)

1. [Snapdrop Node App (with completely Node server)](https://github.com/Bellisario/node-snapdrop)

1. [SnapDrop VSCode Extension](https://github.com/Yash-Garg/snapdrop-vsc)

1. Feel free to make one :)



[< Back](/README.md)


================================================
FILE: docs/local-dev.md
================================================
# Local Development
## Install

First, [Install docker with docker-compose.](https://docs.docker.com/compose/install/)

Then, clone the repository:
```
    git clone https://github.com/RobinLinus/snapdrop.git
    cd snapdrop
    docker-compose up -d
```
Now point your browser to `http://localhost:8080`.

- To restart the containers run `docker-compose restart`.
- To stop the containers run `docker-compose stop`.
- To debug the NodeJS server run `docker logs snapdrop_node_1`.


## Run locally by pulling image from Docker Hub

Have docker installed, then use the command:
```
    docker pull linuxserver/snapdrop
```

To run the image, type (if port 8080 is occupied by host use another random port <random port>:80):
```
    docker run -d -p 8080:80 linuxserver/snapdrop
```






## Testing PWA related features
PWAs require that the app is served under a correctly set up and trusted TLS endpoint.

The nginx container creates a CA certificate and a website certificate for you. To correctly set the common name of the certificate, you need to change the FQDN environment variable in `docker/fqdn.env` to the fully qualified domain name of your workstation.

If you want to test PWA features, you need to trust the CA of the certificate for your local deployment. For your convenience, you can download the crt file from `http://<Your FQDN>:8080/ca.crt`. Install that certificate to the trust store of your operating system.
- On Windows, make sure to install it to the `Trusted Root Certification Authorities` store.
- On MacOS, double click the installed CA certificate in `Keychain Access`, expand `Trust`, and select `Always Trust` for SSL.
- Firefox uses its own trust store. To install the CA, point Firefox at `http://<Your FQDN>:8080/ca.crt`. When prompted, select `Trust this CA to identify websites` and click OK.
- When using Chrome, you need to restart Chrome so it reloads the trust store (`chrome://restart`). Additionally, after installing a new cert, you need to clear the Storage (DevTools -> Application -> Clear storage -> Clear site data).

Please note that the certificates (CA and webserver cert) expire after a day.
Also, whenever you restart the nginx docker, container new certificates are created.

The site is served on `https://<Your FQDN>:443`.
    
## Deployment Notes
The client expects the server at http(s)://your.domain/server.

When serving the node server behind a proxy, the `X-Forwarded-For` header has to be set by the proxy. Otherwise, all clients that are served by the proxy will be mutually visible.

By default, the server listens on port 3000.

For an nginx configuration example, see `docker/nginx/default.conf`.

[< Back](/README.md)


================================================
FILE: server/index.js
================================================
var process = require('process')
// Handle SIGINT
process.on('SIGINT', () => {
  console.info("SIGINT Received, exiting...")
  process.exit(0)
})

// Handle SIGTERM
process.on('SIGTERM', () => {
  console.info("SIGTERM Received, exiting...")
  process.exit(0)
})

const parser = require('ua-parser-js');
const { uniqueNamesGenerator, animals, colors } = require('unique-names-generator');

class SnapdropServer {

    constructor(port) {
        const WebSocket = require('ws');
        this._wss = new WebSocket.Server({ port: port });
        this._wss.on('connection', (socket, request) => this._onConnection(new Peer(socket, request)));
        this._wss.on('headers', (headers, response) => this._onHeaders(headers, response));

        this._rooms = {};

        console.log('Snapdrop is running on port', port);
    }

    _onConnection(peer) {
        this._joinRoom(peer);
        peer.socket.on('message', message => this._onMessage(peer, message));
        peer.socket.on('error', console.error);
        this._keepAlive(peer);

        // send displayName
        this._send(peer, {
            type: 'display-name',
            message: {
                displayName: peer.name.displayName,
                deviceName: peer.name.deviceName
            }
        });
    }

    _onHeaders(headers, response) {
        if (response.headers.cookie && response.headers.cookie.indexOf('peerid=') > -1) return;
        response.peerId = Peer.uuid();
        headers.push('Set-Cookie: peerid=' + response.peerId + "; SameSite=Strict; Secure");
    }

    _onMessage(sender, message) {
        // Try to parse message 
        try {
            message = JSON.parse(message);
        } catch (e) {
            return; // TODO: handle malformed JSON
        }

        switch (message.type) {
            case 'disconnect':
                this._leaveRoom(sender);
                break;
            case 'pong':
                sender.lastBeat = Date.now();
                break;
        }

        // relay message to recipient
        if (message.to && this._rooms[sender.ip]) {
            const recipientId = message.to; // TODO: sanitize
            const recipient = this._rooms[sender.ip][recipientId];
            delete message.to;
            // add sender id
            message.sender = sender.id;
            this._send(recipient, message);
            return;
        }
    }

    _joinRoom(peer) {
        // if room doesn't exist, create it
        if (!this._rooms[peer.ip]) {
            this._rooms[peer.ip] = {};
        }

        // notify all other peers
        for (const otherPeerId in this._rooms[peer.ip]) {
            const otherPeer = this._rooms[peer.ip][otherPeerId];
            this._send(otherPeer, {
                type: 'peer-joined',
                peer: peer.getInfo()
            });
        }

        // notify peer about the other peers
        const otherPeers = [];
        for (const otherPeerId in this._rooms[peer.ip]) {
            otherPeers.push(this._rooms[peer.ip][otherPeerId].getInfo());
        }

        this._send(peer, {
            type: 'peers',
            peers: otherPeers
        });

        // add peer to room
        this._rooms[peer.ip][peer.id] = peer;
    }

    _leaveRoom(peer) {
        if (!this._rooms[peer.ip] || !this._rooms[peer.ip][peer.id]) return;
        this._cancelKeepAlive(this._rooms[peer.ip][peer.id]);

        // delete the peer
        delete this._rooms[peer.ip][peer.id];

        peer.socket.terminate();
        //if room is empty, delete the room
        if (!Object.keys(this._rooms[peer.ip]).length) {
            delete this._rooms[peer.ip];
        } else {
            // notify all other peers
            for (const otherPeerId in this._rooms[peer.ip]) {
                const otherPeer = this._rooms[peer.ip][otherPeerId];
                this._send(otherPeer, { type: 'peer-left', peerId: peer.id });
            }
        }
    }

    _send(peer, message) {
        if (!peer) return;
        if (this._wss.readyState !== this._wss.OPEN) return;
        message = JSON.stringify(message);
        peer.socket.send(message, error => '');
    }

    _keepAlive(peer) {
        this._cancelKeepAlive(peer);
        var timeout = 30000;
        if (!peer.lastBeat) {
            peer.lastBeat = Date.now();
        }
        if (Date.now() - peer.lastBeat > 2 * timeout) {
            this._leaveRoom(peer);
            return;
        }

        this._send(peer, { type: 'ping' });

        peer.timerId = setTimeout(() => this._keepAlive(peer), timeout);
    }

    _cancelKeepAlive(peer) {
        if (peer && peer.timerId) {
            clearTimeout(peer.timerId);
        }
    }
}



class Peer {

    constructor(socket, request) {
        // set socket
        this.socket = socket;


        // set remote ip
        this._setIP(request);

        // set peer id
        this._setPeerId(request)
        // is WebRTC supported ?
        this.rtcSupported = request.url.indexOf('webrtc') > -1;
        // set name 
        this._setName(request);
        // for keepalive
        this.timerId = 0;
        this.lastBeat = Date.now();
    }

    _setIP(request) {
        if (request.headers['x-forwarded-for']) {
            this.ip = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
        } else {
            this.ip = request.connection.remoteAddress;
        }
        // IPv4 and IPv6 use different values to refer to localhost
        if (this.ip == '::1' || this.ip == '::ffff:127.0.0.1') {
            this.ip = '127.0.0.1';
        }
    }

    _setPeerId(request) {
        if (request.peerId) {
            this.id = request.peerId;
        } else {
            this.id = request.headers.cookie.replace('peerid=', '');
        }
    }

    toString() {
        return `<Peer id=${this.id} ip=${this.ip} rtcSupported=${this.rtcSupported}>`
    }

    _setName(req) {
        let ua = parser(req.headers['user-agent']);


        let deviceName = '';
        
        if (ua.os && ua.os.name) {
            deviceName = ua.os.name.replace('Mac OS', 'Mac') + ' ';
        }
        
        if (ua.device.model) {
            deviceName += ua.device.model;
        } else {
            deviceName += ua.browser.name;
        }

        if(!deviceName)
            deviceName = 'Unknown Device';

        const displayName = uniqueNamesGenerator({
            length: 2,
            separator: ' ',
            dictionaries: [colors, animals],
            style: 'capital',
            seed: this.id.hashCode()
        })

        this.name = {
            model: ua.device.model,
            os: ua.os.name,
            browser: ua.browser.name,
            type: ua.device.type,
            deviceName,
            displayName
        };
    }

    getInfo() {
        return {
            id: this.id,
            name: this.name,
            rtcSupported: this.rtcSupported
        }
    }

    // return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
    static uuid() {
        let uuid = '',
            ii;
        for (ii = 0; ii < 32; ii += 1) {
            switch (ii) {
                case 8:
                case 20:
                    uuid += '-';
                    uuid += (Math.random() * 16 | 0).toString(16);
                    break;
                case 12:
                    uuid += '-';
                    uuid += '4';
                    break;
                case 16:
                    uuid += '-';
                    uuid += (Math.random() * 4 | 8).toString(16);
                    break;
                default:
                    uuid += (Math.random() * 16 | 0).toString(16);
            }
        }
        return uuid;
    };
}

Object.defineProperty(String.prototype, 'hashCode', {
  value: function() {
    var hash = 0, i, chr;
    for (i = 0; i < this.length; i++) {
      chr   = this.charCodeAt(i);
      hash  = ((hash << 5) - hash) + chr;
      hash |= 0; // Convert to 32bit integer
    }
    return hash;
  }
});

const server = new SnapdropServer(process.env.PORT || 3000);


================================================
FILE: server/package.json
================================================
{
  "name": "snapdrop",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ua-parser-js": "^0.7.24",
    "unique-names-generator": "^4.3.0",
    "ws": "^7.4.6"
  }
}
Download .txt
gitextract_hpr_ld_l/

├── .github/
│   └── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── client/
│   ├── images/
│   │   └── snapdrop-graphics.sketch
│   ├── index.html
│   ├── manifest.json
│   ├── scripts/
│   │   ├── clipboard.js
│   │   ├── network.js
│   │   └── ui.js
│   ├── service-worker.js
│   ├── sounds/
│   │   └── blop.ogg
│   └── styles.css
├── docker/
│   ├── nginx/
│   │   └── default.conf
│   ├── nginx-with-openssl.Dockerfile
│   └── openssl/
│       ├── create.sh
│       ├── snapdropCA.cnf
│       └── snapdropCert.cnf
├── docker-compose.yml
├── docs/
│   ├── faq.md
│   └── local-dev.md
└── server/
    ├── index.js
    └── package.json
Download .txt
SYMBOL INDEX (160 symbols across 3 files)

FILE: client/scripts/network.js
  class ServerConnection (line 4) | class ServerConnection {
    method constructor (line 6) | constructor() {
    method _connect (line 13) | _connect() {
    method _onMessage (line 25) | _onMessage(msg) {
    method send (line 52) | send(message) {
    method _endpoint (line 57) | _endpoint() {
    method _disconnect (line 65) | _disconnect() {
    method _onDisconnect (line 71) | _onDisconnect() {
    method _onVisibilityChange (line 78) | _onVisibilityChange() {
    method _isConnected (line 83) | _isConnected() {
    method _isConnecting (line 87) | _isConnecting() {
  class Peer (line 92) | class Peer {
    method constructor (line 94) | constructor(serverConnection, peerId) {
    method sendJSON (line 101) | sendJSON(message) {
    method sendFiles (line 105) | sendFiles(files) {
    method _dequeueFile (line 113) | _dequeueFile() {
    method _sendFile (line 120) | _sendFile(file) {
    method _onPartitionEnd (line 133) | _onPartitionEnd(offset) {
    method _onReceivedPartitionEnd (line 137) | _onReceivedPartitionEnd(offset) {
    method _sendNextPartition (line 141) | _sendNextPartition() {
    method _sendProgress (line 146) | _sendProgress(progress) {
    method _onMessage (line 150) | _onMessage(message) {
    method _onFileHeader (line 179) | _onFileHeader(header) {
    method _onChunkReceived (line 188) | _onChunkReceived(chunk) {
    method _onDownloadProgress (line 201) | _onDownloadProgress(progress) {
    method _onFileReceived (line 205) | _onFileReceived(proxyFile) {
    method _onTransferCompleted (line 210) | _onTransferCompleted() {
    method sendText (line 218) | sendText(text) {
    method _onTextReceived (line 223) | _onTextReceived(message) {
  class RTCPeer (line 229) | class RTCPeer extends Peer {
    method constructor (line 231) | constructor(serverConnection, peerId) {
    method _connect (line 237) | _connect(peerId, isCaller) {
    method _openConnection (line 247) | _openConnection(peerId, isCaller) {
    method _openChannel (line 256) | _openChannel() {
    method _onDescription (line 265) | _onDescription(description) {
    method _onIceCandidate (line 272) | _onIceCandidate(event) {
    method onServerMessage (line 277) | onServerMessage(message) {
    method _onChannelOpened (line 294) | _onChannelOpened(event) {
    method _onChannelClosed (line 303) | _onChannelClosed() {
    method _onConnectionStateChange (line 309) | _onConnectionStateChange(e) {
    method _onIceConnectionStateChange (line 322) | _onIceConnectionStateChange() {
    method _onError (line 332) | _onError(error) {
    method _send (line 336) | _send(message) {
    method _sendSignal (line 341) | _sendSignal(signal) {
    method refresh (line 347) | refresh() {
    method _isConnected (line 353) | _isConnected() {
    method _isConnecting (line 357) | _isConnecting() {
  class PeersManager (line 362) | class PeersManager {
    method constructor (line 364) | constructor(serverConnection) {
    method _onMessage (line 374) | _onMessage(message) {
    method _onPeers (line 381) | _onPeers(peers) {
    method sendTo (line 395) | sendTo(peerId, message) {
    method _onFilesSelected (line 399) | _onFilesSelected(message) {
    method _onSendText (line 403) | _onSendText(message) {
    method _onPeerLeft (line 407) | _onPeerLeft(peerId) {
  class WSPeer (line 416) | class WSPeer {
    method _send (line 417) | _send(message) {
  class FileChunker (line 423) | class FileChunker {
    method constructor (line 425) | constructor(file, onChunk, onPartitionEnd) {
    method nextPartition (line 437) | nextPartition() {
    method _readChunk (line 442) | _readChunk() {
    method _onChunkRead (line 447) | _onChunkRead(chunk) {
    method repeatPartition (line 459) | repeatPartition() {
    method _isPartitionEnd (line 464) | _isPartitionEnd() {
    method isFileEnd (line 468) | isFileEnd() {
    method progress (line 472) | get progress() {
  class FileDigester (line 477) | class FileDigester {
    method constructor (line 479) | constructor(meta, callback) {
    method unchunk (line 488) | unchunk(chunk) {
  class Events (line 508) | class Events {
    method fire (line 509) | static fire(type, detail) {
    method on (line 513) | static on(type, callback) {
    method off (line 517) | static off(type, callback) {

FILE: client/scripts/ui.js
  class PeersUI (line 16) | class PeersUI {
    method constructor (line 18) | constructor() {
    method _onPeerJoined (line 26) | _onPeerJoined(peer) {
    method _onPeers (line 33) | _onPeers(peers) {
    method _onPeerLeft (line 38) | _onPeerLeft(peerId) {
    method _onFileProgress (line 44) | _onFileProgress(progress) {
    method _clearPeers (line 51) | _clearPeers() {
    method _onPaste (line 55) | _onPaste(e) {
  class PeerUI (line 73) | class PeerUI {
    method html (line 75) | html() {
    method constructor (line 92) | constructor(peer) {
    method _initDom (line 98) | _initDom() {
    method _bindListeners (line 110) | _bindListeners(el) {
    method _displayName (line 124) | _displayName() {
    method _deviceName (line 128) | _deviceName() {
    method _icon (line 132) | _icon() {
    method _onFilesSelected (line 143) | _onFilesSelected(e) {
    method setProgress (line 153) | setProgress(progress) {
    method _onDrop (line 170) | _onDrop(e) {
    method _onDragOver (line 180) | _onDragOver() {
    method _onDragEnd (line 184) | _onDragEnd() {
    method _onRightClick (line 188) | _onRightClick(e) {
    method _onTouchStart (line 193) | _onTouchStart(e) {
    method _onTouchEnd (line 198) | _onTouchEnd(e) {
  class Dialog (line 209) | class Dialog {
    method constructor (line 210) | constructor(id) {
    method show (line 216) | show() {
    method hide (line 221) | hide() {
  class ReceiveDialog (line 228) | class ReceiveDialog extends Dialog {
    method constructor (line 230) | constructor() {
    method _nextFile (line 239) | _nextFile(nextFile) {
    method _dequeueFile (line 247) | _dequeueFile() {
    method _displayFile (line 259) | _displayFile(file) {
    method _formatFileSize (line 287) | _formatFileSize(bytes) {
    method hide (line 299) | hide() {
    method _autoDownload (line 307) | _autoDownload(){
  class SendTextDialog (line 313) | class SendTextDialog extends Dialog {
    method constructor (line 314) | constructor() {
    method _onRecipient (line 322) | _onRecipient(recipient) {
    method _handleShareTargetText (line 336) | _handleShareTargetText() {
    method _send (line 342) | _send(e) {
  class ReceiveTextDialog (line 351) | class ReceiveTextDialog extends Dialog {
    method constructor (line 352) | constructor() {
    method _onText (line 360) | _onText(e) {
    method _onCopy (line 376) | async _onCopy() {
  class Toast (line 382) | class Toast extends Dialog {
    method constructor (line 383) | constructor() {
    method _onNotfiy (line 388) | _onNotfiy(message) {
  class Notifications (line 396) | class Notifications {
    method constructor (line 398) | constructor() {
    method _requestPermission (line 412) | _requestPermission() {
    method _notify (line 423) | _notify(message, body) {
    method _messageNotification (line 449) | _messageNotification(message) {
    method _downloadNotification (line 461) | _downloadNotification(message) {
    method _download (line 469) | _download(notification) {
    method _copyText (line 474) | _copyText(message, notification) {
    method _bind (line 480) | _bind(notification, handler) {
  class NetworkStatusUI (line 492) | class NetworkStatusUI {
    method constructor (line 494) | constructor() {
    method _showOfflineMessage (line 500) | _showOfflineMessage() {
    method _showOnlineMessage (line 504) | _showOnlineMessage() {
  class WebShareTargetUI (line 509) | class WebShareTargetUI {
    method constructor (line 510) | constructor() {
  class Snapdrop (line 529) | class Snapdrop {
    method constructor (line 530) | constructor() {
  function init (line 583) | function init() {
  function drawCircle (line 597) | function drawCircle(radius) {
  function drawCircles (line 608) | function drawCircles() {
  function animate (line 618) | function animate() {

FILE: server/index.js
  class SnapdropServer (line 17) | class SnapdropServer {
    method constructor (line 19) | constructor(port) {
    method _onConnection (line 30) | _onConnection(peer) {
    method _onHeaders (line 46) | _onHeaders(headers, response) {
    method _onMessage (line 52) | _onMessage(sender, message) {
    method _joinRoom (line 81) | _joinRoom(peer) {
    method _leaveRoom (line 111) | _leaveRoom(peer) {
    method _send (line 131) | _send(peer, message) {
    method _keepAlive (line 138) | _keepAlive(peer) {
    method _cancelKeepAlive (line 154) | _cancelKeepAlive(peer) {
  class Peer (line 163) | class Peer {
    method constructor (line 165) | constructor(socket, request) {
    method _setIP (line 184) | _setIP(request) {
    method _setPeerId (line 196) | _setPeerId(request) {
    method toString (line 204) | toString() {
    method _setName (line 208) | _setName(req) {
    method getInfo (line 245) | getInfo() {
    method uuid (line 254) | static uuid() {
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (126K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 634,
    "preview": "# These are supported funding model platforms\n\ngithub: robinlinus\npatreon: # Replace with a single Patreon username\nopen"
  },
  {
    "path": ".gitignore",
    "chars": 45,
    "preview": "node_modules\n.DS_Store\nfqdn.env\n/docker/certs"
  },
  {
    "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": 1160,
    "preview": "# Snapdrop \n\n[Snapdrop](https://snapdrop.net): local file sharing in your browser. Inspired by Apple's Airdrop.\n\n## Snap"
  },
  {
    "path": "client/index.html",
    "chars": 13466,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"Content-Type\" content=\"text/ht"
  },
  {
    "path": "client/manifest.json",
    "chars": 1017,
    "preview": "{\n    \"name\": \"Snapdrop\",\n    \"short_name\": \"Snapdrop\",\n    \"icons\": [{\n        \"src\": \"images/android-chrome-192x192.pn"
  },
  {
    "path": "client/scripts/clipboard.js",
    "chars": 1164,
    "preview": "// Polyfill for Navigator.clipboard.writeText\nif (!navigator.clipboard) {\n    navigator.clipboard = {\n        writeText:"
  },
  {
    "path": "client/scripts/network.js",
    "chars": 15452,
    "preview": "window.URL = window.URL || window.webkitURL;\nwindow.isRtcSupported = !!(window.RTCPeerConnection || window.mozRTCPeerCon"
  },
  {
    "path": "client/scripts/ui.js",
    "chars": 19810,
    "preview": "const $ = query => document.getElementById(query);\nconst $$ = query => document.body.querySelector(query);\nconst isURL ="
  },
  {
    "path": "client/service-worker.js",
    "chars": 1290,
    "preview": "var CACHE_NAME = 'snapdrop-cache-v2';\nvar urlsToCache = [\n  'index.html',\n  './',\n  'styles.css',\n  'scripts/network.js'"
  },
  {
    "path": "client/styles.css",
    "chars": 11447,
    "preview": "/* Constants */\n\n:root {\n    --icon-size: 24px;\n    --primary-color: #4285f4;\n    --peer-width: 120px;\n    --text-color:"
  },
  {
    "path": "docker/nginx/default.conf",
    "chars": 1749,
    "preview": "server {\n    listen       80;\n    #server_name  your.domain;\n\n    #charset koi8-r;\n    #access_log  /var/log/nginx/host."
  },
  {
    "path": "docker/nginx-with-openssl.Dockerfile",
    "chars": 49,
    "preview": "FROM nginx:alpine\n\nRUN apk add --no-cache openssl"
  },
  {
    "path": "docker/openssl/create.sh",
    "chars": 551,
    "preview": "#!/bin/sh\n\ncnf_dir='/mnt/openssl/'\ncerts_dir='/etc/ssl/certs/'\nopenssl req -config ${cnf_dir}snapdropCA.cnf -new -x509 -"
  },
  {
    "path": "docker/openssl/snapdropCA.cnf",
    "chars": 731,
    "preview": "[ req ]\ndefault_bits       = 2048\ndefault_md         = sha256\ndefault_days       = 1\nencrypt_key        = no\ndistinguish"
  },
  {
    "path": "docker/openssl/snapdropCert.cnf",
    "chars": 995,
    "preview": "[ req ]\ndefault_bits        = 2048\ndefault_md          = sha256\ndefault_days        = 1\nencrypt_key         = no\ndisting"
  },
  {
    "path": "docker-compose.yml",
    "chars": 681,
    "preview": "version: \"3\"\nservices:\n  node:\n    image: \"node:lts-alpine\"\n    user: \"node\"\n    working_dir: /home/node/app\n    volumes"
  },
  {
    "path": "docs/faq.md",
    "chars": 4545,
    "preview": "# Frequently Asked Questions\n\n### Instructions / Discussions\n* [Video Instructions](https://www.youtube.com/watch?v=4XN0"
  },
  {
    "path": "docs/local-dev.md",
    "chars": 2688,
    "preview": "# Local Development\n## Install\n\nFirst, [Install docker with docker-compose.](https://docs.docker.com/compose/install/)\n\n"
  },
  {
    "path": "server/index.js",
    "chars": 8071,
    "preview": "var process = require('process')\n// Handle SIGINT\nprocess.on('SIGINT', () => {\n  console.info(\"SIGINT Received, exiting."
  },
  {
    "path": "server/package.json",
    "chars": 319,
    "preview": "{\n  \"name\": \"snapdrop\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"ech"
  }
]

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

About this extraction

This page contains the full source code of the SnapDrop/snapdrop GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (118.2 KB), approximately 31.0k tokens, and a symbol index with 160 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!