1
0
mirror of https://github.com/varbhat/exatorrent.git synced 2021-09-19 22:57:02 +03:00

first commit

This commit is contained in:
Var Bhat
2021-08-26 02:23:47 +05:30
commit 4727f22ed8
82 changed files with 13958 additions and 0 deletions

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
ko_fi: varbhat
liberapay: varbhat
custom: "https://www.paypal.me/varbhat"

16
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "npm"
directory: "/internal/web"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"

32
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: Build exatorrent
on:
push:
tags:
- v*
jobs:
build:
if: ${{ github.owner }} == "varbhat"
runs-on: ubuntu-latest
container:
image: "ghcr.io/varbhat/void-container:glibc"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- name: Prepare container
run: |
xbps-install -Syu || xbps-install -yu xbps
xbps-install -yu
- name: Install Packages
run: xbps-install -Sy git curl bash make go nodejs cross-x86_64-linux-musl cross-aarch64-linux-musl github-cli
- name: Checkout repository
uses: actions/checkout@v2
- name: Build exatorrent
run: go mod tidy && make web && make app-linux-amd64 && make app-linux-arm64 && make checksum
- name: Publish Releases
run: |
gh config set prompt disabled
gh release create $(git tag -l | tail -n1) -t $(git tag -l | tail -n1) -p build/*

45
.github/workflows/docker.yml vendored Normal file
View File

@@ -0,0 +1,45 @@
name: Create and publish Container Images
on:
push:
tags:
- v*
jobs:
build-container-images:
if: ${{ github.owner }} == "varbhat"
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Setup QEMU
uses: docker/setup-qemu-action@v1
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to GitHub Container Registry
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build the amd64 image
run: docker buildx build --load --platform "linux/amd64" . --tag ghcr.io/varbhat/exatorrent:amd64
- name: Build the arm64 image
run: docker buildx build --load --platform "linux/arm64" . --tag ghcr.io/varbhat/exatorrent:arm64
- name: Push Images
run: docker push ghcr.io/varbhat/exatorrent -a
- name: Create and Push Manifest
run: |
docker manifest create ghcr.io/varbhat/exatorrent:latest ghcr.io/varbhat/exatorrent:amd64 ghcr.io/varbhat/exatorrent:arm64
docker manifest push ghcr.io/varbhat/exatorrent:latest

13
Dockerfile Normal file
View File

@@ -0,0 +1,13 @@
FROM ghcr.io/varbhat/void-container:musl AS build
RUN xbps-install -Syu || xbps-install -yu xbps
RUN xbps-install -yu
RUN xbps-install -Sy git curl bash make go nodejs gcc
WORKDIR /exa
ADD . /exa
RUN go mod tidy && make web && make app
FROM gcr.io/distroless/base
COPY --from=build --chown=1000:1000 /exa/build/exatorrent /exatorrent
USER 1000:1000
WORKDIR /exa
ENTRYPOINT ["/exatorrent"]

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
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>.

41
Makefile Normal file
View File

@@ -0,0 +1,41 @@
SHELL = /usr/bin/env sh
APP_NAME = exatorrent
PACKAGES ?= ./...
MAIN_SOURCE = exatorrent.go
.DEFAULT_GOAL := help
##help: Display list of commands
.PHONY: help
help: Makefile
@printf "Options:\n"
@sed -n 's|^##||p' $<
##web: Build the Web Client
.PHONY: web
web:
cd internal/web && npm install && npm run build
##app: Build the Application
.PHONY: app
app:
env CGO_ENABLED=1 go build -trimpath -buildmode=pie -ldflags '-extldflags "-static -s -w"' -o build/$(APP_NAME) $(MAIN_SOURCE)
##app-linux-amd64: Build the Application for linux (amd64)
.PHONY: app-linux-amd64
app-linux-amd64:
env CGO_ENABLED=1 GOOS="linux" GOARCH="amd64" CC="x86_64-linux-musl-gcc" CXX="x86_64-linux-musl-g++" go build -trimpath -buildmode=pie -ldflags '-extldflags "-static -s -w"' -o build/$(APP_NAME)-linux-amd64 $(MAIN_SOURCE)
##app-linux-arm64: Build the Application for linux (arm64)
.PHONY: app-linux-arm64
app-linux-arm64:
env CGO_ENABLED=1 GOOS="linux" GOARCH="arm64" CC="aarch64-linux-musl-gcc" CXX="aarch64-linux-musl-g++" go build -trimpath -buildmode=pie -ldflags '-extldflags "-static -s -w"' -o build/$(APP_NAME)-linux-arm64 $(MAIN_SOURCE)
##checksum: Generate sha256 checksums for the builds
.PHONY: checksum
checksum:
cd build && sha256sum -b * > checksums_sha256.txt
##run: Runs the build
.PHONY: run
run:
cd build && ./exatorrent*

5
NOTICE.txt Normal file
View File

@@ -0,0 +1,5 @@
This product includes software from the anacrolix/torrent project
* License : Mozilla Public License 2.0
This product includes icons from tailwindlabs/heroicons
* License : MIT

93
README.md Normal file
View File

@@ -0,0 +1,93 @@
<h1 align="center">exatorrent</h1>
<p align="center">self-hostable torrent client</p>
<hr>
<p align="center"><a href="docs/screenshots.md">Screenshots</a> &bull; <a href="https://github.com/varbhat/exatorrent/releases/latest">Releases</a> &bull; <a href="#features">Features</a> &bull; <a href="#installation"> Installation </a> &bull; <a href="docs/usage.md"> Usage</a> &bull; <a href="docs/docker.md">Docker</a> &bull; <a href="docs/build.md"> Build </a> &bull; <a href="LICENSE">License</a></p>
<hr>
## Introduction
exatorrent is [BitTorrent](https://www.bittorrent.org/) Client written in [Go](https://go.dev/).
It can be run locally or be hosted in Remote Server with good resources
to use that Server as [SeedBox](https://en.wikipedia.org/wiki/Seedbox).
It is Single Completely Statically Linked Binary with Zero External Dependencies .
exatorrent is simple yet feature-rich . It is
lightweight and light on resources. It comes with Beautiful Responsive Web Client written in Svelte and Typescript ,
but thanks to documented [WebSocket](https://datatracker.ietf.org/doc/html/rfc6455) [API](docs/API.md) of exatorrent , you can also write your own client if you want to.
exatorrent can operate in Optional Multi-User Mode administrated by admin user/s
but it can successfully be used by Single-User as well.
Torrented Files are stored in local disk of device where it's run, which are then retrievable or streamable via HTTP.
<hr>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/main.png" alt="exatorrent web client" width=400 height=550 />
<p align="center"><a href="docs/screenshots.md">More Screenshots →</a></p>
</p>
<hr>
## Installation
exatorrent can be installed in 3 ways.
* **Releases:** You can download binary for your OS from [Releases](https://github.com/varbhat/exatorrent/releases/latest) . Mark it as executable and run it . Refer [Usage](docs/usage.md) .
```bash
wget https://github.com/varbhat/exatorrent/releases/download/latest/exatorrent-linux-amd64
chmod u+x ./exatorrent-linux-amd64
./exatorrent-linux-amd64
```
* **Docker:** exatorrent can also be run inside Docker ( or Podman ). See [Docker Docs](docs/docker.md) .
```bash
docker pull ghcr.io/varbhat/exatorrent:latest
docker run -p 5000:5000 -p 42069:42069 -v /path/to/directory:/exa/exadir ghcr.io/varbhat/exatorrent:latest
```
* **Build:** exatorrent is open source and can be built from sources . See [Build Docs](docs/build.md) .
```bash
make web && make app
```
Note that **Username** and **Password** of Default User created on first run are `adminuser` and `adminpassword` respectively. You can change Password later but Username of Account can't be changed after creation. Refer [Usage](docs/usage.md#-admin) .
[Github Actions](https://github.com/features/actions) is used to build and publish [Releases](https://github.com/varbhat/exatorrent/releases/latest) and [Docker/Podman Images](https://ghcr.io/varbhat/exatorrent) of exatorrent .
If you want to deploy `exatorrent` on server , please also refer [Deploy Docs](docs/deploy.md) .
## Features
* Single Executable File with No Dependencies
* Small in Size
* Cross Platform
* Download (or Build ) Single Executable Binary and run . That's it
* Open and Stream Torrents in your Browser
* Add Torrents by Magnet or by Infohash or Torrent File
* Individual File Control (Start, Stop or Delete )
* Stop , Remove or Delete Torrent
* Persistent between Sessions
* Stop Torrent once SeedRatio is reached (Optional)
* Powered by [anacrolix/torrent](https://github.com/anacrolix/torrent)
* Download/Upload [Rate limiter](https://github.com/varbhat/exatorrent/blob/main/docs/usage.md#rate-limiter) (Optional)
* Apply [Blocklist](docs/usage.md#blocklist) (Optional)
* [Configurable](docs/config.md) via Config File but works fine with Zero Configuration
* Share Files by Unlocking Torrent or Lock Torrent (protect by Auth) to prevent External Access
* Retrieve or Stream Files via HTTP
* Multi-Users with Authentication
* Auto Add Trackers to Torrent from TrackerList URL
* Auto Fetch Torrent Metainfo from Online/Local Metainfo Cache
* Download Directory as Zip or as Tarball
* Stream directly on Browser or [VLC](https://www.videolan.org/vlc/) or [mpv](https://mpv.io/) or other Media Players
* [Documented API](docs/API.md)
* Uses Sqlite3 (embedded database with no setup and no configuration) by Default for [Database](docs/database.md) but PostgreSQL can be used instead too
<p align="center">
<p align="center"><a href="docs/features.md">Read More →</a></p>
</p>
## Help
Communication about the project is primarily through [Discussions](https://github.com/varbhat/exatorrent/discussions) and the [Issues](https://github.com/varbhat/exatorrent/issues).
## Contribute
You are welcome to contribute . Please Read the [contributing docs](docs/CONTRIBUTING.md) first.
## Sponsor
If you like this Project , please consider this as an opportunity to sponsor / donate to this project . This would help me maintain this project and also work on other Open Source Projects . Use [Liberapay](https://liberapay.com/varbhat) , [Paypal](https://www.paypal.me/varbhat) , [Ko-fi](https://ko-fi.com/varbhat) or [UPI](https://en.wikipedia.org/wiki/Unified_Payments_Interface) (VPA: `mailvarbhat@okhdfcbank`) to Sponsor / Donate to this Project .
## License
[GPL-v3](LICENSE)

97
docs/API.md Normal file
View File

@@ -0,0 +1,97 @@
exatorrent comes with beautiful performant Web Client written in svelte+Typescript but also comes with documented API so that custom clients(TUI, android app ,desktop app,etc.) can be created for it.
Here lies the documented API reference.
## Authentication
exatorrent has authentication and if the connection is not authenticated, it cannot make API request.
exatorrent has user system. user is structure as defined below.
```go
type User struct {
Username string
Password string
Token string
UserType int // 0 for User,1 for Admin,-1 for Disabled
CreatedAt time.Time
}
```
Length of Username and Password fields of User must be more than 5. CreatedAt field stores the creation time of User. UserType field denotes whether the User is Admin / User / Disabled.
if UserType field is 0 , User is Disabled and cannot connect to server. if UserType field is 0 , then the User is Normal User and can connect to server and perform normal operations. if UserType field is 1 ,then the User is Admin User and can connect to server. Admin User can also perform Administration Operations in addition to normal Operations. Token field contains unique random UUID token issued to User which can be used by User to Authenticate.
exatorrent looks whether `session_token` cookie is present in request and if the cookie is present, it validates value of `session_token` as `Token` , and if `Token` is valid, User will be authenticated.
if `session_token` cookie is not present , exatorrent looks whether Query named "token" is present in request's URL and if query named "token" is present , it validates value of `token` query as `Token` , and if `Token` is valid , User will be authenticated.
If both `session_token` cookie and `token` query string are not present OR, value presented in cookie or query is invalid, `basic_auth` will be issued, and if Basic Authentication's values filled by connection are valid, then the User will be authenticated.
After User is authenticated, `session_token` cookie with `Token` value will be set by exatorrent.
Briefly , Connection can be authenticated by Cookie with token ,or URL Query with token , or by Basic Auth(Username and Password).
exatorrent's WebSocket API endpoint `/api/socket` is protected by Authentication and only Authenticated User(Normal User or Admin User) can connect to WebSocket API. Note that Disabled User cannot connect to WebSocket API. Also, Only ONE WebSocket connection is allowed per User(existing WebSocket connection of User gets disconnected on new WebSocket connection of User)
Endpoint `/api/auth` is also provided where you can `POST` json request
```json
{
"data1": "yourusernamehere",
"data2": "yourpasswordhere"
}
```
to get `Token` and `UserType` of the User. Response will be of the form ,
```json
{
"usertype": "user",
"session": "uniqueuuidsession"
}
```
# WebSocket API
exatorrent has WebSocket API which provides API to control exatorrent . Note that there is seperate HTTP API Endpoint to retrieve / stream Torrent Files for which websocket will not be used and is documented later.
Only Authenticated User who is not `disabled` can connect to WebSocket API . Only ONE WebSocket connection is allowed per User(existing WebSocket connection of User gets disconnected on new WebSocket connection of User).
Communication in exatorrent WebSocket is done through JSON . exatorrent WebSocket Only accepts JSON requests of the form,
```json
{
"command": "commandstring",
"data1": "data1string",
"data2": "data2string",
"data3": "data3string",
"aop": 0
}
```
if json request is not of the form mentioned above , json
```json
{
"type": "resp",
"state": "error",
"msg":"invalid command"
}
```
will be sent back as response.
command field of json request represents command that needs to be done. `data1` , `data2` and `data3` fields of json request represents data. `aop` field specifies whether json request is admin request or not. if `aop` field is 1 and user is admin, then exatorrent considers it as admin command (note that if users who are not admins send this,they are not valuated). better omit `aop` field if request is not admin request.
## Stream Requests
Some Requests namely `getalltorrents` , `gettorrents` , `gettorrentinfo` are stream requests . They continuously send data regularly with 5 seconds gap in between. This is useful , say for showing progress of Torrent . There can be only 1 Stream at a time , so if you request new stream , old stream stops . you can also stop stream by sending request `{"command":"stopstream"}` . This stops stream if any do exist.
## Reference
Please Read [wshandler](https://github.com/varbhat/exatorrent/blob/main/internal/core/socket.go#L108) to get more details about API

31
docs/CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,31 @@
Thank you for your interest in `exatorrent` . We highly appreciate it . You are welcome to contribute to `exatorrent` . But, please read this document completely .
**Please ask first before starting work on any significant new features**
It's never a fun experience to have your pull request declined after investing a lot of time and effort into a new feature. To avoid this from happening, we request that contributors create [an issue](https://github.com/varbhat/exatorrent/issues) or use [discussions](https://github.com/varbhat/exatorrent/discussions) to first discuss any **significant** new features.
**Everyone is welcome to contribute**
You are welcome to contribute . We only care about quality contributions . Consider this as Great Opportunity to contribute towards Open Source Software that will benefit the community and which will stay Open Source forever.
If you know [Go](https://go.dev) Programming Language , you can contribute to `exatorrent` by solving issues , finding bugs(if they exist) , adding new features if it can benefit the community (Please ask before if you are adding new features; see above).
Note that `exatorrent` except Web Client has been completely written in `Go` .
Web Client of `exatorrent` has been written in [Svelte](https://svelte.dev/) + [TypeScript](https://www.typescriptlang.org/) . Note that TypeScript is Typed Javascript that prevents many mistakes that are possible when using Javascript .
[Tailwind](https://tailwindcss.com/) CSS framework has been used for the UI . If you know Svelte / TypeScript / Tailwindcss , you can contribute towards improving Web Client . If you find any bugs in Web Client , please Open issue.
If you have expertise in UI/UX , you can work towards making Web Client more awesome and improving UI/UX of Web Client . If you are designer , you can contribute towards creating good identity (logo , favicon and other visual identities) for exatorrent .
Although we prefer Pull Requests , you are welcome to request new Feature in [Issues](https://github.com/varbhat/exatorrent/issues) or [Discussions](https://github.com/varbhat/exatorrent/discussions) . Please include `Feature Request` in the title of post .
**Code must be Formatted**
All `go` code must be formatted using `gofmt` . All Web code must be formatted using `Prettier` (with config existing in `web` subfolder).
**Improve Documentation**
You are free to improve Documentation of `exatorrent` .
**Spread the Word about exatorrent**
If you like `exatorrent` , popularize `exatorrent` by spreading and talking good things about it.

50
docs/build.md Normal file
View File

@@ -0,0 +1,50 @@
# Build Docs
This Documents how to build `exatorrent` from sources .
`exatorrent` is written in [Go](https://golang.org) . As such you need `go` to be installed in order to compile .
`exatorrent` is dependent on [sqlite3](https://www.sqlite.org) ( used as database ) and [libutp](https://github.com/anacrolix/go-libutp) ( used for uTP connections ) . As such , you also require C and C++ compilers to be installed in order to compile . [gcc](https://gcc.gnu.org/) is preferred but [clang](https://clang.llvm.org/) also compiles well . There is no need to install any `devel` packages or `sqlite` or headers in system to compile `exatorrent` , as Source comes bundeled with drivers [`crawshaw/sqlite`](https://github.com/crawshaw/sqlite) and [`libutp`](https://github.com/anacrolix/go-libutp) and C compiler is used to compile cgo code .
`exatorrent` comes with beautiful , small and performant Web Client . It is written in [Svelte](https://svelte.dev/) + [TypeScript](https://www.typescriptlang.org/) . It gets bundled with amazing [esbuild](https://esbuild.github.io/) and the built web client is then embedded within the binary using Go's [embed](https://pkg.go.dev/embed) . [Node.js](https://nodejs.org/) is thus required to build Web Client . Note that Node.js is required only to build Web Client written in Svelte and not required thereafter (i.e exatorrent is not dependent on Node.js and Node.js in only required to build Web Client ).
For sake of Convenience although not necessary to build `exatorrent` , Build commands of `exatorrent` are written in [Makefile](../Makefile) . Install [`make`](https://www.gnu.org/software/make/) to execute make commands . Note that you can also manually type build commands instead of using `make` .
## Requirements
* [go](https://golang.org)
* [gcc](https://gcc.gnu.org/)
* [make](https://www.gnu.org/software/make/) ( to execute make commands )
Requirements to build Web Client :
* [Node.js](https://nodejs.org/) (`node` and `npm` must be available )
## Build
Since Web Client will be embedded within final binary , Web Client needs to be built first .
Web Client can be built by :
```bash
make web
```
After building web client , `exatorrent` can be built by :
```bash
make app
```
You can see built `exatorrent` in `build` directory .
If you don't have `make` installed , you can execute these commands manually to build exatorrent :
```bash
cd internal/web && npm install && npm run build
cd ../..
env CGO_ENABLED=1 go build -trimpath -buildmode=pie -ldflags '-extldflags "-static -s -w"' -o build/exatorrent exatorrent.go
```
## Notes
* See [Building Docker/Podman Images](./docker.md#building-podman--docker-container-image) if you want to build `exatorrent` Docker / Podman Images .
* If you don't want to build Web Client or want to skip building Web Client , you can do it by creating empty / dummy `index.html` file at `internal/web/build` directory ( Create `build` folder if it didn't exist ) . Note that Web Client will not be available then .

16
docs/config.md Normal file
View File

@@ -0,0 +1,16 @@
`exatorrent` is fully configurable . This page details configurations that are possible in `exatorrent`
## Options that are configurable during Runtime
There are options that can be configured during runtime and without restarting `exatorrent` . It can also be configured through Web Client (or API) . See [EngConfig](https://github.com/varbhat/exatorrent/blob/main/internal/core/vars.go#L352) for more details about the engconfig.
When exatorrent gets started, it checks whether engconfig.json file is present in config directory (which is subdirectory of main directory of exatorrent) and if json is valid configuration, it gets applied. also, when you change the configuration during runtime, the json file gets updated. You can generate sample engconfig(so that you can modify it to set value you want it to have) by passing flag `-engc` while starting the program.
## Options that are not configurable during runtime
Many of configuration of torrent engine `anacrolix/torrent` are only applied at start of engine and cannot be configurable during runtime. See [TorConfig](https://github.com/varbhat/exatorrent/blob/main/internal/core/vars.go#L42) for more details.
Note that most of torcconfig maps to [ClientConfig](https://github.com/anacrolix/torrent/blob/master/config.go#L23)
You can generate sample torcconfig(so that you can modify it to set value you want it to have) by passing flag `-torc` while starting the program. Note that if you don't want to configure , set it's value as `null` .

24
docs/database.md Normal file
View File

@@ -0,0 +1,24 @@
To make things persistent between sessions , `exatorrent` uses database . But because `exatorrent` uses awesome `sqlite3` which comes embedded within `exatorrent` , you barely notice it.
Instead of `sqlite3` , you can also use `postgresql` if you want to. Know that both `sqlite` and `postgresql` are provided as choices of Database Implementations . When in doubt, use `sqlite3`(which is used by `exatorrent` as default
,i.e , don't worry about configuring Database at all.
Note that once you start using one Database , you must stick to it . You cannot jump between Database Implementations and if you do , you loose data.
### Data Stored in Database
1. Users and their data
2. Trackers
3. State of Torrent
4. Piece Completion State of Torrent
5. State of Files of Torrent
6. Lock State of Torrent
## Postgresql
Normally you will be fine using `sqlite3` which `exatorrent` uses by default , which you don't need to setup and configure. But , Postgresql is also provided as choice . If you want to try out Postgresql as Database (Note that you can't switch back to sqlite later) , follow instructions below :
* Create Postgresql Database . Remember it's credentials .
* Remember format for Connection URL: `postgres://username:password@localhost:5432/database_name`
* You need to pass connection URL to `exatorrent` . You can either set `DATABASE_URL` environment variable as connection URL or you can write connection URL to file at `<exatorrent-directory>/config/psqlconfig.txt` . If you want sample connection URL written at `psqlconfig.txt` , pass `-psql` flag to `exatorrent`

169
docs/deploy.md Normal file
View File

@@ -0,0 +1,169 @@
# Deploy Docs
This Documents some things on deployment of `exatorrent` .
# Run as Seperate User
Create new seperate user and group to run `exatorrent` . In this document , we assume that `exatorrent` is run as `exatorrent` user and `exatorrent` group but any name is fine . Run `exatorrent` as seperate user and group .
# Service
Using Services help to make sure that `exatorrent` will be running even after reboot and better logging by service Manager . Below are example Service files for `Runit` , `Systemd` , `Sysvinit` and `Openrc` . Modify them to suit your system .
## Runit
`run` file of `exatorrent` is as below .
```sh
#!/bin/sh
cd /path/to/directory
exec chpst -u exatorrent:exatorrent /path/to/exatorrent
```
## Systemd
Systemd unit file `exatorrent.service` is as follows :
```
[Unit]
Description=exatorrent
[Service]
Type=simple
Restart=always
RestartSec=5s
User=exatorrent
Group=exatorrent
WorkingDirectory=/path/to/directory
ExecStart=/path/to/exatorrent
[Install]
WantedBy=multi-user.target
```
## Sysvinit
Sysvinit script is as follows:
```sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: exatorrent
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts exatorrent
# Description: exatorrent is torrent client
### END INIT INFO
PATH=/bin:/usr/bin:/sbin:/usr/sbin
NAME=exatorrent
USER=exatorrent
DESC="exatorrent"
DAEMON_PATH=/path/to/exatorrent/bin/dir
PIDFILE=/run/$NAME.pid
LOGFILE=/var/log/$NAME.log
TIMEOUT=30
SCRIPTNAME=/etc/init.d/$NAME
case "$1" in
start)
echo "Starting $DESC"
start-stop-daemon --start --background --oknodo --startas $DAEMON --chdir $DAEMON_PATH --chuid $USER --exec $DAEMON_PATH/$NAME --
;;
stop)
echo "Stoping $DESC"
start-stop-daemon --stop --quiet --oknodo --retry=0/10/TERM/5/KILL/5 --exec $DAEMON_PATH/$NAME
;;
status)
start-stop-daemon --status --exec $DAEMON_PATH/$NAME && exit_status=$? || exit_status=$?
case "$exit_status" in
0) echo "The '$DESC' is running." ;;
*) echo "The '$DESC' is not running." ;;
esac
;;
restart)
echo "Restarting $DESC: "
sh $0 stop
sleep 20
mv --backup=numbered $LOGFILE $LOGFILE.1
sh $0 start
;;
esac
exit 0
```
## openrc
Openrc `run` file is as follows :
```sh
#!/sbin/openrc-run
description="exatorrent"
depend() {
need net
after firewall
}
start() {
ebegin "Starting exatorrent"
start-stop-daemon --start --background --chdir /path/to/exatorrent/dir --exec /path/to/exatorrent/dir/exatorrent --
eend $?
}
stop() {
local rv=0
ebegin "Stopping exatorrent"
start-stop-daemon --stop --quiet --oknodo --retry=0/10/TERM/5/KILL/5 --exec /path/to/exatorrent/dir/exatorrent
eend $?
}
```
# Reverse Proxy
We recommend running `exatorrent` behind reverse proxy . Below are example configurations of Nginx , Haproxy and Caddy made to reverse proxy `exatorrent` . Please don't put Basic Auth or any kind of custom auth / request modification system as Authentication is handled by `exatorrent` itself . `/api/socket` is WebSocket endpoint and Reverse Proxying server must not hinder it .
## Nginx
```Nginx
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
ssl_certificate /path/to/tls/tls.crt;
ssl_certificate_key /path/to/tls/tls.key;
server_name the.domain.tld;
location / {
proxy_pass http://localhost:5000;
# proxy_pass http://unix:/path/to/exatorrent/unixsocket;
}
location /api/socket {
proxy_pass http://localhost:5000/api/socket;
# proxy_pass http://unix:/path/to/exatorrent/unixsocket:/api/socket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
}
```
## Haproxy
```HAProxy
frontend proxy
#bind *:80
bind *:443 ssl crt /path/to/tls/cert.pem
default_backend exatorrent
backend exatorrent
server exatorrent localhost:5000
```
## Caddy
```
https://the.domain.tld {
reverse_proxy * localhost:5000
}
```

35
docs/docker.md Normal file
View File

@@ -0,0 +1,35 @@
`exatorrent` can be run inside Podman / Docker Container
## Podman
[Podman](https://github.com/containers/podman) is drop-in replacement for Docker . Podman has several advantages over Docker . `exatorrent` can be run in `podman` . If you prefer `podman` , you can alias it to `docker`
```bash
alias docker=podman
```
## Podman / Docker Image
Podman / Docker Images of `exatorrent` are officially available for `amd64` and `arm64` architectures . They are built on release of new version by Github Actions and are Hosted and available at [Github Container Registry](https://ghcr.io/varbhat/exatorrent) . Podman / Docker images of `exatorrent` can be pulled by
```bash
docker pull ghcr.io/varbhat/exatorrent:latest
```
This pulls latest version of `exatorrent` Podman / Docker Image
## Building Podman / Docker Container Image
Podman / Docker Image of `exatorrent` can also be built in your machine if you intend to build . Following commands will build `exatorrent` Podman / Docker Image .
```bash
git clone https://github.com/varbhat/exatorrent
cd exatorrent
docker build -t "exatorrent" .
```
## Usage
Podman / Docker Image of `exatorrent` can be run by following command
```bash
docker run -p 5000:5000 -p 42069:42069 -v /path/to/directory:/exa/exadir ghcr.io/varbhat/exatorrent:latest
# docker run -p 5000:5000 -p 42069:42069 -v /path/to/directory:/exa/exadir exatorrent
```
5000 port is default port where Web Client and API are served . `42069` is default port for Torrent Client where Torrent Transfers occur. So, they need to be exposed . Also Refer [Usage](usage.md) .

29
docs/features.md Normal file
View File

@@ -0,0 +1,29 @@
exatorrent is [BitTorrent](https://www.bittorrent.org) Client . It is written in `go` . It is made to be hosted in Servers to turn them into Torrent Server / Seedbox . It can also be run locally ( it's totally worthy because `exatorrent` provides several features not found in other Torrent Clients ) as well .
exatorrent is small in size and comes with no bloat . It is compiled statically into Single Executable Binary file and is dependent on nothing . No libraries , No frameworks are required to run exatorrent . Just download exatorrent which is single Binary Executable and run it . That's it . You can also build `exatorrent` from sources as `exatorrent` is open source . Thus , deploying / running `exatorrent` is very easy .
`exatorrent` built binary executables are provided with each new [releases](https://github.com/varbhat/exatorrent/releases/latest) . Docker / Podman Images are also provided .
`exatorrent` is cross platform and can run on all major platforms . It can be run on [Linux](https://www.kernel.org/) , [Android](https://www.android.com/) ( through [Termux](https://termux.com/) ) , [Macos](https://developer.apple.com/macos/) and [Windows](https://www.microsoft.com/en-in/windows) . Linux users can Download Executable Binaries from [Releases](https://github.com/varbhat/exatorrent/releases/latest) or use [Docker/Podman](./docker.md) or [Build](./build.md) from Sources . Android Termux Users can run the Linux Builds from [Releases](https://github.com/varbhat/exatorrent/releases/latest) . Windows Users are advised to use [Docker](https://docs.docker.com/docker-for-windows/install/) (refer [docker docs](./docker.md) ) or use [WSL2](https://docs.microsoft.com/en-us/windows/wsl/) or [Build](./build.md) from Sources. Macos users are advised to use [Docker](https://docs.docker.com/docker-for-mac/install/) (refer [docker docs](./docker.md) ) or [Build](./build.md) from Sources .
You can Open and Stream Torrents in your Browser using exatorrent . You can Add Torrents by Magnet or by Infohash or Torrent File . Each file in Torrent can be Started , Stopped or Deleted . Torrents can be Started , Stopped , Removed or Deleted . And all these things persist between sessions , i.e even if you restart `exatorrent` , these things do persist .
If you want to , then `exatorrent` can stop Torrents on reaching certain seedratio (which you need to set). You can also apply Blocklist to block peers if you want to. You can also Rate Limit `exatorrent` .
`exatorrent` works perfectly fine without any configuration , but if you need to configure `exatorrent` , `exatorrent` can be fully configured with configuration files .
Files downloaded via Torrenting in `exatorrent` can be retrieved or streamed or shared ( with auth protection of course ) . Directories can be retrieved as Zip / Tarballs .
`exatorrent` is multi-users (with admin users as administrators ) but also works fine in single user context . All users are authenticated to access `exatorrent` .
`exatorrent` has few niceties like Adding Trackers to Torrent from TrackerList URL/s (which you can configure ofcourse ) which increases Peers thus making Torrenting faster . Also , it can fetch Torrent metainfo from Online Cache (ex. [iTorrents.org](https://itorrents.org/) or Local Cache thus making fetching of Torrent metainfo faster .
`exatorrent` uses `sqlite` as it's [database](./database.md) but `postgresql` can be used as well.
Video / Audio files can be streamed directly in Browser . They can also streamed directly on [VLC](https://www.videolan.org/vlc/) or [mpv](https://mpv.io/) or other Media Players .
`exatorrent` has [documented API](./API.md) that enables you to create other Clients for `exatorrent` and integrate other services with `exatorrent` .

54
docs/screenshots.md Normal file
View File

@@ -0,0 +1,54 @@
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/1.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/2.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/3.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/4.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/5.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/6.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/7.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/8.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/9.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/10.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/11.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/12.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/13.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/14.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/15.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/16.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/17.png" alt="exatorrent images"/>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/varbhat/assets/master/exatorrent/18.png" alt="exatorrent images"/>
</p>

62
docs/usage.md Normal file
View File

@@ -0,0 +1,62 @@
## Usage
```bash
Usage of exatorrent:
-addr <addr> Listen Address (Default: ":5000")
-admin <user> Default admin username (Default Username: "adminuser" and Default Password: "adminpassword")
-cert <path> Path to TLS Certificate (Required for HTTPS)
-dir <path> exatorrent Directory (Default: "exadir")
-engc <opt> Generate Custom Engine Configuration
-key <path> Path to TLS Key (Required for HTTPS)
-psql <opt> Generate Sample Postgresql Connection URL
-torc <opt> Generate Custom Torrent Client Configuration
-unix <path> Unix Socket Path
-help <opt> Print this Help
```
### `-addr`
Listen Address of `exatorrent` . It specifies the TCP address for the `exatorrent` to listen on . It's of form `host:port` . The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in `[2001:db8::1]:80` or `[fe80::1%zone]:80`.
Default Listen Address is `:5000` . Open http://localhost:5000 or http://0.0.0.0:5000 or http://127.0.0.1:5000 to use `exatorrent` Web Client if exatorrent is listening on Default Address .
Valid Listen Addresses include `localhost:9999` , `0.0.0.0:3456` , `127.0.0.1:7777` , `[0:0:0:0:0:0:0:1]:5000` , `x.x.x.x:port` , `[x:x:x:x:x:x:x:x]:port` .
### `-admin`
Usernames of Users in `exatorrent` can't be changed after User is created . It must be choosen while creating User and can't be changed later . Note that password can be changed anytime later .
On the first use of `exatorrent` , `exatorrent` creates Admin user with username `adminuser` and password `adminpassword` . Since this username `adminuser` can't be changed later on , you can customize it before first run itself by passing your desired username to `-admin` flag.
```bash
exatorrent -admin "mycustomadminusername"
```
You are advised to use custom username for default admin using this flag . You can always change password of default admin or other users later .
### `-cert`
If HTTPS needs to be served , Path to TLS Certificate must be specified in this flag . Note that `-cert` flag is also necessary along with this flag to serve HTTPS .
### `-key`
If HTTPS needs to be served , Path to TLS Key must be specified in this flag . Note that `-cert` flag is also necessary along with this flag to serve HTTPS .
### `-unix`
This flag specifies file path where Unix Socket must be served . This flag is alternative to `-addr` flag and works only on Operating Systems that support [Unix Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket) .
### `-dir`
`exatorrent` always operates in specific directory and never leaves beyond that directory . It stores File downloaded through Torrents , Torrent Metadata Files , Sqlite3 Database files if any , Configuration files in this directory.
`-dir` flag specifies the directory where `exatorrent` must store the data .
### `-engc`
Writes Sample Runtime-Configurable Engine connection URL to `<exadirectory>/config/engconfig.json` . All Runtime-Configurable Settings are configured in this file . You can change it anytime in Client .
### `-torc`
Writes Sample Torrent Client connection URL to `<exadirectory>/config/clientconfig.json` . These settings cannot be configured during runtime and must only be configured before starting `exatorrent` .
### `-psql`
Writes Sample Postgresql connection URL to `<exadirectory>/config/psqlconfig.txt` . Instead of reading configuration URL from env variable `DATABASE_URL` , reads `DATABASE_URL` from file . Refer [Database Docs](database.md) for more details .
## Blocklist
Blocklist of PeerGuardian Text Lists (P2P) Format can be placed at `<exadirectory>/config/blocklist` to apply blocking based upon blocklist . You are also required to set `IPBlocklist` value of `clentconfig.json` to `true` . Note that Blocklist can't be changed during runtime .
## Rate Limiter
`UploadLimiterLimit` , `UploadLimiterBurst` , `DownloadLimiterLimit` , `DownloadLimiterBurst` values of `clientconfig.json` can be used to Rate Limit `exatorrent` .

54
exatorrent.go Normal file
View File

@@ -0,0 +1,54 @@
package main
import (
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/varbhat/exatorrent/internal/core"
"github.com/varbhat/exatorrent/internal/web"
)
const Version string = "src"
func main() {
core.Initialize()
http.HandleFunc("/api/socket", core.SocketAPI)
http.HandleFunc("/api/auth", core.AuthCheck)
http.HandleFunc("/api/stream/", core.StreamFile)
http.HandleFunc("/api/torrent/", core.TorrentServe)
http.Handle("/", web.FrontEndHandler)
if core.Flagconfig.UnixSocket != "" {
// Run under specified Unix Socket Path
core.Info.Println("Starting server at Path (Unix Socket)", core.Flagconfig.UnixSocket)
usock, err := net.Listen("unix", core.Flagconfig.UnixSocket)
if err != nil {
core.Err.Fatalln("Failed listening", err)
}
go func() {
if core.Flagconfig.TLSCertPath != "" && core.Flagconfig.TLSKeyPath != "" {
core.Info.Println("Serving the HTTPS with TLS Cert ", core.Flagconfig.TLSCertPath, " and TLS Key", core.Flagconfig.TLSKeyPath)
core.Err.Fatal(http.ServeTLS(usock, nil, core.Flagconfig.TLSCertPath, core.Flagconfig.TLSKeyPath))
} else {
core.Err.Fatal(http.Serve(usock, nil))
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
<-c
_ = usock.Close()
} else {
// Run under specified Port
core.Info.Println("Starting server on", core.Flagconfig.ListenAddress)
if core.Flagconfig.TLSCertPath != "" && core.Flagconfig.TLSKeyPath != "" {
core.Info.Println("Serving the HTTPS with TLS Cert ", core.Flagconfig.TLSCertPath, " and TLS Key", core.Flagconfig.TLSKeyPath)
core.Err.Fatal(http.ListenAndServeTLS(core.Flagconfig.ListenAddress, core.Flagconfig.TLSCertPath, core.Flagconfig.TLSKeyPath, nil))
} else {
core.Err.Fatal(http.ListenAndServe(core.Flagconfig.ListenAddress, nil))
}
}
}

87
go.mod Normal file
View File

@@ -0,0 +1,87 @@
module github.com/varbhat/exatorrent
go 1.17
require (
crawshaw.io/sqlite v0.3.3-0.20210127221821-98b1f83c5508
github.com/anacrolix/go-libutp v1.0.4
github.com/anacrolix/log v0.9.0
github.com/anacrolix/torrent v1.30.4
github.com/google/uuid v1.3.0
github.com/gorilla/websocket v1.4.2
github.com/jackc/pgx/v4 v4.13.0
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58
github.com/shirou/gopsutil v3.21.7+incompatible
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
)
require (
github.com/RoaringBitmap/roaring v0.9.4 // indirect
github.com/StackExchange/wmi v1.2.1 // indirect
github.com/anacrolix/chansync v0.1.0 // indirect
github.com/anacrolix/confluence v1.8.0 // indirect
github.com/anacrolix/dht/v2 v2.10.3 // indirect
github.com/anacrolix/envpprof v1.1.1 // indirect
github.com/anacrolix/missinggo v1.3.0 // indirect
github.com/anacrolix/missinggo/perf v1.0.0 // indirect
github.com/anacrolix/missinggo/v2 v2.5.2 // indirect
github.com/anacrolix/mmsg v1.0.0 // indirect
github.com/anacrolix/multiless v0.1.1-0.20210529082330-de2f6cf29619 // indirect
github.com/anacrolix/stm v0.3.0 // indirect
github.com/anacrolix/sync v0.4.0 // indirect
github.com/anacrolix/upnp v0.1.2-0.20200416075019-5e9378ed1425 // indirect
github.com/anacrolix/utp v0.1.0 // indirect
github.com/benbjohnson/immutable v0.3.0 // indirect
github.com/bits-and-blooms/bitset v1.2.0 // indirect
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/edsrzf/mmap-go v1.0.0 // indirect
github.com/elliotchance/orderedmap v1.4.0 // indirect
github.com/go-ole/go-ole v1.2.5 // indirect
github.com/google/btree v1.0.1 // indirect
github.com/huandu/xstrings v1.3.2 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.10.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.1.1 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.8.1 // indirect
github.com/jackc/puddle v1.1.3 // indirect
github.com/mschoch/smat v0.2.0 // indirect
github.com/pion/datachannel v1.4.21 // indirect
github.com/pion/dtls/v2 v2.0.9 // indirect
github.com/pion/ice/v2 v2.1.12 // indirect
github.com/pion/interceptor v0.0.15 // indirect
github.com/pion/logging v0.2.2 // indirect
github.com/pion/mdns v0.0.5 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.6 // indirect
github.com/pion/rtp v1.7.2 // indirect
github.com/pion/sctp v1.7.12 // indirect
github.com/pion/sdp/v3 v3.0.4 // indirect
github.com/pion/srtp/v2 v2.0.5 // indirect
github.com/pion/stun v0.3.5 // indirect
github.com/pion/transport v0.12.3 // indirect
github.com/pion/turn/v2 v2.0.5 // indirect
github.com/pion/udp v0.1.1 // indirect
github.com/pion/webrtc/v3 v3.0.32 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rs/dnscache v0.0.0-20210201191234-295bba877686 // indirect
github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/tklauser/go-sysconf v0.3.8 // indirect
github.com/tklauser/numcpus v0.3.0 // indirect
github.com/willf/bitset v1.1.11 // indirect
github.com/willf/bloom v2.0.3+incompatible // indirect
go.etcd.io/bbolt v1.3.6 // indirect
golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71 // indirect
golang.org/x/text v0.3.6 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
)
exclude github.com/willf/bitset v1.2.0

1070
go.sum Normal file

File diff suppressed because it is too large Load Diff

185
internal/core/auth.go Normal file
View File

@@ -0,0 +1,185 @@
package core
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/google/uuid"
)
func AuthCheck(w http.ResponseWriter, r *http.Request) {
var username string
var usertype int
var token string
var err error
if r.Method == http.MethodPost {
c, err := r.Cookie("session_token")
if err != nil {
if val := r.URL.Query().Get("token"); val != "" {
username, usertype, err = Engine.UDb.ValidateToken(val)
if err != nil {
username, usertype, token, err = rauthHelper(w, r)
if err != nil {
Warn.Printf("not authorized (%s)\n", r.RemoteAddr)
http.Error(w, "invalid credentials", http.StatusBadRequest)
return
}
} else {
token = val
}
} else {
username, usertype, token, err = rauthHelper(w, r)
if err != nil {
Warn.Printf("not authorized (%s)\n", r.RemoteAddr)
http.Error(w, "invalid credentials", http.StatusBadRequest)
return
}
}
} else {
username, usertype, err = Engine.UDb.ValidateToken(c.Value)
if err != nil {
username, usertype, token, err = rauthHelper(w, r)
if err != nil {
Warn.Printf("not authorized (%s)\n", r.RemoteAddr)
http.Error(w, "invalid credentials", http.StatusBadRequest)
return
}
} else {
token = c.Value
}
}
} else {
username, usertype, token, err = authHelper(w, r)
if err != nil {
Warn.Printf("%s (%s)\n", err, r.RemoteAddr)
return
}
}
var cmsg []byte
if usertype == 0 {
cmsg, err = json.Marshal(&ConnectionMsg{Type: "user", Session: token})
} else if usertype == 1 {
cmsg, err = json.Marshal(&ConnectionMsg{Type: "admin", Session: token})
} else if usertype == -1 {
cmsg, err = json.Marshal(&ConnectionMsg{Type: "disabled", Session: token})
}
if err != nil {
return
}
_, err = w.Write(cmsg)
if err != nil {
return
}
Info.Printf("User %s (%s) Authenticated", username, r.RemoteAddr)
}
func authHelper(w http.ResponseWriter, r *http.Request) (username string, usertype int, token string, err error) {
c, err := r.Cookie("session_token")
if err != nil {
if val := r.URL.Query().Get("token"); val != "" {
username, usertype, err = Engine.UDb.ValidateToken(val)
if err != nil {
return bauthHelper(w, r)
}
token = val
} else {
return bauthHelper(w, r)
}
} else {
username, usertype, err = Engine.UDb.ValidateToken(c.Value)
if err != nil {
return bauthHelper(w, r)
}
token = c.Value
}
return username, usertype, token, nil
}
func bauthHelper(w http.ResponseWriter, r *http.Request) (username string, usertype int, token string, err error) {
defer func() {
if r := recover(); r != nil { // uuid may panic
username = ""
usertype = -1
token = ""
err = fmt.Errorf("uuid error")
return
}
}()
var password string
var ok bool
w.Header().Set("WWW-Authenticate", `Basic realm="Protected"`)
username, password, ok = r.BasicAuth()
if !ok {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return "", -1, "", fmt.Errorf("not authorized")
}
if len(username) < 5 || len(password) < 5 {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return "", -1, "", fmt.Errorf("not authorized")
}
usertype, ok = Engine.UDb.Validate(username, password)
if !ok {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return "", -1, "", fmt.Errorf("not authorized")
}
token = uuid.New().String()
err = Engine.UDb.SetToken(username, token)
if err != nil {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return "", -1, "", fmt.Errorf("not authorized")
}
http.SetCookie(w, &http.Cookie{
Name: "session_token",
Path: "/",
Value: token,
Expires: time.Now().Add(48 * time.Hour),
SameSite: http.SameSiteStrictMode,
})
return username, usertype, token, nil
}
func rauthHelper(w http.ResponseWriter, r *http.Request) (username string, usertype int, token string, err error) {
defer func() {
if r := recover(); r != nil { // uuid may panic
username = ""
usertype = -1
token = ""
err = fmt.Errorf("uuid error")
return
}
}()
var ok bool
var cred ConReq
reqreader := io.LimitReader(r.Body, 1048576) // 1MB limiter
err = json.NewDecoder(reqreader).Decode(&cred)
if err != nil {
return "", -1, "", err
}
if len(cred.Data1) < 5 || len(cred.Data2) < 5 {
return "", -1, "", fmt.Errorf("invalid credentials")
}
usertype, ok = Engine.UDb.Validate(cred.Data1, cred.Data2)
if !ok {
return "", -1, "", fmt.Errorf("invalid credentials")
}
token = uuid.New().String()
err = Engine.UDb.SetToken(cred.Data1, token)
if err != nil {
return "", -1, "", fmt.Errorf("not authorized")
}
http.SetCookie(w, &http.Cookie{
Name: "session_token",
Path: "/",
Value: token,
Expires: time.Now().Add(48 * time.Hour),
SameSite: http.SameSiteStrictMode,
})
username = cred.Data1
return username, usertype, token, nil
}

45
internal/core/cache.go Normal file
View File

@@ -0,0 +1,45 @@
package core
import (
"fmt"
"os"
"path/filepath"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
)
func AddMetaCache(ih metainfo.Hash, mi metainfo.MetaInfo) {
// create .torrent file
if w, err := os.Stat(Dirconfig.CacheDir); err == nil && w.IsDir() {
cacheFilePath := filepath.Join(Dirconfig.CacheDir, fmt.Sprintf("%s.torrent", ih.HexString()))
// only create the cache file if not exists
if _, err := os.Stat(cacheFilePath); os.IsNotExist(err) {
cf, err := os.Create(cacheFilePath)
if err == nil {
werr := mi.Write(cf)
if werr != nil {
Warn.Println("failed to create torrent file ", err)
}
Info.Println("created torrent cache file", ih.HexString())
} else {
Warn.Println("failed to create torrent file ", err)
}
_ = cf.Close()
}
}
}
func RemMetaCache(ih metainfo.Hash) {
_ = os.Remove(filepath.Join(Dirconfig.CacheDir, fmt.Sprintf("%s.torrent", ih.HexString())))
}
func GetMetaCache(ih metainfo.Hash) (spec *torrent.TorrentSpec, reterr error) {
return SpecfromPath(filepath.Join(Dirconfig.CacheDir, fmt.Sprintf("%s.torrent", ih.HexString())))
}
func EmptyMetaCache() {
_ = os.Remove(Dirconfig.CacheDir)
checkDir(Dirconfig.CacheDir)
}

151
internal/core/connection.go Normal file
View File

@@ -0,0 +1,151 @@
package core
import (
"encoding/json"
"sync"
"time"
"github.com/gorilla/websocket"
)
// Hub
type Hub struct {
sync.RWMutex
Conns map[string]*UserConn
}
func (h *Hub) Add(Uc *UserConn) {
conn, ok := h.Conns[Uc.Username]
if ok && conn != nil {
conn.Close()
}
h.Lock()
h.Conns[Uc.Username] = Uc
h.Unlock()
Info.Printf("User %s (%s) Connected\n", Uc.Username, Uc.Conn.RemoteAddr().String())
}
func (h *Hub) SendMsg(User string, Type string, State string, Resp string) {
if User != "" {
conn, ok := h.Conns[User]
if ok && conn != nil {
_ = conn.SendMsg(Type, State, Resp)
}
}
}
func (h *Hub) SendMsgU(User string, Type string, Infohash string, State string, Resp string) {
if User != "" {
conn, ok := h.Conns[User]
if ok && conn != nil {
_ = conn.SendMsgU(Type, State, Infohash, Resp)
}
}
}
func (h *Hub) Remove(Uc *UserConn) {
if Uc == nil {
return
}
h.Lock()
defer h.Unlock()
conn, ok := h.Conns[Uc.Username]
if ok && conn != nil {
if conn.Time == Uc.Time {
delete(h.Conns, Uc.Username)
Info.Printf("User %s (%s) Disconnected\n", Uc.Username, Uc.Conn.RemoteAddr().String())
}
}
}
func (h *Hub) RemoveUser(Username string) {
conn, ok := h.Conns[Username]
if ok && conn != nil {
conn.Close()
}
}
func (h *Hub) ListUsers() (ret []byte) {
var userconnmsg []*UserConnMsg
h.Lock()
defer h.Unlock()
for name, user := range h.Conns {
var usermsg UserConnMsg
if user != nil {
usermsg.Username = name
usermsg.IsAdmin = user.IsAdmin
usermsg.Time = user.Time
}
userconnmsg = append(userconnmsg, &usermsg)
}
ret, _ = json.Marshal(DataMsg{Type: "userconn", Data: userconnmsg})
return
}
var MainHub Hub = Hub{
RWMutex: sync.RWMutex{},
Conns: make(map[string]*UserConn),
}
// UserConn
type UserConn struct {
Sendmu sync.Mutex
Username string
IsAdmin bool
Time time.Time
Conn *websocket.Conn
Stream sync.Mutex
Streamers MutInt
}
func NewUserConn(Username string, Conn *websocket.Conn, IsAdmin bool) (uc *UserConn) {
uc = &UserConn{
Username: Username,
Conn: Conn,
IsAdmin: IsAdmin,
Time: time.Now(),
}
MainHub.Add(uc)
return
}
func (uc *UserConn) SendMsg(Type string, State string, Msg string) (err error) {
resp, _ := json.Marshal(Resp{Type: Type, State: State, Msg: Msg})
err = uc.Send(resp)
return
}
func (uc *UserConn) SendMsgU(Type string, State string, Infohash string, Msg string) (err error) {
resp, _ := json.Marshal(Resp{Type: Type, State: State, Infohash: Infohash, Msg: Msg})
err = uc.Send(resp)
return
}
func (uc *UserConn) Send(v []byte) (err error) {
uc.Sendmu.Lock()
_ = uc.Conn.SetWriteDeadline(time.Now().Add(writeWait))
err = uc.Conn.WriteMessage(websocket.TextMessage, v)
uc.Sendmu.Unlock()
if err != nil {
Err.Println(err)
uc.Close()
return
}
return
}
func (uc *UserConn) StopStream() {
uc.Streamers.Inc()
uc.Stream.Lock()
Info.Println("Stopped Stream for ", uc.Username)
uc.Stream.Unlock()
uc.Streamers.Dec()
}
func (uc *UserConn) Close() {
uc.Sendmu.Lock()
_ = uc.Conn.Close()
uc.Sendmu.Unlock()
MainHub.Remove(uc)
}

584
internal/core/engine.go Normal file
View File

@@ -0,0 +1,584 @@
package core
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/varbhat/exatorrent/internal/db"
)
type Eng struct {
Tconfig TorConfig
Econfig EngConfig
PsqlCon string
Torc *torrent.Client
PcDb db.PcDb
TorDb db.TorrentDb
TrackerDB db.TrackerDb
FsDb db.FileStateDb
LsDb db.LockStateDb
UDb db.UserDb
TUDb db.TorrentUserDb
}
// AddfromSpec Adds Torrent by Torrent Spec
func AddfromSpec(User string, spec *torrent.TorrentSpec, dontstart bool, nofsdb bool) {
if spec == nil {
return
}
if Engine.Econfig.GetDTU() {
RemTrackersSpec(spec)
}
Info.Println("Adding Torrent")
var trnt *torrent.Torrent
var new bool
var err error
// Add Torrent to Bittorrent Client
if Engine.Torc != nil {
trnt, new, err = Engine.Torc.AddTorrentSpec(spec)
if err != nil {
Warn.Println("Error adding Torrent Spec", err)
MainHub.SendMsgU(User, "nfn", trnt.InfoHash().HexString(), "error", "Error adding Torrent Spec")
return
}
if !new {
Info.Printf("Torrent %s is not new", spec.InfoHash)
MainHub.SendMsgU(User, "nfn", trnt.InfoHash().HexString(), "warning", "Torrent is not new")
if User != "" {
_ = Engine.TUDb.Add(User, trnt.InfoHash())
}
return
}
if Engine.Econfig.GetLBD() {
_ = Engine.LsDb.Lock(spec.InfoHash)
Info.Println("lock of torrent ", spec.InfoHash, " is set to true (due to config option)")
}
} else {
Err.Println("Torrent Client is nil")
return
}
if User != "" {
_ = Engine.TUDb.Add(User, trnt.InfoHash())
Info.Println("Torrent: ", spec.InfoHash, " User: ", User)
}
// Add Trackers to Torrent
count := Engine.TrackerDB.Count()
if count > 0 && (len(Engine.Econfig.TrackerListURLs) != 0 || len(trnt.Metainfo().AnnounceList) == 0) {
trnt.AddTrackers([][]string{Engine.TrackerDB.Get()})
Info.Println("Added ", count, " Trackers for Added Torrent")
}
ih := trnt.InfoHash()
hasadded := Engine.TorDb.Exists(ih)
if !hasadded {
_ = Engine.TorDb.Add(ih)
Info.Println("Added Torrent to Torrent Database")
}
var cancelled Mutbool
go func() {
defer func() {
if err := recover(); err != nil {
Warn.Println(err)
}
}()
var notmerged bool = true
if !Engine.Econfig.GetDLC() {
Info.Println("Getting Metainfo from Local Cache")
sp, err := GetMetaCache(ih)
if err != nil {
Info.Println("Torrent Metainfo is not present in Cache", err)
notmerged = true
} else {
if !(cancelled.Get()) {
if Engine.Econfig.GetDTC() {
RemTrackersSpec(sp)
}
if sp != nil {
err := trnt.MergeSpec(sp)
if err != nil {
Warn.Println(err)
notmerged = true
} else {
Info.Println("Torrent Metainfo merged from Local Cache")
MainHub.SendMsgU(User, "nfn", ih.HexString(), "info", "Metainfo of Torrent "+ih.HexString()+" merged from Local Cache")
notmerged = false
}
}
}
}
}
if len(Engine.Econfig.GetOCU()) != 0 && notmerged {
Info.Println("Torrent Metainfo requested from Online Cache")
uspec, err := SpecfromURL(fmt.Sprintf(Engine.Econfig.GetOCU(), strings.TrimSpace(trnt.InfoHash().HexString())))
if err != nil {
Warn.Println(err)
} else {
if !(cancelled.Get()) {
if Engine.Econfig.GetDTC() {
RemTrackersSpec(uspec)
}
if uspec != nil {
trmerr := trnt.MergeSpec(uspec)
if trmerr != nil {
Warn.Println(err)
return
}
Info.Println("Torrent Metainfo merged form Online Cache")
MainHub.SendMsgU(User, "nfn", ih.HexString(), "info", "Metainfo of Torrent merged from Online Cache")
}
}
}
}
}()
select {
case <-Engine.Torc.Closed():
cancelled.Set(true)
Warn.Println("Torrent Client Closed! So,Torrent Not Started")
MainHub.SendMsgU(User, "nfn", ih.HexString(), "error", "Torrent Client Closed! So,Torrent Not Added")
case <-trnt.Closed():
cancelled.Set(true)
Warn.Println("Torrent Task that was being added was Deleted !")
MainHub.SendMsgU(User, "nfn", ih.HexString(), "warning", "Torrent Task cancelled = true that was being added was Deleted !")
case <-trnt.GotInfo():
Info.Println("Torrent ", ih, " is Loaded")
MainHub.SendMsgU(User, "nfn", ih.HexString(), "info", "Torrent is Loaded")
if !dontstart {
go StartTorrent(User, ih, nofsdb)
}
if !Engine.Econfig.GetDLC() {
AddMetaCache(ih, trnt.Metainfo())
}
}
}
// StartTorrent Starts Torrent given infohash
func StartTorrent(User string, infohash metainfo.Hash, nofsdb bool) {
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
Info.Println("Starting Torrent for Infohash ", infohash)
t, err := Engine.TorDb.GetTorrent(infohash)
if err != nil {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
Warn.Println(err)
return
}
if t.Started {
Info.Println("Already Started")
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "info", "Torrent is Already Started")
}
trnt, ok := Engine.Torc.Torrent(infohash)
if !ok {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
Warn.Println("Error fetching torrent of infohash ", infohash, " from the client")
return
}
if trnt.Info() != nil {
trnt.AllowDataUpload()
trnt.AllowDataDownload()
// start file by setting the priority
for _, f := range trnt.Files() {
f.SetPriority(torrent.PiecePriorityNormal)
}
} else {
Warn.Println("Torrent can't be Started Because Metainfo is not yet recieved")
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent couldn't be Started Because Metainfo is not yet recieved")
return
}
err = Engine.TorDb.Start(infohash)
if err != nil {
Warn.Println(err)
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent couldn't be Started")
return
}
if !nofsdb {
err = Engine.FsDb.Delete(infohash)
if err != nil {
Warn.Println(err)
}
}
Info.Println("Torrent ", infohash, " Started by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "Torrent Started")
}
// StopTorrent Stops Torrent given infohash
func StopTorrent(User string, infohash metainfo.Hash) {
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
Warn.Println("Stopping Torrent for Infohash ", infohash)
t, err := Engine.TorDb.GetTorrent(infohash)
if err != nil {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
Warn.Println(err)
return
}
if !t.Started {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "info", "Torrent Already Stopped !")
Warn.Println("Already stopped")
}
trnt, ok := Engine.Torc.Torrent(infohash)
if !ok {
Warn.Println("Error fetching torrent of infohash ", infohash, " from the client")
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
if trnt.Info() != nil {
trnt.DisallowDataUpload()
trnt.DisallowDataDownload()
for _, f := range trnt.Files() {
f.SetPriority(torrent.PiecePriorityNone)
}
} else {
Warn.Println("Torrent can't be Stopped Because Metainfo is not yet recieved")
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent couldn't be Stopped Because Metainfo is not yet recieved")
return
}
err = Engine.TorDb.SetStarted(infohash, false)
if err != nil {
Warn.Println(err)
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent couldn't be Stopped")
return
}
err = Engine.FsDb.Delete(infohash)
if err != nil {
Warn.Println(err)
}
Info.Println("Torrent ", infohash, " Stopped by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "Torrent Stopped")
}
// RemoveTorrent Removes Torrent from Torrent Client
func RemoveTorrent(User string, infohash metainfo.Hash) {
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
StopTorrent(User, infohash)
Warn.Println("Removing Torrent of Infohash ", infohash)
trnt, ok := Engine.Torc.Torrent(infohash)
if !ok {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
Warn.Println("Error fetching torrent of infohash ", infohash, " from the client")
return
}
trnt.Drop()
err := Engine.TorDb.Delete(infohash)
if err != nil {
Warn.Println(err)
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent couldn't be Removed")
}
err = Engine.FsDb.Delete(infohash)
if err != nil {
Warn.Println(err)
}
Info.Println("Torrent ", infohash, " Removed by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "Torrent Removed")
}
// DeleteTorrent in addition to Removing Torrent from Client also Deletes it from Storage
func DeleteTorrent(User string, infohash metainfo.Hash) {
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
RemoveTorrent(User, infohash)
var err error
if infohash.HexString() != "" {
err = os.RemoveAll(filepath.Join(Dirconfig.TrntDir, infohash.HexString()))
if err != nil {
Warn.Println(err)
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
} else {
Warn.Println("Unknown Error")
return
}
Engine.PcDb.Delete(infohash)
err = Engine.TUDb.RemoveAllMi(infohash)
if err != nil {
Warn.Println(err)
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent couldn't be Deleted")
}
_ = Engine.LsDb.Unlock(infohash)
if !Engine.Econfig.DRCI() {
RemMetaCache(infohash)
}
Info.Println("Torrent ", infohash, " Deleted by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "Torrent Deleted")
}
// StartFile Starts File in Torrent given infohash and Filepath
func StartFile(User string, infohash metainfo.Hash, fp string) {
fp = filepath.ToSlash(fp)
if fp == "" {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Filepath Invalid!")
return
}
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
Info.Println("Starting File in Torrent for Infohash ", infohash, "and Filepath ", fp)
t, ok := Engine.Torc.Torrent(infohash)
if !ok {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
Warn.Println("Error fetching torrent of infohash ", infohash, " from the client")
return
}
// Get File from Given Torrent
var f *torrent.File
if t.Info() != nil {
for _, file := range t.Files() {
if file.Path() == fp {
f = file
break
}
}
} else {
Warn.Println("File ", fp, "can't be Started Because Metainfo is not yet recieved")
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "File "+fp+" couldn't be Started Because Metainfo is not yet recieved")
return
}
// If File is missing , return the error
if f == nil {
Warn.Printf("%s not present", fp)
MainHub.SendMsgU(User, "error", infohash.HexString(), "info", "File"+fp+" not present")
return
}
// Set Priority to Normal / Start the Torrent
f.SetPriority(torrent.PiecePriorityNormal)
var err error
err = Engine.FsDb.Deletefile(fp, infohash)
if err != nil {
Warn.Println(err)
}
if !Engine.TorDb.HasStarted(infohash.HexString()) {
err = Engine.FsDb.Add(f.Path(), infohash)
if err != nil {
Warn.Println(err)
}
}
Info.Println("File", fp, "of Torrent", infohash, " Started by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "File "+fp+" started")
}
// StopFile Stops File in Torrent given infohash and Filepath
func StopFile(User string, infohash metainfo.Hash, fp string) {
fp = filepath.ToSlash(fp)
if fp == "" {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Filepath Invalid!")
return
}
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
Warn.Println("Stopping File in Torrent for Infohash ", infohash, "and Filepath ", fp)
t, ok := Engine.Torc.Torrent(infohash)
if !ok {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
Warn.Println("Error fetching torrent of infohash ", infohash, " from the client")
return
}
// Get File from Given Torrent
var f *torrent.File
if t.Info() != nil {
for _, file := range t.Files() {
if file.Path() == fp {
f = file
break
}
}
} else {
Warn.Println("File ", fp, "can't be Stopped Because Metainfo is not yet recieved")
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "File "+fp+" couldn't be Stopped Because Metainfo is not yet recieved")
return
}
// If File is missing , return the error
if f == nil {
Warn.Printf("%s not present", fp)
MainHub.SendMsgU(User, infohash.HexString(), "error", "info", "File"+fp+" not present")
return
}
// Set Priority to None ( Stop the File)
f.SetPriority(torrent.PiecePriorityNone)
var err error
err = Engine.FsDb.Deletefile(fp, infohash)
if err != nil {
Warn.Println(err)
}
if Engine.TorDb.HasStarted(infohash.HexString()) {
err = Engine.FsDb.Add(f.Path(), infohash)
if err != nil {
Warn.Println(err)
}
}
Info.Println("File", fp, "of Torrent", infohash, " Stopped by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "File "+fp+" stopped")
}
// DeleteFilePath deletes the file or Folder
func DeleteFilePath(User string, infohash metainfo.Hash, fp string) {
if fp == "" {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Filepath Invalid!")
return
}
if infohash.HexString() == "" {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Infohash Invalid!")
return
}
fp = filepath.ToSlash(fp)
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
Warn.Println("Deleting File in Torrent for Infohash ", infohash, "and Filepath ", fp)
_, ok := Engine.Torc.Torrent(infohash)
if ok {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Currently Present in Client. Please Remove it from Torrent Client First!")
return
}
file := filepath.Join(Dirconfig.TrntDir, infohash.HexString(), filepath.FromSlash(fp))
if !strings.HasPrefix(file, filepath.Join(Dirconfig.TrntDir, infohash.HexString())) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "FilePath Invalid!")
return
}
if file == filepath.Join(Dirconfig.TrntDir, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Cannot Delete whole Torrent Directory")
return
}
err := os.RemoveAll(file)
if err != nil {
Warn.Println("DeleteFile error by Username: ", User, "Filepath: ", fp, " ", err)
MainHub.SendMsgU(User, "error", infohash.HexString(), "info", "Error removing File "+fp)
return
}
Info.Println("File", fp, "of Torrent", infohash, " Deleted by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "File"+fp+" Deleted")
}
// AbandonTorrent unlinks Torrent from User
func AbandonTorrent(User string, infohash metainfo.Hash) {
err := Engine.TUDb.Remove(User, infohash)
if err != nil {
Warn.Println("AbandonTorrent error", err)
MainHub.SendMsgU(User, "error", infohash.HexString(), "info", "AbandonTorrent error")
return
}
Info.Println("User ", User, " abandoned ", infohash)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "Torrent Abandoned")
}
// AddTrackerstoTorrent Adds Tracker to Torrent
func AddTrackerstoTorrent(User string, infohash metainfo.Hash, announcelist [][]string) {
if User != "" {
if !Engine.TUDb.HasUser(User, infohash.HexString()) {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
return
}
}
trnt, ok := Engine.Torc.Torrent(infohash)
if !ok {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Torrent Not Present!")
Warn.Println("Error fetching torrent of infohash ", infohash, " from the client")
return
}
if !(Engine.Econfig.GetDTU()) {
trnt.AddTrackers(announcelist)
} else {
MainHub.SendMsgU(User, "nfn", infohash.HexString(), "error", "Trackers Couldn't be Added!")
return
}
Info.Println("Trackers added to torrent ", infohash, "by ", User)
MainHub.SendMsgU(User, "resp", infohash.HexString(), "success", "Trackers added")
}

334
internal/core/get.go Normal file
View File

@@ -0,0 +1,334 @@
package core
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"time"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
)
type Torrent1 struct {
Infohash string `json:"infohash"`
Name string `json:"name,omitempty"`
BytesCompleted int64 `json:"bytescompleted,omitempty"`
BytesMissing int64 `json:"bytesmissing,omitempty"`
Length int64 `json:"length,omitempty"`
State string `json:"state"`
Seeding bool `json:"seeding,omitempty"`
}
type Torrent2 struct {
Torrent1
StartedAt time.Time `json:"startedat"`
AddedAt time.Time `json:"addedat"`
}
type FileInfo struct {
BytesCompleted int64 `json:"bytescompleted"`
DisplayPath string `json:"displaypath"`
Length int64 `json:"length"`
Offset int64 `json:"offset"`
Path string `json:"path"`
Priority byte `json:"priority"`
}
type FsFileInfo struct {
Name string `json:"name"`
Path string `json:"path"`
Size int64 `json:"size"`
IsDir bool `json:"isdir"`
}
func GetTorrents(lt []metainfo.Hash) (ret []byte) {
var tinits []*Torrent1
for _, ih := range lt {
var tinit Torrent1
tinit.Infohash = ih.HexString()
tinits = append(tinits, &tinit)
t, ok := Engine.Torc.Torrent(ih)
if !ok {
tinit.State = "removed"
continue
}
tinit.Name = t.Name()
if t == nil || t.Info() == nil {
tinit.State = "loading"
continue
}
if Engine.TorDb.HasStarted(ih.HexString()) {
tinit.State = "active"
} else {
tinit.State = "inactive"
}
tinit.Length = t.Length()
tinit.BytesCompleted = t.BytesCompleted()
tinit.BytesMissing = t.BytesMissing()
tinit.Seeding = t.Seeding()
}
ret, _ = json.Marshal(DataMsg{Type: "torrentstream", Data: tinits})
return
}
func GetTorrentInfo(ih metainfo.Hash) (ret []byte) {
var tinit Torrent1
tinit.Infohash = ih.HexString()
t, ok := Engine.Torc.Torrent(ih)
if !ok {
tinit.State = "removed"
ret, _ = json.Marshal(DataMsg{Type: "torrentinfo", Data: tinit})
return
}
tinit.Name = t.Name()
if t == nil || t.Info() == nil {
tinit.State = "loading"
ret, _ = json.Marshal(DataMsg{Type: "torrentinfo", Data: tinit})
return
}
if Engine.TorDb.HasStarted(ih.HexString()) {
tinit.State = "active"
} else {
tinit.State = "inactive"
}
tinit.Length = t.Length()
tinit.BytesCompleted = t.BytesCompleted()
tinit.BytesMissing = t.BytesMissing()
tinit.Seeding = t.Seeding()
ret, _ = json.Marshal(DataMsg{Type: "torrentinfo", Data: tinit})
return
}
func GetTorrentInfoStat(ih metainfo.Hash) (ret []byte) {
trnt, err := Engine.TorDb.GetTorrent(ih)
if err == nil {
ret, _ = json.Marshal(DataMsg{Type: "torrentinfostat", Data: trnt})
}
return
}
func GetTorrentStats(ih metainfo.Hash) (ret []byte) {
defer func() {
if r := recover(); r != nil {
Warn.Println("There was Panic in GetTorrentStats")
}
}()
t, ok := Engine.Torc.Torrent(ih)
if !ok {
ret, _ = json.Marshal(DataMsg{Type: "torrentstats", Data: nil})
return
}
if t == nil || t.Info() == nil {
ret, _ = json.Marshal(DataMsg{Type: "torrentstats", Data: nil})
return
}
ts := t.Stats()
ret, _ = json.Marshal(DataMsg{Data: &ts, Infohash: ih.HexString(), Type: "torrentstats"})
return
}
func GetFsDirInfo(ih metainfo.Hash, fp string) (ret []byte) {
fp = filepath.ToSlash(fp)
ret, _ = json.Marshal(DataMsg{Type: "fsdirinfo", Data: nil})
ihs := ih.HexString()
if ihs == "" {
Warn.Println("empty infohash")
return
}
dirpath := filepath.Join(Dirconfig.TrntDir, ihs, fp)
if !strings.HasPrefix(dirpath, filepath.Join(Dirconfig.TrntDir, ihs)) {
return
}
rl, err := os.ReadDir(filepath.FromSlash(dirpath))
if err != nil {
Warn.Println(err.Error())
return
}
var retfiles []FsFileInfo
for _, eachdirentry := range rl {
var retfile FsFileInfo
inf, err := eachdirentry.Info()
if err != nil {
continue
}
retfile.Name = inf.Name()
retfile.IsDir = inf.IsDir()
retfile.Size = inf.Size()
retfile.Path = filepath.ToSlash(filepath.Join(fp, retfile.Name))
retfiles = append(retfiles, retfile)
}
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "fsdirinfo", Data: retfiles})
return
}
func GetFsFileInfo(ih metainfo.Hash, fp string) (ret []byte) {
fp = filepath.ToSlash(fp)
ret, _ = json.Marshal(DataMsg{Type: "fsfileinfo", Data: nil})
ihs := ih.HexString()
if ihs == "" {
Warn.Println("empty infohash")
return
}
dirpath := filepath.Join(Dirconfig.TrntDir, ihs, fp)
if !strings.HasPrefix(dirpath, filepath.Join(Dirconfig.TrntDir, ihs)) {
return
}
var retfile FsFileInfo
inf, err := os.Stat(filepath.FromSlash(dirpath))
if err != nil {
Warn.Println("GetFsFileInfo Error", err)
return
}
retfile.Name = inf.Name()
retfile.IsDir = inf.IsDir()
retfile.Size = inf.Size()
retfile.Path = fp
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "fsfileinfo", Data: retfile})
return
}
func GetTorrentFiles(ih metainfo.Hash) (ret []byte) {
ret, _ = json.Marshal(DataMsg{Type: "torrentfiles", Data: nil})
t, ok := Engine.Torc.Torrent(ih)
if !ok {
return
}
if t == nil || t.Info() == nil {
return
}
var retfiles []FileInfo
for _, file := range t.Files() {
if file == nil {
continue
}
var retfile FileInfo
retfile.BytesCompleted = file.BytesCompleted()
retfile.DisplayPath = file.DisplayPath()
retfile.Length = file.Length()
retfile.Offset = file.Offset()
retfile.Path = file.Path()
retfile.Priority = byte(file.Priority())
retfiles = append(retfiles, retfile)
}
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "torrentfiles", Data: retfiles})
return
}
func GetTorrentFileInfo(ih metainfo.Hash, fp string) (ret []byte) {
ret, _ = json.Marshal(DataMsg{Type: "torrentfileinfo", Data: nil})
t, ok := Engine.Torc.Torrent(ih)
if !ok {
return
}
if t == nil || t.Info() == nil {
return
}
// Get File from Given Torrent
var file *torrent.File
for _, f := range t.Files() {
if f.Path() == fp {
file = f
break
}
}
if file == nil {
return
}
var retfile FileInfo
retfile.BytesCompleted = file.BytesCompleted()
retfile.DisplayPath = file.DisplayPath()
retfile.Length = file.Length()
retfile.Offset = file.Offset()
retfile.Path = file.Path()
retfile.Priority = byte(file.Priority())
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "torrentfileinfo", Data: retfile})
return
}
func GetTorrentPieceStateRuns(ih metainfo.Hash) (ret []byte) {
ret, _ = json.Marshal(DataMsg{Type: "torrentpiecestateruns", Data: nil})
t, ok := Engine.Torc.Torrent(ih)
if !ok {
return
}
if t == nil || t.Info() == nil {
return
}
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "torrentpiecestateruns", Data: t.PieceStateRuns()})
return
}
func GetTorrentKnownSwarm(ih metainfo.Hash) (ret []byte) {
ret, _ = json.Marshal(DataMsg{Type: "torrentknownswarm", Data: nil})
t, ok := Engine.Torc.Torrent(ih)
if !ok {
return
}
if t == nil || t.Info() == nil {
return
}
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "torrentknownswarm", Data: t.KnownSwarm()})
return
}
func GetTorrentNumpieces(ih metainfo.Hash) (ret []byte) {
ret, _ = json.Marshal(DataMsg{Type: "torrentnumpieces", Data: nil})
t, ok := Engine.Torc.Torrent(ih)
if !ok {
return
}
if t == nil || t.Info() == nil {
return
}
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "torrentnumpieces", Data: t.NumPieces()})
return
}
func GetTorrentMetainfo(ih metainfo.Hash) (ret []byte) {
ret, _ = json.Marshal(DataMsg{Type: "torrentmetainfo", Data: nil})
t, ok := Engine.Torc.Torrent(ih)
if !ok {
return
}
if t == nil || t.Info() == nil {
return
}
mi := t.Metainfo()
mi.CreatedBy = "exatorrent"
var tmi bytes.Buffer
err := mi.Write(&tmi)
if err != nil {
return
}
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "torrentmetainfo", Data: tmi.Bytes()})
return
}
func GetTorrentPeerConns(ih metainfo.Hash) (ret []byte) {
ret, _ = json.Marshal(DataMsg{Type: "torrentpeerconns", Data: nil})
t, ok := Engine.Torc.Torrent(ih)
if !ok {
return
}
if t == nil || t.Info() == nil {
return
}
ret, _ = json.Marshal(DataMsg{Infohash: ih.HexString(), Type: "torrentpeerconns", Data: t.PeerConns()})
return
}

121
internal/core/getspec.go Normal file
View File

@@ -0,0 +1,121 @@
package core
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
)
// SpecfromURL Returns Torrent Spec from HTTP URL
func SpecfromURL(torrentURL string) (spec *torrent.TorrentSpec, reterr error) {
// TorrentSpecFromMetaInfo may panic if the info is malformed
defer func() {
if r := recover(); r != nil {
reterr = fmt.Errorf("SpecfromURL: error loading spec from URL")
}
reterr = nil
}()
Info.Println("Adding Torrent from Torrent URL ", torrentURL)
torrentURL = strings.TrimSpace(torrentURL)
resp, reterr := http.Get(torrentURL)
if reterr != nil {
return
}
// Limit Response
lr := io.LimitReader(resp.Body, 20971520) // 20MB
info, reterr := metainfo.Load(lr)
if reterr != nil {
_ = resp.Body.Close()
return
}
spec = torrent.TorrentSpecFromMetaInfo(info)
_ = resp.Body.Close()
return
}
// SpecfromPath Returns Torrent Spec from File Path
func SpecfromPath(path string) (spec *torrent.TorrentSpec, reterr error) {
// TorrentSpecFromMetaInfo may panic if the info is malformed
defer func() {
if r := recover(); r != nil {
reterr = fmt.Errorf("SpecfromPath: error loading new torrent from file %s: %v+", path, r)
}
}()
fi, err := os.Stat(path)
if os.IsNotExist(err) {
return nil, fmt.Errorf("file doesn't exist")
}
if fi.IsDir() {
Err.Println("Directory Present instead of file")
return nil, fmt.Errorf("directory present")
}
Info.Println("Getting Torrent Metainfo from File Path", path)
info, reterr := metainfo.LoadFromFile(path)
if reterr != nil {
return
}
spec = torrent.TorrentSpecFromMetaInfo(info)
return
}
// SpecfromBytes Returns Torrent Spec from Bytes
func SpecfromBytes(trnt []byte) (spec *torrent.TorrentSpec, reterr error) {
// TorrentSpecFromMetaInfo may panic if the info is malformed
defer func() {
if r := recover(); r != nil {
reterr = fmt.Errorf("SpecfromBytes: error loading new torrent from bytes")
}
}()
Info.Println("Getting Torrent Metainfo from Torrent Bytes")
info, reterr := metainfo.Load(bytes.NewReader(trnt))
if reterr != nil {
return nil, reterr
}
spec = torrent.TorrentSpecFromMetaInfo(info)
return
}
// SpecfromB64String Returns Torrent Spec from Base64 Encoded Torrent File
func SpecfromB64String(trnt string) (spec *torrent.TorrentSpec, reterr error) {
t, err := base64.StdEncoding.DecodeString(trnt)
if err != nil {
return nil, err
}
return SpecfromBytes(t)
}
// MetafromHex returns metainfo.Hash from given infohash string
func MetafromHex(infohash string) (h metainfo.Hash, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error parsing string to InfoHash")
}
}()
h = metainfo.NewHashFromHex(infohash)
return h, nil
}
// RemTrackersSpec removes trackers from torrent.Spec
func RemTrackersSpec(spec *torrent.TorrentSpec) {
if spec == nil {
return
}
spec.Trackers = [][]string{}
}

310
internal/core/init.go Normal file
View File

@@ -0,0 +1,310 @@
package core
import (
"bufio"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"log"
"os"
"os/signal"
"path/filepath"
"syscall"
utp "github.com/anacrolix/go-libutp"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
"github.com/varbhat/exatorrent/internal/db"
)
func checkDir(dir string) {
fi, err := os.Stat(dir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
er := os.MkdirAll(dir, 0755)
if er != nil {
Err.Fatalln("Error Creating Directory")
}
return
} else {
Err.Fatalf("Error Stat Directory %s ( %s ) \n", dir, err.Error())
return
}
}
if fi != nil {
if !fi.IsDir() {
Err.Fatalln("Non-Directory File Present")
return
}
} else {
Err.Fatalln("Error Stat Directory ", dir)
}
}
func Initialize() {
var cfilename string
var torcc bool
var psql bool
var engc bool
var err error
var auser string
flag.Usage = func() {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "exatorrent is bittorrent client\n\n")
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
flag.VisitAll(func(f *flag.Flag) {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), " -%-5v %v\n", f.Name, f.Usage)
})
_, _ = fmt.Fprintf(flag.CommandLine.Output(), " -%-5v %v\n", "help", "<opt> Print this Help")
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nVersion: %s", Version)
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nLicense: GPLv3")
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nSource : https://github.com/varbhat/exatorrent\n")
}
flag.StringVar(&Flagconfig.ListenAddress, "addr", ":5000", `<addr> Listen Address (Default: ":5000")`)
flag.StringVar(&Flagconfig.UnixSocket, "unix", "", `<path> Unix Socket Path`)
flag.StringVar(&Flagconfig.TLSKeyPath, "key", "", "<path> Path to TLS Key (Required for HTTPS)")
flag.StringVar(&Flagconfig.TLSCertPath, "cert", "", "<path> Path to TLS Certificate (Required for HTTPS)")
flag.StringVar(&Dirconfig.DirPath, "dir", "exadir", `<path> exatorrent Directory (Default: "exadir")`)
flag.StringVar(&auser, "admin", "adminuser", `<user> Default admin username (Default Username: "adminuser" and Default Password: "adminpassword")`)
flag.BoolVar(&psql, "psql", false, "<opt> Generate Sample Postgresql Connection URL")
flag.BoolVar(&engc, "engc", false, "<opt> Generate Custom Engine Configuration")
flag.BoolVar(&torcc, "torc", false, "<opt> Generate Custom Torrent Client Configuration")
flag.Parse()
if len(flag.Args()) != 0 {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Invalid Flags Provided: %s\n\n", flag.Args())
flag.Usage()
return
}
// Display All Flag Configurations Provided to exatorrent
if Flagconfig.UnixSocket != "" {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nUnix Socket Path => %s", Flagconfig.UnixSocket)
} else {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nAddress => %s", Flagconfig.ListenAddress)
}
if Flagconfig.TLSKeyPath != "" {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nTLS Key Path => %s", Flagconfig.TLSKeyPath)
}
if Flagconfig.TLSCertPath != "" {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nTLS Certificate Path => %s", Flagconfig.TLSCertPath)
}
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nDirectory => %s\n\n", Dirconfig.DirPath)
// Create Required SubDirectories if not present
checkDir(Dirconfig.DirPath)
Dirconfig.ConfigDir = filepath.Join(Dirconfig.DirPath, "config")
checkDir(Dirconfig.ConfigDir)
Dirconfig.CacheDir = filepath.Join(Dirconfig.DirPath, "cache")
checkDir(Dirconfig.CacheDir)
Dirconfig.DataDir = filepath.Join(Dirconfig.DirPath, "data")
checkDir(Dirconfig.DataDir)
Dirconfig.TrntDir = filepath.Join(Dirconfig.DirPath, "torrents")
checkDir(Dirconfig.TrntDir)
// Load Torrent Client Configuration
cfilename = filepath.Join(Dirconfig.ConfigDir, "clientconfig.json")
_, cfileerr := os.Stat(cfilename)
if cfileerr == nil {
var e error
cf, e := os.Open(cfilename)
if e != nil {
Err.Fatalln("Error Opening ", cfilename)
}
if cf != nil {
e = json.NewDecoder(cf).Decode(&Engine.Tconfig)
if e != nil {
Err.Fatalln("Error Decoding ", cfilename)
}
Info.Println("Torrent Client Configuration is now loaded from ", cfilename)
torcc = true
_ = cf.Close()
}
} else if os.IsNotExist(cfileerr) && torcc {
jfile, _ := json.MarshalIndent(Engine.Tconfig, "", "\t")
_ = os.WriteFile(cfilename, jfile, 0644)
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nSample Torrent Client Configuration has been written at %s\n", cfilename)
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Please Customize Torrent Client Configuration File %s if required , and restart\n", cfilename)
os.Exit(0)
}
// Load Custom Engine Configuration
Engine.Econfig = EngConfig{GlobalSeedRatio: 0, OnlineCacheURL: "https://itorrents.org/torrent/%s.torrent", SRRefresh: 150, TrackerRefresh: 60, TrackerListURLs: []string{"https://ngosang.github.io/trackerslist/trackers_best.txt"}}
// You can also add these "https://newtrackon.com/api/stable" , "https://cdn.jsdelivr.net/gh/XIU2/TrackersListCollection@master/best.txt"
cfilename = filepath.Join(Dirconfig.ConfigDir, "engconfig.json")
_, cfileerr = os.Stat(cfilename)
if cfileerr == nil {
var e error
cf, e := os.Open(cfilename)
if e != nil {
Err.Fatalln("Error Opening ", cfilename)
} else {
if cf != nil {
e = json.NewDecoder(cf).Decode(&Engine.Econfig)
if e != nil {
Err.Fatalln("Error Decoding ", cfilename)
}
Info.Printf("Engine Configuration %+v is now loaded\n", Engine.Econfig)
engc = true
_ = cf.Close()
}
}
} else if os.IsNotExist(cfileerr) && engc {
_ = Engine.Econfig.WriteConfig()
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nSample Engine Configuration has been written at %s\n", cfilename)
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Please Customize Engine Configuration File %s if required , and restart\n", cfilename)
os.Exit(0)
}
// Read Postgresql Secret
cfilename = filepath.Join(Dirconfig.ConfigDir, "psqlconfig.txt")
_, cfileerr = os.Stat(cfilename)
if cfileerr == nil {
pfile, err := os.Open(cfilename)
if err != nil {
Err.Fatalln("Error Reading Postgresql Connection URL: ", err)
}
defer pfile.Close()
scanner := bufio.NewScanner(pfile)
for scanner.Scan() {
Engine.PsqlCon = scanner.Text()
psql = true
Info.Println("Postgresql Connection URL at", cfilename, " has been Read")
break
}
if err := scanner.Err(); err != nil {
Err.Fatalln("Error Reading Postgresql Connection URL: ", err)
}
} else {
Engine.PsqlCon = os.Getenv("DATABASE_URL")
if len(Engine.PsqlCon) != 0 {
psql = true
_ = os.Unsetenv("DATABASE_URL")
}
}
if os.IsNotExist(cfileerr) && psql {
_ = os.WriteFile(cfilename, []byte("postgres://username:password@localhost:5432/database_name"), 0644)
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\nSample Postgresql Connection URL has been written at %s\n", cfilename)
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Please Enter your Postgresql Connection URL at File %s , and restart\n", cfilename)
os.Exit(0)
}
tc := Engine.Tconfig.ToTorrentConfig()
// Set Different Logger for UTP
utp.Logger = log.New(os.Stderr, "[UTP ] ", log.LstdFlags) // Info Logger
if psql {
Engine.TorDb = &db.PsqlTrntDb{}
Engine.TorDb.Open(Engine.PsqlCon)
Engine.FsDb = &db.PsqlFsDb{}
Engine.FsDb.Open(Engine.PsqlCon)
Engine.LsDb = &db.PsqlLsDb{}
Engine.LsDb.Open(Engine.PsqlCon)
Engine.UDb = &db.PsqlUserDb{}
Engine.UDb.Open(Engine.PsqlCon)
Engine.TUDb = &db.PsqlTrntUserDb{}
Engine.TUDb.Open(Engine.PsqlCon)
Engine.TrackerDB = &db.PsqlTDb{}
Engine.TrackerDB.Open(Engine.PsqlCon)
Engine.PcDb, err = db.NewPsqlPieceCompletion(Engine.PsqlCon)
if err != nil {
Err.Fatalln("Unable to Connect to Postgresql for PieceCompletion")
}
} else {
sqliteSetup(tc)
}
_, err = os.Stat(filepath.Join(Dirconfig.DataDir, ".adminadded"))
if errors.Is(err, os.ErrNotExist) {
Info.Println(`Adding Admin user with username "` + auser + `" and password "adminpassword"`)
er := Engine.UDb.Add(auser, "adminpassword", 1)
if er != nil {
Err.Fatalln("Unable to add admin user to adminless exatorrent instance", er)
}
_, er = os.Create(filepath.Join(Dirconfig.DataDir, ".adminadded"))
if er != nil {
Err.Fatalln(er)
}
}
tc.DefaultStorage = storage.NewFileWithCustomPathMakerAndCompletion(Dirconfig.TrntDir, func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string {
return filepath.Join(baseDir, infoHash.HexString())
}, Engine.PcDb)
Engine.Torc, err = torrent.NewClient(tc)
if err != nil {
Err.Fatalln("Unable to Create Torrent Client ", err)
} else {
Info.Println("Torrent Client Created")
}
go func() {
defer func() {
if err := recover(); err != nil {
Warn.Println(err)
}
}()
stopsignal := make(chan os.Signal, 5)
signal.Notify(stopsignal, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
sig := <-stopsignal
fmt.Fprintf(os.Stderr, "\n")
Warn.Println("Recieved ", sig)
Warn.Println("Closing exatorrent")
Engine.TorDb.Close()
Engine.TrackerDB.Close()
Engine.TUDb.Close()
_ = Engine.PcDb.Close() // Close PcDb at the end
// Stop The Engine
Engine.Torc.Close()
os.Exit(1)
}()
//Recover Torrents from Database
torlist, err := Engine.TorDb.GetTorrents()
if err != nil {
Err.Fatalln("Error Recovering Torrents")
}
for _, eachtrnt := range torlist {
go func(started bool, infohash metainfo.Hash) {
AddfromSpec("", &torrent.TorrentSpec{InfoHash: infohash}, true, true)
if started {
StartTorrent("", infohash, true)
}
flist := Engine.FsDb.Get(infohash)
if started {
for _, f := range flist {
StopFile("", infohash, f)
}
} else {
for _, f := range flist {
StartFile("", infohash, f)
}
}
}(eachtrnt.Started, eachtrnt.Infohash)
}
go UpdateTrackers()
go TorrentRoutine()
}

103
internal/core/routine.go Normal file
View File

@@ -0,0 +1,103 @@
package core
import (
"bufio"
"net/http"
"strings"
"time"
)
// UpdateTrackers Updates the Trackers from TrackerURL
func UpdateTrackers() {
defer func() {
if err := recover(); err != nil {
Warn.Println(err)
}
}()
for {
updatetrackers()
// Pause UpdateTrackers() every Engine.Econfig.TrackerRefresh Minutes
time.Sleep(time.Minute * time.Duration(Engine.Econfig.GetTR()))
}
}
// TorrentRoutine Stops Torrent on Reaching Global SeedRatio
func TorrentRoutine() {
defer func() {
if err := recover(); err != nil {
Warn.Println(err)
}
}()
for range time.Tick(time.Minute * time.Duration(Engine.Econfig.GetSRR())) {
stoponseedratio(Engine.Econfig.GetGSR())
}
}
func updatetrackers() {
for _, url := range Engine.Econfig.GetTLU() {
resp, err := http.Get(url)
if err != nil {
Warn.Println("TrackerList URL: ", url, " is Invalid")
continue
}
// Add Trackers to txtlines string slice
scanner := bufio.NewScanner(resp.Body)
scanner.Split(bufio.ScanLines)
var trackerpertrurl int
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
Engine.TrackerDB.Add(line)
trackerpertrurl++
}
_ = resp.Body.Close()
Info.Println("Loaded ", trackerpertrurl, " trackers from ", url)
}
Info.Println("Loaded ", Engine.TrackerDB.Count(), " trackers in total , eliminating duplicates")
// Add Trackers to Every Torrents
trckrs := [][]string{Engine.TrackerDB.Get()}
en := Engine.Torc
if en != nil {
for _, trnt := range en.Torrents() {
if trnt != nil {
trnt.AddTrackers(trckrs)
}
}
Info.Println("Added Loaded Trackers to Torrents")
}
}
func stoponseedratio(sr float64) {
if sr != 0 {
if Engine.Torc != nil {
trnts := Engine.Torc.Torrents()
for _, trnt := range trnts {
if trnt == nil {
continue
}
if trnt.Info() == nil {
continue
}
stats := trnt.Stats()
seedratio := float64(stats.BytesWrittenData.Int64()) / float64(stats.BytesReadData.Int64())
// stops task on reaching ratio
if seedratio >= sr {
Warn.Printf("Torrent %s Stopped on Reaching Global SeedRatio", trnt.InfoHash())
go StopTorrent("", trnt.InfoHash())
}
}
}
}
}

226
internal/core/serve.go Normal file
View File

@@ -0,0 +1,226 @@
package core
import (
"archive/tar"
"archive/zip"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/anacrolix/torrent"
)
func TorrentServe(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if !(len(parts) > 4) {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
if Engine.LsDb.IsLocked(parts[3]) {
u, ut, _, err := authHelper(w, r)
if err != nil {
Err.Println(err)
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
if ut != 1 {
if ut == -1 {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
if !Engine.TUDb.HasUser(u, parts[3]) {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
}
}
if val := r.URL.Query().Get("dl"); val != "" {
file := filepath.Join(Dirconfig.TrntDir, filepath.Join(parts[3:]...))
if !strings.HasPrefix(file, filepath.Join(Dirconfig.TrntDir, parts[3])) {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
info, err := os.Stat(file)
if err != nil {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
} else if info.IsDir() {
if val == "tar" {
TarDir(file, w, path.Base(r.URL.Path))
return
} else if val == "zip" {
ZipDir(file, w, path.Base(r.URL.Path))
return
}
}
}
http.StripPrefix("/api/torrent/", http.FileServer(http.Dir(Dirconfig.TrntDir))).ServeHTTP(w, r)
}
func StreamFile(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if !(len(parts) > 4) {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
if Engine.LsDb.IsLocked(parts[3]) {
u, ut, _, err := authHelper(w, r)
if err != nil {
Err.Println(err)
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
if ut != 1 {
if ut == -1 {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
if !Engine.TUDb.HasUser(u, parts[3]) {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
}
}
ih, err := MetafromHex(parts[3])
if err != nil {
Warn.Println(err)
return
}
t, ok := Engine.Torc.Torrent(ih)
if !ok {
Warn.Println("Error fetching torrent of infohash ", ih, " from the client")
return
}
if t.Info() == nil {
Warn.Println("Metainfo not yet recieved")
http.Error(w, "Metainfo not yet recieved", http.StatusNotFound)
return
}
// Get File from Given Torrent
reqpath := strings.Join(parts[4:], "/")
var f *torrent.File
for _, file := range t.Files() {
if file.Path() == reqpath {
f = file
break
}
}
if f == nil {
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
filereader := f.NewReader()
defer filereader.Close()
filereader.SetReadahead(48 << 20)
http.ServeContent(w, r, reqpath, time.Time{}, filereader)
}
func TarDir(dirpath string, w http.ResponseWriter, name string) {
w.Header().Set("Content-Type", "application/x-tar")
w.Header().Set("Content-disposition", `attachment; filename="`+name+`.tar"`)
w.WriteHeader(http.StatusOK)
tw := tar.NewWriter(w)
defer tw.Close()
_ = filepath.WalkDir(dirpath, func(p string, de fs.DirEntry, err error) error {
if err != nil {
return err
}
info, ierr := de.Info()
if ierr != nil {
return ierr
}
if !info.Mode().IsRegular() {
return nil
}
rel, err := filepath.Rel(dirpath, p)
if err != nil {
return err
}
f, err := os.Open(p)
if err != nil {
return err
}
defer f.Close()
h, err := tar.FileInfoHeader(info, "")
if err != nil {
return err
}
h.Name = rel
if err := tw.WriteHeader(h); err != nil {
return err
}
n, err := io.Copy(tw, f)
if info.Size() != n {
return fmt.Errorf("mismatch of size with %s", rel)
}
return err
})
}
func ZipDir(dirpath string, w http.ResponseWriter, name string) {
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-disposition", `attachment; filename="`+name+`.zip"`)
w.WriteHeader(http.StatusOK)
zw := zip.NewWriter(w)
defer zw.Close()
_ = filepath.WalkDir(dirpath, func(p string, de fs.DirEntry, err error) error {
if err != nil {
return err
}
info, ierr := de.Info()
if ierr != nil {
return ierr
}
if !info.Mode().IsRegular() {
return nil
}
rel, err := filepath.Rel(dirpath, p)
if err != nil {
return err
}
f, err := os.Open(p)
if err != nil {
return err
}
defer f.Close()
h, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
h.Name = rel
//h.Method = zip.Deflate
zf, err := zw.CreateHeader(h)
if err != nil {
return err
}
n, err := io.Copy(zf, f)
if info.Size() != n {
return fmt.Errorf("mismatch of size with %s", rel)
}
return err
})
}

995
internal/core/socket.go Normal file
View File

@@ -0,0 +1,995 @@
package core
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/shirou/gopsutil/disk"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 31457280 // 30 MB
)
func SocketAPI(w http.ResponseWriter, r *http.Request) {
username, usertype, _, err := authHelper(w, r)
if err != nil {
Warn.Printf("%s (%s)\n", err, r.RemoteAddr)
return
}
var admin bool
if usertype == 1 {
admin = true
} else if usertype == -1 {
Err.Println("Disabled User denied to Connect", username)
http.Error(w, "User Disabled", http.StatusUnauthorized)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
Warn.Println(err)
return
}
conn.SetReadLimit(maxMessageSize)
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error { _ = conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
Uc := NewUserConn(username, conn, admin)
// Ping Handler
go func() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
}()
var perr error
for {
<-ticker.C
Uc.Sendmu.Lock()
_ = Uc.Conn.SetWriteDeadline(time.Now().Add(writeWait))
perr = Uc.Conn.WriteMessage(websocket.PingMessage, nil)
Uc.Sendmu.Unlock()
if perr != nil {
Uc.Close()
return
}
}
}()
var Req []byte
for {
_, Req, err = Uc.Conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
Warn.Printf("WebSocket Unexpected Close: %v", err)
}
Uc.Close()
return
}
var resp ConReq
err = json.Unmarshal(Req, &resp)
if err != nil {
_ = Uc.SendMsg("resp", "error", "incorrect request")
continue
}
go wshandler(Uc, &resp)
}
}
func wshandler(uc *UserConn, req *ConReq) {
if len(req.Command) == 0 {
_ = uc.SendMsg("resp", "error", "no command sent")
return
}
// Admin Operations
if uc.IsAdmin && req.Aop == 1 {
switch req.Command {
// parse these in normal block
case "abandontorrent":
case "removetorrent":
case "addtrackerstotorrent":
case "starttorrent":
case "stoptorrent":
case "startfile":
case "stopfile":
case "deletefilepath":
case "deletetorrent":
//
case "adduser":
if !(len(req.Data1) > 5 || len(req.Data2) > 5) {
_ = uc.SendMsg("resp", "error", "length of username and password must be more than 5")
return
}
var err error
if req.Data3 == "admin" {
err = Engine.UDb.Add(req.Data1, req.Data2, 1) // Admin
} else if req.Data3 == "user" {
err = Engine.UDb.Add(req.Data1, req.Data2, 0) // User
} else if req.Data3 == "disabled" {
err = Engine.UDb.Add(req.Data1, req.Data2, -1) // Disabled
} else {
_ = uc.SendMsg("resp", "error", "incorrect adduser request")
return
}
if err != nil {
_ = uc.SendMsg("resp", "error", "Error Adding User to Database")
return
}
_ = uc.SendMsg("resp", "success", req.Data1+" User Added")
Info.Println("New User ", req.Data1, " added by ", uc.Username)
return
case "removeuser":
if !(len(req.Data1) > 5) {
_ = uc.SendMsg("resp", "error", "length of username must be more than 5")
return
}
if req.Data1 == uc.Username {
_ = uc.SendMsg("resp", "error", "you cannot remove yourself")
return
}
err := Engine.UDb.Delete(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "Error Removing User from Database")
return
}
err = Engine.TUDb.RemoveAll(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "Error Deleting User Records from Database")
return
}
MainHub.RemoveUser(req.Data1)
_ = uc.SendMsg("resp", "success", req.Data1+" User Removed")
Info.Println("User ", req.Data1, " is removed by ", uc.Username)
return
case "getalltorrents":
uc.Streamers.Inc()
uc.Stream.Lock()
defer uc.Streamers.Dec()
defer uc.Stream.Unlock()
files, ferr := os.ReadDir(Dirconfig.TrntDir)
if ferr != nil {
Warn.Println(ferr)
return
}
var lt []metainfo.Hash = make([]metainfo.Hash, 0)
for _, file := range files {
if file.IsDir() {
tm, terr := MetafromHex(file.Name())
if terr != nil {
Warn.Println(terr)
Warn.Println("Non Torrent Directories found in ", Dirconfig.TrntDir, file, file.Name())
}
lt = append(lt, tm)
} else {
Warn.Println("Non Torrent Directories found in ", Dirconfig.TrntDir, file, file.Name())
}
}
var err error
Info.Println("Starting getalltorrents for ", uc.Username)
for uc.Streamers.Get() == 1 {
err = uc.Send(GetTorrents(lt))
if err != nil {
return
}
if uc.Streamers.Get() == 1 {
time.Sleep(time.Second * 5) // Stream Every 5 Seconds
}
}
Info.Println("Stopped getalltorrents for ", uc.Username)
return
case "listalltorrents":
files, ferr := os.ReadDir(Dirconfig.TrntDir)
if ferr != nil {
Warn.Println(ferr)
return
}
var lt []metainfo.Hash = make([]metainfo.Hash, 0)
for _, file := range files {
if file.IsDir() {
tm, terr := MetafromHex(file.Name())
if terr != nil {
Warn.Println(terr)
Warn.Println("Non Torrent Directories found in ", Dirconfig.TrntDir, file, file.Name())
}
lt = append(lt, tm)
} else {
Warn.Println("Non Torrent Directories found in ", Dirconfig.TrntDir, file, file.Name())
}
}
_ = uc.Send(GetTorrents(lt))
return
case "listtorrentsforuser":
if req.Data1 != "" {
ret, _ := json.Marshal(DataMsg{Type: "torrentsforuser", Data: Engine.TUDb.ListTorrents(req.Data1)})
_ = uc.Send(ret)
} else {
_ = uc.SendMsg("resp", "error", "username is empty")
}
return
case "getusers":
retusers := Engine.UDb.GetUsers()
ret, _ := json.Marshal(DataMsg{Type: "users", Data: retusers})
_ = uc.Send(ret)
return
case "updatepw":
defer func() {
if r := recover(); r != nil { // uuid may panic
_ = uc.SendMsg("resp", "error", "uuid error")
Warn.Println("uuid error")
return
}
}()
if req.Data1 == "" {
_ = uc.SendMsg("resp", "error", "request error")
return
}
err := Engine.UDb.UpdatePw(req.Data1, req.Data2)
if err != nil {
_ = uc.SendMsg("resp", "error", err.Error())
}
MainHub.RemoveUser(req.Data1)
err = Engine.UDb.SetToken(req.Data1, uuid.New().String())
if err != nil {
_ = uc.SendMsg("resp", "error", err.Error())
}
_ = uc.SendMsg("resp", "success", "Password of "+req.Data1+" updated")
return
case "revoketoken":
defer func() {
if r := recover(); r != nil { // uuid may panic
_ = uc.SendMsg("resp", "error", "uuid error")
Warn.Println("uuid error")
return
}
}()
if req.Data1 == "" {
_ = uc.SendMsg("resp", "error", "request error")
return
}
MainHub.RemoveUser(req.Data1)
err := Engine.UDb.SetToken(req.Data1, uuid.New().String())
if err != nil {
_ = uc.SendMsg("resp", "error", err.Error())
}
_ = uc.SendMsg("resp", "success", "revoked token of "+req.Data1)
return
case "changeusertype":
Info.Println(uc.Username, "has requested to change usertype of ", req.Data1, " to ", req.Data2)
if req.Data1 == "" {
_ = uc.SendMsg("resp", "error", "username can be empty")
Warn.Println("Usertype change request of ", uc.Username, " failed")
return
}
if req.Data1 == uc.Username {
_ = uc.SendMsg("resp", "error", "you can't change usertype of yourself")
Warn.Println("Usertype change request of ", uc.Username, " failed")
return
}
MainHub.RemoveUser(req.Data1)
err := Engine.UDb.ChangeType(req.Data1, req.Data2)
if err != nil {
_ = uc.SendMsg("resp", "error", err.Error())
}
_ = uc.SendMsg("resp", "success", "changed usertype of "+req.Data1+" to "+req.Data2)
Info.Println(uc.Username, "has changed usertype of ", req.Data1, " to ", req.Data2)
return
case "machinfo":
ret, _ := json.Marshal(DataMsg{Type: "machinfo", Data: MachInfo})
_ = uc.Send(ret)
return
case "machstats":
MachStats.LoadStats(".")
ret, _ := json.Marshal(DataMsg{Type: "machstats", Data: MachStats})
_ = uc.Send(ret)
return
case "torcstatus":
var torcstatus bytes.Buffer
Engine.Torc.WriteStatus(&torcstatus)
ret, _ := json.Marshal(DataMsg{Type: "torcstatus", Data: torcstatus.String()})
_ = uc.Send(ret)
return
case "getconfig":
Configmu.Lock()
ret, _ := json.Marshal(DataMsg{Type: "engconf", Data: Engine.Econfig})
Configmu.Unlock()
_ = uc.Send(ret)
return
case "updateconfig":
if req.Data1 == "" {
_ = uc.SendMsg("resp", "error", "empty config file")
return
}
configfile, berr := base64.StdEncoding.DecodeString(req.Data1)
if berr != nil {
_ = uc.SendMsg("resp", "error", "error decoding config file")
return
}
var newconfig EngConfig
berr = json.Unmarshal(configfile, &newconfig)
if berr != nil {
_ = uc.SendMsg("resp", "error", "error decoding config file")
return
}
Configmu.Lock()
Engine.Econfig = newconfig
_ = Engine.Econfig.WriteConfig()
Info.Println("Torrent Configuration has been Updated by ", uc.Username)
Configmu.Unlock()
_ = uc.SendMsg("resp", "success", "New Torrent Config File has been set successfully")
return
case "listusersfortorrent":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "listusersfortorrent: infohash couldn't be parsed "+req.Data1)
return
}
ret, _ := json.Marshal(DataMsg{Type: "usersfortorrent", Infohash: ih.HexString(), Data: Engine.TUDb.ListUsers(ih)})
_ = uc.Send(ret)
return
case "listuserconns":
_ = uc.Send(MainHub.ListUsers())
return
case "kickuser":
MainHub.RemoveUser(req.Data1)
_ = uc.SendMsg("resp", "success", "kicked "+req.Data1)
return
case "changedataload":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "stopfile: infohash couldn't be parsed "+req.Data1)
return
}
t, ok := Engine.Torc.Torrent(ih)
if !ok {
_ = uc.SendMsgU("nfn", ih.HexString(), "error", "Torrent Not Present!")
Warn.Println("Error fetching torrent of infohash ", ih, " from the client")
return
}
if t.Info() != nil {
if req.Data2 == "upload" {
if req.Data3 == "disallow" {
t.DisallowDataUpload()
_ = uc.SendMsg("resp", "success", "Disallowed Data Upload for torrent "+ih.HexString())
return
} else if req.Data3 == "allow" {
t.AllowDataUpload()
_ = uc.SendMsg("resp", "success", "Allowed Data Upload for torrent "+ih.HexString())
return
} else {
_ = uc.SendMsg("resp", "error", "invalid request")
return
}
} else if req.Data2 == "download" {
if req.Data3 == "disallow" {
t.DisallowDataDownload()
_ = uc.SendMsg("resp", "success", "Disallowed Data Download for torrent "+ih.HexString())
return
} else if req.Data3 == "allow" {
t.AllowDataDownload()
_ = uc.SendMsg("resp", "success", "Allowed Data Download for torrent "+ih.HexString())
return
} else {
_ = uc.SendMsg("resp", "error", "invalid request")
return
}
} else {
_ = uc.SendMsg("resp", "error", "invalid request")
return
}
}
return
case "nooftrackersintrackerdb":
ret, _ := json.Marshal(DataMsg{Type: "nooftrackersintrackerdb", Data: Engine.TrackerDB.Count()})
_ = uc.Send(ret)
return
case "deletetrackersintrackerdb":
if req.Data1 == "all" {
Engine.TrackerDB.DeleteAll()
Info.Println("Deleted All Trackers from TrackerDB")
_ = uc.SendMsg("resp", "success", "Deleted All Trackers from TrackerDB")
return
}
notobedeleted, err := strconv.Atoi(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "invalid request")
return
}
Engine.TrackerDB.DeleteN(notobedeleted)
Info.Println("Deleted ", req.Data1, " no of Trackers from TrackerDB")
_ = uc.SendMsg("resp", "success", "Deleted "+req.Data1+" trackers from TrackerDB")
return
case "trackerdbrefresh":
Info.Println("TrackerDB Refresh command has been issued by", uc.Username)
updatetrackers()
_ = uc.SendMsg("resp", "success", "Fetched Trackers from Tracker URLs and Updated TrackerDB")
return
case "stoponseedratio":
Info.Println("stoponseedratio command has been issued by ", uc.Username)
if req.Data1 == "" {
stoponseedratio(Engine.Econfig.GetGSR())
_ = uc.SendMsg("resp", "success", "Stopped Torrents which have reached seedratio defined in config")
return
}
if sr, err := strconv.ParseFloat(req.Data1, 64); err == nil {
stoponseedratio(sr)
_ = uc.SendMsg("resp", "success", "Stopped Torrents which have reached seedratio = "+req.Data1)
return
}
_ = uc.SendMsg("resp", "error", "Invalid request")
return
default:
_ = uc.SendMsg("resp", "error", "invalid admin command")
return
}
}
switch req.Command {
case "addmagnet":
tspec, terr := torrent.TorrentSpecFromMagnetUri(req.Data1)
if terr != nil {
_ = uc.SendMsg("resp", "error", "incorrect torrent spec")
return
}
if req.Data2 == "true" {
go AddfromSpec(uc.Username, tspec, true, false)
} else {
go AddfromSpec(uc.Username, tspec, false, false)
}
_ = uc.SendMsgU("resp", "success", tspec.InfoHash.HexString(), "torrent spec added")
return
case "addtorrent":
tspec, terr := SpecfromB64String(req.Data1)
if terr != nil {
_ = uc.SendMsg("resp", "error", "incorrect torrent spec")
return
}
if req.Data2 == "true" {
go AddfromSpec(uc.Username, tspec, true, false)
} else {
go AddfromSpec(uc.Username, tspec, false, false)
}
_ = uc.SendMsgU("resp", "success", tspec.InfoHash.HexString(), "torrent spec added")
return
case "addinfohash":
ih, terr := MetafromHex(req.Data1)
if terr != nil {
_ = uc.SendMsg("resp", "error", "incorrect Infohash")
return
}
tspec := &torrent.TorrentSpec{InfoHash: ih}
if req.Data2 == "true" {
go AddfromSpec(uc.Username, tspec, true, false)
} else {
go AddfromSpec(uc.Username, tspec, false, false)
}
_ = uc.SendMsgU("resp", "success", ih.HexString(), "torrent spec added")
return
case "starttorrent":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "starttorrent: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go StartTorrent("", ih, false)
return
}
go StartTorrent(uc.Username, ih, false)
return
case "stoptorrent":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "stoptorrent: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go StopTorrent("", ih)
return
}
go StopTorrent(uc.Username, ih)
return
case "startfile":
if req.Data2 == "" {
_ = uc.SendMsg("resp", "error", "no path provided")
return
}
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "startfile: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go StartFile("", ih, req.Data2)
return
}
go StartFile(uc.Username, ih, req.Data2)
return
case "stopfile":
if req.Data2 == "" {
_ = uc.SendMsg("resp", "error", "no path provided")
return
}
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "stopfile: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go StopFile("", ih, req.Data2)
return
}
go StopFile(uc.Username, ih, req.Data2)
return
case "deletefilepath":
if req.Data2 == "" {
_ = uc.SendMsg("resp", "error", "no path provided")
return
}
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "deletefilepath: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go DeleteFilePath("", ih, req.Data2)
return
}
go DeleteFilePath(uc.Username, ih, req.Data2)
return
case "deletetorrent":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "deletetorrent: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go DeleteTorrent("", ih)
return
}
go DeleteTorrent(uc.Username, ih)
uc.StopStream()
return
case "removetorrent":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "removetorrent: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go RemoveTorrent("", ih)
return
}
go RemoveTorrent(uc.Username, ih)
return
case "abandontorrent":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "abandontorrent: infohash couldn't be parsed "+req.Data1)
return
}
if uc.IsAdmin && req.Aop == 1 {
go AbandonTorrent(req.Data2, ih)
return
}
go AbandonTorrent(uc.Username, ih)
return
case "gettorrents":
uc.Streamers.Inc()
uc.Stream.Lock()
defer uc.Streamers.Dec()
defer uc.Stream.Unlock()
lt := Engine.TUDb.ListTorrents(uc.Username)
var err error
Info.Println("Starting gettorrents for ", uc.Username)
for uc.Streamers.Get() == 1 {
err = uc.Send(GetTorrents(lt))
if err != nil {
return
}
if uc.Streamers.Get() == 1 {
time.Sleep(time.Second * 5) // Stream Every 5 Seconds
}
}
Info.Println("Stopped gettorrents for ", uc.Username)
return
case "listtorrents":
_ = uc.Send(GetTorrents(Engine.TUDb.ListTorrents(uc.Username)))
return
case "gettorrentinfo":
uc.Streamers.Inc()
uc.Stream.Lock()
defer uc.Streamers.Dec()
defer uc.Stream.Unlock()
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentinfo: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
Info.Println("Starting gettorrentinfo for ", uc.Username)
for uc.Streamers.Get() == 1 {
err = uc.Send(GetTorrentInfo(ih))
if err != nil {
return
}
if uc.Streamers.Get() == 1 {
time.Sleep(time.Second * 5) // Stream Every 5 Seconds
}
}
Info.Println("Stopped gettorrentinfo for ", uc.Username)
return
case "listtorrentinfo":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "listtorrentinfo: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
_ = uc.Send(GetTorrentInfo(ih))
return
case "gettorrentstats":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentstats: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentStats(ih))
if err != nil {
return
}
return
case "gettorrentinfostat":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentinfostat: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentInfoStat(ih))
if err != nil {
return
}
return
case "gettorrentfiles":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentfiles: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentFiles(ih))
if err != nil {
return
}
return
case "getfsdirinfo":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "getfsdirinfo: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetFsDirInfo(ih, filepath.Clean(req.Data2)))
if err != nil {
return
}
return
case "getfsfileinfo":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "getfsfileinfo: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetFsFileInfo(ih, filepath.Clean(req.Data2)))
if err != nil {
return
}
return
case "gettorrentfileinfo":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentfileinfo: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentFileInfo(ih, filepath.Clean(req.Data2)))
if err != nil {
return
}
return
case "gettorrentpiecestateruns":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentpiecestateruns: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentPieceStateRuns(ih))
if err != nil {
return
}
return
case "istorrentlocked":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "istorrentlocked: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
ret, _ := json.Marshal(DataMsg{Type: "torrentlockstate", Infohash: ih.HexString(), Data: Engine.LsDb.IsLocked(ih.HexString())})
_ = uc.Send(ret)
return
case "toggletorrentlock":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "toggletorrentlock: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
} else {
_, err = os.Stat(filepath.Join(Dirconfig.TrntDir, ih.HexString()))
if err != nil {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
if Engine.LsDb.IsLocked(ih.HexString()) {
_ = Engine.LsDb.Unlock(ih)
Info.Println("lock of torrent ", ih.HexString(), " is set to false by ", uc.Username)
_ = uc.SendMsgU("resp", "success", ih.HexString(), "lock of torrent "+ih.HexString()+" is set to false")
} else {
_ = Engine.LsDb.Lock(ih)
Info.Println("lock of torrent ", ih.HexString(), " is set to true by ", uc.Username)
_ = uc.SendMsgU("resp", "success", ih.HexString(), "lock of torrent "+ih.HexString()+" is set to true")
}
return
case "addtrackerstotorrent":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "addtrackerstotorrent: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
if req.Data2 == "" {
_ = uc.SendMsg("resp", "error", "Invalid Request")
}
// Add Trackers to txtlines string slice
trackerlist, berr := base64.StdEncoding.DecodeString(req.Data2)
if berr != nil {
_ = uc.SendMsg("resp", "error", "trackerlist error")
return
}
tlr := bytes.NewReader(trackerlist)
scanner := bufio.NewScanner(tlr)
scanner.Split(bufio.ScanLines)
var trackerno int
var al []string
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
al = append(al, line)
trackerno++
}
Info.Println("Read ", trackerno, " Trackers from Trackerlist uploaded by ", uc.Username)
if uc.IsAdmin && req.Aop == 1 {
go AddTrackerstoTorrent("", ih, [][]string{al})
} else {
go AddTrackerstoTorrent(uc.Username, ih, [][]string{al})
}
return
case "updatepw":
err := Engine.UDb.UpdatePw(uc.Username, req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", err.Error())
}
return
case "stopstream":
uc.StopStream()
return
case "diskusage":
var diskusage DiskUsageStat
if stat, err := disk.Usage(Dirconfig.TrntDir); err == nil {
diskusage.UsedPercent = stat.UsedPercent
diskusage.Free = stat.Free
diskusage.Total = stat.Total
diskusage.Used = stat.Used
}
ret, _ := json.Marshal(DataMsg{Type: "diskusage", Data: diskusage})
_ = uc.Send(ret)
return
case "gettorrentknownswarm":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentknownswarm: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentKnownSwarm(ih))
if err != nil {
return
}
return
case "gettorrentnumpieces":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentnumpieces: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentNumpieces(ih))
if err != nil {
return
}
return
case "gettorrentmetainfo":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentmetainfo: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentMetainfo(ih))
if err != nil {
return
}
return
case "gettorrentpeerconns":
ih, err := MetafromHex(req.Data1)
if err != nil {
_ = uc.SendMsg("resp", "error", "gettorrentpeerconns: infohash couldn't be parsed "+req.Data1)
return
}
if !uc.IsAdmin {
if !Engine.TUDb.HasUser(uc.Username, ih.HexString()) {
_ = uc.SendMsg("resp", "error", "torrent doesn't exist")
return
}
}
err = uc.Send(GetTorrentPeerConns(ih))
if err != nil {
return
}
return
case "version":
ret, _ := json.Marshal(DataMsg{Type: "version", Data: Version})
_ = uc.Send(ret)
return
default:
_ = uc.SendMsg("resp", "error", "invalid command")
}
}

85
internal/core/statsapi.go Normal file
View File

@@ -0,0 +1,85 @@
package core
import (
"os"
"runtime"
"time"
"github.com/pbnjay/memory"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/mem"
)
type machInfo struct {
Arch string `json:"arch"`
NumberCPUs int `json:"numbercpu"`
CPUModel string `json:"cpumodel"`
HostName string `json:"hostname"`
Platform string `json:"platform"`
OS string `json:"os"`
TotalMem uint64 `json:"totalmem"`
GoVersion string `json:"goversion"`
StartedAt time.Time `json:"startedat"`
}
type machStats struct {
CPU float64 `json:"cpucycles"`
DiskFree uint64 `json:"diskfree"`
DiskUsedPercent float64 `json:"diskpercent"`
MemUsedPercent float64 `json:"mempercent"`
GoMemory int64 `json:"gomem"`
GoMemorySys int64 `json:"gomemsys"`
GoRoutines int `json:"goroutines"`
}
var MachInfo machInfo = loadMachInfo()
var MachStats machStats
func loadMachInfo() (retmachinfo machInfo) {
hostInfo, err := host.Info()
if err == nil && hostInfo != nil {
retmachinfo.OS = hostInfo.Platform + " " + hostInfo.PlatformVersion
retmachinfo.Platform = hostInfo.OS
}
cpuInfo, err := cpu.Info()
if err == nil && len(cpuInfo) > 0 {
retmachinfo.CPUModel = cpuInfo[0].ModelName
}
retmachinfo.HostName, _ = os.Hostname()
retmachinfo.GoVersion = runtime.Version()
retmachinfo.TotalMem = memory.TotalMemory()
retmachinfo.Arch = runtime.GOARCH
retmachinfo.NumberCPUs = runtime.NumCPU()
retmachinfo.StartedAt = time.Now()
return retmachinfo
}
func (s *machStats) LoadStats(diskDir string) {
//count cpu cycles between last count
if cpu, err := cpu.Percent(0, false); err == nil {
if len(cpu) > 0 {
s.CPU = cpu[0]
}
}
//count disk usage
if stat, err := disk.Usage(diskDir); err == nil {
s.DiskUsedPercent = stat.UsedPercent
s.DiskFree = stat.Free
}
//count memory usage
if stat, err := mem.VirtualMemory(); err == nil {
s.MemUsedPercent = stat.UsedPercent
}
//count total bytes allocated by the go runtime
memStats := runtime.MemStats{}
runtime.ReadMemStats(&memStats)
s.GoMemory = int64(memStats.Alloc)
s.GoMemorySys = int64(memStats.Sys)
//count current number of goroutines
s.GoRoutines = runtime.NumGoroutine()
}

12
internal/core/storage.go Normal file
View File

@@ -0,0 +1,12 @@
//go:build !cgo
// +build !cgo
package core
import (
"github.com/anacrolix/torrent"
)
func sqliteSetup(tc *torrent.ClientConfig) {
Err.Fatalln("Postgresql Connection URL was not provided")
}

View File

@@ -0,0 +1,40 @@
//go:build cgo
// +build cgo
package core
import (
"path/filepath"
"github.com/anacrolix/torrent"
"github.com/varbhat/exatorrent/internal/db"
)
func sqliteSetup(tc *torrent.ClientConfig) {
var err error
Engine.TorDb = &db.Sqlite3Db{}
Engine.TorDb.Open(filepath.Join(Dirconfig.DataDir, "torc.db"))
Engine.TrackerDB = &db.SqliteTdb{}
Engine.TrackerDB.Open(filepath.Join(Dirconfig.DataDir, "trackers.db"))
Engine.FsDb = &db.SqliteFSDb{}
Engine.FsDb.Open(filepath.Join(Dirconfig.DataDir, "filestate.db"))
Engine.LsDb = &db.SqliteLSDb{}
Engine.LsDb.Open(filepath.Join(Dirconfig.DataDir, "lockstate.db"))
Engine.UDb = &db.Sqlite3UserDb{}
Engine.UDb.Open(filepath.Join(Dirconfig.DataDir, "user.db"))
Engine.TUDb = &db.SqliteTorrentUserDb{}
Engine.TUDb.Open(filepath.Join(Dirconfig.DataDir, "torrentuser.db"))
Engine.PcDb, err = db.NewSqlitePieceCompletion(Dirconfig.DataDir)
if err != nil {
Err.Fatalln("Unable to create sqlite3 database for PieceCompletion")
}
}

540
internal/core/vars.go Normal file
View File

@@ -0,0 +1,540 @@
package core
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"sync"
"time"
anaclog "github.com/anacrolix/log"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/iplist"
"github.com/anacrolix/torrent/mse"
"golang.org/x/time/rate"
)
var (
Engine Eng
Info = log.New(os.Stderr, "[INFO] ", log.LstdFlags) // Info Logger
Warn = log.New(os.Stderr, "[WARN] ", log.LstdFlags) // Logger for Warnings
Err = log.New(os.Stderr, "[ERR ] ", log.LstdFlags) // Error Logger
Flagconfig = struct { // Configuration for HTTP Handlers
ListenAddress string
UnixSocket string
TLSKeyPath string
TLSCertPath string
}{}
Dirconfig = struct {
DirPath string
ConfigDir string
CacheDir string
DataDir string
TrntDir string
}{}
Configmu sync.Mutex //TODO
)
type TorConfig struct {
ListenHost *string
ListenPort *int
NoDefaultPortForwarding *bool
UpnpID *string
DisableTrackers *bool
DisablePEX *bool
NoDHT *bool
PeriodicallyAnnounceTorrentsToDht *bool
NoUpload *bool
DisableAggressiveUpload *bool
Seed *bool
UploadLimiterLimit *float64
UploadLimiterBurst *int
DownloadLimiterLimit *float64
DownloadLimiterBurst *int
MaxUnverifiedBytes *int64
PeerID *string
DisableUTP *bool
DisableTCP *bool
HeaderObfuscationPolicy *string
CryptoProvides *uint32
IPBlocklist *bool
DisableIPv6 *bool
DisableIPv4 *bool
DisableIPv4Peers *bool
Debug *bool
Logger *bool
HTTPUserAgent *string
ExtendedHandshakeClientVersion *string
Bep20 *string
NominalDialTimeout *int64
MinDialTimeout *int64
EstablishedConnsPerTorrent *int
HalfOpenConnsPerTorrent *int
TotalHalfOpenConns *int
TorrentPeersHighWater *int
TorrentPeersLowWater *int
HandshakesTimeout *int64
PublicIP4 *string
PublicIP6 *string
DisableAcceptRateLimiting *bool
DropDuplicatePeerIds *bool
DropMutuallyCompletePeers *bool
AcceptPeerConnections *bool
DisableWebtorrent *bool
DisableWebseeds *bool
}
func (t *TorConfig) ToTorrentConfig() (tc *torrent.ClientConfig) {
tc = torrent.NewDefaultClientConfig()
tc.Logger = anaclog.Discard // Discard Logging of Torrent Client by Default
tc.HTTPProxy = http.ProxyFromEnvironment // Use Proxy Variables from Environment
if t.ListenHost != nil {
tc.ListenHost = func(string) string { return *t.ListenHost }
Info.Println("ListenHost of Torrent Client has been set to ", t.ListenHost)
}
if t.ListenPort != nil {
tc.ListenPort = *t.ListenPort
Info.Println("ListenPort of Torrent Client has been set to ", tc.ListenPort)
}
if t.NoDefaultPortForwarding != nil {
tc.NoDefaultPortForwarding = *t.NoDefaultPortForwarding
Info.Println("NoDefaultPortForwarding of Torrent Client has been set to ", tc.NoDefaultPortForwarding)
}
if t.UpnpID != nil {
tc.UpnpID = *t.UpnpID
Info.Println("UpnpID of Torrent Client has been set to ", tc.UpnpID)
}
if t.DisableTrackers != nil {
tc.DisableTrackers = *t.DisableTrackers
Info.Println("DisableTrackers of Torrent Client has been set to ", tc.DisableTrackers)
}
if t.DisablePEX != nil {
tc.DisablePEX = *t.DisablePEX
Info.Println("DisablePEX of Torrent Client has been set to ", tc.DisablePEX)
}
if t.NoDHT != nil {
tc.NoDHT = *t.NoDHT
Info.Println("NoDHT of Torrent Client has been set to ", tc.NoDHT)
}
if t.PeriodicallyAnnounceTorrentsToDht != nil {
tc.PeriodicallyAnnounceTorrentsToDht = *t.PeriodicallyAnnounceTorrentsToDht
Info.Println("PeriodicallyAnnounceTorrentsToDht has been set to", tc.PeriodicallyAnnounceTorrentsToDht)
}
if t.NoUpload != nil {
tc.NoUpload = *t.NoUpload
Info.Println("NoUpload of Torrent Client has been set to ", tc.NoUpload)
}
if t.DisableAggressiveUpload != nil {
tc.DisableAggressiveUpload = *t.DisableAggressiveUpload
Info.Println("DisableAggressiveUpload of Torrent Client has been set to ", tc.DisableAggressiveUpload)
}
if t.Seed != nil {
tc.Seed = *t.Seed
Info.Println("Seed of Torrent Client has been set to ", tc.Seed)
}
if t.UploadLimiterLimit != nil && t.UploadLimiterBurst != nil {
tc.UploadRateLimiter = rate.NewLimiter(rate.Limit(*t.UploadLimiterLimit), *t.UploadLimiterBurst)
Info.Println("Upload Rate Limiter is now Active with ", t.UploadLimiterLimit, " as limit and ", t.UploadLimiterBurst, " as Burst")
}
if t.DownloadLimiterLimit != nil && t.DownloadLimiterBurst != nil {
tc.DownloadRateLimiter = rate.NewLimiter(rate.Limit(*t.DownloadLimiterLimit), *t.DownloadLimiterBurst)
Info.Println("Download Rate Limiter is now Active with ", t.DownloadLimiterLimit, " as limit and ", t.DownloadLimiterBurst, " as Burst")
}
if t.MaxUnverifiedBytes != nil {
tc.MaxUnverifiedBytes = *t.MaxUnverifiedBytes
Info.Println("MaxUnverifiedBytes of Torrent Client has been set to ", tc.MaxUnverifiedBytes)
}
if t.PeerID != nil {
tc.PeerID = *t.PeerID
Info.Println("PeerID of Torrent Client has been set to ", tc.PeerID)
}
if t.DisableUTP != nil {
tc.DisableUTP = *t.DisableUTP
Info.Println("DisableUTP of Torrent Client has been set to ", tc.DisableUTP)
}
if t.DisableTCP != nil {
tc.DisableTCP = *t.DisableTCP
Info.Println("DisableTCP of Torrent Client has been set to ", tc.DisableTCP)
}
if t.HeaderObfuscationPolicy != nil {
if *t.HeaderObfuscationPolicy == "notpreferred" {
tc.HeaderObfuscationPolicy = torrent.HeaderObfuscationPolicy{
RequirePreferred: false,
Preferred: false,
}
} else if *t.HeaderObfuscationPolicy == "preferred" {
tc.HeaderObfuscationPolicy = torrent.HeaderObfuscationPolicy{
RequirePreferred: false,
Preferred: true,
}
} else if *t.HeaderObfuscationPolicy == "requirepreferred" {
tc.HeaderObfuscationPolicy = torrent.HeaderObfuscationPolicy{
RequirePreferred: true,
Preferred: true,
}
}
Info.Println("HeaderObfuscationPolicy of Torrent Client has been set")
}
if t.CryptoProvides != nil {
if *t.CryptoProvides == 1 {
tc.CryptoProvides = mse.CryptoMethodPlaintext
} else if *t.CryptoProvides == 2 {
tc.CryptoProvides = mse.CryptoMethodRC4
} else if *t.CryptoProvides == 3 {
tc.CryptoProvides = mse.AllSupportedCrypto
}
Info.Println("CryptoProvides of Torrent Client has been set")
}
if t.IPBlocklist != nil {
if *t.IPBlocklist {
Info.Println("Trying to Read Torrent Client Blocklist from", filepath.Join(Dirconfig.ConfigDir, "blocklist"))
blockfile, err := os.Open(filepath.Join(Dirconfig.ConfigDir, "blocklist"))
if err != nil {
Err.Println("Please put your Blocklist at", filepath.Join(Dirconfig.ConfigDir, "blocklist"))
Err.Fatalln("Error Opening Blocklist: ", err)
}
defer blockfile.Close()
// Read blocklist
tc.IPBlocklist, err = iplist.NewFromReader(blockfile)
if err != nil {
Err.Fatalln("Invalid Blocklist: ", err)
}
Info.Println("Loading blocklist of ", tc.IPBlocklist.NumRanges(), " Ranges")
}
}
if t.DisableIPv6 != nil {
tc.DisableIPv6 = *t.DisableIPv6
Info.Println("DisableIPv6 of Torrent Client has been set to ", tc.DisableIPv6)
}
if t.DisableIPv4 != nil {
tc.DisableIPv4 = *t.DisableIPv4
Info.Println("DisableIPv4 of Torrent Client has been set to ", tc.DisableIPv4)
}
if t.DisableIPv4Peers != nil {
tc.DisableIPv4Peers = *t.DisableIPv4Peers
Info.Println("DisableIPv4Peers of Torrent Client has been set to ", tc.DisableIPv4Peers)
}
if t.Debug != nil {
tc.Debug = *t.Debug
Info.Println("Debug has been set to ", tc.Debug)
}
if t.Logger != nil {
if *t.Logger {
tc.Logger = anaclog.Logger{
LoggerImpl: anaclog.StreamLogger{
W: os.Stderr,
Fmt: func(msg anaclog.Msg) []byte {
var pc [1]uintptr
msg.Callers(1, pc[:])
return []byte(fmt.Sprintf("[TORC] %s %s\n", time.Now().Format("2006/01/02 03:04:05"), msg.Text()))
},
},
}
}
}
if t.HTTPUserAgent != nil {
tc.HTTPUserAgent = *t.HTTPUserAgent
Info.Println("HTTP User Agent of Torrent Client has been set to ", tc.HTTPUserAgent)
}
if t.ExtendedHandshakeClientVersion != nil {
tc.ExtendedHandshakeClientVersion = *t.ExtendedHandshakeClientVersion
Info.Println("ExtendedHandshakeClientVersion of Torrent Client has been set to ", tc.ExtendedHandshakeClientVersion)
}
if t.NominalDialTimeout != nil {
tc.NominalDialTimeout = time.Duration(*t.NominalDialTimeout)
Info.Println("NominalDialTimeout of Torrent Client has been set to ", tc.NominalDialTimeout)
}
if t.MinDialTimeout != nil {
tc.MinDialTimeout = time.Duration(*t.MinDialTimeout)
Info.Println("MinDialTimeout of Torrent Client has been set to ", tc.MinDialTimeout)
}
if t.EstablishedConnsPerTorrent != nil {
tc.EstablishedConnsPerTorrent = *t.EstablishedConnsPerTorrent
Info.Println("EstablishedConnsPerTorrent of Torrent Client has been set to ", tc.EstablishedConnsPerTorrent)
}
if t.HalfOpenConnsPerTorrent != nil {
tc.HalfOpenConnsPerTorrent = *t.HalfOpenConnsPerTorrent
Info.Println("HalfOpenConnsPerTorrent of Torrent Client has been set to ", tc.HalfOpenConnsPerTorrent)
}
if t.TotalHalfOpenConns != nil {
tc.TotalHalfOpenConns = *t.TotalHalfOpenConns
Info.Println("TotalHalfOpenConns of Torrent Client has been set to ", tc.TotalHalfOpenConns)
}
if t.TorrentPeersHighWater != nil {
tc.TorrentPeersHighWater = *t.TorrentPeersHighWater
Info.Println("TorrentPeersHighWater of Torrent Client has been set to ", tc.TorrentPeersHighWater)
}
if t.TorrentPeersLowWater != nil {
tc.TorrentPeersLowWater = *t.TorrentPeersLowWater
Info.Println("TorrentPeersLowWater of Torrent Client has been set to ", tc.TorrentPeersLowWater)
}
if t.HandshakesTimeout != nil {
tc.HandshakesTimeout = time.Duration(*t.HandshakesTimeout)
Info.Println("HandshakesTimeout of Torrent Client has been set to ", tc.HandshakesTimeout)
}
if t.PublicIP4 != nil {
tc.PublicIp4 = net.ParseIP(*t.PublicIP4)
Info.Println("PublicIpv4 of Torrent Client has been set to ", *t.PublicIP4)
}
if t.PublicIP6 != nil {
tc.PublicIp6 = net.ParseIP(*t.PublicIP6)
Info.Println("PublicIpv6 of Torrent Client has been set to ", *t.PublicIP6)
}
if t.DisableAcceptRateLimiting != nil {
tc.DisableAcceptRateLimiting = *t.DisableAcceptRateLimiting
Info.Println("DisableAcceptRateLimiting of Torrent Client has been set to ", tc.DisableAcceptRateLimiting)
}
if t.DropDuplicatePeerIds != nil {
tc.DropDuplicatePeerIds = *t.DropDuplicatePeerIds
Info.Println("DropDuplicatePeerIds of Torrent Client has been set to ", tc.DropDuplicatePeerIds)
}
if t.DropMutuallyCompletePeers != nil {
tc.DropMutuallyCompletePeers = *t.DropMutuallyCompletePeers
Info.Println("DropMutuallyCompletePeers of Torrent Client has been set to ", tc.DropMutuallyCompletePeers)
}
if t.AcceptPeerConnections != nil {
tc.AcceptPeerConnections = *t.AcceptPeerConnections
Info.Println("AcceptPeerConnections of Torrent Client has been set to ", tc.AcceptPeerConnections)
}
if t.DisableWebtorrent != nil {
tc.DisableWebtorrent = *t.DisableWebtorrent
Info.Println("DisableWebtorrent of Torrent Client has been set to ", tc.DisableWebtorrent)
}
if t.DisableWebseeds != nil {
tc.DisableWebseeds = *t.DisableWebseeds
Info.Println("DisableWebseeds of Torrent Client has been set to ", tc.DisableWebseeds)
}
return
}
// EngConfig is Engine Configuration Structure which doesn't require restart of Torrent Client
type EngConfig struct {
DisableLocalCache bool `json:"disableonlinecache"` // Disables Local Torrent Storage
OnlineCacheURL string `json:"onlinecacheurl"` // Default is https://itorrents.org/torrent/%s.torrent , Setting Empty Disables OnlineCache
TrackerRefresh int64 `json:"trackerrefreshinterval"` // In Minutes
TrackerListURLs []string `json:"trackerlisturls"` // Default List is []string{"https://ngosang.github.io/trackerslist/trackers_best.txt"}
DisAllowTrackersUser bool `json:"disallowtrackersforuser"` // If set to true , Remove all Trackers that is Added by User to magnet/torrent file. Also disallow adding trackers to torrent
DisAllowTrackersCache bool `json:"disallowtrackersforcache"` // If set to true , Remove all Trackers from Torrent File fetched from Online/Local Cache
GlobalSeedRatio float64 `json:"globalseedratio"` // Stops Torrent on Reaching Provided SeedRatio
SRRefresh int64 `json:"seedratiocheckinterval"` // In Minutes
DontRemoveCacheInfo bool `json:"dontremovecacheinfo"` // When Torrent is Deleted from Storage, it's cache file(.torrent) from Local Cache is not Deleted
LockbyDefault bool `json:"lockbydefault"` // If set to true , locks every torrent on Add
}
func (ec *EngConfig) GetDTU() (ret bool) {
Configmu.Lock()
ret = ec.DisAllowTrackersUser
Configmu.Unlock()
return
}
func (ec *EngConfig) GetDTC() (ret bool) {
Configmu.Lock()
ret = ec.DisAllowTrackersCache
Configmu.Unlock()
return
}
func (ec *EngConfig) GetDLC() (ret bool) {
Configmu.Lock()
ret = ec.DisableLocalCache
Configmu.Unlock()
return
}
func (ec *EngConfig) GetOCU() (ret string) {
Configmu.Lock()
ret = ec.OnlineCacheURL
Configmu.Unlock()
return
}
func (ec *EngConfig) GetTR() (ret int64) {
Configmu.Lock()
ret = ec.TrackerRefresh
if ret < 0 {
ret = 0
}
Configmu.Unlock()
return
}
func (ec *EngConfig) GetTLU() (ret []string) {
Configmu.Lock()
ret = ec.TrackerListURLs
Configmu.Unlock()
return
}
func (ec *EngConfig) GetGSR() (ret float64) {
Configmu.Lock()
ret = ec.GlobalSeedRatio
Configmu.Unlock()
return
}
func (ec *EngConfig) GetSRR() (ret int64) {
Configmu.Lock()
ret = ec.SRRefresh
if ret < 0 {
ret = 0
}
Configmu.Unlock()
return
}
func (ec *EngConfig) GetLBD() (ret bool) {
Configmu.Lock()
ret = ec.LockbyDefault
Configmu.Unlock()
return
}
func (ec *EngConfig) WriteConfig() (err error) {
_ = os.Remove(filepath.Join(Dirconfig.ConfigDir, "engconfig.json"))
f, err := os.OpenFile(filepath.Join(Dirconfig.ConfigDir, "engconfig.json"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return
}
jfile, _ := json.MarshalIndent(ec, "", "\t")
_, _ = f.Write(jfile)
if err = f.Close(); err != nil {
return
}
return
}
func (ec *EngConfig) DRCI() (ret bool) {
Configmu.Lock()
ret = ec.DontRemoveCacheInfo
Configmu.Unlock()
return
}
type ConReq struct {
Command string `json:"command"`
Data1 string `json:"data1"`
Data2 string `json:"data2"`
Data3 string `json:"data3"`
Aop int `json:"aop"`
}
type Resp struct {
Type string `json:"type"`
State string `json:"state"`
Infohash string `json:"infohash,omitempty"`
Msg string `json:"message"`
}
type DataMsg struct {
Type string `json:"type"`
Data interface{} `json:"data,omitempty"`
Infohash string `json:"infohash,omitempty"`
}
type ConnectionMsg struct {
Type string `json:"usertype"`
Session string `json:"session"`
}
type DiskUsageStat struct {
Total uint64 `json:"total"`
Free uint64 `json:"free"`
Used uint64 `json:"used"`
UsedPercent float64 `json:"usedPercent"`
}
type UserConnMsg struct {
Username string `json:"username"`
IsAdmin bool `json:"isadmin"`
Time time.Time `json:"contime"`
}
type Mutbool struct {
sync.Mutex
val bool
}
func (M *Mutbool) Set(v bool) {
M.Lock()
M.val = v
M.Unlock()
}
func (M *Mutbool) Get() (ret bool) {
M.Lock()
ret = M.val
M.Unlock()
return
}
type MutInt struct {
sync.Mutex
val int
}
func (M *MutInt) Set(v int) {
M.Lock()
M.val = v
M.Unlock()
}
func (M *MutInt) Get() (ret int) {
M.Lock()
ret = M.val
M.Unlock()
return
}
func (M *MutInt) Inc() {
M.Lock()
M.val++
M.Unlock()
}
func (M *MutInt) Dec() {
M.Lock()
M.val--
M.Unlock()
}

3
internal/core/version.go Normal file
View File

@@ -0,0 +1,3 @@
package core
const Version string = "v0.0.1"

116
internal/db/db.go Normal file
View File

@@ -0,0 +1,116 @@
package db
import (
"fmt"
"log"
"os"
"time"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
)
var DbL = log.New(os.Stderr, "[DB] ", log.LstdFlags) // Database Logger
// MetafromHex returns metainfo.Hash from given infohash string
func MetafromHex(infohash string) (h metainfo.Hash, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error parsing string to InfoHash")
}
}()
h = metainfo.NewHashFromHex(infohash)
return h, nil
}
// Interfaces
type TorrentDb interface {
Open(string)
Close()
Exists(metainfo.Hash) bool
Add(metainfo.Hash) error
Delete(metainfo.Hash) error
Start(metainfo.Hash) error
SetStarted(metainfo.Hash, bool) error
HasStarted(string) bool
GetTorrent(metainfo.Hash) (*Torrent, error)
GetTorrents() ([]*Torrent, error)
}
type TrackerDb interface {
Open(string)
Close()
Add(string)
Delete(string)
DeleteN(int)
DeleteAll()
Count() int64
Get() []string
}
type FileStateDb interface {
Open(string)
Close()
Add(string, metainfo.Hash) error
Get(metainfo.Hash) []string
Deletefile(string, metainfo.Hash) error
Delete(metainfo.Hash) error
}
type LockStateDb interface {
Open(string)
Close()
Lock(metainfo.Hash) error
Unlock(metainfo.Hash) error
IsLocked(string) bool
}
type UserDb interface {
Open(string)
Close()
Add(string, string, int) error // Username , Password , Usertype
ChangeType(string, string) error
Delete(string) error
UpdatePw(string, string) error
GetUsers() []*User
Validate(string, string) (int, bool)
ValidateToken(string) (string, int, error)
SetToken(string, string) error
}
type TorrentUserDb interface {
Open(string)
Close()
Add(string, metainfo.Hash) error
Remove(string, metainfo.Hash) error
RemoveAll(string) error
RemoveAllMi(metainfo.Hash) error
HasUser(string, string) bool
ListTorrents(string) []metainfo.Hash
ListUsers(metainfo.Hash) []string
}
type PcDb interface {
storage.PieceCompletion
Delete(metainfo.Hash)
}
// Struct
type Torrent struct {
Infohash metainfo.Hash
Started bool
AddedAt time.Time
StartedAt time.Time
}
type User struct {
Username string
Password string `json:"-"`
Token string
UserType int // 0 for User,1 for Admin,-1 for Disabled
CreatedAt time.Time
}

View File

@@ -0,0 +1,65 @@
package db
import (
"context"
"github.com/anacrolix/torrent/metainfo"
"github.com/jackc/pgx/v4/pgxpool"
)
type PsqlFsDb struct {
Db *pgxpool.Pool
}
func (db *PsqlFsDb) Open(dburl string) {
var err error
db.Db, err = pgxpool.Connect(context.Background(), dburl)
if err != nil {
DbL.Fatalln(err)
}
_, err = db.Db.Exec(context.Background(), `create table if not exists filestatedb (filepath text,infohash text, unique(filepath, infohash));`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *PsqlFsDb) Close() {
db.Db.Close()
}
func (db *PsqlFsDb) Add(fp string, ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `insert into filestatedb (filepath,infohash) values ($1,$2) on conflict (filepath,infohash) do nothing;`, fp, ih.HexString())
return
}
func (db *PsqlFsDb) Get(ih metainfo.Hash) (ret []string) {
ret = make([]string, 0)
rows, err := db.Db.Query(context.Background(), `select filepath from filestatedb WHERE infohash=$1;`, ih.HexString())
if err != nil {
DbL.Println(err)
return
}
for rows.Next() {
var fpstring string
err = rows.Scan(&fpstring)
if err != nil {
DbL.Println(err)
return
}
ret = append(ret, fpstring)
}
return
}
func (db *PsqlFsDb) Deletefile(fp string, ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from filestatedb where filepath=$1 and infohash=$2;`, fp, ih.HexString())
return err
}
func (db *PsqlFsDb) Delete(ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from filestatedb where infohash=$1;`, ih.HexString())
return
}

View File

@@ -0,0 +1,46 @@
package db
import (
"context"
"github.com/anacrolix/torrent/metainfo"
"github.com/jackc/pgx/v4/pgxpool"
)
type PsqlLsDb struct {
Db *pgxpool.Pool
}
func (db *PsqlLsDb) Open(dburl string) {
var err error
db.Db, err = pgxpool.Connect(context.Background(), dburl)
if err != nil {
DbL.Fatalln(err)
}
_, err = db.Db.Exec(context.Background(), `create table if not exists lockstatedb (infohash text primary key);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *PsqlLsDb) Close() {
db.Db.Close()
}
func (db *PsqlLsDb) Lock(m metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `insert into lockstatedb (infohash) values ($1) on conflict (infohash) do nothing;`, m.HexString())
return
}
func (db *PsqlLsDb) Unlock(m metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from lockstatedb where infohash=$1;`, m.HexString())
return
}
func (db *PsqlLsDb) IsLocked(m string) (b bool) {
if db.Db.QueryRow(context.Background(), `select true from lockstatedb where infohash=$1;`, m).Scan(&b) != nil {
return false
}
return
}

52
internal/db/psqlpc.go Normal file
View File

@@ -0,0 +1,52 @@
package db
import (
"context"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
"github.com/jackc/pgx/v4/pgxpool"
)
type psqlPieceCompletion struct {
db *pgxpool.Pool
}
func NewPsqlPieceCompletion(databaseurl string) (ret *psqlPieceCompletion, err error) {
db, err := pgxpool.Connect(context.Background(), databaseurl)
if err != nil {
return
}
_, err = db.Exec(context.Background(), `create table if not exists pcomp (infohash text,pindex integer,complete boolean, unique(infohash, pindex));`)
if err != nil {
db.Close()
return
}
ret = &psqlPieceCompletion{db: db}
return
}
func (me *psqlPieceCompletion) Get(pk metainfo.PieceKey) (c storage.Completion, err error) {
if me.db.QueryRow(context.Background(), `select complete from pcomp where infohash=$1 and pindex=$2;`, pk.InfoHash.HexString(), pk.Index).Scan(&c.Complete) == nil {
c.Ok = true
}
return
}
func (me *psqlPieceCompletion) Set(pk metainfo.PieceKey, b bool) (err error) {
_, err = me.db.Exec(context.Background(), `insert into pcomp (infohash,pindex,complete) values ($1,$2,$3) on conflict (infohash,pindex) do update set complete=$3;`, pk.InfoHash.HexString(), pk.Index, b)
return
}
func (me *psqlPieceCompletion) Delete(m metainfo.Hash) {
if me != nil {
_, _ = me.db.Exec(context.Background(), `delete from pcomp where infohash=$1;`, m.HexString())
}
}
func (me *psqlPieceCompletion) Close() error {
me.db.Close()
return nil
}

View File

@@ -0,0 +1,109 @@
package db
import (
"context"
"time"
"github.com/anacrolix/torrent/metainfo"
"github.com/jackc/pgx/v4/pgxpool"
)
type PsqlTrntDb struct {
Db *pgxpool.Pool
}
func (db *PsqlTrntDb) Open(dburl string) {
var err error
db.Db, err = pgxpool.Connect(context.Background(), dburl)
if err != nil {
DbL.Fatalln(err)
}
_, err = db.Db.Exec(context.Background(), `create table if not exists torrent (infohash text primary key,started boolean,addedat timestamptz,startedat timestamptz);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *PsqlTrntDb) Close() {
db.Db.Close()
}
func (db *PsqlTrntDb) Exists(ih metainfo.Hash) (ret bool) {
var err error
row := db.Db.QueryRow(context.Background(), `select true from torrent where infohash=$1;`, ih.HexString())
err = row.Scan(&ret)
if err != nil {
return false
}
return
}
func (db *PsqlTrntDb) HasStarted(ih string) (ret bool) {
row := db.Db.QueryRow(context.Background(), `select started from torrent where infohash=$1;`, ih)
err := row.Scan(&ret)
if err != nil {
return false
}
return
}
func (db *PsqlTrntDb) Add(ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `insert into torrent (infohash,started,addedat,startedat) values ($1,$2,$3,$4) on conflict (infohash) do update set startedat=$4;`, ih.HexString(), false, time.Now(), time.Now())
return
}
func (db *PsqlTrntDb) Delete(ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from torrent where infohash=$1;`, ih.HexString())
return
}
func (db *PsqlTrntDb) Start(ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `update torrent set started=$1,startedat=$2 where infohash=$3;`, true, time.Now(), ih.HexString())
return
}
func (db *PsqlTrntDb) SetStarted(ih metainfo.Hash, inp bool) (err error) {
_, err = db.Db.Exec(context.Background(), `update torrent set started=$1 where infohash=$2;`, inp, ih.HexString())
return
}
func (db *PsqlTrntDb) GetTorrent(ih metainfo.Hash) (*Torrent, error) {
var trnt Torrent
var infoh string
row := db.Db.QueryRow(context.Background(), `select * from torrent where infohash=$1;`, ih.HexString())
err := row.Scan(&infoh, &trnt.Started, &trnt.AddedAt, &trnt.StartedAt)
if err != nil {
return nil, err
}
trnt.Infohash = ih
return &trnt, nil
}
func (db *PsqlTrntDb) GetTorrents() (Trnts []*Torrent, err error) {
Trnts = make([]*Torrent, 0)
rows, err := db.Db.Query(context.Background(), `select * from torrent;`)
if err != nil {
DbL.Println(err)
return
}
for rows.Next() {
var trnt Torrent
var ih string
err = rows.Scan(&ih, &trnt.Started, &trnt.AddedAt, &trnt.StartedAt)
if err != nil {
DbL.Println(err)
return Trnts, err
}
trnt.Infohash, err = MetafromHex(ih)
if err != nil {
DbL.Println(err)
return Trnts, err
}
Trnts = append(Trnts, &trnt)
}
return Trnts, rows.Err()
}

View File

@@ -0,0 +1,109 @@
package db
import (
"context"
"github.com/anacrolix/torrent/metainfo"
"github.com/jackc/pgx/v4/pgxpool"
)
type PsqlTrntUserDb struct {
Db *pgxpool.Pool
}
func (db *PsqlTrntUserDb) Open(dburl string) {
var err error
db.Db, err = pgxpool.Connect(context.Background(), dburl)
if err != nil {
DbL.Fatalln(err)
}
_, err = db.Db.Exec(context.Background(), `create table if not exists torrentuserdb (username text,infohash text, unique(username,infohash));`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *PsqlTrntUserDb) Close() {
db.Db.Close()
}
func (db *PsqlTrntUserDb) Add(username string, ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `insert into torrentuserdb (username,infohash) values ($1,$2) on conflict (username,infohash) do nothing;`, username, ih.HexString())
return
}
func (db *PsqlTrntUserDb) Remove(username string, ih metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from torrentuserdb where username=$1 and infohash=$2;`, username, ih.HexString())
return
}
func (db *PsqlTrntUserDb) RemoveAll(username string) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from torrentuserdb where username=$1;`, username)
return
}
func (db *PsqlTrntUserDb) RemoveAllMi(mi metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from torrentuserdb where infohash=$1;`, mi.HexString())
return
}
func (db *PsqlTrntUserDb) HasUser(username string, ih string) (ret bool) {
var err error
row := db.Db.QueryRow(context.Background(), `select true from torrentuserdb where username=$1 and infohash=$2;`, username, ih)
err = row.Scan(&ret)
if err != nil {
return false
}
return
}
func (db *PsqlTrntUserDb) ListTorrents(username string) (ret []metainfo.Hash) {
rows, err := db.Db.Query(context.Background(), `select infohash from torrentuserdb where username=$1;`, username)
if err != nil {
DbL.Println(err)
return
}
for rows.Next() {
var ih string
err = rows.Scan(&ih)
if err != nil {
DbL.Println(err)
return
}
infoh, err := MetafromHex(ih)
if err != nil {
DbL.Println(err)
return
}
ret = append(ret, infoh)
}
return
}
func (db *PsqlTrntUserDb) ListUsers(mi metainfo.Hash) (ret []string) {
ret = make([]string, 0)
rows, err := db.Db.Query(context.Background(), `select username from torrentuserdb where infohash=$1;`, mi.HexString())
if err != nil {
DbL.Println(err)
return
}
for rows.Next() {
var username string
err = rows.Scan(&username)
if err != nil {
DbL.Println(err)
return
}
ret = append(ret, username)
}
return
}

View File

@@ -0,0 +1,68 @@
package db
import (
"context"
"github.com/jackc/pgx/v4/pgxpool"
)
type PsqlTDb struct {
Db *pgxpool.Pool
}
func (db *PsqlTDb) Open(dburl string) {
var err error
db.Db, err = pgxpool.Connect(context.Background(), dburl)
if err != nil {
DbL.Fatalln(err)
}
_, err = db.Db.Exec(context.Background(), `create table if not exists trackerdb (url text primary key);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *PsqlTDb) Close() {
db.Db.Close()
}
func (db *PsqlTDb) Add(url string) {
_, _ = db.Db.Exec(context.Background(), `insert into trackerdb (url) values ($1) on conflict (url) do nothing;`, url)
}
func (db *PsqlTDb) Delete(url string) {
_, _ = db.Db.Exec(context.Background(), `delete from trackerdb where url=$1;`, url)
}
func (db *PsqlTDb) DeleteN(count int) {
_, _ = db.Db.Exec(context.Background(), `delete from trackerdb where url in (select url from trackerdb limit $1);`, count)
}
func (db *PsqlTDb) DeleteAll() {
_, _ = db.Db.Exec(context.Background(), `delete from trackerdb;`)
}
func (db *PsqlTDb) Count() (ret int64) {
row := db.Db.QueryRow(context.Background(), `select count(*) from trackerdb;`)
_ = row.Scan(&ret)
return
}
func (db *PsqlTDb) Get() (ret []string) {
rows, err := db.Db.Query(context.Background(), `select url from trackerdb;`)
if err != nil {
DbL.Println(err)
}
for rows.Next() {
var tr string
err := rows.Scan(&tr)
if err != nil {
DbL.Println(err)
return
}
ret = append(ret, tr)
}
return
}

139
internal/db/psqluserdb.go Normal file
View File

@@ -0,0 +1,139 @@
package db
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v4/pgxpool"
"golang.org/x/crypto/bcrypt"
)
type PsqlUserDb struct {
Db *pgxpool.Pool
}
func (db *PsqlUserDb) Open(dburl string) {
var err error
db.Db, err = pgxpool.Connect(context.Background(), dburl)
if err != nil {
DbL.Fatalln(err)
}
_, err = db.Db.Exec(context.Background(), `create table if not exists userdb (username text unique,password text,token text unique,usertype integer,createdat timestamptz);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *PsqlUserDb) Close() {
db.Db.Close()
}
func (db *PsqlUserDb) Add(Username string, Password string, UserType int) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("uuid error") // uuid may panic
}
}()
if len(Username) < 5 || len(Password) < 5 {
return fmt.Errorf("username or password size too small")
}
bytes, err := bcrypt.GenerateFromPassword([]byte(Password), 10)
if err != nil {
return
}
_, err = db.Db.Exec(context.Background(), `insert into userdb (username,password,token,usertype,createdat) values ($1,$2,$3,$4,$5);`, Username, string(bytes), uuid.New().String(), UserType, time.Now())
return
}
func (db *PsqlUserDb) Delete(username string) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from userdb where username=$1;`, username)
return
}
func (db *PsqlUserDb) GetID(username string) (ret int64) {
ret = -1
row := db.Db.QueryRow(context.Background(), `select userid from userdb where username=$1;`, username)
_ = row.Scan(&ret)
return
}
func (db *PsqlUserDb) UpdatePw(Username string, Password string) (err error) {
if len(Password) < 5 {
return fmt.Errorf("username or password size too small")
}
bytes, err := bcrypt.GenerateFromPassword([]byte(Password), 10)
if err != nil {
return
}
_, err = db.Db.Exec(context.Background(), `update userdb set password=$1 where username=$2;`, string(bytes), Username)
return
}
func (db *PsqlUserDb) ChangeType(Username string, Type string) (err error) {
if len(Username) == 0 {
return fmt.Errorf("empty username")
}
var ut int
if Type == "admin" {
ut = 1
} else if Type == "user" {
ut = 0
} else if Type == "disabled" {
ut = -1
} else {
return fmt.Errorf("unknown type")
}
_, err = db.Db.Exec(context.Background(), `update userdb set usertype=$1 where username=$2;`, ut, Username)
return
}
func (db *PsqlUserDb) GetUsers() (ret []*User) {
ret = make([]*User, 0)
rows, err := db.Db.Query(context.Background(), `select * from userdb;`)
if err != nil {
DbL.Println(err)
}
for rows.Next() {
var user User
err := rows.Scan(&user.Username, &user.Password, &user.Token, &user.UserType, &user.CreatedAt)
if err != nil {
DbL.Println(err)
return
}
ret = append(ret, &user)
}
return
}
func (db *PsqlUserDb) Validate(Username string, Password string) (ut int, b bool) {
var pw string
row := db.Db.QueryRow(context.Background(), `select usertype,password from userdb where username=$1;`, Username)
err := row.Scan(&ut, &pw)
if err != nil {
return ut, false
}
err = bcrypt.CompareHashAndPassword([]byte(pw), []byte(Password))
return ut, err == nil
}
func (db *PsqlUserDb) SetToken(Username string, Token string) (err error) {
_, err = db.Db.Exec(context.Background(), `update userdb set token=$1 where username=$2;`, Token, Username)
return
}
func (db *PsqlUserDb) ValidateToken(Token string) (user string, ut int, err error) {
if Token == "" {
return "", -1, fmt.Errorf("token is empty")
}
row := db.Db.QueryRow(context.Background(), `select username,usertype from userdb where token=$1;`, Token)
err = row.Scan(&user, &ut)
if err != nil {
return "", -1, err
}
return
}

View File

@@ -0,0 +1,73 @@
package db
import (
"sync"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
"github.com/anacrolix/torrent/metainfo"
)
type SqliteFSDb struct {
Db *sqlite.Conn
mu sync.Mutex
}
func (db *SqliteFSDb) Open(fp string) {
var err error
db.Db, err = sqlite.OpenConn(fp, 0)
if err != nil {
DbL.Fatalln(err)
}
err = sqlitex.ExecScript(db.Db, `create table if not exists filestatedb (filepath text,infohash text, unique(filepath, infohash));`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteFSDb) Close() {
db.mu.Lock()
defer db.mu.Unlock()
err := db.Db.Close()
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteFSDb) Add(fp string, ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `insert into filestatedb (filepath,infohash) values (?,?) on conflict (filepath,infohash) do nothing;`, nil, fp, ih.HexString())
return
}
func (db *SqliteFSDb) Get(ih metainfo.Hash) (ret []string) {
ret = make([]string, 0)
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select filepath from filestatedb where infohash=?;`,
func(stmt *sqlite.Stmt) error {
ret = append(ret, stmt.GetText("filepath"))
return nil
}, ih.HexString())
return
}
func (db *SqliteFSDb) Delete(ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from filestatedb where infohash=?;`, nil, ih.HexString())
return
}
func (db *SqliteFSDb) Deletefile(fp string, ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from filestatedb where filepath=? and infohash=?;`, nil, fp, ih.HexString())
return err
}

View File

@@ -0,0 +1,66 @@
package db
import (
"sync"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
"github.com/anacrolix/torrent/metainfo"
)
type SqliteLSDb struct {
Db *sqlite.Conn
mu sync.Mutex
}
func (db *SqliteLSDb) Open(fp string) {
var err error
db.Db, err = sqlite.OpenConn(fp, 0)
if err != nil {
DbL.Fatalln(err)
}
err = sqlitex.ExecScript(db.Db, `create table if not exists lockstatedb (infohash text primary key);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteLSDb) Close() {
db.mu.Lock()
defer db.mu.Unlock()
err := db.Db.Close()
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteLSDb) Lock(m metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `insert into lockstatedb (infohash) values (?) on conflict (infohash) do nothing;`, nil, m.HexString())
return
}
func (db *SqliteLSDb) Unlock(m metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from lockstatedb where infohash=?;`, nil, m.HexString())
return
}
func (db *SqliteLSDb) IsLocked(m string) (b bool) {
db.mu.Lock()
defer db.mu.Unlock()
if sqlitex.Exec(
db.Db, `select 1 from lockstatedb where infohash=?;`,
func(stmt *sqlite.Stmt) error {
b = true
return nil
}, m) != nil {
return false
}
return
}

81
internal/db/sqlite3pc.go Normal file
View File

@@ -0,0 +1,81 @@
//go:build cgo && !nosqlite
// +build cgo,!nosqlite
package db
import (
"path/filepath"
"sync"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
)
type sqlitePieceCompletion struct {
mu sync.Mutex
db *sqlite.Conn
}
func NewSqlitePieceCompletion(dir string) (ret *sqlitePieceCompletion, err error) {
p := filepath.Join(dir, "pcomp.db")
db, err := sqlite.OpenConn(p, 0)
if err != nil {
return
}
err = sqlitex.ExecScript(db, `create table if not exists pcomp (infohash text, pindex integer, complete boolean, unique(infohash, pindex));`)
if err != nil {
_ = db.Close()
return
}
ret = &sqlitePieceCompletion{db: db}
return
}
func (me *sqlitePieceCompletion) Get(pk metainfo.PieceKey) (c storage.Completion, err error) {
me.mu.Lock()
defer me.mu.Unlock()
err = sqlitex.Exec(
me.db, `select complete from pcomp where infohash=? and pindex=?;`,
func(stmt *sqlite.Stmt) error {
c.Complete = stmt.ColumnInt(0) != 0
c.Ok = true
return nil
},
pk.InfoHash.HexString(), pk.Index)
return
}
func (me *sqlitePieceCompletion) Set(pk metainfo.PieceKey, b bool) error {
me.mu.Lock()
defer me.mu.Unlock()
return sqlitex.Exec(
me.db,
`insert into pcomp (infohash,pindex,complete) values (?,?,?) on conflict (infohash,pindex) do update set complete=?;`,
nil,
pk.InfoHash.HexString(), pk.Index, b, b)
}
func (me *sqlitePieceCompletion) Delete(m metainfo.Hash) {
me.mu.Lock()
defer me.mu.Unlock()
if me.db != nil {
_ = sqlitex.Exec(
me.db,
`delete from pcomp where infohash=?;`,
nil,
m.HexString())
}
}
func (me *sqlitePieceCompletion) Close() (err error) {
me.mu.Lock()
defer me.mu.Unlock()
if me.db != nil {
err = me.db.Close()
me.db = nil
}
return
}

View File

@@ -0,0 +1,196 @@
//go:build cgo
// +build cgo
package db
import (
"fmt"
"sync"
"time"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
"github.com/anacrolix/torrent/metainfo"
)
type Sqlite3Db struct {
Db *sqlite.Conn
mu sync.Mutex
}
func (db *Sqlite3Db) Open(fp string) {
var err error
db.Db, err = sqlite.OpenConn(fp, 0)
if err != nil {
DbL.Fatalln(err)
}
err = sqlitex.ExecScript(db.Db, `create table if not exists torrent (infohash text primary key,started boolean,addedat text,startedat text);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *Sqlite3Db) Close() {
db.mu.Lock()
defer db.mu.Unlock()
err := db.Db.Close()
if err != nil {
DbL.Fatalln(err)
}
}
func (db *Sqlite3Db) Exists(ih metainfo.Hash) (ret bool) {
db.mu.Lock()
defer db.mu.Unlock()
serr := sqlitex.Exec(
db.Db, `select 1 from torrent where infohash=?;`,
func(stmt *sqlite.Stmt) error {
ret = stmt.ColumnInt(0) == 1
return nil
}, ih.HexString())
if serr != nil {
return false
}
return
}
func (db *Sqlite3Db) IsLocked(ih string) (ret bool) {
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select locked from torrent where infohash=?;`,
func(stmt *sqlite.Stmt) error {
ret = stmt.ColumnInt(0) != 0
return nil
}, ih)
return
}
func (db *Sqlite3Db) HasStarted(ih string) (ret bool) {
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select started from torrent where infohash=?;`,
func(stmt *sqlite.Stmt) error {
ret = stmt.ColumnInt(0) != 0
return nil
}, ih)
return
}
func (db *Sqlite3Db) SetLocked(ih string, b bool) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `update torrent set locked=? where infohash=?;`, nil, b, ih)
return
}
func (db *Sqlite3Db) Add(ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
tn := time.Now().Format(time.RFC3339)
err = sqlitex.Exec(db.Db, `insert into torrent (infohash,started,addedat,startedat) values (?,?,?,?) on conflict (infohash) do update set startedat=?;`, nil, ih.HexString(), 0, tn, tn, tn)
return
}
func (db *Sqlite3Db) Delete(ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from torrent where infohash=?;`, nil, ih.HexString())
return
}
func (db *Sqlite3Db) Start(ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
tn := time.Now().Format(time.RFC3339)
err = sqlitex.Exec(db.Db, `update torrent set started=?,startedat=? where infohash=?;`, nil, 1, tn, ih.HexString())
return
}
func (db *Sqlite3Db) SetStarted(ih metainfo.Hash, inp bool) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `update torrent set started=? where infohash=?;`, nil, inp, ih.HexString())
return
}
func (db *Sqlite3Db) GetTorrent(ih metainfo.Hash) (*Torrent, error) {
var trnt Torrent
var exists bool
var serr error
var terr error
db.mu.Lock()
defer db.mu.Unlock()
serr = sqlitex.Exec(
db.Db, `select * from torrent where infohash=?;`,
func(stmt *sqlite.Stmt) error {
exists = true
trnt.Infohash = ih
trnt.Started = stmt.ColumnInt(1) != 0
trnt.AddedAt, terr = time.Parse(time.RFC3339, stmt.GetText("addedat"))
if terr != nil {
DbL.Println(terr)
return terr
}
trnt.StartedAt, terr = time.Parse(time.RFC3339, stmt.GetText("startedat"))
if terr != nil {
DbL.Println(terr)
return terr
}
return nil
}, ih.HexString())
if serr != nil {
return nil, serr
}
if !exists {
return nil, fmt.Errorf("Torrent doesn't exist")
}
return &trnt, nil
}
func (db *Sqlite3Db) GetTorrents() (Trnts []*Torrent, err error) {
Trnts = make([]*Torrent, 0)
var serr error
var terr error
db.mu.Lock()
defer db.mu.Unlock()
serr = sqlitex.Exec(
db.Db, `select * from torrent;`,
func(stmt *sqlite.Stmt) error {
var trnt Torrent
trnt.Infohash, terr = MetafromHex(stmt.GetText("infohash"))
if terr != nil {
DbL.Println(terr)
return terr
}
trnt.Started = stmt.ColumnInt(1) != 0
trnt.AddedAt, terr = time.Parse(time.RFC3339, stmt.GetText("addedat"))
if terr != nil {
DbL.Println(terr)
return terr
}
trnt.StartedAt, terr = time.Parse(time.RFC3339, stmt.GetText("startedat"))
if terr != nil {
DbL.Println(terr)
return terr
}
Trnts = append(Trnts, &trnt)
return nil
})
if serr != nil {
return Trnts, serr
}
return Trnts, nil
}

View File

@@ -0,0 +1,120 @@
//go:build cgo
// +build cgo
package db
import (
"sync"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
"github.com/anacrolix/torrent/metainfo"
)
type SqliteTorrentUserDb struct {
Db *sqlite.Conn
mu sync.Mutex
}
func (db *SqliteTorrentUserDb) Open(fp string) {
var err error
db.Db, err = sqlite.OpenConn(fp, 0)
if err != nil {
DbL.Fatalln(err)
}
err = sqlitex.ExecScript(db.Db, `create table if not exists torrentuserdb (username text,infohash text, unique(username,infohash));`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteTorrentUserDb) Close() {
db.mu.Lock()
defer db.mu.Unlock()
err := db.Db.Close()
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteTorrentUserDb) Add(username string, ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `insert into torrentuserdb (username,infohash) values (?,?) on conflict (username,infohash) do nothing;`, nil, username, ih.HexString())
return
}
func (db *SqliteTorrentUserDb) Remove(username string, ih metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from torrentuserdb where username=? and infohash=?;`, nil, username, ih.HexString())
return
}
func (db *SqliteTorrentUserDb) RemoveAll(username string) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from torrentuserdb where username=?;`, nil, username)
return
}
func (db *SqliteTorrentUserDb) RemoveAllMi(mi metainfo.Hash) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from torrentuserdb where infohash=?;`, nil, mi.HexString())
return
}
func (db *SqliteTorrentUserDb) HasUser(username string, ih string) (ret bool) {
db.mu.Lock()
defer db.mu.Unlock()
serr := sqlitex.Exec(
db.Db, `select 1 from torrentuserdb where username=? and infohash=?;`,
func(stmt *sqlite.Stmt) error {
ret = stmt.ColumnInt(0) == 1
return nil
}, username, ih)
if serr != nil {
return false
}
return
}
func (db *SqliteTorrentUserDb) ListTorrents(username string) (ret []metainfo.Hash) {
ret = make([]metainfo.Hash, 0)
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select infohash from torrentuserdb where username=?;`,
func(stmt *sqlite.Stmt) error {
tm, terr := MetafromHex(stmt.GetText("infohash"))
if terr != nil {
DbL.Println(terr)
return terr
}
ret = append(ret, tm)
return nil
}, username)
return
}
func (db *SqliteTorrentUserDb) ListUsers(mi metainfo.Hash) (ret []string) {
ret = make([]string, 0)
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select username from torrentuserdb where infohash=?;`,
func(stmt *sqlite.Stmt) error {
username := stmt.GetText("username")
ret = append(ret, username)
return nil
}, mi.HexString())
return
}

View File

@@ -0,0 +1,90 @@
//go:build cgo
// +build cgo
package db
import (
"sync"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
)
type SqliteTdb struct {
Db *sqlite.Conn
mu sync.Mutex
}
func (db *SqliteTdb) Open(fp string) {
var err error
db.Db, err = sqlite.OpenConn(fp, 0)
if err != nil {
DbL.Fatalln(err)
}
err = sqlitex.ExecScript(db.Db, `create table if not exists trackerdb (url text primary key);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteTdb) Close() {
db.mu.Lock()
defer db.mu.Unlock()
err := db.Db.Close()
if err != nil {
DbL.Fatalln(err)
}
}
func (db *SqliteTdb) Add(url string) {
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(db.Db, `insert into trackerdb (url) values (?);`, nil, url)
}
func (db *SqliteTdb) Delete(url string) {
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(db.Db, `delete from trackerdb where url=?;`, nil, url)
}
func (db *SqliteTdb) DeleteN(count int) {
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(db.Db, `delete from trackerdb where url in (select url from trackerdb limit ?);`, nil, count)
}
func (db *SqliteTdb) DeleteAll() {
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(db.Db, `delete from trackerdb;`, nil)
}
func (db *SqliteTdb) Count() (ret int64) {
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select count(*) from trackerdb;`,
func(stmt *sqlite.Stmt) error {
ret = stmt.ColumnInt64(0)
return nil
})
return
}
func (db *SqliteTdb) Get() (ret []string) {
ret = make([]string, 0)
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select url from trackerdb;`,
func(stmt *sqlite.Stmt) error {
ret = append(ret, stmt.GetText("url"))
return nil
})
return
}

View File

@@ -0,0 +1,191 @@
//go:build cgo
// +build cgo
package db
import (
"fmt"
"sync"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"crawshaw.io/sqlite"
"crawshaw.io/sqlite/sqlitex"
)
type Sqlite3UserDb struct {
Db *sqlite.Conn
mu sync.Mutex
}
func (db *Sqlite3UserDb) Open(fp string) {
var err error
db.Db, err = sqlite.OpenConn(fp, 0)
if err != nil {
DbL.Fatalln(err)
}
err = sqlitex.ExecScript(db.Db, `create table if not exists userdb (username text unique,password text,token text unique,usertype integer,createdat text);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *Sqlite3UserDb) Close() {
db.mu.Lock()
defer db.mu.Unlock()
err := db.Db.Close()
if err != nil {
DbL.Fatalln(err)
}
}
func (db *Sqlite3UserDb) Add(Username string, Password string, UserType int) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("uuid error") // uuid may panic
}
}()
if len(Username) < 5 || len(Password) < 5 {
return fmt.Errorf("username or password size too small")
}
bytes, err := bcrypt.GenerateFromPassword([]byte(Password), 10)
if err != nil {
return
}
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `insert into userdb (username,password,token,usertype,createdat) values (?,?,?,?,?);`, nil, Username, string(bytes), uuid.New().String(), UserType, time.Now().Format(time.RFC3339))
return
}
func (db *Sqlite3UserDb) Delete(Username string) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `delete from userdb where username=?;`, nil, Username)
return
}
func (db *Sqlite3UserDb) UpdatePw(Username string, Password string) (err error) {
if len(Password) < 5 {
return fmt.Errorf("username or password size too small")
}
bytes, err := bcrypt.GenerateFromPassword([]byte(Password), 10)
if err != nil {
return
}
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `update userdb set password=? where username=?;`, nil, string(bytes), Username)
return
}
func (db *Sqlite3UserDb) ChangeType(Username string, Type string) (err error) {
if len(Username) == 0 {
return fmt.Errorf("empty username")
}
var ut int
if Type == "admin" {
ut = 1
} else if Type == "user" {
ut = 0
} else if Type == "disabled" {
ut = -1
} else {
return fmt.Errorf("unknown type")
}
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `update userdb set usertype=? where username=?;`, nil, ut, Username)
return
}
func (db *Sqlite3UserDb) GetUsers() (ret []*User) {
ret = make([]*User, 0)
var terr error
db.mu.Lock()
defer db.mu.Unlock()
_ = sqlitex.Exec(
db.Db, `select * from userdb;`,
func(stmt *sqlite.Stmt) error {
var user User
user.Username = stmt.GetText("username")
user.Password = stmt.GetText("password")
user.Token = stmt.GetText("token")
user.UserType = stmt.ColumnInt(3)
user.CreatedAt, terr = time.Parse(time.RFC3339, stmt.GetText("createdat"))
if terr != nil {
DbL.Println(terr)
return terr
}
ret = append(ret, &user)
return nil
})
return
}
func (db *Sqlite3UserDb) Validate(Username string, Password string) (ut int, ret bool) {
var pw string
var exists bool
var serr error
db.mu.Lock()
defer db.mu.Unlock()
serr = sqlitex.Exec(
db.Db, `select usertype,password from userdb where username=?;`,
func(stmt *sqlite.Stmt) error {
exists = true
ut = stmt.ColumnInt(0)
pw = stmt.GetText("password")
return nil
}, Username)
if serr != nil {
return -1, false
}
if !exists {
return -1, false
}
serr = bcrypt.CompareHashAndPassword([]byte(pw), []byte(Password))
return ut, serr == nil
}
func (db *Sqlite3UserDb) ValidateToken(Token string) (user string, ut int, err error) {
if Token == "" {
return "", -1, fmt.Errorf("token is empty")
}
var exists bool
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(
db.Db, `select usertype,username from userdb where token=?;`,
func(stmt *sqlite.Stmt) error {
exists = true
ut = stmt.ColumnInt(0)
user = stmt.GetText("username")
return nil
}, Token)
if err != nil {
return "", -1, err
}
if !exists {
return "", -1, fmt.Errorf("token doesn't exist")
}
if user == "" {
return "", -1, fmt.Errorf("user doesn't exist")
}
return
}
func (db *Sqlite3UserDb) SetToken(Username string, Token string) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
err = sqlitex.Exec(db.Db, `update userdb set token=? where username=?;`, nil, Token, Username)
return
}

2
internal/web/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules
build

1
internal/web/.npmrc Normal file
View File

@@ -0,0 +1 @@
engine-strict=true

View File

@@ -0,0 +1,3 @@
static/**
build/**
node_modules/**

6
internal/web/.prettierrc Normal file
View File

@@ -0,0 +1,6 @@
{
"singleQuote": true,
"trailingComma": "none",
"printWidth": 300,
"jsxBracketSameLine": true
}

View File

@@ -0,0 +1,46 @@
import { existsSync, mkdirSync, copyFile } from 'fs';
import { build } from 'esbuild';
import sveltePlugin from 'esbuild-svelte';
import sveltePreprocess from 'svelte-preprocess';
import tailwindcss from 'tailwindcss';
const WATCH = process.argv.includes('-w');
//make sure the directoy exists before stuff gets put into it
if (!existsSync('./build/')) {
mkdirSync('./build/');
}
copyFile('./src/index.html', './build/index.html', (err) => {
if (err) throw err;
});
//build the application
build({
entryPoints: ['./src/index.js'],
outdir: './build',
format: 'esm',
minify: true,
bundle: true,
treeShaking: true,
splitting: true,
watch: WATCH,
incremental: WATCH,
plugins: [
sveltePlugin({
compileOptions: {
dev: WATCH
},
preprocess: sveltePreprocess({
aliases: ['ts', 'typescript'],
postcss: {
plugins: [tailwindcss()]
}
})
})
],
tsconfig: 'tsconfig.json'
}).catch((err) => {
console.error(err);
process.exit(1);
});

2732
internal/web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
internal/web/package.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "exatorrent",
"scripts": {
"build": "node ./esbuild.config.js",
"watch": "node ./esbuild.config.js -w",
"format": "prettier --write --plugin-search-dir=. ."
},
"repository": {
"type": "git",
"url": "git+https://github.com/varbhat/exatorrent.git"
},
"author": "varbhat",
"license": "GPL-3.0-or-later",
"bugs": {
"url": "https://github.com/varbhat/exatorrent/issues"
},
"homepage": "https://github.com/varbhat/exatorrent#readme",
"private": true,
"type": "module",
"devDependencies": {
"@tsconfig/svelte": "^2.0.1",
"prettier": "^2.3.2",
"prettier-plugin-svelte": "^2.3.1",
"svelte-check": "^2.2.5",
"typescript": "^4.3.5"
},
"dependencies": {
"slocation": "latest",
"esbuild": "^0.12.22",
"esbuild-svelte": "^0.5.4",
"autoprefixer": "^10.3.2",
"@tailwindcss/forms": "^0.3.3",
"postcss": "^8.3.6",
"tailwindcss": "^2.2.7",
"svelte-preprocess": "^4.8.0",
"svelte": "latest"
}
}

View File

@@ -0,0 +1,69 @@
<script lang="ts">
import { slocation } from 'slocation';
import { isAdmin, isDisConnected } from './partials/core';
import Index from './partials/Index.svelte';
import Notifications from './partials/Notifications.svelte';
import Signin from './partials/Signin.svelte';
import Top from './partials/Top.svelte';
import Torrents from './partials/Torrents.svelte';
import Disconnect from './partials/Disconnect.svelte';
import Settings from './partials/Settings.svelte';
import Torrent from './partials/Torrent.svelte';
import Stats from './partials/Stats.svelte';
import Users from './partials/Users.svelte';
import File from './partials/File.svelte';
import About from './partials/About.svelte';
import User from './partials/User.svelte';
</script>
<svelte:head>
<title>exatorrent</title>
<link rel="icon" href="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' stroke='mediumslateblue'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4' /></svg>" />
</svelte:head>
{#if $isDisConnected === false && $slocation.pathname !== '/signin' && $slocation.pathname !== '/file'}
<Top />
{/if}
{#if $isDisConnected === true && $slocation.pathname !== '/signin' && $slocation.pathname !== '/file'}
<Disconnect />
{:else if $slocation.pathname === '/'}
<Index />
{:else if $slocation.pathname === '/signin'}
<Signin />
{:else if $slocation.pathname === '/notifications'}
<Notifications />
{:else if $slocation.pathname === '/torrents'}
<Torrents />
{:else if $slocation.pathname === '/settings'}
<Settings />
{:else if $slocation.pathname === '/file'}
<File />
{:else if $slocation.pathname === '/stats' && $isAdmin === true}
<Stats />
{:else if $slocation.pathname === '/users' && $isAdmin === true}
<Users />
{:else if $slocation.pathname.startsWith('/user/') && $isAdmin === true}
<User />
{:else if $slocation.pathname.startsWith('/torrent/')}
<Torrent />
{:else if $slocation.pathname === '/about'}
<About />
{:else}
<div class="mx-auto max-w-3xl">
<p class="text-xl text-center text-red-400 font-sans">Not Found</p>
</div>
{/if}
<style global lang="postcss">
body {
@apply bg-gray-900;
}
.noHL {
-webkit-tap-highlight-color: transparent;
}
@tailwind base;
@tailwind components;
@tailwind utilities;
</style>

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/index.css" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/index.js"></script>
</body>
</html>

View File

@@ -0,0 +1,5 @@
import Index from './Index.svelte';
new Index({
target: document.getElementById('app')
});

View File

@@ -0,0 +1,23 @@
<script lang="ts">
import { onMount } from 'svelte';
import { versionstr, versionchecked, Send } from './core';
onMount(() => {
if ($versionchecked === false) {
Send({
command: 'version'
});
}
});
</script>
<div class="mx-auto max-w-3xl text-gray-200 mt-3">
<p class="text-center text-lg mb-1 text-blue-300">exatorrent is torrent client</p>
<p class="text-center mb-2 font-mono">License: GPLv3</p>
<p class="text-center mb-5 font-mono">Version: {$versionstr}</p>
<div class="flex justify-around">
<a href="https://github.com/varbhat/exatorrent" target="_blank" rel="noopener noreferrer">
<button type="button" class="my-2 mx-2 flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-secGray-700 no-HL font-mono focus:outline-none">Source</button>
</a>
</div>
</div>

View File

@@ -0,0 +1,45 @@
<script lang="ts">
import { SignOut, Connect } from './core';
</script>
<div class="mx-auto max-w-xl">
<div class="flex justify-center p-10">
<svg xmlns="http://www.w3.org/2000/svg" class="h-11 w-11 text-red-600 animate-bounce" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M18.364 5.636a9 9 0 010 12.728m0 0l-2.829-2.829m2.829 2.829L21 21M15.536 8.464a5 5 0 010 7.072m0 0l-2.829-2.829m-4.243 2.829a4.978 4.978 0 01-1.414-2.83m-1.414 5.658a9 9 0 01-2.167-9.238m7.824 2.167a1 1 0 111.414 1.414m-1.414-1.414L3 3m8.293 8.293l1.414 1.414"
/>
</svg>
</div>
<p class="text-center text-red-400 font-sans">Disconnected</p>
<div class="grid grid-flow-col grid-cols-2 mt-3">
<div
class="bg-gradient-to-r from-green-900 to-green-700 text-gray-200 px-5 py-5 rounded-lg m-3"
title="reconnect"
on:click={() => {
Connect();
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.636 18.364a9 9 0 010-12.728m12.728 0a9 9 0 010 12.728m-9.9-2.829a5 5 0 010-7.07m7.072 0a5 5 0 010 7.07M13 12a1 1 0 11-2 0 1 1 0 012 0z" />
</svg>
Reconnect
</div>
<div
class="bg-gradient-to-r from-red-700 to-red-500 text-gray-200 px-5 py-5 rounded-lg m-3"
title="signout"
on:click={() => {
SignOut();
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
</svg>
Sign Out
</div>
</div>
</div>

View File

@@ -0,0 +1,90 @@
<script lang="ts">
import { Send, fileviewpath, fileviewinfohash, fsfileinfo, fileType, socket, fileSize, filepagediscon } from './core';
import { slocation } from 'slocation';
import { onDestroy, onMount } from 'svelte';
let stream = false;
let ft = 'unknown';
onMount(() => {
if (socket == null || socket == undefined || socket?.readyState === WebSocket.CLOSED) {
slocation.goto('/');
}
Send({
command: 'getfsfileinfo',
data1: $fileviewinfohash,
data2: $fileviewpath
});
filepagediscon.set(true);
ft = fileType($fileviewpath);
});
onDestroy(() => {
filepagediscon.set(false);
});
</script>
<div class="mx-auto max-w-xl">
<div class="flex justify-between h-16">
<button
class="flex-shrink-0 focus:outline-none bg-gray-800 m-2 px-3 rounded-md"
on:click={() => {
history.length > 2 ? history.back() : slocation.goto('/');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
</button>
<button
class="flex items-center focus:outline-none p-5 mt-2"
on:click={() => {
slocation.goto('/');
}}
>
<p class="font-sans text-2xl text-gray-200">exatorrent</p>
</button>
<div class="flex-shrink-0 focus:outline-none m-2 px-3 rounded-md" />
</div>
<div class="flex justify-center">
<!-- svelte-ignore a11y-media-has-caption -->
{#if ft === 'video'}
<video controls src="/api/{stream ? 'stream' : 'torrent'}/{$fileviewinfohash}/{$fileviewpath}" />
{:else if ft === 'audio'}
<audio controls src="/api/{stream ? 'stream' : 'torrent'}/{$fileviewinfohash}/{$fileviewpath}" />
{/if}
</div>
<p class="text-center text-gray-400 font-sans break-all">{$fsfileinfo?.name}</p>
<p class="text-center text-gray-400 font-sans truncate">({fileSize($fsfileinfo?.size)})</p>
<div class="grid grid-flow-col grid-cols-4 bg-black my-2 appearance-none border border-gray-800 w-full rounded-md">
<div class="col-span-3 appearance-none w-full flex-grow px-3 py-2 border-none text-gray-300 focus:outline-none mx-1">Use Stream API</div>
<div class="flex items-center justify-end w-full my-2 mr-2">
<label for="dontstarttoggle" class="flex items-center cursor-pointer mx-1">
<div class="relative">
<input type="checkbox" class="rounded text-indigo-700 bg-gray-800 form-checkbox mx-1" bind:checked={stream} />
</div>
</label>
</div>
</div>
{#if ft === 'video' || ft === 'audio'}
<a href="vlc://{location.origin}/api/{stream ? 'stream' : 'torrent'}/{$fileviewinfohash}/{$fileviewpath}?token={localStorage.getItem('exasession')}" target="_blank" rel="noopener noreferrer">
<button class="bg-yellow-700 w-full my-2 flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white focus:outline-none"> Play in VLC </button>
</a>
<a href="intent://{location.host}/api/{stream ? 'stream' : 'torrent'}/{$fileviewinfohash}/{$fileviewpath}?token={localStorage.getItem('exasession')}#Intent;type=video/any;package=is.xyz.mpv;scheme={location.protocol.slice(0, -1)};end;" target="_blank" rel="noopener noreferrer">
<button class="flex md:hidden bg-purple-700 w-full my-2 justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white focus:outline-none"> Play in MPV </button>
</a>
{/if}
<input type="text" class="bg-secGray-700 rounded-md w-full my-2 py-2 px-4 text-sm text-gray-300 truncate" disabled value="{location.origin}/api/{stream ? 'stream' : 'torrent'}/{$fileviewinfohash}/{$fileviewpath}" />
<a href="{location.origin}/api/{stream ? 'stream' : 'torrent'}/{$fileviewinfohash}/{$fileviewpath}?token={localStorage.getItem('exasession')}" target="_blank" rel="noopener noreferrer" download>
<button type="button" class="w-full my-3 flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-900 focus:outline-none"> Download </button>
</a>
</div>

View File

@@ -0,0 +1,167 @@
<script lang="ts">
import { dontstart, Send, isAdmin } from './core';
import { slocation } from 'slocation';
let ismetainfo = true;
let torrentinput = '';
let trntfilestring = '';
let trntfileinput: HTMLInputElement;
let addfunc = () => {
if (ismetainfo === true) {
if (torrentinput === '') {
alert('Empty Input');
return;
}
if (torrentinput.startsWith('magnet:')) {
console.log('Adding Magnet', torrentinput, $dontstart);
Send({
command: 'addmagnet',
data1: torrentinput,
data2: $dontstart === 'true' ? 'true' : 'false'
});
torrentinput = '';
} else {
console.log('Adding Infohash', torrentinput, $dontstart);
Send({
command: 'addinfohash',
data1: torrentinput,
data2: $dontstart === 'true' ? 'true' : 'false'
});
torrentinput = '';
}
} else {
if (trntfilestring === '') {
alert('File Invalid');
return;
}
console.log('Adding Torrent', trntfilestring, $dontstart);
Send({
command: 'addtorrent',
data1: trntfilestring,
data2: $dontstart === 'true' ? 'true' : 'false'
});
trntfilestring = '';
}
};
let entertoadd = (event: KeyboardEvent) => {
if (event.code === 'Enter') {
addfunc();
}
};
function toggleismetainfo() {
ismetainfo = !ismetainfo;
}
function readtrnt(e: Event) {
let f = (e.target as HTMLInputElement).files[0];
if (f.size > 20971520) {
alert('Error: Maximum Torrent File Size is 20MB');
return;
}
let reader = new FileReader();
reader.onload = (e) => {
trntfilestring = btoa(e.target.result as string);
};
reader.readAsBinaryString(f);
(e.target as HTMLInputElement).value = null;
}
</script>
<div class="mt-10 flex items-center justify-center px-4">
<div class="max-w-md w-full ">
<div>
<h2 class=" text-center text-3xl font-extrabold text-gray-300">
{#if ismetainfo}Enter Magnet or Infohash{:else}Select Torrent File{/if}
</h2>
</div>
<div class="mt-8">
<div class="flex bg-gray-800 rounded-md mb-3 border border-gray-800">
{#if ismetainfo}
<input id="torrentinput" type="text" required class=" bg-gray-800 appearance-none rounded-md w-full flex-grow px-3 py-2 border-none placeholder-gray-500 text-gray-200 focus:outline-none sm:text-sm" placeholder="Magnet / Infohash" bind:value={torrentinput} on:keydown={entertoadd} />
{:else}
<label class="bg-gray-800 appearance-none rounded-md w-full flex-grow px-3 py-2 placeholder-gray-500 text-gray-200 focus:outline-none sm:text-sm">
<div class="text-gray-200 flex">
<svg xmlns="http://www.w3.org/2000/svg" class="text-gray-400 h-6 w-6 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
</svg>
Select a Torrent File
</div>
<input accept=".torrent,application/x-bittorrent" bind:this={trntfileinput} on:change={(e) => readtrnt(e)} id="torrentfile" name="torrentfile" type="file" class="hidden" />
</label>
{/if}
<button type="button" class="focus:outline-none focus:text-green-500" on:click={toggleismetainfo}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-400 my-2 mx-2 flex-grow" fill="none" viewBox="0 0 24 24" stroke="currentColor">
{#if ismetainfo}
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
{:else}
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
{/if}
</svg>
</button>
</div>
<button type="button" class="w-full my-2 flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-900 hover:bg-indigo-700 focus:outline-none focus:ring-2" on:click={addfunc}> Add </button>
</div>
</div>
</div>
<div class="mx-auto max-w-xl">
<div class="grid grid-flow-col grid-cols-2 mt-3">
<div
class="bg-gray-800 text-gray-200 px-5 py-5 rounded-lg m-3 cursor-pointer"
on:click={() => {
slocation.goto('/torrents');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
</svg>
Torrents
</div>
<div
class="bg-gray-800 text-gray-200 px-5 py-5 rounded-lg m-3 cursor-pointer"
on:click={() => {
slocation.goto('/settings');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
/>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Settings
</div>
</div>
{#if $isAdmin}
<div class="grid grid-flow-col grid-cols-2 mt-3 cursor-pointer">
<div
class="bg-gray-800 text-gray-200 px-5 py-5 rounded-lg m-3"
on:click={() => {
slocation.goto('/users');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
Users
</div>
<div
class="bg-gray-800 text-gray-200 px-5 py-5 rounded-lg m-3 cursor-pointer"
on:click={() => {
slocation.goto('/stats');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4z" />
</svg>
Stats
</div>
</div>
{/if}
</div>

View File

@@ -0,0 +1,41 @@
<script lang="ts">
import { slocation } from 'slocation';
import { resplist } from './core';
</script>
<div class="mx-auto max-w-3xl ">
{#if $resplist?.has === true}
<button
type="button"
class="w-full my-2 flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-secGray-600 focus:outline-none"
on:click={() => {
resplist.set({ has: false, data: [] });
}}
>
Clear All
</button>
{#each $resplist?.data as resp}
<div
class="bg-gray-800 text-gray-200 px-3 py-5 rounded-lg m-3 noHL"
on:click={() => {
if (typeof resp?.infohash === 'string' && resp?.infohash.length > 0) {
slocation.goto(`/torrent/${resp?.infohash}`);
}
}}
>
<div class="break-all mx-1 mb-1 font-bold">
{resp?.message}
</div>
<div class="text-gray-300 flex justify-between text-sm font-medium tabular-nums">
<div class="break-all mx-1">
{resp?.type}
{resp?.state}
{resp?.infohash ? `( ${resp?.infohash} )` : ''}
</div>
</div>
</div>
{/each}
{:else}
<p class="text-xl text-center text-red-400 font-sans">No Notifications</p>
{/if}
</div>

View File

@@ -0,0 +1,28 @@
<script lang="ts">
import { fileSize } from './core';
export let bytescompleted: number;
export let length: number;
export let offset: number;
let progress: number;
$: progress = (bytescompleted / length) * 100;
</script>
<div class="space-y-2 mt-1">
<div class="bg-black rounded-full overflow-hidden">
<div class="bg-blue-700 h-1.5" style="width:{progress ? progress : 0}%" />
</div>
<div class="text-gray-400 flex justify-between text-sm font-medium">
<div class="break-all">
{fileSize(bytescompleted)} / {fileSize(length)} (Off. {offset})
</div>
<div>
{progress?.toLocaleString('en-US', {
maximumFractionDigits: 2,
minimumFractionDigits: 2
})} %
</div>
</div>
</div>

View File

@@ -0,0 +1,385 @@
<script lang="ts">
import { dontstart, Send, SignOut, socket, adminmode, isAdmin, engconfig, fileSize, diskstats, nooftrackersintrackerdb } from './core';
import { slocation } from 'slocation';
let ds = false;
if ($dontstart === 'true') {
ds = true;
}
let toggledontstart = (ds: boolean) => {
console.log('dontstart changed to', ds);
ds ? (localStorage.setItem('dontstart', 'true'), ($dontstart = 'true')) : (localStorage.setItem('dontstart', 'false'), ($dontstart = 'false'));
};
$: toggledontstart(ds);
let editmode: boolean = false;
let newpassword: string = '';
let diskstatsOpen = false;
let miscOpen = false;
let miscfirsttime = true;
let trdelno: string;
let srno: string;
let changepw = () => {
if (newpassword.length < 5) {
alert('Size of New Password must be more than 5');
return;
}
Send({
command: 'updatepw',
data1: newpassword
});
socket?.readyState === WebSocket.OPEN ? socket?.close() : console.log('socket already closed');
SignOut();
};
let engsettingsOpen = false;
let engsettingsstring = '';
let whenengconfigChange = (ec: Object) => {
engsettingsstring = JSON.stringify(ec, null, 2);
};
$: whenengconfigChange($engconfig);
let diskusageaction = () => {
if (diskstatsOpen === false) {
Send({
command: 'diskusage'
});
diskstatsOpen = true;
} else {
diskstatsOpen = false;
}
};
let miscsettingsaction = () => {
miscOpen = !miscOpen;
if (miscfirsttime === true) {
Send({
command: 'nooftrackersintrackerdb',
aop: 1
});
}
};
let enginesettingsOpen = () => {
if (engsettingsOpen === false) {
Send({
command: 'getconfig',
aop: 1
});
engsettingsOpen = true;
} else {
engsettingsOpen = false;
}
};
</script>
<div class="mx-auto max-w-xl">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center">
<p class="mx-1 font-medium truncate">
User Settings {#if localStorage.getItem('exausertype') === 'admin'} <span class="text-xs font-semibold inline-block py-1 px-2 rounded-md text-gray-300 bg-secGray-700 ml-3 last:mr-0 mr-1">admin</span>{/if}
</p>
</div>
</div>
<div class="flex flex-col">
<div class="flex bg-gray-800 rounded-md my-2 appearance-none border border-gray-800 w-full">
{#if editmode === false}
<input id="username" name="username" type="text" class=" bg-gray-800 appearance-none rounded-md w-full flex-grow px-3 py-2 border-none placeholder-gray-500 text-gray-100 focus:outline-none" placeholder={localStorage.getItem('exausername')} disabled />
<button
type="button"
class="focus:outline-none"
on:click={() => {
editmode = true;
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-400 my-2 mx-2 flex-grow" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
</svg>
</button>
{:else if editmode === true}
<input id="password" name="password" type="text" class=" bg-gray-800 appearance-none rounded-md w-full flex-grow px-3 py-2 border-none placeholder-gray-500 text-gray-200 focus:outline-none" placeholder="Enter New Password" bind:value={newpassword} />
<button
type="button"
class="focus:outline-none"
on:click={() => {
editmode = false;
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-red-400 my-2 mx-2 flex-grow" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<button type="button" class="focus:outline-none" on:click={changepw}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-400 my-2 mx-2 flex-grow" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
</button>
{/if}
</div>
<div class="grid grid-flow-col grid-cols-4 pr-2 bg-gray-800 rounded-md my-2 appearance-none border border-gray-800 w-full">
<div class=" bg-gray-800 col-span-3 appearance-none rounded-md w-full flex-grow px-3 py-2 border-none text-gray-300 focus:outline-none">Don't Start Torrents on Add</div>
<div class="flex items-center justify-end w-full my-2 mr-2">
<label for="dontstarttoggle" class="flex items-center cursor-pointer">
<div class="relative">
<input type="checkbox" class="rounded text-indigo-700 bg-gray-800 form-checkbox" bind:checked={ds} />
</div>
</label>
</div>
</div>
{#if $isAdmin === true}
<div class="grid grid-flow-col grid-cols-4 pr-2 bg-gray-800 my-2 appearance-none border border-gray-800 w-full rounded-md">
<div class=" bg-gray-800 col-span-3 appearance-none w-full flex-grow px-3 py-2 border-none text-gray-300 focus:outline-none">Admin Mode</div>
<div class="flex items-center justify-end w-full my-2 mr-2">
<label for="dontstarttoggle" class="flex items-center cursor-pointer">
<div class="relative">
<input type="checkbox" class="rounded text-indigo-700 bg-gray-800 form-checkbox" bind:checked={$adminmode} />
</div>
</label>
</div>
</div>
{/if}
</div>
</div>
</div>
<div class="mx-auto max-w-xl">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={diskusageaction}>
<p class="ml-3 font-medium truncate">Disk Usage</p>
</div>
{#if diskstatsOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({
command: 'diskusage'
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={diskusageaction}>
{#if diskstatsOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if diskstatsOpen === true}
<div class="m-1 p-1 break-all">
Total: {fileSize($diskstats?.total)}
</div>
<div class="m-1 p-1 break-all">
Free: {fileSize($diskstats?.free)}
</div>
<div class="m-1 p-1 break-all">
Used: {fileSize($diskstats?.used)} ({$diskstats?.usedPercent} %)
</div>
{/if}
</div>
</div>
</div>
{#if $isAdmin === true}
<div class="mx-auto max-w-xl">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={miscsettingsaction}>
<p class="ml-3 font-medium truncate">Misc Settings</p>
</div>
{#if miscOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({
command: 'nooftrackersintrackerdb',
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={miscsettingsaction}>
{#if miscOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if miscOpen === true}
<div class="m-1 p-1 break-all">
Total Number of Trackers in TrackerDB: {$nooftrackersintrackerdb}
</div>
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'deletetrackersintrackerdb',
data1: 'all',
aop: 1
});
}}>Delete All Trackers in TrackerDB</button
>
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'trackerdbrefresh',
aop: 1
});
}}>Refresh TrackerDB</button
>
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'stoponseedratio',
aop: 1
});
}}>Seed Ratio Check</button
>
<div class="flex flex-col mt-1">
<input type="text" bind:value={trdelno} required class="m-1 bg-gray-800 appearance-none rounded-md max-w-3xl px-3 py-2 border border-blue-800 placeholder-gray-500 text-gray-200 focus:outline-none sm:text-sm mx-1" placeholder="Delete these many trackers from TrackerDB" />
<button
type="button"
class="m-1 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center noHL"
on:click={() => {
Send({
command: 'deletetrackersintrackerdb',
data1: trdelno,
aop: 1
});
}}
>
Delete Trackers
</button>
</div>
<div class="flex flex-col mt-3">
<input type="text" bind:value={srno} required class="mt-3 bg-gray-800 appearance-none rounded-md max-w-3xl px-3 py-2 border border-blue-800 placeholder-gray-500 text-gray-200 focus:outline-none sm:text-sm mx-1" placeholder="Stop Torrents on Reaching this Seedratio" />
<button
type="button"
class="m-1 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center noHL"
on:click={() => {
Send({
command: 'stoponseedratio',
data1: srno,
aop: 1
});
}}
>
Stop Torrents
</button>
</div>
{/if}
</div>
</div>
</div>
<div class="mx-auto max-w-xl ">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={enginesettingsOpen}>
<p class="ml-3 font-medium truncate">Engine Settings</p>
</div>
{#if engsettingsOpen === true}
<button
class="bg-indigo-700 text-white p-2 rounded-md focus:outline-none flex-shrink-0 mx-1"
type="button"
on:click={() => {
if (engsettingsstring?.length === 0) {
alert('Empty Config!');
} else {
let b64config = window.btoa(engsettingsstring);
Send({
command: 'updateconfig',
data1: b64config,
aop: 1
});
}
}}>Update</button
>
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1"
on:click={() => {
Send({
command: 'getconfig',
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={enginesettingsOpen}>
{#if engsettingsOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col gap-1">
{#if engsettingsOpen === true && $engconfig != null}
<textarea class="form-textarea bg-gray-900 border-1 border-blue-800 max-w-3xl text-white resize-y appearance-none h-screen rounded-md" bind:value={engsettingsstring} />
{/if}
</div>
</div>
</div>
{/if}
<div class="mx-auto max-w-xl flex items-center mt-2">
<button
type="button"
class="w-full my-2 mx-3 flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-black focus:outline-none"
on:click={() => {
slocation.goto('/about');
}}>About exatorrent</button
>
</div>

View File

@@ -0,0 +1,103 @@
<script lang="ts">
// Password box visibility toggle
let pwvisible = false;
let pwbox: HTMLInputElement;
function toggleinput() {
pwvisible = !pwvisible;
pwbox.type = pwvisible ? 'text' : 'password';
}
// Signing in
let exausername: string;
let exapassword: string;
import { Connect } from './core';
import { onMount } from 'svelte';
onMount(() => {
let un = localStorage.getItem('exausername');
let pw = localStorage.getItem('exapassword');
if (un != '' && un != undefined && un != null) {
if (pw != '' && pw != undefined && pw != null) {
Connect();
} else {
return;
}
} else {
return;
}
});
function signIn() {
if (exausername != '' && exausername != undefined && exausername != null) {
if (exapassword != '' && exapassword != undefined && exapassword != null) {
if (!(exausername.length > 5) || !(exapassword.length > 5)) {
alert('Invalid Credentials');
return;
}
localStorage.setItem('exausername', exausername);
localStorage.setItem('exapassword', exapassword);
Connect();
} else {
alert('Password Field Cannot be Empty');
return;
}
} else {
alert('Username Field Cannot be Empty');
return;
}
return;
}
let entertosignin = (event: KeyboardEvent) => {
if (event.code === 'Enter') {
signIn();
}
};
</script>
<div class="mt-10 flex items-center justify-center px-4">
<div class="max-w-md w-full ">
<div>
<a href="https://github.com/varbhat/exatorrent" target="_blank" rel="noopener noreferrer">
<h2 class=" text-center text-5xl font-extrabold text-blue-200">exatorrent</h2>
</a>
<p class="mt-2 text-center text-sm text-gray-300">Sign in to your account</p>
</div>
<div class="mt-2">
<label for="username" class="sr-only">Username</label>
<input id="username" name="email" type="text" bind:value={exausername} required class="bg-gray-800 my-2 appearance-none rounded-md w-full px-3 py-2 border border-gray-800 placeholder-gray-500 text-gray-200 focus:outline-none" placeholder="Username" />
<label for="password" class="sr-only">Password</label>
<div class="flex bg-gray-800 rounded-md my-2 appearance-none border border-gray-800 w-full">
<input
id="password"
name="password"
type="password"
bind:value={exapassword}
bind:this={pwbox}
on:keydown={entertosignin}
required
class=" bg-gray-800 appearance-none rounded-md w-full flex-grow px-3 py-2 border-none placeholder-gray-500 text-gray-200 focus:outline-none"
placeholder="Password"
/>
<button type="button" class="focus:outline-none focus:text-green-500" on:click={toggleinput}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-400 my-2 mx-2 flex-grow " fill="none" viewBox="0 0 24 24" stroke="currentColor">
{#if pwvisible}
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
/>
{:else}
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
{/if}
</svg>
</button>
</div>
<button type="button" on:click={signIn} class="w-full my-2 py-2 px-4 border-none text-sm font-medium rounded-md text-white bg-blue-900 outline-none focus:outline-none"> Sign in </button>
</div>
</div>
</div>

View File

@@ -0,0 +1,170 @@
<script lang="ts">
import { torcstatus, machinfo, machstats, Send, fileSize, hasMachinfo, isAdmin } from './core';
import { onMount } from 'svelte';
import { slocation } from 'slocation';
let deviceinfoOpen = false;
let devicestatsOpen = false;
let torcstatsOpen = false;
onMount(() => {
if ($isAdmin === false) {
slocation.goto('/');
}
Send({ command: 'machstats', aop: 1 });
Send({ command: 'torcstatus', aop: 1 });
});
let devinfoaction = () => {
deviceinfoOpen = !deviceinfoOpen;
if ($hasMachinfo === false) {
Send({ command: 'machinfo', aop: 1 });
}
};
let devicestatsaction = () => {
if (devicestatsOpen === false) {
Send({ command: 'machstats', aop: 1 });
devicestatsOpen = true;
} else {
devicestatsOpen = false;
}
};
let torcstatsaction = () => {
if (torcstatsOpen === false) {
Send({ command: 'torcstatus', aop: 1 });
torcstatsOpen = true;
} else {
torcstatsOpen = false;
}
};
</script>
<div class="mx-auto max-w-xl">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={devinfoaction}>
<p class="ml-3 font-medium truncate">Device Info</p>
</div>
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={devinfoaction}>
{#if deviceinfoOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if deviceinfoOpen === true}
{#if $hasMachinfo === true}
<div class="m-1 p-1 break-all">Arch: {$machinfo?.arch}</div>
<div class="m-1 p-1 break-all">CPU Model: {$machinfo?.cpumodel}</div>
<div class="m-1 p-1 break-all">Go Version: {$machinfo?.goversion}</div>
<div class="m-1 p-1 break-all">Hostname: {$machinfo?.hostname}</div>
<div class="m-1 p-1 break-all">CPU No: {$machinfo?.numbercpu}</div>
<div class="m-1 p-1 break-all">OS: {$machinfo?.os}</div>
<div class="m-1 p-1 break-all">Platform: {$machinfo?.platform}</div>
<div class="m-1 p-1 break-all">Started at {new Date($machinfo?.startedat)?.toLocaleString()}</div>
<div class="m-1 p-1 break-all">Total Mem: {fileSize($machinfo?.totalmem)}</div>
{/if}
{/if}
</div>
</div>
</div>
<div class="mx-auto max-w-xl">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={devicestatsaction}>
<p class="ml-3 font-medium truncate">Device Stats</p>
</div>
{#if devicestatsOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({ command: 'machstats', aop: 1 });
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={devicestatsaction}>
{#if devicestatsOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if devicestatsOpen === true}
<div class="m-1 p-1 break-all">CPU Cycles: {$machstats?.cpucycles}</div>
<div class="m-1 p-1 break-all">Disk Free: {$machstats?.diskfree}</div>
<div class="m-1 p-1 break-all">Disk Percent: {$machstats?.diskpercent} %</div>
<div class="m-1 p-1 break-all">Memory Percent: {$machstats?.mempercent} %</div>
<div class="m-1 p-1 break-all">Go Mem: {fileSize($machstats?.gomem)}</div>
<div class="m-1 p-1 break-all">Go Mem(sys): {fileSize($machstats?.gomemsys)}</div>
<div class="m-1 p-1 break-all">Goroutines: {$machstats?.goroutines}</div>
{/if}
</div>
</div>
</div>
<div class="mx-auto max-w-xl">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={torcstatsaction}>
<p class="ml-3 font-medium truncate">Torrent Client Status</p>
</div>
{#if torcstatsOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({ command: 'torcstatus', aop: 1 });
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={torcstatsaction}>
{#if torcstatsOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col overflow-x-auto bg-gray-800 rounded-md">
{#if torcstatsOpen === true}
<pre class="whitespace-pre mb-2 p-2">{$torcstatus} </pre>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,67 @@
<script lang="ts">
import { onMount } from 'svelte';
import { socket, Connect } from './core';
import { slocation } from 'slocation';
function closeSocket() {
if (socket?.readyState === WebSocket.OPEN) {
socket.close();
}
}
onMount(() => {
if (socket == null || socket == undefined || socket?.readyState === WebSocket.CLOSED) {
console.log('Attempting to Connect');
slocation.goto('/');
Connect();
}
});
</script>
<nav class="max-w-xl mx-auto">
<div class="flex justify-between h-16">
{#if $slocation.pathname !== '/'}
<button
class="flex-shrink-0 focus:outline-none bg-gray-800 m-2 px-3 rounded-md"
on:click={() => {
history.length > 2 ? history.back() : slocation.goto('/');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
</button>
{:else}
<button
class="flex-shrink-0 focus:outline-none bg-gray-800 m-2 px-3 rounded-md"
on:click={() => {
slocation.goto('/notifications');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
</svg>
</button>
{/if}
<button
class="flex items-center focus:outline-none p-5 noHL"
title="exatorrent"
on:click={() => {
if ($slocation.pathname === '/') {
slocation.goto('/about');
} else {
slocation.goto('/');
}
}}
>
<p class="font-sans text-2xl text-gray-200">exatorrent</p>
</button>
<button class="flex-shrink-0 focus:outline-none bg-gray-800 m-2 px-3 rounded-md" on:click={closeSocket} title="Disconnect">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.636 18.364a9 9 0 010-12.728m12.728 0a9 9 0 010 12.728m-9.9-2.829a5 5 0 010-7.07m7.072 0a5 5 0 010 7.07M13 12a1 1 0 11-2 0 1 1 0 012 0z" />
</svg>
</button>
</div>
</nav>

View File

@@ -0,0 +1,684 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { Send, adminmode, torrentstats, isAdmin, usersfortorrent, torctime, torrentinfo, fileSize, fsdirinfo, torrentfiles, fileviewpath, fileviewinfohash, istrntlocked, torrentinfostat } from './core';
import { slocation } from 'slocation';
import TorrentCard from './TorrentCard.svelte';
import type { DlObject } from './core';
import ProgStat from './ProgStat.svelte';
onMount(() => {
torrentinfo.set({} as DlObject);
Send({ command: 'listtorrentinfo', data1: infohash });
Send({ command: 'gettorrentinfo', data1: infohash });
Send({ command: 'istorrentlocked', data1: infohash });
});
onDestroy(() => {
Send({ command: 'stopstream' });
});
let infohash = $slocation.pathname?.split('/').reverse()[0];
let fileProgressOpen = false;
let browseFilesOpen = false;
let trntStatsOpen = false;
let trntUsersOpen = false;
let miscOpen = false;
let firsttimetis = true;
let trackerfilestring = '';
let trckrfileinput: HTMLInputElement;
let readtracker = (e: Event) => {
trackerfilestring = '';
let f = (e.target as HTMLInputElement).files[0];
if (f.size > 20971520) {
alert('Error: Maximum Tracker File Size is 20MB');
return;
}
let reader = new FileReader();
reader.onload = (e) => {
trackerfilestring = btoa(e.target.result as string);
Send({
command: 'addtrackerstotorrent',
data1: infohash,
data2: trackerfilestring,
...($adminmode === true && { aop: 1 })
});
};
reader.readAsBinaryString(f);
(e.target as HTMLInputElement).value = null;
};
let fileProgressaction = () => {
if (fileProgressOpen === false) {
Send({
command: 'gettorrentfiles',
data1: infohash
});
fileProgressOpen = true;
} else {
fileProgressOpen = false;
}
};
let browseFilesaction = () => {
if (browseFilesOpen === false) {
Send({
command: 'getfsdirinfo',
data1: infohash
});
browseFilesOpen = true;
} else {
browseFilesOpen = false;
}
};
let trntStatsaction = () => {
if (trntStatsOpen === false) {
Send({
command: 'gettorrentstats',
data1: infohash
});
trntStatsOpen = true;
} else {
trntStatsOpen = false;
}
};
let uwottaction = () => {
if (trntUsersOpen === false) {
Send({
command: 'listusersfortorrent',
data1: infohash,
aop: 1
});
trntUsersOpen = true;
} else {
trntUsersOpen = false;
}
};
let miscaction = () => {
miscOpen = !miscOpen;
if (firsttimetis === true) {
Send({
command: 'gettorrentinfostat',
data1: infohash
});
firsttimetis = false;
}
};
</script>
<svelte:head>
<title>{$torrentinfo?.name} ({$torrentinfo?.infohash})</title>
</svelte:head>
<div class="mx-auto max-w-3xl ">
<TorrentCard state={$torrentinfo?.state} name={$torrentinfo?.name} infohash={$torrentinfo?.infohash} bytescompleted={$torrentinfo?.bytescompleted} bytesmissing={$torrentinfo?.bytesmissing} length={$torrentinfo?.length} seeding={$torrentinfo?.seeding} locked={$istrntlocked} isTorrentPage={true} />
<div class="bg-black grid grid-flow-col text-white rounded-lg m-3 p-2">
{#if $adminmode === false}
<div class=" text-center">
<button
type="button"
on:click={() => {
Send({
command: 'abandontorrent',
data1: infohash
});
slocation.goto('/');
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7a4 4 0 11-8 0 4 4 0 018 0zM9 14a6 6 0 00-6 6v1h12v-1a6 6 0 00-6-6zM21 12h-6" />
</svg>
<p class="text-gray-500 text-sm">Abandon</p>
</button>
</div>
{/if}
<div class=" text-center">
<a href="/api/torrent/{infohash}/?dl=tar" target="_blank" rel="noopener noreferrer" download>
<button type="button">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
</svg>
<p class="text-gray-500 text-sm">Tar</p>
</button>
</a>
</div>
<div class=" text-center">
<a href="/api/torrent/{infohash}/?dl=zip" target="_blank" rel="noopener noreferrer" download>
<button type="button">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" viewBox="0 0 20 20" fill="currentColor">
<path d="M4 3a2 2 0 100 4h12a2 2 0 100-4H4z" />
<path fill-rule="evenodd" d="M3 8h14v7a2 2 0 01-2 2H5a2 2 0 01-2-2V8zm5 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" clip-rule="evenodd" />
</svg>
<p class="text-gray-500 text-sm">Zip</p>
</button>
</a>
</div>
</div>
{#if $torrentinfo?.state === 'active' || $torrentinfo?.state === 'inactive'}
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus:appearance-none active:appearance-none focus-within:appearance-none focus:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={fileProgressaction}>
<p class="ml-3 font-medium truncate">File Progress</p>
</div>
{#if fileProgressOpen === true}
<div
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 noHL"
on:click={() => {
Send({
command: 'gettorrentfiles',
data1: infohash
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</div>
{/if}
<div class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL" on:click={fileProgressaction}>
{#if fileProgressOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</div>
</div>
<div class="flex flex-col">
{#if fileProgressOpen === true}
{#each $torrentfiles as file (file.path)}
<div class="text-gray-200 bg-secGray-900 px-3 py-3 rounded-md w-full my-1">
<div class="flex items-center justify-between flex-wrap py-1">
<div
class="w-0 flex-1 flex"
on:click={() => {
fileviewpath.set(file?.path);
fileviewinfohash.set(infohash);
slocation.goto('/file');
}}
>
<p class="font-medium truncate">
{file?.displaypath}
</p>
</div>
{#if file?.priority === 1}
<div
class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1"
on:click={() => {
Send({
command: 'stopfile',
data1: infohash,
data2: file?.path,
...($adminmode === true && {
aop: 1
})
});
setTimeout(() => {
Send({
command: 'gettorrentfiles',
data1: infohash
});
}, 1000);
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
{:else if file?.priority === 0}
<div
class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1"
on:click={() => {
Send({
command: 'startfile',
data1: infohash,
data2: file?.path,
...($adminmode === true && {
aop: 1
})
});
setTimeout(() => {
Send({
command: 'gettorrentfiles',
data1: infohash
});
}, 1000);
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
{/if}
</div>
<ProgStat bytescompleted={file?.bytescompleted} length={file?.length} offset={file?.offset} />
</div>
{/each}
{/if}
</div>
</div>
{/if}
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={browseFilesaction}>
<p class="ml-3 font-medium truncate">Browse Files</p>
</div>
{#if browseFilesOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({
command: 'getfsdirinfo',
data1: infohash
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={browseFilesaction}>
{#if browseFilesOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if browseFilesOpen === true}
{#each $fsdirinfo as file (file.path)}
<div class="text-gray-200 bg-gray-900 px-3 py-3 rounded-md w-full my-1">
<div class="flex flex-col justify-between flex-wrap py-1">
<div
class="w-full"
on:click={() => {
if (file?.isdir === true) {
Send({
command: 'getfsdirinfo',
data1: infohash,
data2: file?.path
});
} else if (file?.isdir === false) {
fileviewpath.set(file?.path);
fileviewinfohash.set(infohash);
slocation.goto('/file');
}
}}
>
<p class="font-medium break-all text-left">
{file?.name}
</p>
</div>
<div class="grid grid-flow-col">
<p class="py-2 font-extralight break-all">
{#if file?.isdir === false}{fileSize(file?.size)}{:else}Directory{/if}
</p>
<div class="flex flex-row justify-end gap-1 flex-wrap py-1">
{#if file?.isdir === true}
<a href="/api/torrent/{infohash}/{file?.path}/?dl=zip" target="_blank" rel="noopener noreferrer" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL" download>
<button type="button">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" viewBox="0 0 20 20" fill="currentColor">
<path d="M4 3a2 2 0 100 4h12a2 2 0 100-4H4z" />
<path fill-rule="evenodd" d="M3 8h14v7a2 2 0 01-2 2H5a2 2 0 01-2-2V8zm5 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" clip-rule="evenodd" />
</svg>
</button>
</a>
<a href="/api/torrent/{infohash}/{file?.path}/?dl=tar" target="_blank" rel="noopener noreferrer" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL" download>
<button type="button">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
</svg>
</button>
</a>
{/if}
{#if $torrentinfo?.state === 'removed'}
<button
type="button"
class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL"
on:click={() => {
Send({
command: 'deletefilepath',
data1: infohash,
data2: file?.path,
...($adminmode === true && {
aop: 1
})
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
{/if}
</div>
</div>
</div>
</div>
{/each}
{/if}
</div>
</div>
{#if $torrentinfo?.state === 'active' || $torrentinfo?.state === 'inactive' || $torrentinfo?.state === 'loading'}
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={trntStatsaction}>
<p class="ml-3 font-medium truncate">Stats</p>
</div>
{#if trntStatsOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({
command: 'gettorrentstats',
data1: infohash
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={trntStatsaction}>
{#if trntStatsOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if trntStatsOpen === true}
<div class="m-1 p-1 break-all">
Total Peers: {$torrentstats?.TotalPeers}
</div>
<div class="m-1 p-1 break-all">
Pending Peers: {$torrentstats?.PendingPeers}
</div>
<div class="m-1 p-1 break-all">
Active Peers: {$torrentstats?.ActivePeers}
</div>
<div class="m-1 p-1 break-all">
Connected Seeders: {$torrentstats?.ConnectedSeeders}
</div>
<div class="m-1 p-1 break-all">
Half Open Peers: {$torrentstats?.HalfOpenPeers}
</div>
<div class="m-1 p-1 break-all">
Written: {fileSize($torrentstats?.BytesWritten)}
</div>
<div class="m-1 p-1 break-all">
WrittenData: {fileSize($torrentstats?.BytesWrittenData)}
</div>
<div class="m-1 p-1 break-all">
Read: {fileSize($torrentstats?.BytesRead)}
</div>
<div class="m-1 p-1 break-all">
ReadData: {fileSize($torrentstats?.BytesReadData)}
</div>
<div class="m-1 p-1 break-all">
ReadUsefulData: {fileSize($torrentstats?.BytesReadUsefulData)}
</div>
<div class="m-1 p-1 break-all">
Seed Ratio: {($torrentstats?.BytesWrittenData / $torrentstats.BytesReadData).toLocaleString('en-US', {
maximumFractionDigits: 5,
minimumFractionDigits: 5
})}
</div>
<div class="m-1 p-1 break-all">
Chunks Written: {$torrentstats?.ChunksWritten}
</div>
<div class="m-1 p-1 break-all">
Chunks Read: {$torrentstats?.ChunksRead}
</div>
<div class="m-1 p-1 break-all">
Chunks Read Useful: {$torrentstats?.ChunksReadUseful}
</div>
<div class="m-1 p-1 break-all">
Chunks Read Wasted: {$torrentstats?.ChunksReadWasted}
</div>
<div class="m-1 p-1 break-all">
Metadata Chunks Read: {$torrentstats?.MetadataChunksRead}
</div>
<div class="m-1 p-1 break-all">
Piece Dirtied Good: {$torrentstats?.PiecesDirtiedGood}
</div>
<div class="m-1 p-1 break-all">
Piece Dirtied Bad: {$torrentstats?.PiecesDirtiedBad}
</div>
{/if}
</div>
</div>
{/if}
{#if $isAdmin === true}
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={uwottaction}>
<p class="ml-3 font-medium truncate">Users who Own this Torrent</p>
</div>
{#if trntUsersOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({
command: 'listusersfortorrent',
data1: infohash,
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={uwottaction}>
{#if trntUsersOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if trntUsersOpen === true}
{#each $usersfortorrent as eachuser (eachuser)}
<div class="text-gray-200 bg-secGray-900 px-3 py-3 rounded-md w-full my-1">
<div class="flex items-center justify-between flex-wrap py-1">
<div class="w-0 flex-1 flex">
<p class="font-medium break-all">
{eachuser}
</p>
</div>
<div
class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1"
on:click={() => {
Send({
command: 'abandontorrent',
data1: infohash,
data2: eachuser,
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
</div>
</div>
{/each}
{/if}
</div>
</div>
{/if}
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus:appearance-none active:appearance-none focus-within:appearance-none focus:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={miscaction}>
<p class="ml-3 font-medium truncate">Misc</p>
</div>
{#if miscOpen === true}
<div
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 noHL"
on:click={() => {
Send({
command: 'gettorrentinfostat',
data1: infohash
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</div>
{/if}
<div class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL" on:click={miscaction}>
{#if miscOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</div>
</div>
<div class="flex flex-col">
{#if miscOpen === true}
{#if $torrentinfo?.state === 'active' || $torrentinfo?.state === 'inactive' || $torrentinfo?.state === 'loading'}
<div class="m-1 p-1 break-all text-center">
Added at {$torctime.addedat}
</div>
<div class="m-1 p-1 break-all text-center">
{#if $torrentinfo?.state === 'active'}Started At {$torctime.startedat}{/if}
</div>
<label class="appearance-none">
<div class="text-gray-200 flex m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center">
<svg xmlns="http://www.w3.org/2000/svg" class="text-gray-400 h-6 w-6 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
</svg>
Add Trackers (List)
</div>
<input accept=".txt" bind:this={trckrfileinput} on:change={(e) => readtracker(e)} id="torrentfile" name="torrentfile" type="file" class="hidden" />
</label>
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'gettorrentmetainfo',
data1: infohash
});
}}>Download Torrent File</button
>
{/if}
{#if $isAdmin === true && $adminmode === true}
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'changedataload',
data1: infohash,
data2: 'upload',
data3: 'allow',
aop: 1
});
}}>Allow Data Upload</button
>
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'changedataload',
data1: infohash,
data2: 'upload',
data3: 'disallow',
aop: 1
});
}}>Disallow Data Upload</button
>
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'changedataload',
data1: infohash,
data2: 'download',
data3: 'allow',
aop: 1
});
}}>Allow Data Download</button
>
<button
class="m-2 bg-secGray-800 py-3 max-w-3xl rounded-md justify-center"
on:click={() => {
Send({
command: 'changedataload',
data1: infohash,
data2: 'download',
data3: 'disallow',
aop: 1
});
}}>Disallow Data Download</button
>
{/if}
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,225 @@
<script lang="ts">
import { fileSize, Send, adminmode } from './core';
import { slocation } from 'slocation';
export let state: string = '';
export let name: string | undefined = '';
export let infohash: string = '';
export let bytescompleted: number | undefined = 0;
export let bytesmissing: number | undefined = 0;
export let length: number | undefined = 0;
export let seeding: boolean | undefined = false;
export let isTorrentPage: boolean = false;
export let locked: boolean = false;
let progpercentage = 0;
let refresh = () => {
if (isTorrentPage === false) {
Send({
command: 'listtorrents'
});
} else if (isTorrentPage === true) {
Send({
command: 'listtorrentinfo',
data1: infohash
});
}
};
$: progpercentage = (bytescompleted / length) * 100;
</script>
<div class="bg-black text-gray-200 rounded-lg m-3">
<div class="px-3 py-5">
<div class="flex items-center space-x-3.5 sm:space-x-5 lg:space-x-3.5 xl:space-x-5">
<div class="min-w-0 flex-auto space-y-0.5">
<div class="text-gray-400 flex justify-between text-sm font-medium tabular-nums">
<div class="truncate">{infohash}</div>
<div>
{#if state === 'active' || state === 'inactive'}{#if seeding === true}(Seeding)
{/if}{fileSize(bytesmissing == null ? 0 : bytesmissing)} R.{/if}
</div>
</div>
{#if state !== 'removed'}
<h2
class="text-white text-base sm:text-xl lg:text-base xl:text-xl font-semibold break-all"
on:click={() => {
if (isTorrentPage === false) {
slocation.goto(`/torrent/${infohash}`);
}
}}
>
{name}
</h2>
{/if}
</div>
</div>
{#if state === 'active' || state === 'inactive'}
<div class="space-y-2 mt-1">
<div class="bg-secGray-900 rounded-full overflow-hidden">
<div class="bg-blue-700 h-1.5" style="width:{progpercentage ? progpercentage : 0}%" />
</div>
<div class="text-gray-500 dark:text-gray-400 flex justify-between text-sm font-medium tabular-nums">
<div>{fileSize(bytescompleted)} / {fileSize(length)}</div>
<div>
{progpercentage?.toLocaleString('en-US', {
maximumFractionDigits: 2,
minimumFractionDigits: 2
})} %
</div>
</div>
</div>
{/if}
</div>
<div class="bg-gradient-to-r from-black via-gray-900 to-black text-white py-2 px-1 grid grid-flow-col grid-cols-3 justify-items-center mt-1 rounded-b-lg">
{#if state === 'active' || state === 'loading' || state === 'inactive'}
<button
type="button"
class="grid"
on:click={() => {
Send({
command: 'removetorrent',
data1: infohash,
...($adminmode === true && { aop: 1 })
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-gray-500 text-sm">Remove</p>
</button>
{:else if state === 'removed'}
<button
type="button"
class="grid"
on:click={() => {
Send({
command: 'deletetorrent',
data1: infohash,
...($adminmode === true && { aop: 1 })
});
if (isTorrentPage === true) {
slocation.goto('/');
} else if (isTorrentPage === false) {
refresh();
Send({ command: 'gettorrents' });
}
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
<p class="text-gray-500 text-sm">Delete</p>
</button>
{/if}
{#if state === 'loading'}
<button type="button" class="grid">
<svg class="animate-spin h-6 w-6 mx-auto text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
<p class="text-gray-500 text-sm">Loading</p>
</button>
{:else if state === 'active'}
<button
type="button"
class="grid"
on:click={() => {
Send({
command: 'stoptorrent',
data1: infohash,
...($adminmode === true && { aop: 1 })
});
refresh();
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-gray-500 text-sm">Stop</p>
</button>
{:else if state === 'removed'}
<button
type="button"
class="grid"
on:click={() => {
Send({
command: 'addinfohash',
data1: infohash
});
refresh();
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-gray-500 text-sm">Add</p>
</button>
{:else if state === 'inactive'}
<button
type="button"
class="grid"
on:click={() => {
Send({
command: 'starttorrent',
data1: infohash,
...($adminmode === true && { aop: 1 })
});
refresh();
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-gray-500 text-sm">Start</p>
</button>
{/if}
{#if isTorrentPage === false}
<button
type="button"
class="grid"
on:click={() => {
slocation.goto(`/torrent/${infohash}`);
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
<p class="text-gray-500 text-sm">View</p>
</button>
{:else}
<button
type="button"
class="grid"
on:click={() => {
Send({
command: 'toggletorrentlock',
data1: infohash
});
setTimeout(() => {
Send({ command: 'istorrentlocked', data1: infohash });
}, 1000);
}}
>
{#if locked === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
<p class="text-gray-500 text-sm">Locked</p>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z" />
</svg>
<p class="text-gray-500 text-sm">Unlocked</p>
{/if}
</button>
{/if}
</div>
</div>

View File

@@ -0,0 +1,49 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { downloadslist, Send, adminmode, isAdmin, terrormsg } from './core';
import TorrentCard from './TorrentCard.svelte';
onMount(() => {
if ($adminmode === false) {
Send({ command: 'listtorrents' });
Send({ command: 'gettorrents' });
} else {
Send({ command: 'listalltorrents', aop: 1 });
Send({ command: 'getalltorrents', aop: 1 });
}
});
onDestroy(() => {
console.log('on destroy');
Send({ command: 'stopstream' });
});
let checam = (b: boolean) => {
b ? (Send({ command: 'listalltorrents', aop: 1 }), Send({ command: 'getalltorrents', aop: 1 })) : Send({ command: 'gettorrents' });
};
$: checam($adminmode);
</script>
<div class="mx-auto max-w-3xl ">
{#if $terrormsg?.has === false}
{#if $isAdmin === true && $adminmode === true}
<div class="grid grid-flow-col grid-cols-4 pr-2 bg-gray-800 my-2 appearance-none border border-gray-800 w-full">
<div class=" bg-gray-800 col-span-3 appearance-none w-full flex-grow px-3 py-2 border-none text-gray-300 focus:outline-none">Admin Mode</div>
<div class="flex items-center justify-end w-full my-2 mr-2">
<label for="dontstarttoggle" class="flex items-center cursor-pointer">
<div class="relative">
<input type="checkbox" class="rounded text-indigo-700 bg-gray-800 form-checkbox" bind:checked={$adminmode} />
</div>
</label>
</div>
</div>
{/if}
{#each $downloadslist?.data as dl (dl.infohash)}
<TorrentCard state={dl.state} name={dl?.name} infohash={dl.infohash} bytescompleted={dl?.bytescompleted} bytesmissing={dl?.bytesmissing} length={dl?.length} seeding={dl?.seeding} />
{/each}
{:else}
<p class="text-xl text-center text-red-400 font-sans">{$terrormsg?.msg}</p>
{/if}
</div>

View File

@@ -0,0 +1,37 @@
<script lang="ts">
import { slocation } from 'slocation';
import { onMount } from 'svelte';
import { torrentsforuser, Send, adminmode, isAdmin } from './core';
let username = $slocation.pathname?.split('/').reverse()[0];
onMount(() => {
if ($isAdmin === false) {
slocation.goto('/');
}
torrentsforuser.set([]);
adminmode.set(true);
Send({ command: 'listtorrentsforuser', data1: username, aop: 1 });
});
</script>
<div class="mx-auto max-w-3xl ">
{#if Array.isArray($torrentsforuser) && $torrentsforuser?.length}
{#each $torrentsforuser as trnt (trnt)}
<div
class="bg-gray-800 text-gray-200 px-3 py-5 rounded-lg m-3 noHL"
on:click={() => {
if (typeof trnt === 'string' && trnt?.length > 0) {
slocation.goto(`/torrent/${trnt}`);
}
}}
>
<div class="break-all mx-1 mb-1 font-bold">
{trnt}
</div>
</div>
{/each}
{:else}
<p class="text-xl text-center text-red-400 font-sans">User owns no Torrents</p>
{/if}
</div>

View File

@@ -0,0 +1,120 @@
<script lang="ts">
import { onMount } from 'svelte';
import { slocation } from 'slocation';
onMount(() => {
console.log('on mount');
oldselected = selected;
utchangeallowed = true;
});
import { Send } from './core';
export let username = '';
export let timestring = '';
export let selected: 'user' | 'disabled' | 'admin' = 'disabled';
let oldselected: 'user' | 'disabled' | 'admin' = 'disabled';
let usereditmode = false;
let newpw = '';
let utchangeallowed = false;
let updateuser = () => {
if (newpw?.length > 5) {
Send({
command: 'updatepw',
data1: username,
data2: newpw,
aop: 1
});
}
if (utchangeallowed === true) {
if (selected !== oldselected) {
Send({
command: 'changeusertype',
data1: username,
data2: selected,
aop: 1
});
} else {
alert('Same Usertype Selected');
}
}
};
</script>
<div class="text-gray-200 bg-gray-900 px-3 py-3 rounded-md w-full my-1">
<div class="flex flex-col justify-between flex-wrap py-1">
<div class="flex flex-row justify-between">
<div class="font-medium break-all text-left mx-1">{username}</div>
<div class="flex">
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL"
on:click={() => {
usereditmode = !usereditmode;
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
</svg>
</button>
<button
type="button"
class="flex p-2 rounded-md bg-red-900 focus:outline-none flex-shrink-0 mx-1 noHL"
on:click={() => {
Send({
command: 'removeuser',
data1: username,
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL"
on:click={() => {
slocation.goto(`/user/${username}`);
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
</button>
</div>
</div>
<p class="text-sm font-extralight truncate">Created at {timestring}</p>
</div>
{#if usereditmode === true}
<div class="flex mt-1">
<input id="changepw" type="text" bind:value={newpw} required class=" bg-gray-800 appearance-none rounded-md w-full flex-grow px-3 py-2 border-none placeholder-gray-500 text-gray-200 focus:outline-none sm:text-sm mx-1" placeholder="Enter New Password" />
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1 noHL"
on:click={() => {
Send({
command: 'revoketoken',
data1: username,
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
</svg>
</button>
<select class="bg-gray-800 text-gray-200 mx-1 rounded-md" bind:value={selected}>
<option value="user">User</option>
<option value="disabled">Disabled</option>
<option value="admin">Admin</option>
</select>
<button class="bg-indigo-700 text-white p-3 rounded-md" on:click={updateuser}>Update</button>
</div>
{/if}
</div>

View File

@@ -0,0 +1,273 @@
<script lang="ts">
import { Send, userconnlist, userlist, isAdmin } from './core';
import { slocation } from 'slocation';
import { onMount } from 'svelte';
import Useredit from './Useredit.svelte';
onMount(() => {
if ($isAdmin === false) {
slocation.goto('/');
}
});
let userconnlistOpen = false;
let manageUsersOpen = false;
let addUserOpen = false;
let newusername = '';
let newpassword = '';
let newusertype: 'user' | 'disabled' | 'admin' = 'user';
let pwbox: HTMLInputElement;
let pwvisible = false;
let toggleinput = () => {
pwvisible = !pwvisible;
pwbox.type = pwvisible ? 'text' : 'password';
};
let addUser = () => {
Send({
command: 'adduser',
data1: newusername,
data2: newpassword,
data3: newusertype,
aop: 1
});
};
let typenotostring = (t: number): 'user' | 'disabled' | 'admin' => {
switch (t) {
case 0:
return 'user';
case 1:
return 'admin';
case -1:
return 'disabled';
}
};
let userconnlistaction = () => {
if (userconnlistOpen === false) {
Send({
command: 'listuserconns',
aop: 1
});
userconnlistOpen = true;
} else {
userconnlistOpen = false;
}
};
let manageUsersaction = () => {
if (manageUsersOpen === false) {
Send({
command: 'getusers',
aop: 1
});
manageUsersOpen = true;
} else {
manageUsersOpen = false;
}
};
let useraddaction = () => {
if (addUserOpen === false) {
addUserOpen = true;
} else {
addUserOpen = false;
}
};
</script>
<div class="mx-auto max-w-3xl ">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={userconnlistaction}>
<p class="ml-3 font-medium truncate">User Connections</p>
</div>
{#if userconnlistOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({
command: 'listuserconns',
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={userconnlistaction}>
{#if userconnlistOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if userconnlistOpen === true}
{#each $userconnlist as eachuser (eachuser?.username)}
<div class="text-gray-200 bg-gray-900 px-1 py-3 rounded-md w-full my-1">
<div>
<div class="flex items-center justify-between flex-wrap py-1 mr-1">
<div class="w-0 flex-1 flex">
<p class="font-medium break-all mx-1">
{eachuser?.username}
{#if eachuser?.isadmin === true}(admin){/if}
</p>
</div>
<div
class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1"
on:click={() => {
Send({
command: 'kickuser',
data1: eachuser?.username,
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
</div>
</div>
<p class="text-sm font-extralight truncate mx-1">
Connected at {new Date(eachuser?.contime)?.toLocaleString()}
</p>
</div>
{/each}
{/if}
</div>
</div>
</div>
<div class="mx-auto max-w-3xl ">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={manageUsersaction}>
<p class="ml-3 font-medium truncate">Manage Users</p>
</div>
{#if manageUsersOpen === true}
<button
type="button"
class="flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0"
on:click={() => {
Send({
command: 'getusers',
aop: 1
});
}}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
{/if}
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={manageUsersaction}>
{#if manageUsersOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if manageUsersOpen === true}
{#each $userlist as eachuser (eachuser?.Username)}
<Useredit username={eachuser?.Username} selected={typenotostring(eachuser?.UserType)} timestring={new Date(eachuser?.CreatedAt)?.toLocaleString()} />
{/each}
{/if}
</div>
</div>
</div>
<div class="mx-auto max-w-3xl ">
<div class="bg-black grid grid-flow-row text-white rounded-lg m-3 p-2 cursor-pointer focus:outline-none focus-within:bg-black noHL">
<div class="flex items-center justify-between flex-wrap py-1 px-3">
<div class="w-0 flex-1 flex items-center" on:click={useraddaction}>
<p class="ml-3 font-medium truncate">Add User</p>
</div>
<button type="button" class="-mr-1 flex p-2 rounded-md bg-gray-800 focus:outline-none flex-shrink-0 mx-1" on:click={useraddaction}>
{#if addUserOpen === true}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
{:else}
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
{/if}
</button>
</div>
<div class="flex flex-col">
{#if addUserOpen === true}
<div class="mt-2">
<label for="username" class="sr-only">Username</label>
<input id="username" name="email" type="text" bind:value={newusername} required class="bg-gray-800 appearance-none rounded-md w-full px-3 py-2 border border-gray-800 placeholder-gray-500 text-gray-200 focus:outline-none" placeholder="Username" />
<label for="password" class="sr-only">Password</label>
<div class="flex bg-gray-800 rounded-md my-2 appearance-none border border-gray-800 w-full">
<input
id="password"
name="password"
type="password"
autocomplete="current-password"
bind:value={newpassword}
bind:this={pwbox}
required
class="bg-gray-800 appearance-none rounded-md w-full flex-grow px-3 py-2 border-none placeholder-gray-500 text-gray-200 focus:outline-none"
placeholder="Password"
/>
<button type="button" class="focus:outline-none focus:text-green-500" on:click={toggleinput}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-400 my-2 mx-2 flex-grow" fill="none" viewBox="0 0 24 24" stroke="currentColor">
{#if pwvisible}
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
/>
{:else}
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
{/if}
</svg>
</button>
</div>
<select class="bg-gray-800 rounded-md w-full flex-grow px-3 py-2 border-none placeholder-gray-500 text-gray-200 focus:outline-none" bind:value={newusertype}>
<option value="user">User</option>
<option value="disabled">Disabled</option>
<option value="admin">Admin</option>
</select>
<button type="button" on:click={addUser} class="w-full my-2 py-2 px-4 border-none text-sm font-medium rounded-md text-white bg-indigo-900 outline-none focus:outline-none">Add User</button>
</div>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,517 @@
import { writable, get } from 'svelte/store';
import type { Writable } from 'svelte/store';
import { slocation } from 'slocation';
export interface DlObject {
infohash: string;
name?: string;
bytescompleted?: number;
bytesmissing?: number;
length?: number;
state: string;
seeding?: boolean;
}
interface DlObject2 {
locked: boolean;
addedat: string;
startedat: string;
}
interface RespObject {
type: string;
state: string;
infohash?: string;
message: string;
}
interface FsFile {
name: string;
path: string;
size: number;
isdir: boolean;
}
interface TorrentFile {
bytescompleted: number;
displaypath: string;
length: number;
offset: number;
path: string;
priority: number;
}
interface DevInfo {
arch: string;
numbercpu: number;
cpumodel: string;
hostname: string;
platform: string;
os: string;
totalmem: number;
goversion: string;
startedat: string;
}
interface DevStats {
cpucycles: number;
diskfree: number;
diskpercent: number;
mempercent: number;
gomem: number;
gomemsys: number;
goroutines: number;
}
interface TorrentStats {
TotalPeers: number;
PendingPeers: number;
ActivePeers: number;
ConnectedSeeders: number;
HalfOpenPeers: number;
BytesWritten: number;
BytesWrittenData: number;
BytesRead: number;
BytesReadData: number;
BytesReadUsefulData: number;
ChunksWritten: number;
ChunksRead: number;
ChunksReadUseful: number;
ChunksReadWasted: number;
MetadataChunksRead: number;
PiecesDirtiedGood: number;
PiecesDirtiedBad: number;
}
interface UserConn {
username: string;
isadmin: boolean;
contime: string;
}
interface Userrepr {
Username: string;
Token: string;
UserType: number;
CreatedAt: string;
}
interface TorcSettings {
TUploadRateLimiter: number;
TDownloadRateLimiter: number;
DisableLocalCache: boolean;
OnlineCacheURL: string;
TrackerRefresh: number;
TrackerListURLs: string[];
DisAllowTrackersUser: boolean;
DisAllowTrackersCache: boolean;
GlobalSeedRatio: number;
SRRefresh: number;
DontRemoveCacheInfo: boolean;
}
interface DiskStats {
total: number;
free: number;
used: number;
usedPercent: number;
}
export let socket: WebSocket;
export const isSignedIn = writable(false);
export const isDisConnected = writable(false);
export const filepagediscon = writable(false);
export const dontstart = writable('false');
export const isAdmin = writable(false);
export const downloadslist: Writable<{ has: boolean; data: DlObject[] }> = writable({
has: false,
data: []
});
export const torrentinfo: Writable<DlObject> = writable({} as DlObject);
export const torrentinfostat: Writable<DlObject2> = writable({} as DlObject2);
export const istrntlocked: Writable<boolean> = writable(false);
export const resplist: Writable<{ has: boolean; data: RespObject[] }> = writable({
has: false,
data: []
});
export const torrentstats: Writable<TorrentStats> = writable({} as TorrentStats);
export const torcstatus: Writable<Object> = writable({});
export const machinfo: Writable<DevInfo> = writable({} as DevInfo);
export const machstats: Writable<DevStats> = writable({} as DevStats);
export const fsdirinfo: Writable<FsFile[]> = writable([]);
export const torrentfiles: Writable<TorrentFile[]> = writable([]);
export const fileviewpath: Writable<string> = writable('');
export const fileviewinfohash: Writable<string> = writable('');
export const fsfileinfo: Writable<FsFile> = writable({} as FsFile);
export const torrentfileinfo: Writable<TorrentFile> = writable({} as TorrentFile);
export const adminmode: Writable<boolean> = writable(false);
export const usersfortorrent: Writable<string[]> = writable([] as string[]);
export const torrentsforuser: Writable<string[]> = writable([] as string[]);
export const userconnlist: Writable<UserConn[]> = writable([] as UserConn[]);
export const userlist: Writable<Userrepr[]> = writable([] as Userrepr[]);
export const engconfig: Writable<TorcSettings> = writable({} as TorcSettings);
export const torctime: Writable<{ addedat: string; startedat: string }> = writable({ addedat: '', startedat: '' });
export const diskstats: Writable<DiskStats> = writable({} as DiskStats);
export const nooftrackersintrackerdb: Writable<number> = writable(0);
export const hasMachinfo: Writable<boolean> = writable(false);
export const terrormsg: Writable<{ has: boolean; msg: string }> = writable({ has: true, msg: '' });
export const versionstr: Writable<string> = writable('');
export const versionchecked: Writable<boolean> = writable(false);
let curobj: Location;
let un = '';
let pw = '';
let firsttimecon = true;
let wonopenfn = () => {
firsttimecon = false;
isDisConnected.set(false);
localStorage.getItem('exausertype') === 'admin' ? isAdmin.set(true) : isAdmin.set(false);
curobj = get(slocation);
if (curobj?.pathname === '/signin') {
slocation.goto('/');
}
};
let wonclosefn = () => {
isDisConnected.set(true);
};
let werrorfn = () => {
if (firsttimecon === false && location.pathname !== '/signin') {
alert('Error Connecting');
return;
}
try {
fetch('/api/auth', {
method: 'POST',
body: JSON.stringify({ data1: un, data2: pw })
})
.then((res) => {
if (res.status >= 200 && res.status <= 299) {
return res.json();
} else {
alert('Error Authenticating');
throw new Error('Error Authenticating');
}
})
.then((res) => {
localStorage.setItem('exasession', res?.session);
localStorage.setItem('exausertype', res?.usertype);
if (!(localStorage.getItem('dontstart') == undefined)) {
localStorage.setItem('dontstart', 'false');
} else {
dontstart.set(localStorage.getItem('dontstart'));
}
socket = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/api/socket');
socket.onopen = wonopenfn;
socket.onmessage = SocketHandler;
socket.onclose = wonclosefn;
socket.onerror = werrorfn;
isSignedIn.set(true);
});
} catch (err) {
console.log(err);
SignOut();
return;
}
};
export let Connect = () => {
un = localStorage.getItem('exausername');
pw = localStorage.getItem('exapassword');
if (un != '' && un != undefined && un != null) {
if (pw != '' && pw != undefined && pw != null) {
console.log('Signing In');
} else {
slocation.goto('/signin');
return;
}
} else {
slocation.goto('/signin');
return;
}
if (!(un.length > 5) || !(pw.length > 5)) {
alert('Invalid Credentials');
return;
}
if (socket != null || socket != undefined) {
socket?.close();
}
socket = new WebSocket((window.location.protocol === 'https:' ? 'wss://' : 'ws://') + window.location.host + '/api/socket');
socket.onopen = wonopenfn;
socket.onmessage = SocketHandler;
socket.onclose = wonclosefn;
socket.onerror = werrorfn;
};
export let SocketHandler = (event: MessageEvent) => {
console.log('On Message:', event.data);
let msg = JSON.parse(event.data);
console.log(msg);
switch (msg.type) {
case 'resp':
if (!(msg == null)) {
if (msg?.state === 'error' || msg?.state === 'success') {
alert(msg?.message);
}
let rl = get(resplist);
resplist.set({ has: true, data: [msg, ...rl?.data] as RespObject[] });
} else {
resplist.set({ has: false, data: [] as RespObject[] });
}
break;
case 'nfn':
if (!(msg == null)) {
let rl = get(resplist);
resplist.set({ has: true, data: [msg, ...rl?.data] as RespObject[] });
} else {
resplist.set({ has: false, data: [] as RespObject[] });
}
break;
case 'torrentstream':
if (!(msg.data == null)) {
terrormsg.set({ has: false, msg: '' });
downloadslist.set({ has: true, data: msg.data as DlObject[] });
} else {
terrormsg.set({ has: true, msg: 'No Torrents' });
downloadslist.set({ has: true, data: [] as DlObject[] });
}
break;
case 'torrentinfo':
if (!(msg.data == null)) {
terrormsg.set({ has: false, msg: '' });
torrentinfo.set({
infohash: msg.data?.infohash,
name: msg.data?.name,
bytescompleted: msg.data?.bytescompleted,
bytesmissing: msg.data?.bytesmissing,
length: msg.data?.length,
state: msg.data?.state,
seeding: msg.data?.seeding
} as DlObject);
} else {
terrormsg.set({ has: true, msg: 'No Torrent Info' });
torrentinfo.set({} as DlObject);
}
break;
case 'torrentinfostat':
if (!(msg.data == null)) {
torctime.set({ addedat: new Date(msg.data?.AddedAt)?.toLocaleString(), startedat: new Date(msg.data?.StartedAt)?.toLocaleString() });
} else {
torctime.set({ addedat: '', startedat: '' });
}
break;
case 'torrentstats':
console.log(msg);
if (!(msg.data == null)) {
torrentstats.set(msg.data as TorrentStats);
} else {
torrentstats.set({} as TorrentStats);
}
break;
case 'fsdirinfo':
console.log(msg);
if (!(msg.data == null)) {
fsdirinfo.set(msg.data as FsFile[]);
} else {
fsdirinfo.set([]);
}
break;
case 'torrentfiles':
console.log(msg);
if (!(msg.data == null)) {
torrentfiles.set(msg.data as TorrentFile[]);
} else {
torrentfiles.set([]);
}
break;
case 'torrentmetainfo':
const linkSource = `data:application/x-bittorrent;base64,${msg?.data}`;
const downloadLink = document.createElement('a');
downloadLink.href = linkSource;
downloadLink.download = `${msg?.infohash}.torrent`;
downloadLink.click();
break;
case 'torrentfileinfo':
console.log(msg);
if (!(msg.data == null)) {
torrentfileinfo.set(msg.data as TorrentFile);
} else {
torrentfileinfo.set({} as TorrentFile);
}
break;
case 'fsfileinfo':
console.log(msg);
if (!(msg.data == null)) {
fsfileinfo.set(msg.data as FsFile);
} else {
fsfileinfo.set({} as FsFile);
}
if (get(filepagediscon) === true) {
socket?.readyState === WebSocket.OPEN ? socket?.close() : console.log('socket already closed');
}
break;
case 'usersfortorrent':
console.log(msg);
if (!(msg.data == null)) {
usersfortorrent.set(msg.data as string[]);
} else {
usersfortorrent.set([]);
}
break;
case 'torrentsforuser':
console.log(msg);
if (!(msg.data == null)) {
torrentsforuser.set(msg.data as string[]);
} else {
torrentsforuser.set([]);
}
break;
case 'torcstatus':
console.log(msg);
if (!(msg.data == null)) {
torcstatus.set(msg.data as TorrentStats);
} else {
torcstatus.set({});
}
break;
case 'torrentlockstate':
console.log(msg);
if (!(msg.data == null)) {
istrntlocked.set(msg.data === true);
} else {
istrntlocked.set(false);
}
break;
case 'userconn':
console.log(msg);
if (!(msg.data == null)) {
userconnlist.set(msg.data as UserConn[]);
} else {
userconnlist.set([] as UserConn[]);
}
break;
case 'users':
console.log(msg);
if (!(msg.data == null)) {
userlist.set(msg.data as Userrepr[]);
} else {
userlist.set([] as Userrepr[]);
}
break;
case 'engconf':
console.log(msg);
if (!(msg.data == null)) {
engconfig.set(msg.data as TorcSettings);
} else {
engconfig.set({} as TorcSettings);
}
break;
case 'machinfo':
console.log(msg);
if (!(msg.data == null)) {
hasMachinfo.set(true);
machinfo.set(msg.data as DevInfo);
} else {
machinfo.set({} as DevInfo);
}
break;
case 'machstats':
console.log(msg);
if (!(msg.data == null)) {
machstats.set(msg.data as DevStats);
} else {
machstats.set({} as DevStats);
}
break;
case 'diskusage':
console.log(msg);
if (!(msg.data == null)) {
diskstats.set(msg.data as DiskStats);
} else {
diskstats.set({} as DiskStats);
}
break;
case 'version':
console.log(msg);
if (!(msg.data == null)) {
versionchecked.set(true);
versionstr.set(msg.data as string);
} else {
versionstr.set('');
}
break;
case 'nooftrackersintrackerdb':
console.log(msg);
if (!(msg.data == null)) {
nooftrackersintrackerdb.set(msg.data as number);
} else {
nooftrackersintrackerdb.set(0);
}
break;
}
};
export let SignOut = () => {
localStorage.removeItem('exausername');
localStorage.removeItem('exapassword');
localStorage.removeItem('exasession');
localStorage.removeItem('exausertype');
localStorage.removeItem('dontstart');
// Remove Cookies
document.cookie.split(';').forEach((c) => {
document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/;SameSite=Lax;');
});
isDisConnected.set(false);
slocation.goto('/signin');
};
export let Send = (value: any) => {
console.log('sending ', value);
if (socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(value));
}
};
export let fileSize = (b: number) => {
let u = 0,
s = 1024;
while (b >= s || -b >= s) {
b /= s;
u++;
}
return (u ? b.toFixed(3) + ' ' : b) + ' KMGTPEZY'[u] + 'B';
};
export let fileType = (filepath: string): string => {
let ext = filepath.split('.').pop();
let vidext = ['webm', 'mkv', 'flv', 'vob', 'ogv', 'ogg', 'rrc', 'gifv', 'mng', 'mov', 'avi', 'qt', 'wmv', 'yuv', 'rm', 'asf', 'amv', 'mp4', 'm4p', 'm4v', 'mpg', 'mp2', 'mpeg', 'mpe', 'mpv', 'm4v', 'svi', '3gp', '3g2', 'mxf', 'roq', 'nsv', 'flv', 'f4v', 'f4p', 'f4a', 'f4b'];
let audext = ['aac', 'aiff', 'ape', 'au', 'flac', 'gsm', 'it', 'm3u', 'm4a', 'mid', 'mod', 'mp3', 'mpa', 'pls', 'ra', 's3m', 'sid', 'wav', 'wma', 'xm'];
if (vidext.includes(ext)) {
return 'video';
} else if (audext.includes(ext)) {
return 'audio';
}
return 'unknown';
};

View File

@@ -0,0 +1,26 @@
const colors = require('tailwindcss/colors');
const { colors: defaultColors } = require('tailwindcss/defaultTheme');
module.exports = {
mode: 'jit',
purge: {
enabled: true,
content: ['./src/*.{html,js,svelte,ts}', './src/**/*.{html,js,svelte,ts}']
},
darkMode: 'media',
theme: {
colors: {
...defaultColors,
gray: colors.trueGray,
secGray: colors.gray
},
extend: {}
},
variants: {
extend: {}
},
plugins: [
require('@tailwindcss/forms')({
strategy: 'class'
})
]
};

View File

@@ -0,0 +1,9 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"include": ["src/**/*", "src/node_modules", "src/**/*.d.ts", "src/*", "src/**/*.svelte"],
"compilerOptions": {
"outDir": "tscheck",
"target": "ESNext",
"types": ["svelte"]
}
}

30
internal/web/web.go Normal file
View File

@@ -0,0 +1,30 @@
package web
import (
"embed"
"io/fs"
"net/http"
)
//go:embed build/*
var webUI embed.FS
type webFS struct {
Fs http.FileSystem
}
func (fs *webFS) Open(name string) (http.File, error) {
f, err := fs.Fs.Open(name)
if err != nil {
return fs.Fs.Open("index.html")
}
return f, err
}
// FrontEndHandler Provides Handler to Serve Frontend
var FrontEndHandler http.Handler
func init() {
contentStatic, _ := fs.Sub(fs.FS(webUI), "build")
FrontEndHandler = http.FileServer(&webFS{Fs: http.FS(contentStatic)})
}