Compare commits

...
29 Commits
Author SHA1 Message Date
death-claw 733f5c926e version bump 2024-04-20 22:34:47 +01:00
death-clawandGitHub 0012e3b8ca fixes #185 (#186) 2024-04-20 22:24:40 +01:00
death-claw 564033eb03 version bump 2024-04-19 21:38:26 +01:00
death-claw 776f996673 fixes #176
fixes #179
fixes #180
fixes #181
fixes #182
2024-04-19 21:38:06 +01:00
death-clawandGitHub 06942c70c8 Update README.md 2024-03-17 18:07:09 +01:00
death-clawandGitHub 0d95b97aee Update README.md 2024-03-17 18:03:28 +01:00
death-clawandGitHub e3598769cd screenshot 2024-03-17 18:02:32 +01:00
death-claw 331749ca91 fixes #171 2024-03-17 15:47:13 +01:00
death-claw e9b4ca24eb fixes #171 2024-03-17 15:33:02 +01:00
death-claw e5bbbd651f version bump 2024-03-17 15:19:14 +01:00
death-claw e7a2ed6e8b fixes #171 2024-03-17 15:19:00 +01:00
death-claw 2923cc350c fixes #171 2024-03-17 14:18:35 +01:00
death-clawandGitHub 53cdc8a4a1 fixes #171 (#174)
fixes #173
2024-03-17 13:53:57 +01:00
UncleRoger33andGitHub 592a6d44c3 Update README.md (#170)
- Updated direct download links for v5.4.0 in the downloads table.
- Formatted "HOME_FOLDER" description for Windows. Previous one was a bit confusing for basic users.
2024-02-29 20:49:48 +01:00
death-clawandGitHub dbf6e3436a fixes #139 (#169) 2024-02-28 15:42:57 +01:00
death-claw f934eb07fb fix build 2024-02-28 14:31:35 +01:00
death-claw ac3194ca6a version bump 2024-02-28 12:22:57 +01:00
death-clawandGitHub df89d332df fixes #167 (#168) 2024-02-28 12:14:13 +01:00
death-clawandGitHub 2d5dc9d5cc Merge pull request #166 from UncleRoger33/patch-1
Update README.md
2024-02-26 11:15:03 +01:00
death-clawandGitHub abe5a42050 Update README.md
Update minimum requirements for Java
2024-02-26 11:13:57 +01:00
UncleRoger33andGitHub ed01b837e5 Update README.md
Added direct download links from Releases page.
2024-02-26 10:01:12 +03:00
death-claw ed9b26b4ef fixes #165 2024-02-25 17:23:07 +01:00
death-clawandGitHub 37b54d555b Create LICENSE 2024-02-24 00:04:44 +01:00
death-claw 0b9c78a44d bug fix 2024-02-22 23:54:57 +01:00
death-claw 6d9aa4c350 version bump 2024-02-22 23:28:14 +01:00
death-clawandGitHub d1c8a658e4 Merge pull request #164
* fixes #48
2024-02-22 21:13:24 +01:00
death-clawandGitHub c91d906759 Merge pull request #160 from twwat/main
Added viper.to to proxies list
2024-01-31 13:01:11 +01:00
twwatandGitHub 673a04b173 Merge pull request #1 from twwat/twat-patch-1
Update proxies.json
2024-01-28 10:58:25 -05:00
twwatandGitHub d5a3ec8af1 Update proxies.json
Added viper.to to proxies list
2024-01-28 10:55:05 -05:00
203 changed files with 9279 additions and 3424 deletions
+674
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>.
+17 -17
View File
@@ -3,16 +3,25 @@
This is my spin for a cross-platform gallery ripper for [vipergirls.to](https://vipergirls.to).
![1Jw0oq8h_o](https://github.com/UncleRoger33/vripper-project/assets/66418211/80b44389-7620-4e05-8696-4b62fa626b1b)
![GitHub Image](/image.png)
## Requirements
Direct access to vipergirls.to (or one of its [alternative domains](https://vipergirls.to/threads/5887340)), consider using a VPN otherwise.
## Installing VRipper
<img src="https://github.com/stashapp/stash/raw/develop/docs/readme_assets/windows_logo.svg" width="100%" height="75"> Windows | <img src="https://github.com/stashapp/stash/raw/develop/docs/readme_assets/mac_logo.svg" width="100%" height="75"> macOS | <img src="https://github.com/stashapp/stash/raw/develop/docs/readme_assets/linux_logo.svg" width="100%" height="75"> Linux | <img src="https://images.vexels.com/media/users/3/166401/isolated/preview/b82aa7ac3f736dd78570dd3fa3fa9e24-java-programming-language-icon-by-vexels.png" width="100%" height="75"> Java
:---:|:---:|:---:|:---:
[Installer (EXE)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-windows-installer-5.5.0.exe) <br /> [Installer (MSI)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-windows-installer-5.5.0.msi) <br /> [Portable (ZIP)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-windows-portable-5.5.0.zip) | [Installer (DMG)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-macos-5.5.0.dmg) <br /> [Installer (PKG)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-macos-5.5.0.pkg) <br /> [Portable (ZIP)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-macos-portable-5.5.0.zip) | [Linux (amd64) (DEB)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-linux-5.5.0_amd64.deb) <br /> [Linux (x86_64) (RPM)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-linux-5.5.0.x86_64.rpm) <br /> [Portable (ZIP)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-linux-portable-5.5.0.zip) | [Java GUI (noarch)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-noarch-gui-5.5.0.jar) <br /> [Java Web (noarch)](https://github.com/death-claw/vripper-project/releases/download/5.5.0/vripper-noarch-web-5.5.0.jar)
Source code and previous versions are available on the [Releases page](https://github.com/death-claw/vripper-project/releases).
Application data (application logs, settings and persisted data) is stored in `C:\USERS\<your Windows username>\vripper (Windows)` or `HOME_FOLDER/.config/vripper (Linux and macOS)`
## Supported Image Hosts
The following hosts are supported:
* acidimg.cc
* imagetwist.com
* imagezilla.com
@@ -29,17 +38,8 @@ The following hosts are supported:
* pixroute.to
* vipr.im
## Installation
Download the latest version from the Release page and execute the installer depending on your Operating System
Application data (application logs, settings and persisted data) is stored in
HOME_FOLDER/vripper (Windows)
HOME_FOLDER/.config/vripper (Linux and macOS)
## Instructions for Jar
You need Java 17+, you can download from https://adoptium.net/
## Instructions to run from Jar file
You need Java 21+, you can download from https://adoptium.net/
Download the latest jar file from the Release page, open a command prompt and run the jar file using the following command
@@ -56,16 +56,16 @@ Application data (application logs, settings and persisted data) is stored in th
## How to build
You need JDK 17 and a recent version of maven 3.6.1+
You need JDK 21 and a recent version of maven 3.8.x+
To build run the following:
To build, run the following command:
mvn clean install
Build artifact is located under
vripper-project\vripper-gui\target\vripper-gui-{{version}}.jar
vripper-project\vripper-gui\target\vripper-gui-{{version}}-jar-with-dependencies.jar
Copy the artifact into any other folder and run:
java -jar vripper-gui-{{version}}.jar
java -jar vripper-gui-{{version}}-jar-with-dependencies.jar
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
--input jar
--main-jar vripper-gui.jar
--add-modules java.base,java.desktop,java.sql,jdk.unsupported,jdk.crypto.ec,java.security.jgss
--add-modules java.base,java.desktop,java.sql,jdk.unsupported,jdk.crypto.ec,java.security.jgss,java.net.http
--jlink-options "--strip-native-commands --strip-debug --no-man-pages --no-header-files --compress=zip-6"
--name VRipper
--description "Image ripper tool for vipergirls"
+206 -177
View File
@@ -1,180 +1,209 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.vripper</groupId>
<artifactId>vripper-project</artifactId>
<packaging>pom</packaging>
<version>${revision}</version>
<properties>
<java.version>21</java.version>
<kotlin.version>1.9.20</kotlin.version>
<maven.deploy.skip>false</maven.deploy.skip>
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<revision>5.2.0</revision>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<updatePomFile>true</updatePomFile>
<flattenMode>resolveCiFriendliesOnly</flattenMode>
</configuration>
<executions>
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<modules>
<module>vripper-core</module>
<module>vripper-web-ui</module>
<module>vripper-web</module>
<module>vripper-gui</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<artifactId>logback-classic</artifactId>
<groupId>ch.qos.logback</groupId>
<version>1.4.12</version>
</dependency>
<dependency>
<artifactId>kotlin-stdlib</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core-jvm</artifactId>
<version>1.7.3</version>
</dependency>
<dependency>
<groupId>org.jetbrains.exposed</groupId>
<artifactId>exposed-jdbc</artifactId>
<version>0.41.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains.exposed</groupId>
<artifactId>exposed-java-time</artifactId>
<version>0.41.1</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>io.insert-koin</groupId>
<artifactId>koin-core-jvm</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<artifactId>jackson-module-kotlin</artifactId>
<groupId>com.fasterxml.jackson.module</groupId>
<version>2.15.2</version>
</dependency>
<dependency>
<artifactId>h2</artifactId>
<groupId>com.h2database</groupId>
<version>2.2.224</version>
</dependency>
<dependency>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents</groupId>
<version>4.5.14</version>
</dependency>
<dependency>
<artifactId>htmlcleaner</artifactId>
<groupId>net.sourceforge.htmlcleaner</groupId>
<version>2.26</version>
</dependency>
<dependency>
<artifactId>failsafe</artifactId>
<groupId>net.jodah</groupId>
<version>2.4.4</version>
</dependency>
<dependency>
<artifactId>caffeine</artifactId>
<groupId>com.github.ben-manes.caffeine</groupId>
<version>3.1.8</version>
</dependency>
<dependency>
<artifactId>jackson-databind</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.13.0</version>
</dependency>
<dependency>
<artifactId>kotlin-reflect</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<artifactId>jcl-over-slf4j</artifactId>
<groupId>org.slf4j</groupId>
<version>1.7.32</version>
</dependency>
<dependency>
<artifactId>httpclient5</artifactId>
<groupId>org.apache.httpcomponents.client5</groupId>
<version>5.2.1</version>
</dependency>
<dependency>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
<version>1.16.0</version>
</dependency>
<dependency>
<artifactId>liquibase-core</artifactId>
<groupId>org.liquibase</groupId>
<version>4.24.0</version>
</dependency>
<dependency>
<artifactId>liquibase-slf4j</artifactId>
<groupId>com.mattbertolini</groupId>
<version>5.0.0</version>
</dependency>
</dependencies>
</dependencyManagement>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.vripper</groupId>
<artifactId>vripper-project</artifactId>
<packaging>pom</packaging>
<version>${revision}</version>
<properties>
<java.version>21</java.version>
<maven.deploy.skip>false</maven.deploy.skip>
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<revision>5.7.0</revision>
<kotlin.version>1.9.22</kotlin.version>
<slf4j.version>2.0.12</slf4j.version>
<logback.version>1.5.0</logback.version>
<kotlinx-coroutines.version>1.8.0</kotlinx-coroutines.version>
<exposed.version>0.47.0</exposed.version>
<snakeyaml.version>2.0</snakeyaml.version>
<koin.version>3.5.3</koin.version>
<h2.version>2.2.224</h2.version>
<htmlcleaner.version>2.29</htmlcleaner.version>
<failsafe.version>2.4.4</failsafe.version>
<caffeine.version>3.1.8</caffeine.version>
<jna-platform.version>5.14.0</jna-platform.version>
<kotlinx-serialization-json.version>1.6.2</kotlinx-serialization-json.version>
<httpclient5.version>5.3.1</httpclient5.version>
<commons-codec.version>1.16.1</commons-codec.version>
<liquibase-core.version>4.26.0</liquibase-core.version>
<liquibase-slf4j.version>5.0.0</liquibase-slf4j.version>
<grpc.kotlin.version>1.4.1</grpc.kotlin.version>
<java.grpc.version>1.62.2</java.grpc.version>
<protobuf.version>3.25.3</protobuf.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<updatePomFile>true</updatePomFile>
<flattenMode>resolveCiFriendliesOnly</flattenMode>
</configuration>
<executions>
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<modules>
<module>vripper-core</module>
<module>vripper-web-ui</module>
<module>vripper-web</module>
<module>vripper-gui</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<artifactId>logback-classic</artifactId>
<groupId>ch.qos.logback</groupId>
<version>${logback.version}</version>
</dependency>
<dependency>
<artifactId>logback-core</artifactId>
<groupId>ch.qos.logback</groupId>
<version>${logback.version}</version>
</dependency>
<dependency>
<artifactId>kotlin-stdlib</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core-jvm</artifactId>
<version>${kotlinx-coroutines.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-javafx</artifactId>
<version>${kotlinx-coroutines.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.exposed</groupId>
<artifactId>exposed-jdbc</artifactId>
<version>${exposed.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.exposed</groupId>
<artifactId>exposed-java-time</artifactId>
<version>${exposed.version}</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>io.insert-koin</groupId>
<artifactId>koin-core-jvm</artifactId>
<version>${koin.version}</version>
</dependency>
<dependency>
<artifactId>h2</artifactId>
<groupId>com.h2database</groupId>
<version>${h2.version}</version>
</dependency>
<dependency>
<artifactId>htmlcleaner</artifactId>
<groupId>net.sourceforge.htmlcleaner</groupId>
<version>${htmlcleaner.version}</version>
</dependency>
<dependency>
<artifactId>failsafe</artifactId>
<groupId>net.jodah</groupId>
<version>${failsafe.version}</version>
</dependency>
<dependency>
<artifactId>caffeine</artifactId>
<groupId>com.github.ben-manes.caffeine</groupId>
<version>${caffeine.version}</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>${jna-platform.version}</version>
</dependency>
<dependency>
<artifactId>kotlin-reflect</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-serialization-json</artifactId>
<version>${kotlinx-serialization-json.version}</version>
</dependency>
<dependency>
<artifactId>jcl-over-slf4j</artifactId>
<groupId>org.slf4j</groupId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<artifactId>httpclient5</artifactId>
<groupId>org.apache.httpcomponents.client5</groupId>
<version>${httpclient5.version}</version>
</dependency>
<dependency>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<artifactId>liquibase-core</artifactId>
<groupId>org.liquibase</groupId>
<version>${liquibase-core.version}</version>
</dependency>
<dependency>
<artifactId>liquibase-slf4j</artifactId>
<groupId>com.mattbertolini</groupId>
<version>${liquibase-slf4j.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-kotlin-stub</artifactId>
<version>${grpc.kotlin.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${java.grpc.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-kotlin</artifactId>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>${java.grpc.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
+108 -26
View File
@@ -15,10 +15,18 @@
<description>vripper-core</description>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<artifactId>logback-classic</artifactId>
<groupId>ch.qos.logback</groupId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<artifactId>kotlin-stdlib</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
@@ -27,10 +35,6 @@
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core-jvm</artifactId>
</dependency>
<dependency>
<artifactId>kotlin-reflect</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
</dependency>
<dependency>
<groupId>org.jetbrains.exposed</groupId>
<artifactId>exposed-jdbc</artifactId>
@@ -43,10 +47,6 @@
<groupId>io.insert-koin</groupId>
<artifactId>koin-core-jvm</artifactId>
</dependency>
<dependency>
<artifactId>jackson-module-kotlin</artifactId>
<groupId>com.fasterxml.jackson.module</groupId>
</dependency>
<dependency>
<artifactId>h2</artifactId>
<groupId>com.h2database</groupId>
@@ -71,18 +71,6 @@
<artifactId>caffeine</artifactId>
<groupId>com.github.ben-manes.caffeine</groupId>
</dependency>
<dependency>
<artifactId>jackson-databind</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
@@ -101,14 +89,41 @@
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-serialization-json</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-kotlin-stub</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-kotlin</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>version</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>version</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
@@ -121,11 +136,78 @@
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>1.8</jvmTarget>
<compilerPlugins>
<plugin>kotlinx-serialization</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-serialization</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.7.1</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>detect</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
<configuration>
<sourceDirs>
<source>src/main/kotlin</source>
<source>target/generated-sources/annotations</source>
</sourceDirs>
<protocArtifact>
com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>
io.grpc:protoc-gen-grpc-java:${java.grpc.version}:exe:${os.detected.classifier}
</pluginArtifact>
<protocPlugins>
<protocPlugin>
<id>grpc-kotlin</id>
<groupId>io.grpc</groupId>
<artifactId>protoc-gen-grpc-kotlin</artifactId>
<version>${grpc.kotlin.version}</version>
<classifier>jdk8</classifier>
<mainClass>io.grpc.kotlin.generator.GeneratorRunner</mainClass>
</protocPlugin>
</protocPlugins>
</configuration>
</execution>
<execution>
<id>compile-kt</id>
<goals>
<goal>compile-custom</goal>
</goals>
<configuration>
<protocArtifact>
com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
</protocArtifact>
<outputDirectory>${project.build.directory}/generated-sources/protobuf/kotlin
</outputDirectory>
<pluginId>kotlin</pluginId>
</configuration>
</execution>
</executions>
@@ -6,6 +6,7 @@ import me.vripper.host.*
import me.vripper.repositories.*
import me.vripper.repositories.impl.*
import me.vripper.services.*
import org.koin.core.qualifier.named
import org.koin.dsl.bind
import org.koin.dsl.module
@@ -52,8 +53,17 @@ val coreModule = module {
single<DownloadSpeedService> {
DownloadSpeedService(get())
}
single<AppEndpointService> {
AppEndpointService(get(), get(), get(), get())
AppEndpointService(get(), get(), get(), get(), get())
}
single((named("localAppEndpointService"))) {
AppEndpointService(get(), get(), get(), get(), get())
} bind IAppEndpointService::class
single<MetadataService> {
MetadataService(get(), get(), get(), get())
}
single {
AcidimgHost(get(), get(), get())
@@ -1,13 +1,17 @@
package me.vripper.download
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Runnable
import me.vripper.entities.Image
import me.vripper.entities.LogEntry
import me.vripper.entities.Post
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import me.vripper.entities.ImageEntity
import me.vripper.entities.LogEntryEntity
import me.vripper.entities.PostEntity
import me.vripper.entities.domain.Status
import me.vripper.event.ErrorCountEvent
import me.vripper.event.EventBus
import me.vripper.event.QueueStateEvent
import me.vripper.event.StoppedEvent
import me.vripper.host.Host
import me.vripper.model.ErrorCount
import me.vripper.model.QueueState
@@ -37,8 +41,9 @@ class DownloadService(
private val pending: MutableMap<Byte, MutableList<ImageDownloadRunnable>> = mutableMapOf()
private val lock = ReentrantLock()
private val condition = lock.newCondition()
private val coroutineScope = CoroutineScope(SupervisorJob())
fun init() {
init {
Thread.ofVirtual().name("Download Loop").unstarted(Runnable {
val accepted: MutableList<ImageDownloadRunnable> = mutableListOf()
val candidates: MutableList<ImageDownloadRunnable> = mutableListOf()
@@ -46,14 +51,14 @@ class DownloadService(
lock.withLock {
candidates.addAll(getCandidates(candidateCount()))
candidates.forEach {
if (canRun(it.context.image.host)) {
if (canRun(it.context.imageEntity.host)) {
accepted.add(it)
running[it.context.image.host]!!.add(it)
log.debug("${it.context.image.url} accepted to run")
running[it.context.imageEntity.host]!!.add(it)
log.debug("${it.context.imageEntity.url} accepted to run")
}
}
accepted.forEach {
pending[it.context.image.host]?.remove(it)
pending[it.context.imageEntity.host]?.remove(it)
scheduleForDownload(it)
}
accepted.clear()
@@ -71,30 +76,35 @@ class DownloadService(
fun stop(postIds: List<Long> = emptyList()) {
if (postIds.isNotEmpty()) {
stopInternal(postIds)
coroutineScope.launch {
eventBus.publishEvent(StoppedEvent(postIds))
}
} else {
stopAll()
coroutineScope.launch {
eventBus.publishEvent(StoppedEvent(listOf(-1)))
}
}
}
fun restartAll(postIds: List<Post> = emptyList()) {
if (postIds.isNotEmpty()) {
restart(postIds.associateWith { dataTransaction.findByPostIdAndIsNotCompleted(it.postId) })
fun restartAll(postEntityIds: List<PostEntity> = emptyList()) {
if (postEntityIds.isNotEmpty()) {
restart(postEntityIds.associateWith { dataTransaction.findByPostIdAndIsNotCompleted(it.postId) })
} else {
restart(dataTransaction.findAllPosts()
.associateWith { dataTransaction.findByPostIdAndIsNotCompleted(it.postId) })
}
}
private fun restart(posts: Map<Post, List<Image>>) {
private fun restart(posts: Map<PostEntity, List<ImageEntity>>) {
lock.withLock {
val toProcess = mutableMapOf<Post, List<Image>>()
val toProcess = mutableMapOf<PostEntity, List<ImageEntity>>()
for ((post, images) in posts) {
if (images.isEmpty()) {
continue
}
if (isPending(post.postId)) {
log.warn("Cannot restart, jobs are currently running for post id $posts")
continue
}
toProcess[post] = images
@@ -142,11 +152,11 @@ class DownloadService(
}
private fun isPending(postId: Long): Boolean {
return pending.values.flatten().any { it.context.image.postId == postId }
return pending.values.flatten().any { it.context.imageEntity.postId == postId }
}
private fun isRunning(postId: Long): Boolean {
return running.values.flatten().any { it.context.image.postId == postId }
return running.values.flatten().any { it.context.imageEntity.postId == postId }
}
private fun stopAll() {
@@ -164,9 +174,10 @@ class DownloadService(
lock.withLock {
for (postId in postIds) {
pending.values.forEach { pending ->
pending.removeIf { it.context.image.postId == postId }
pending.removeIf { it.context.imageEntity.postId == postId }
}
running.values.flatten().filter { p: ImageDownloadRunnable -> p.context.image.postId == postId }
running.values.flatten()
.filter { p: ImageDownloadRunnable -> p.context.imageEntity.postId == postId }
.forEach { obj: ImageDownloadRunnable -> obj.stop() }
}
postIds.forEach {
@@ -202,7 +213,7 @@ class DownloadService(
val list: List<ImageDownloadRunnable> =
pending[host]!!.sortedWith(Comparator.comparingInt<ImageDownloadRunnable> { it.postRank }
.thenComparingInt { it.context.image.index })
.thenComparingInt { it.context.imageEntity.index })
for (imageDownloadRunnable in list) {
val count = hostIntegerMap[host] ?: 0
@@ -218,41 +229,47 @@ class DownloadService(
}
private fun scheduleForDownload(imageDownloadRunnable: ImageDownloadRunnable) {
log.debug("Scheduling a job for ${imageDownloadRunnable.context.image.url}")
log.debug("Scheduling a job for ${imageDownloadRunnable.context.imageEntity.url}")
CompletableFuture.runAsync({
eventBus.publishEvent(QueueStateEvent(QueueState(runningCount(), pendingCount())))
coroutineScope.launch {
eventBus.publishEvent(QueueStateEvent(QueueState(runningCount(), pendingCount())))
}
Failsafe.with<Any, RetryPolicy<Any>>(retryPolicyService.buildRetryPolicyForDownload())
.onFailure {
try {
dataTransaction.saveLog(
LogEntry(
type = LogEntry.Type.DOWNLOAD,
status = LogEntry.Status.ERROR,
message = "Failed to download ${imageDownloadRunnable.context.image.url}\n ${it.failure.formatToString()}"
LogEntryEntity(
type = LogEntryEntity.Type.DOWNLOAD,
status = LogEntryEntity.Status.ERROR,
message = "Failed to download ${imageDownloadRunnable.context.imageEntity.url}\n ${it.failure.formatToString()}"
)
)
} catch (exp: Exception) {
log.error("Failed to save event", exp)
}
log.error(
"Failed to download ${imageDownloadRunnable.context.image.url} after ${it.attemptCount} tries",
"Failed to download ${imageDownloadRunnable.context.imageEntity.url} after ${it.attemptCount} tries",
it.failure
)
val image = imageDownloadRunnable.context.image
val image = imageDownloadRunnable.context.imageEntity
image.status = Status.ERROR
dataTransaction.updateImage(image)
}.onComplete {
afterJobFinish(imageDownloadRunnable)
eventBus.publishEvent(
QueueStateEvent(
QueueState(
runningCount(), pendingCount()
coroutineScope.launch {
eventBus.publishEvent(
QueueStateEvent(
QueueState(
runningCount(), pendingCount()
)
)
)
)
eventBus.publishEvent(ErrorCountEvent(ErrorCount(dataTransaction.countImagesInError())))
}
coroutineScope.launch {
eventBus.publishEvent(ErrorCountEvent(ErrorCount(dataTransaction.countImagesInError())))
}
log.debug(
"Finished downloading ${imageDownloadRunnable.context.image.url}"
"Finished downloading ${imageDownloadRunnable.context.imageEntity.url}"
)
}.run(imageDownloadRunnable::run)
}, GLOBAL_EXECUTOR)
@@ -260,7 +277,7 @@ class DownloadService(
private fun afterJobFinish(imageDownloadRunnable: ImageDownloadRunnable) {
lock.withLock {
val image = imageDownloadRunnable.context.image
val image = imageDownloadRunnable.context.imageEntity
running[image.host]!!.remove(imageDownloadRunnable)
if (!isPending(image.postId) && !isRunning(
image.postId
@@ -1,17 +1,17 @@
package me.vripper.download
import me.vripper.entities.Image
import me.vripper.entities.ImageEntity
import me.vripper.model.Settings
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase
import org.apache.hc.client5.http.cookie.BasicCookieStore
import org.apache.hc.client5.http.protocol.HttpClientContext
import org.koin.core.component.KoinComponent
class ImageDownloadContext(val image: Image, val settings: Settings) : KoinComponent {
class ImageDownloadContext(val imageEntity: ImageEntity, val settings: Settings) : KoinComponent {
val httpContext: HttpClientContext =
HttpClientContext.create().apply { cookieStore = BasicCookieStore() }
val requests = mutableListOf<HttpUriRequestBase>()
val postId = image.postIdRef
val postId = imageEntity.postIdRef
var stopped = false
}
@@ -1,7 +1,7 @@
package me.vripper.download
import kotlinx.coroutines.*
import me.vripper.entities.Image
import me.vripper.entities.ImageEntity
import me.vripper.entities.domain.Status
import me.vripper.exception.DownloadException
import me.vripper.exception.HostException
@@ -10,8 +10,9 @@ import me.vripper.host.Host
import me.vripper.host.ImageMimeType
import me.vripper.model.Settings
import me.vripper.services.*
import me.vripper.utilities.PathUtils
import me.vripper.utilities.PathUtils.getExtension
import me.vripper.utilities.PathUtils.getFileNameWithoutExtension
import me.vripper.utilities.PathUtils.sanitize
import net.jodah.failsafe.function.CheckedRunnable
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
@@ -24,14 +25,14 @@ import kotlin.io.path.Path
import kotlin.io.path.pathString
class ImageDownloadRunnable(
private val image: Image, val postRank: Int, private val settings: Settings
private val imageEntity: ImageEntity, val postRank: Int, private val settings: Settings
) : KoinComponent, CheckedRunnable {
private val log by me.vripper.delegate.LoggerDelegate()
private val dataTransaction: DataTransaction by inject()
private val hosts: List<Host> = getKoin().getAll()
val context: ImageDownloadContext = ImageDownloadContext(image, settings)
val context: ImageDownloadContext = ImageDownloadContext(imageEntity, settings)
private var stopped: Boolean
get() = context.stopped
set(value) {
@@ -41,47 +42,43 @@ class ImageDownloadRunnable(
@Throws(DownloadException::class)
fun download() {
try {
image.status = Status.DOWNLOADING
image.downloaded = 0
dataTransaction.updateImage(image)
synchronized(image.postId.toString().intern()) {
imageEntity.status = Status.DOWNLOADING
imageEntity.downloaded = 0
dataTransaction.updateImage(imageEntity)
synchronized(imageEntity.postId.toString().intern()) {
val post = dataTransaction.findPostById(context.postId).orElseThrow()
if (post.status != Status.DOWNLOADING) {
post.status = Status.DOWNLOADING
dataTransaction.updatePost(post)
}
}
log.debug("Getting image url and name from ${image.url} using ${image.host}")
val host = hosts.first { it.isSupported(image.url) }
val downloadedImage = host.downloadInternal(image.url, context)
log.debug("Resolved name for ${image.url}: ${downloadedImage.name}")
log.debug("Downloaded image {} to {}", image.url, downloadedImage.path)
val sanitizedFileName = PathUtils.sanitize(downloadedImage.name)
log.debug(
"Sanitizing image name from ${downloadedImage.name} to $sanitizedFileName"
)
synchronized(image.postId.toString().intern()) {
log.debug("Getting image url and name from ${imageEntity.url} using ${imageEntity.host}")
val host = hosts.first { it.isSupported(imageEntity.url) }
val downloadedImage = host.downloadInternal(imageEntity.url, context)
log.debug("Resolved name for ${imageEntity.url}: ${downloadedImage.name}")
log.debug("Downloaded image {} to {}", imageEntity.url, downloadedImage.path)
synchronized(imageEntity.postId.toString().intern()) {
val post = dataTransaction.findPostById(context.postId).orElseThrow()
val downloadDirectory = Path(post.downloadDirectory, post.folderName).pathString
checkImageTypeAndRename(
downloadDirectory, downloadedImage, image.index
downloadDirectory, downloadedImage, imageEntity.index
)
if (image.downloaded == image.size && image.size > 0) {
image.status = Status.FINISHED
if (imageEntity.downloaded == imageEntity.size && imageEntity.size > 0) {
imageEntity.status = Status.FINISHED
post.done += 1
post.downloaded += image.size
post.downloaded += imageEntity.size
dataTransaction.updatePost(post)
} else {
image.status = Status.ERROR
imageEntity.status = Status.ERROR
}
dataTransaction.updateImage(image)
dataTransaction.updateImage(imageEntity)
}
} catch (e: Exception) {
if (stopped) {
return
}
image.status = Status.ERROR
dataTransaction.updateImage(image)
imageEntity.status = Status.ERROR
dataTransaction.updateImage(imageEntity)
throw DownloadException(e)
}
}
@@ -91,6 +88,7 @@ class ImageDownloadRunnable(
downloadDirectory: String, downloadedImage: DownloadedImage, index: Int
) {
val existingExtension = getExtension(downloadedImage.name).lowercase()
val fileNameWithoutExtension = getFileNameWithoutExtension(downloadedImage.name)
val extension = when (downloadedImage.type) {
ImageMimeType.IMAGE_BMP -> "BMP"
ImageMimeType.IMAGE_GIF -> "GIF"
@@ -99,27 +97,28 @@ class ImageDownloadRunnable(
ImageMimeType.IMAGE_WEBP -> "WEBP"
}
val filename =
if (existingExtension.isBlank()) "${downloadedImage.name}.$extension" else downloadedImage.name
if (existingExtension.isBlank()) "${sanitize(downloadedImage.name)}.$extension" else "${
sanitize(
fileNameWithoutExtension
)
}.$extension"
try {
val downloadDestinationFolder = Path.of(downloadDirectory)
Files.createDirectories(downloadDestinationFolder)
val image = downloadDestinationFolder.resolve(
"${
if (settings.downloadSettings.forceOrder) String.format(
"%03d_", index + 1
) else ""
}$filename"
)
Files.copy(downloadedImage.path, image, StandardCopyOption.REPLACE_EXISTING)
val finalFilename = "${
if (settings.downloadSettings.forceOrder) String.format(
"%03d_", index + 1
) else ""
}$filename"
imageEntity.filename = finalFilename
val imageDownloadPath = downloadDestinationFolder.resolve(finalFilename)
Files.copy(downloadedImage.path, imageDownloadPath, StandardCopyOption.REPLACE_EXISTING)
} catch (e: Exception) {
throw HostException("Failed to rename the image", e)
} finally {
try {
Files.delete(downloadedImage.path)
} catch (e: IOException) {
log.warn(
"Failed to delete temporary file ${downloadedImage.path}"
)
} catch (_: IOException) {
}
}
}
@@ -136,11 +135,11 @@ class ImageDownloadRunnable(
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that = other as ImageDownloadRunnable
return image.id == that.image.id
return imageEntity.id == that.imageEntity.id
}
override fun hashCode(): Int {
return Objects.hash(image.id)
return Objects.hash(imageEntity.id)
}
fun stop() {
@@ -2,7 +2,7 @@ package me.vripper.entities
import me.vripper.entities.domain.Status
data class Image(
data class ImageEntity(
val id: Long = -1,
val postId: Long,
val url: String,
@@ -13,12 +13,13 @@ data class Image(
var size: Long = -1,
var downloaded: Long = 0,
var status: Status = Status.STOPPED,
var filename: String = "",
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Image
other as ImageEntity
if (url != other.url) return false
@@ -1,13 +1,12 @@
package me.vripper.entities
import com.fasterxml.jackson.annotation.JsonFormat
import java.time.LocalDateTime
data class LogEntry(
data class LogEntryEntity(
val id: Long = -1,
val type: Type,
val status: Status,
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") val time: LocalDateTime = LocalDateTime.now(),
val time: LocalDateTime = LocalDateTime.now(),
val message: String,
) {
@@ -1,19 +0,0 @@
package me.vripper.entities
class Metadata {
var postIdRef: Long? = null
var postId: String? = null
var postedBy: String? = null
var resolvedNames = emptyList<String>()
companion object {
fun from(metadata: Metadata): Metadata {
val copy = Metadata()
copy.postIdRef = metadata.postIdRef
copy.postId = metadata.postId
copy.postedBy = metadata.postedBy
copy.resolvedNames = metadata.resolvedNames
return copy
}
}
}
@@ -0,0 +1,11 @@
package me.vripper.entities
import kotlinx.serialization.Serializable
data class MetadataEntity(val postId: Long, val data: Data) {
@Serializable
data class Data(
val postedBy: String,
val resolvedNames: List<String>
)
}
@@ -1,12 +1,9 @@
package me.vripper.entities
import com.fasterxml.jackson.annotation.JsonFormat
import me.vripper.entities.domain.Status
import java.time.LocalDateTime
import kotlin.io.path.Path
import kotlin.io.path.pathString
data class Post(
data class PostEntity(
val id: Long = -1,
val postTitle: String,
val threadTitle: String,
@@ -18,7 +15,7 @@ data class Post(
val total: Int,
val hosts: Set<String>,
val downloadDirectory: String,
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") val addedOn: LocalDateTime = LocalDateTime.now(),
val addedOn: LocalDateTime = LocalDateTime.now(),
var folderName: String,
var status: Status = Status.STOPPED,
var done: Int = 0,
@@ -27,15 +24,11 @@ data class Post(
var downloaded: Long = 0,
) {
fun getDownloadFolder(): String {
return Path(downloadDirectory, folderName).pathString
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Post
other as PostEntity
return postId == other.postId
}
@@ -1,6 +1,6 @@
package me.vripper.entities
data class Thread(
data class ThreadEntity(
val id: Long = -1,
val title: String,
val link: String,
@@ -11,7 +11,7 @@ data class Thread(
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Thread
other as ThreadEntity
return threadId == other.threadId
}
@@ -1,19 +1,17 @@
package me.vripper.event
import me.vripper.entities.Image
import me.vripper.entities.LogEntry
import me.vripper.entities.Post
import me.vripper.entities.Thread
import me.vripper.entities.*
import me.vripper.model.DownloadSpeed
import me.vripper.model.ErrorCount
import me.vripper.model.QueueState
import me.vripper.model.Settings
data class PostCreateEvent(val posts: List<Post>)
data class PostUpdateEvent(val posts: List<Post>)
data class PostCreateEvent(val postEntities: List<PostEntity>)
data class PostUpdateEvent(val postEntities: List<PostEntity>)
data class PostDeleteEvent(val postIds: List<Long>)
data class ImageEvent(val images: List<Image>)
data class ThreadCreateEvent(val thread: Thread)
data class ImageEvent(val imageEntities: List<ImageEntity>)
data class ThreadCreateEvent(val threadEntity: ThreadEntity)
data class ThreadUpdateEvent(val threadEntity: ThreadEntity)
data class ThreadDeleteEvent(val threadId: Long)
class ThreadClearEvent
data class VGUserLoginEvent(val username: String)
@@ -21,9 +19,9 @@ data class DownloadSpeedEvent(val downloadSpeed: DownloadSpeed)
data class QueueStateEvent(val queueState: QueueState)
data class ErrorCountEvent(val errorCount: ErrorCount)
data class SettingsUpdateEvent(val settings: Settings)
data class LogCreateEvent(val logEntry: LogEntry)
data class LogUpdateEvent(val logEntry: LogEntry)
data class MetadataUpdateEvent(val metadataEntity: MetadataEntity)
data class LogCreateEvent(val logEntryEntity: LogEntryEntity)
data class LogUpdateEvent(val logEntryEntity: LogEntryEntity)
data class LogDeleteEvent(val deleted: List<Long>)
data class LoadingTasks(val loading: Boolean)
data class LoadingTasks(val loading: Boolean)
data class StoppedEvent(val postIds: List<Long>)
@@ -1,17 +1,14 @@
package me.vripper.event
import reactor.core.publisher.Flux
import reactor.core.publisher.Sinks
import reactor.core.scheduler.Scheduler
import reactor.core.scheduler.Schedulers
import java.util.concurrent.Executors
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
object EventBus {
private val scheduler: Scheduler = Schedulers.fromExecutor(Executors.newSingleThreadExecutor())
private val _events = Sinks.many().multicast().onBackpressureBuffer<Any>()
val events: Flux<Any> = _events.asFlux().publishOn(scheduler)
fun publishEvent(event: Any) {
_events.emitNext(event) { _, _ -> true }
private val _events = MutableSharedFlow<Any>()
val events = _events.asSharedFlow()
suspend fun publishEvent(event: Any) {
_events.emit(event)
}
}
@@ -95,7 +95,7 @@ abstract class Host(
".tmp"
)
return Files.newOutputStream(tempImage).use { fos ->
val image = context.image
val image = context.imageEntity
synchronized(image.postId.toString().intern()) {
val post = dataTransaction.findPostById(context.postId).orElseThrow()
val size = if (image.size < 0) {
@@ -155,7 +155,8 @@ abstract class Host(
context: ImageDownloadContext,
transformer: (ClassicHttpResponse) -> T
): T {
val httpGet = HttpGet(url).also { it.addHeader("Referer", context.image.url) }.also { context.requests.add(it) }
val httpGet =
HttpGet(url).also { it.addHeader("Referer", context.imageEntity.url) }.also { context.requests.add(it) }
log.debug(String.format("Requesting %s", url))
return httpService.client.execute(httpGet, context.httpContext) {
if (it.code / 100 != 2) {
@@ -165,6 +166,7 @@ abstract class Host(
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun getImageMimeType(headers: Array<Header>): ImageMimeType? {
// first check if content type header exists
@@ -68,6 +68,6 @@ class ImageVenueHost(
companion object {
private const val CONTINUE_BUTTON_XPATH = "//a[@title='Continue to ImageVenue']"
private const val IMG_XPATH = "//a[@data-toggle='full']/img"
private const val IMG_XPATH = "//a[@data-toggle='full']/img[@id='main-image']"
}
}
@@ -1,24 +1,16 @@
package me.vripper.listeners
import me.vripper.download.DownloadService
import me.vripper.services.*
import me.vripper.services.DataTransaction
import me.vripper.services.MetadataService
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
open class OnStartupListener : KoinComponent {
private val dataTransaction: DataTransaction by inject()
private val downloadService: DownloadService by inject()
private val httpService: HTTPService by inject()
private val retryPolicyService: RetryPolicyService by inject()
private val vgAuthService: VGAuthService by inject()
private val downloadSpeedService: DownloadSpeedService by inject()
private val metadataService: MetadataService by inject()
open fun run() {
dataTransaction.setDownloadingToStopped()
httpService.init()
retryPolicyService.init()
vgAuthService.init()
downloadService.init()
downloadSpeedService.init()
metadataService.init()
}
}
@@ -0,0 +1,5 @@
package me.vripper.model
import me.vripper.entities.ImageEntity
typealias Image = ImageEntity
@@ -0,0 +1,5 @@
package me.vripper.model
import me.vripper.entities.LogEntryEntity
typealias LogEntry = LogEntryEntity
@@ -0,0 +1,5 @@
package me.vripper.model
import me.vripper.entities.MetadataEntity
typealias Metadata = MetadataEntity
@@ -0,0 +1,34 @@
package me.vripper.model
import me.vripper.entities.domain.Status
import java.time.LocalDateTime
import kotlin.io.path.Path
import kotlin.io.path.pathString
data class Post(
val id: Long = -1,
val postTitle: String,
val threadTitle: String,
val forum: String,
val url: String,
val token: String,
val postId: Long,
val threadId: Long,
val total: Int,
val hosts: Set<String>,
val downloadDirectory: String,
val addedOn: LocalDateTime = LocalDateTime.now(),
var folderName: String,
var status: Status = Status.STOPPED,
var done: Int = 0,
var rank: Int = Int.MAX_VALUE,
var size: Long = -1,
var downloaded: Long = 0,
val previews: List<String>,
val postedBy: String,
val resolvedNames: List<String>
) {
fun getDownloadFolder(): String {
return Path(downloadDirectory, folderName).pathString
}
}
@@ -0,0 +1,14 @@
package me.vripper.model
data class PostSelection(
val threadId: Long,
val threadTitle: String,
val postId: Long,
val number: Int,
val title: String,
val imageCount: Int,
val url: String,
val hosts: String,
val forum: String,
val previews: List<String>
)
@@ -1,42 +1,48 @@
package me.vripper.model
import kotlinx.serialization.Serializable
@Serializable
data class Settings(
var connectionSettings: ConnectionSettings = ConnectionSettings(),
var downloadSettings: DownloadSettings = DownloadSettings(),
var viperSettings: ViperSettings = ViperSettings(),
var systemSettings: SystemSettings = SystemSettings()
val connectionSettings: ConnectionSettings = ConnectionSettings(),
val downloadSettings: DownloadSettings = DownloadSettings(),
val viperSettings: ViperSettings = ViperSettings(),
val systemSettings: SystemSettings = SystemSettings()
)
@Serializable
data class ViperSettings(
var login: Boolean = false,
var username: String = "",
var password: String = "",
var thanks: Boolean = false,
var host: String = "https://vipergirls.to",
val login: Boolean = false,
val username: String = "",
val password: String = "",
val thanks: Boolean = false,
val host: String = "https://vipergirls.to",
)
@Serializable
data class DownloadSettings(
var downloadPath: String = System.getProperty("user.home"),
var autoStart: Boolean = true,
var autoQueueThreshold: Int = 1,
var forceOrder: Boolean = false,
var forumSubDirectory: Boolean = false,
var threadSubLocation: Boolean = false,
var clearCompleted: Boolean = false,
var appendPostId: Boolean = false
val downloadPath: String = System.getProperty("user.home"),
val autoStart: Boolean = true,
val autoQueueThreshold: Int = 1,
val forceOrder: Boolean = false,
val forumSubDirectory: Boolean = false,
val threadSubLocation: Boolean = false,
val clearCompleted: Boolean = false,
val appendPostId: Boolean = false
)
@Serializable
data class ConnectionSettings(
var maxConcurrentPerHost: Int = 2,
var maxGlobalConcurrent: Int = 0,
var timeout: Long = 30,
var maxAttempts: Int = 3,
val maxConcurrentPerHost: Int = 2,
val maxGlobalConcurrent: Int = 0,
val timeout: Int = 30,
val maxAttempts: Int = 3,
)
@Serializable
data class SystemSettings(
var tempPath: String = System.getProperty("java.io.tmpdir"),
var cachePath: String = System.getProperty("java.io.tmpdir"),
var enableClipboardMonitoring: Boolean = false,
var clipboardPollingRate: Int = 500,
var maxEventLog: Int = 1_000,
val tempPath: String = System.getProperty("java.io.tmpdir"),
val enableClipboardMonitoring: Boolean = false,
val clipboardPollingRate: Int = 500,
val maxEventLog: Int = 1_000,
)
@@ -0,0 +1,5 @@
package me.vripper.model
import me.vripper.entities.ThreadEntity
typealias Thread = ThreadEntity
@@ -1,4 +1,4 @@
package me.vripper.model
package me.vripper.parser
import me.vripper.host.Host
@@ -1,4 +1,4 @@
package me.vripper.model
package me.vripper.parser
data class PostItem(
val threadId: Long,
@@ -0,0 +1,74 @@
package me.vripper.parser
import me.vripper.entities.LogEntryEntity
import me.vripper.exception.DownloadException
import me.vripper.exception.PostParseException
import me.vripper.services.*
import me.vripper.utilities.Tasks
import me.vripper.utilities.formatToString
import net.jodah.failsafe.Failsafe
import net.jodah.failsafe.function.CheckedSupplier
import org.apache.hc.client5.http.classic.HttpClient
import org.apache.hc.client5.http.classic.methods.HttpGet
import org.apache.hc.core5.net.URIBuilder
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import javax.xml.parsers.SAXParserFactory
class PostLookupAPIParser(private val threadId: Long, private val postId: Long) : KoinComponent {
private val log by me.vripper.delegate.LoggerDelegate()
private val settingsService: SettingsService by inject()
private val retryPolicyService: RetryPolicyService by inject()
private val httpService: HTTPService by inject()
private val vgAuthService: VGAuthService by inject()
private val dataTransaction: DataTransaction by inject()
@Throws(PostParseException::class)
fun parse(): ThreadItem? {
log.debug("Parsing post $postId")
val httpGet =
HttpGet(URIBuilder("${settingsService.settings.viperSettings.host}/vr.php").also {
it.setParameter(
"p", postId.toString()
)
}.build())
val threadLookupAPIResponseHandler = ThreadLookupAPIResponseHandler()
log.debug("Requesting {}", httpGet)
Tasks.increment()
return try {
Failsafe.with(retryPolicyService.buildGenericRetryPolicy<Any>()).onFailure {
log.error(
"parsing failed for thread $threadId, post $postId", it.failure
)
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.POST, status = LogEntryEntity.Status.ERROR, message = """
Failed to process thread $threadId, post $postId
${it.failure.formatToString()}
""".trimIndent()
)
)
}.get(CheckedSupplier {
val connection: HttpClient = httpService.client
connection.execute(
httpGet, vgAuthService.context
) { response ->
if (response.code / 100 != 2) {
throw DownloadException("Unexpected response code '${response.code}' for $httpGet")
}
factory.newSAXParser()
.parse(response.entity.content, threadLookupAPIResponseHandler)
threadLookupAPIResponseHandler.result
}
})
} catch (e: Exception) {
throw PostParseException(e)
} finally {
Tasks.decrement()
}
}
companion object {
private val factory = SAXParserFactory.newInstance()
}
}
@@ -1,9 +1,10 @@
package me.vripper.model
package me.vripper.parser
data class ThreadItem(
val threadId: Long,
val title: String,
val securityToken: String,
val forum: String,
val postItemList: List<PostItem>
val postItemList: List<PostItem>,
val error: String
)
@@ -1,12 +1,11 @@
package me.vripper.parser
import me.vripper.entities.LogEntryEntity
import me.vripper.exception.DownloadException
import me.vripper.exception.PostParseException
import me.vripper.model.ThreadItem
import me.vripper.services.HTTPService
import me.vripper.services.RetryPolicyService
import me.vripper.services.SettingsService
import me.vripper.services.VGAuthService
import me.vripper.services.*
import me.vripper.utilities.Tasks
import me.vripper.utilities.formatToString
import net.jodah.failsafe.Failsafe
import net.jodah.failsafe.function.CheckedSupplier
import org.apache.hc.client5.http.classic.methods.HttpGet
@@ -23,6 +22,7 @@ class ThreadLookupAPIParser(private val threadId: Long) : KoinComponent {
private val retryPolicyService: RetryPolicyService by inject()
private val vgAuthService: VGAuthService by inject()
private val settingsService: SettingsService by inject()
private val dataTransaction: DataTransaction by inject()
@Throws(PostParseException::class)
fun parse(): ThreadItem {
@@ -36,12 +36,21 @@ class ThreadLookupAPIParser(private val threadId: Long) : KoinComponent {
}.build())
val threadLookupAPIResponseHandler = ThreadLookupAPIResponseHandler()
log.debug("Requesting {}", httpGet)
Tasks.increment()
return try {
Failsafe.with(retryPolicyService.buildGenericRetryPolicy<Any>()).onFailure {
log.error(
"parsing failed for thread $threadId",
it.failure
)
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.THREAD, status = LogEntryEntity.Status.ERROR, message = """
Failed to process thread $threadId
${it.failure.formatToString()}
""".trimIndent()
)
)
}.get(CheckedSupplier {
cm.client.execute(
httpGet, vgAuthService.context
@@ -58,6 +67,8 @@ class ThreadLookupAPIParser(private val threadId: Long) : KoinComponent {
})
} catch (e: Exception) {
throw PostParseException(e)
} finally {
Tasks.decrement()
}
}
@@ -1,9 +1,6 @@
package me.vripper.parser
import me.vripper.host.Host
import me.vripper.model.ImageItem
import me.vripper.model.PostItem
import me.vripper.model.ThreadItem
import me.vripper.services.SettingsService
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
@@ -11,7 +8,6 @@ import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler
class ThreadLookupAPIResponseHandler : KoinComponent, DefaultHandler() {
private val log by me.vripper.delegate.LoggerDelegate()
private val supportedHosts: List<Host> = getKoin().getAll()
private val settingsService: SettingsService by inject()
private var error: String = ""
@@ -20,13 +16,13 @@ class ThreadLookupAPIResponseHandler : KoinComponent, DefaultHandler() {
private val imageItemList: MutableList<ImageItem> = mutableListOf()
private lateinit var threadItem: ThreadItem
private var threadId: Long = -1
private lateinit var threadTitle: String
private lateinit var forum: String
private lateinit var securityToken: String
private var threadTitle: String = ""
private var forum: String = ""
private var securityToken: String = ""
private var postId: Long = -1
private lateinit var postTitle: String
private var postCounter: Int = 0
private var postTitle: String = ""
private var postCounter: Int = 0
val result: ThreadItem
get() = threadItem
@@ -78,7 +74,7 @@ class ThreadLookupAPIResponseHandler : KoinComponent, DefaultHandler() {
postCounter,
postTitle,
imageItemList.size,
"${settingsService.settings.viperSettings.host}/threads/?p=$postId&viewfull=1#post$postId",
"${settingsService.settings.viperSettings.host}/threads/$threadId?p=$postId&viewfull=1#post$postId",
hostMap.toMap().map { Pair(it.key.hostName, it.value) },
securityToken,
forum,
@@ -92,6 +88,6 @@ class ThreadLookupAPIResponseHandler : KoinComponent, DefaultHandler() {
}
override fun endDocument() {
threadItem = ThreadItem(threadId, threadTitle, securityToken, forum, postItemList.toList())
threadItem = ThreadItem(threadId, threadTitle, securityToken, forum, postItemList.toList(), error)
}
}
@@ -1,20 +1,20 @@
package me.vripper.repositories
import me.vripper.entities.Image
import me.vripper.entities.ImageEntity
import java.util.*
interface ImageRepository {
fun save(image: Image): Image
fun save(imageList: List<Image>)
fun save(imageEntity: ImageEntity): ImageEntity
fun save(imageEntityList: List<ImageEntity>)
fun deleteAllByPostId(postId: Long)
fun findByPostId(postId: Long): List<Image>
fun findByPostId(postId: Long): List<ImageEntity>
fun countError(): Int
fun findByPostIdAndIsNotCompleted(postId: Long): List<Image>
fun findByPostIdAndIsNotCompleted(postId: Long): List<ImageEntity>
fun stopByPostIdAndIsNotCompleted(postId: Long): Int
fun stopByPostIdAndIsNotCompleted(): Int
fun findByPostIdAndIsError(postId: Long): List<Image>
fun findById(id: Long): Optional<Image>
fun update(image: Image)
fun update(images: List<Image>)
fun findByPostIdAndIsError(postId: Long): List<ImageEntity>
fun findById(id: Long): Optional<ImageEntity>
fun update(imageEntity: ImageEntity)
fun update(imageEntities: List<ImageEntity>)
fun deleteAllByPostId(postIds: List<Long>)
}
@@ -1,13 +1,13 @@
package me.vripper.repositories
import me.vripper.entities.LogEntry
import me.vripper.entities.LogEntryEntity
import java.util.*
interface LogRepository {
fun save(logEntry: LogEntry): LogEntry
fun update(logEntry: LogEntry)
fun findAll(): List<LogEntry>
fun findById(id: Long): Optional<LogEntry>
fun save(logEntryEntity: LogEntryEntity): LogEntryEntity
fun update(logEntryEntity: LogEntryEntity)
fun findAll(): List<LogEntryEntity>
fun findById(id: Long): Optional<LogEntryEntity>
fun deleteOldest(): List<Long>
fun deleteAll()
@@ -1,10 +1,11 @@
package me.vripper.repositories
import me.vripper.entities.Metadata
import me.vripper.entities.MetadataEntity
import java.util.*
interface MetadataRepository {
fun save(metadata: Metadata): Metadata
fun findByPostId(postId: Long): Optional<Metadata>
fun save(metadataEntity: MetadataEntity): MetadataEntity
fun findByPostId(postId: Long): Optional<MetadataEntity>
fun deleteByPostId(postId: Long): Int
fun deleteAllByPostId(postIds: List<Long>)
}
@@ -1,19 +1,19 @@
package me.vripper.repositories
import me.vripper.entities.Post
import me.vripper.entities.PostEntity
import java.util.*
interface PostDownloadStateRepository {
fun save(posts: List<Post>): List<Post>
fun findByPostId(postId: Long): Optional<Post>
fun findById(id: Long): Optional<Post>
fun save(postEntities: List<PostEntity>): List<PostEntity>
fun findByPostId(postId: Long): Optional<PostEntity>
fun findById(id: Long): Optional<PostEntity>
fun findCompleted(): List<Long>
fun findAll(): List<Post>
fun findAll(): List<PostEntity>
fun existByPostId(postId: Long): Boolean
fun setDownloadingToStopped(): Int
fun deleteByPostId(postId: Long): Int
fun update(post: Post)
fun update(posts: List<Post>)
fun update(postEntity: PostEntity)
fun update(postEntities: List<PostEntity>)
fun findMaxRank(): Int?
fun deleteAll(postIds: List<Long>)
fun stopAll()
@@ -1,13 +1,14 @@
package me.vripper.repositories
import me.vripper.entities.Thread
import me.vripper.entities.ThreadEntity
import java.util.*
interface ThreadRepository {
fun save(thread: Thread): Thread
fun findByThreadId(threadId: Long): Optional<Thread>
fun findAll(): List<Thread>
fun findById(id: Long): Optional<Thread>
fun save(threadEntity: ThreadEntity): ThreadEntity
fun update(threadEntity: ThreadEntity)
fun findByThreadId(threadId: Long): Optional<ThreadEntity>
fun findAll(): List<ThreadEntity>
fun findById(id: Long): Optional<ThreadEntity>
fun deleteByThreadId(threadId: Long): Int
fun deleteAll()
}
@@ -1,6 +1,6 @@
package me.vripper.repositories.impl
import me.vripper.entities.Image
import me.vripper.entities.ImageEntity
import me.vripper.entities.domain.Status
import me.vripper.repositories.ImageRepository
import me.vripper.tables.ImageTable
@@ -11,23 +11,24 @@ import java.sql.Connection
import java.util.*
class ImageRepositoryImpl : ImageRepository {
override fun save(image: Image): Image {
override fun save(imageEntity: ImageEntity): ImageEntity {
val id = ImageTable.insertAndGetId {
it[downloaded] = image.downloaded
it[host] = image.host
it[index] = image.index
it[postId] = image.postId
it[status] = image.status.name
it[size] = image.size
it[url] = image.url
it[thumbUrl] = image.thumbUrl
it[postIdRef] = image.postIdRef
it[downloaded] = imageEntity.downloaded
it[host] = imageEntity.host
it[index] = imageEntity.index
it[postId] = imageEntity.postId
it[status] = imageEntity.status.name
it[size] = imageEntity.size
it[url] = imageEntity.url
it[thumbUrl] = imageEntity.thumbUrl
it[postIdRef] = imageEntity.postIdRef
it[filename] = imageEntity.filename
}.value
return image.copy(id = id)
return imageEntity.copy(id = id)
}
override fun save(imageList: List<Image>) {
ImageTable.batchInsert(imageList, shouldReturnGeneratedValues = false) {
override fun save(imageEntityList: List<ImageEntity>) {
ImageTable.batchInsert(imageEntityList, shouldReturnGeneratedValues = false) {
this[ImageTable.downloaded] = it.downloaded
this[ImageTable.host] = it.host
this[ImageTable.index] = it.index
@@ -37,6 +38,7 @@ class ImageRepositoryImpl : ImageRepository {
this[ImageTable.url] = it.url
this[ImageTable.thumbUrl] = it.thumbUrl
this[ImageTable.postIdRef] = it.postIdRef
this[ImageTable.filename] = it.filename
}
}
@@ -44,7 +46,7 @@ class ImageRepositoryImpl : ImageRepository {
ImageTable.deleteWhere { ImageTable.postId eq postId }
}
override fun findByPostId(postId: Long): List<Image> {
override fun findByPostId(postId: Long): List<ImageEntity> {
return ImageTable.select {
ImageTable.postId eq postId
}.map(this::transform)
@@ -57,7 +59,7 @@ class ImageRepositoryImpl : ImageRepository {
.count().toInt()
}
override fun findByPostIdAndIsNotCompleted(postId: Long): List<Image> {
override fun findByPostIdAndIsNotCompleted(postId: Long): List<ImageEntity> {
return ImageTable
.select {
(ImageTable.postId eq postId) and (ImageTable.status neq Status.FINISHED.name)
@@ -76,13 +78,13 @@ class ImageRepositoryImpl : ImageRepository {
}
}
override fun findByPostIdAndIsError(postId: Long): List<Image> {
override fun findByPostIdAndIsError(postId: Long): List<ImageEntity> {
return ImageTable.select {
(ImageTable.postId eq postId) and (ImageTable.status eq Status.ERROR.name)
}.map(this::transform)
}
override fun findById(id: Long): Optional<Image> {
override fun findById(id: Long): Optional<ImageEntity> {
val result = ImageTable.select {
ImageTable.id eq id
}.map(this::transform)
@@ -93,16 +95,17 @@ class ImageRepositoryImpl : ImageRepository {
}
}
override fun update(image: Image) {
ImageTable.update({ ImageTable.id eq image.id }) {
it[status] = image.status.name
it[downloaded] = image.downloaded
it[size] = image.size
override fun update(imageEntity: ImageEntity) {
ImageTable.update({ ImageTable.id eq imageEntity.id }) {
it[status] = imageEntity.status.name
it[downloaded] = imageEntity.downloaded
it[size] = imageEntity.size
it[filename] = imageEntity.filename
}
}
override fun update(images: List<Image>) {
ImageTable.batchReplace(images, shouldReturnGeneratedValues = false) {
override fun update(imageEntities: List<ImageEntity>) {
ImageTable.batchUpsert(imageEntities, shouldReturnGeneratedValues = false) {
this[ImageTable.id] = it.id
this[ImageTable.downloaded] = it.downloaded
this[ImageTable.host] = it.host
@@ -113,6 +116,7 @@ class ImageRepositoryImpl : ImageRepository {
this[ImageTable.url] = it.url
this[ImageTable.thumbUrl] = it.thumbUrl
this[ImageTable.postIdRef] = it.postIdRef
this[ImageTable.filename] = it.filename
}
}
@@ -136,10 +140,12 @@ class ImageRepositoryImpl : ImageRepository {
it.execute()
}
conn.prepareStatement("TRUNCATE TABLE IMAGES_DELETE")
conn.prepareStatement("TRUNCATE TABLE IMAGES_DELETE").use {
it.execute()
}
}
private fun transform(resultRow: ResultRow): Image {
private fun transform(resultRow: ResultRow): ImageEntity {
val id = resultRow[ImageTable.id].value
val postId = resultRow[ImageTable.postId]
val url = resultRow[ImageTable.url]
@@ -150,7 +156,8 @@ class ImageRepositoryImpl : ImageRepository {
val total = resultRow[ImageTable.size]
val status = Status.valueOf(resultRow[ImageTable.status])
val postIdRef = resultRow[ImageTable.postIdRef]
return Image(
val filename = resultRow[ImageTable.filename]
return ImageEntity(
id,
postId,
url,
@@ -160,7 +167,8 @@ class ImageRepositoryImpl : ImageRepository {
postIdRef,
total,
current,
status
status,
filename
)
}
}
@@ -1,6 +1,6 @@
package me.vripper.repositories.impl
import me.vripper.entities.LogEntry
import me.vripper.entities.LogEntryEntity
import me.vripper.repositories.LogRepository
import me.vripper.services.SettingsService
import me.vripper.tables.LogTable
@@ -11,25 +11,25 @@ import java.util.*
class LogRepositoryImpl(val settingsService: SettingsService) : LogRepository {
@Synchronized
override fun save(logEntry: LogEntry): LogEntry {
override fun save(logEntryEntity: LogEntryEntity): LogEntryEntity {
val id = LogTable.insertAndGetId {
it[type] = logEntry.type.name
it[status] = logEntry.status.name
it[time] = logEntry.time
it[message] = logEntry.message.take(500)
it[type] = logEntryEntity.type.name
it[status] = logEntryEntity.status.name
it[time] = logEntryEntity.time
it[message] = logEntryEntity.message.take(500)
}.value
return logEntry.copy(id = id)
return logEntryEntity.copy(id = id)
}
override fun update(logEntry: LogEntry) {
LogTable.update({ LogTable.id eq logEntry.id }) {
it[type] = logEntry.type.name
it[status] = logEntry.status.name
it[message] = logEntry.message.take(500)
override fun update(logEntryEntity: LogEntryEntity) {
LogTable.update({ LogTable.id eq logEntryEntity.id }) {
it[type] = logEntryEntity.type.name
it[status] = logEntryEntity.status.name
it[message] = logEntryEntity.message.take(500)
}
}
override fun findById(id: Long): Optional<LogEntry> {
override fun findById(id: Long): Optional<LogEntryEntity> {
val result = LogTable.select {
LogTable.id eq id
}.map(::transform)
@@ -41,7 +41,7 @@ class LogRepositoryImpl(val settingsService: SettingsService) : LogRepository {
}
}
override fun findAll(): List<LogEntry> {
override fun findAll(): List<LogEntryEntity> {
return LogTable.selectAll().map(::transform)
}
@@ -57,13 +57,13 @@ class LogRepositoryImpl(val settingsService: SettingsService) : LogRepository {
LogTable.deleteAll()
}
private fun transform(resultRow: ResultRow): LogEntry {
private fun transform(resultRow: ResultRow): LogEntryEntity {
val id = resultRow[LogTable.id].value
val type = LogEntry.Type.valueOf(resultRow[LogTable.type])
val status = LogEntry.Status.valueOf(resultRow[LogTable.status])
val type = LogEntryEntity.Type.valueOf(resultRow[LogTable.type])
val status = LogEntryEntity.Status.valueOf(resultRow[LogTable.status])
val time = resultRow[LogTable.time]
val message = resultRow[LogTable.message]
return LogEntry(
return LogEntryEntity(
id,
type,
status,
@@ -1,20 +1,75 @@
package me.vripper.repositories.impl
import me.vripper.entities.Metadata
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import me.vripper.entities.MetadataEntity
import me.vripper.repositories.MetadataRepository
import me.vripper.tables.MetadataTable
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.TransactionManager
import java.sql.Connection
import java.util.*
class MetadataRepositoryImpl: MetadataRepository {
override fun save(metadata: Metadata): Metadata {
return metadata
override fun save(metadataEntity: MetadataEntity): MetadataEntity {
MetadataTable.insert {
it[postId] = metadataEntity.postId
it[data] = Json.encodeToString(metadataEntity.data)
}
return metadataEntity
}
override fun findByPostId(postId: Long): Optional<Metadata> {
return Optional.empty()
override fun findByPostId(postId: Long): Optional<MetadataEntity> {
val result = MetadataTable.select {
MetadataTable.postId eq postId
}.map(::transform)
return if (result.isEmpty()) {
Optional.empty()
} else {
Optional.of(result.first())
}
}
private fun transform(row: ResultRow): MetadataEntity {
val id = row[MetadataTable.postId]
val data = Json.decodeFromString(row[MetadataTable.data]) as MetadataEntity.Data
return MetadataEntity(id, data)
}
override fun deleteByPostId(postId: Long): Int {
return 0
return MetadataTable.deleteWhere { MetadataTable.postId eq postId }
}
override fun deleteAllByPostId(postIds: List<Long>) {
val conn = TransactionManager.current().connection.connection as Connection
conn.prepareStatement("CREATE LOCAL TEMPORARY TABLE METADATA_DELETE(POST_ID BIGINT PRIMARY KEY)")
.use {
it.execute()
}
conn.prepareStatement("INSERT INTO METADATA_DELETE VALUES ( ? )").use { ps ->
postIds.forEach {
ps.setLong(1, it)
ps.addBatch()
}
ps.executeBatch()
}
conn.prepareStatement("DELETE FROM METADATA WHERE POST_ID IN (SELECT POST_ID FROM METADATA_DELETE)")
.use {
it.execute()
}
conn.prepareStatement("TRUNCATE TABLE METADATA_DELETE").use {
it.execute()
}
}
}
@@ -1,6 +1,6 @@
package me.vripper.repositories.impl
import me.vripper.entities.Post
import me.vripper.entities.PostEntity
import me.vripper.entities.domain.Status
import me.vripper.repositories.PostDownloadStateRepository
import me.vripper.tables.PostTable
@@ -15,8 +15,8 @@ class PostDownloadStateRepositoryImpl :
private val delimiter = ";"
override fun save(posts: List<Post>): List<Post> {
return PostTable.batchInsert(posts, shouldReturnGeneratedValues = true) { post ->
override fun save(postEntities: List<PostEntity>): List<PostEntity> {
return PostTable.batchInsert(postEntities, shouldReturnGeneratedValues = true) { post ->
this[PostTable.status] = post.status.name
this[PostTable.done] = post.done
this[PostTable.total] = post.total
@@ -37,7 +37,7 @@ class PostDownloadStateRepositoryImpl :
}.map(::transform)
}
override fun findByPostId(postId: Long): Optional<Post> {
override fun findByPostId(postId: Long): Optional<PostEntity> {
val result = PostTable.select {
PostTable.postId eq postId
}.map(::transform)
@@ -54,7 +54,7 @@ class PostDownloadStateRepositoryImpl :
}.map { it[PostTable.postId] }
}
override fun findById(id: Long): Optional<Post> {
override fun findById(id: Long): Optional<PostEntity> {
val result = PostTable.select {
PostTable.id eq id
}.map { transform(it) }
@@ -66,7 +66,7 @@ class PostDownloadStateRepositoryImpl :
}
}
override fun findAll(): List<Post> {
override fun findAll(): List<PostEntity> {
return PostTable.selectAll().map { transform(it) }
}
@@ -84,19 +84,19 @@ class PostDownloadStateRepositoryImpl :
return PostTable.deleteWhere { PostTable.postId eq postId }
}
override fun update(post: Post) {
PostTable.update({ PostTable.id eq post.id }) {
it[status] = post.status.name
it[done] = post.done
it[rank] = post.rank
it[size] = post.size
it[downloaded] = post.downloaded
it[folderName] = post.folderName
override fun update(postEntity: PostEntity) {
PostTable.update({ PostTable.id eq postEntity.id }) {
it[status] = postEntity.status.name
it[done] = postEntity.done
it[rank] = postEntity.rank
it[size] = postEntity.size
it[downloaded] = postEntity.downloaded
it[folderName] = postEntity.folderName
}
}
override fun update(posts: List<Post>) {
PostTable.batchReplace(posts, shouldReturnGeneratedValues = false) { post ->
override fun update(postEntities: List<PostEntity>) {
PostTable.batchUpsert(postEntities, shouldReturnGeneratedValues = false) { post ->
this[PostTable.id] = post.id
this[PostTable.status] = post.status.name
this[PostTable.done] = post.done
@@ -144,7 +144,9 @@ class PostDownloadStateRepositoryImpl :
it.execute()
}
conn.prepareStatement("TRUNCATE TABLE POSTS_DELETE")
conn.prepareStatement("TRUNCATE TABLE POSTS_DELETE").use {
it.execute()
}
}
override fun stopAll() {
@@ -159,7 +161,7 @@ class PostDownloadStateRepositoryImpl :
}.map { it[PostTable.postId] }
}
private fun transform(resultRow: ResultRow): Post {
private fun transform(resultRow: ResultRow): PostEntity {
val id = resultRow[PostTable.id].value
val status = Status.valueOf(resultRow[PostTable.status])
val postId = resultRow[PostTable.postId]
@@ -179,7 +181,7 @@ class PostDownloadStateRepositoryImpl :
val rank = resultRow[PostTable.rank]
val size = resultRow[PostTable.size]
val downloaded = resultRow[PostTable.downloaded]
return Post(
return PostEntity(
id,
postTitle,
threadTitle,
@@ -1,6 +1,6 @@
package me.vripper.repositories.impl
import me.vripper.entities.Thread
import me.vripper.entities.ThreadEntity
import me.vripper.repositories.ThreadRepository
import me.vripper.tables.ThreadTable
import org.jetbrains.exposed.sql.*
@@ -9,17 +9,24 @@ import java.util.*
class ThreadRepositoryImpl : ThreadRepository {
override fun save(thread: Thread): Thread {
override fun save(threadEntity: ThreadEntity): ThreadEntity {
val id = ThreadTable.insertAndGetId {
it[title] = thread.title
it[total] = thread.total
it[url] = thread.link
it[threadId] = thread.threadId
it[title] = threadEntity.title
it[total] = threadEntity.total
it[url] = threadEntity.link
it[threadId] = threadEntity.threadId
}.value
return thread.copy(id = id)
return threadEntity.copy(id = id)
}
override fun findByThreadId(threadId: Long): Optional<Thread> {
override fun update(threadEntity: ThreadEntity) {
ThreadTable.update({ ThreadTable.id eq threadEntity.id }) {
it[title] = threadEntity.title
it[total] = threadEntity.total
}
}
override fun findByThreadId(threadId: Long): Optional<ThreadEntity> {
val result = ThreadTable.select {
ThreadTable.threadId eq threadId
}.map(this::transform)
@@ -30,11 +37,11 @@ class ThreadRepositoryImpl : ThreadRepository {
}
}
override fun findAll(): List<Thread> {
override fun findAll(): List<ThreadEntity> {
return ThreadTable.selectAll().map(this::transform)
}
override fun findById(id: Long): Optional<Thread> {
override fun findById(id: Long): Optional<ThreadEntity> {
val result = ThreadTable.select {
ThreadTable.id eq id
}.map(this::transform)
@@ -53,12 +60,12 @@ class ThreadRepositoryImpl : ThreadRepository {
ThreadTable.deleteAll()
}
private fun transform(resultRow: ResultRow): Thread {
private fun transform(resultRow: ResultRow): ThreadEntity {
val id = resultRow[ThreadTable.id].value
val title = resultRow[ThreadTable.title]
val url = resultRow[ThreadTable.url]
val threadId = resultRow[ThreadTable.threadId]
val total = resultRow[ThreadTable.total]
return Thread(id, title, url, threadId, total)
return ThreadEntity(id, title, url, threadId, total)
}
}
@@ -1,160 +1,338 @@
package me.vripper.services
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.time.sample
import me.vripper.download.DownloadService
import me.vripper.entities.LogEntryEntity
import me.vripper.entities.PostEntity
import me.vripper.event.*
import me.vripper.exception.PostParseException
import me.vripper.model.PostItem
import me.vripper.model.ThreadPostId
import me.vripper.services.*
import me.vripper.model.*
import me.vripper.tasks.AddPostRunnable
import me.vripper.tasks.ThreadLookupRunnable
import me.vripper.utilities.ApplicationProperties
import me.vripper.utilities.GLOBAL_EXECUTOR
import me.vripper.utilities.PathUtils
import java.util.*
import java.time.Duration
import java.util.concurrent.CompletableFuture
import java.util.concurrent.locks.ReentrantLock
import java.util.regex.Pattern
import kotlin.concurrent.withLock
import kotlin.io.path.Path
import kotlin.io.path.exists
import kotlin.jvm.optionals.getOrNull
class AppEndpointService(
private val downloadService: DownloadService,
private val dataTransaction: DataTransaction,
private val threadCacheService: ThreadCacheService,
private val settingsService: SettingsService
) {
private val settingsService: SettingsService,
private val vgAuthService: VGAuthService,
) : IAppEndpointService {
private val log by me.vripper.delegate.LoggerDelegate()
@Synchronized
fun scanLinks(postLinks: String) {
if (postLinks.isBlank()) {
log.warn("Nothing to scan")
return
}
val urlList = postLinks.split(Pattern.compile("\\r?\\n")).dropLastWhile { it.isEmpty() }.map { it.trim() }
.filter { it.isNotEmpty() }
for (link in urlList) {
log.debug("Starting to process thread: $link")
if (!link.startsWith(settingsService.settings.viperSettings.host)) {
continue
private val lock = ReentrantLock()
override suspend fun scanLinks(postLinks: String) {
lock.withLock {
if (postLinks.isBlank()) {
return
}
var threadId: Long
var postId: Long?
val m = Pattern.compile(
Pattern.quote(settingsService.settings.viperSettings.host) + "/threads/(\\d+)((.*p=)(\\d+))?"
).matcher(link)
if (m.find()) {
threadId = m.group(1).toLong()
postId = m.group(4)?.toLong()
if (postId == null) {
CompletableFuture.runAsync(
ThreadLookupRunnable(
threadId, settingsService.settings
),
GLOBAL_EXECUTOR
)
val urlList = postLinks.split(Pattern.compile("\\r?\\n")).dropLastWhile { it.isEmpty() }.map { it.trim() }
.filter { it.isNotEmpty() }
for (link in urlList) {
log.debug("Starting to process thread: $link")
if (!link.startsWith(settingsService.settings.viperSettings.host)) {
continue
}
var threadId: Long
var postId: Long?
val m = Pattern.compile(
Pattern.quote(settingsService.settings.viperSettings.host) + "/threads/(\\d+)((.*p=)(\\d+))?"
).matcher(link)
if (m.find()) {
threadId = m.group(1).toLong()
postId = m.group(4)?.toLong()
if (postId == null) {
CompletableFuture.runAsync(
ThreadLookupRunnable(
threadId, settingsService.settings
), GLOBAL_EXECUTOR
)
} else {
CompletableFuture.runAsync(
AddPostRunnable(
listOf(ThreadPostId(threadId, postId))
), GLOBAL_EXECUTOR
)
}
} else {
CompletableFuture.runAsync(
AddPostRunnable(
listOf(ThreadPostId(threadId, postId))
),
GLOBAL_EXECUTOR
log.error("Cannot retrieve thread id from URL $link")
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.SCAN,
status = LogEntryEntity.Status.ERROR,
message = "Invalid link $link, link is missing the threadId"
)
)
continue
}
} else {
log.error("Cannot retrieve thread id from URL $link")
continue
}
}
}
@Synchronized
fun restartAll(posIds: List<Long> = listOf()) {
downloadService.restartAll(posIds.map { dataTransaction.findPostByPostId(it) }.filter { it.isPresent }
.map { it.get() })
override suspend fun restartAll(posIds: List<Long>) {
lock.withLock {
downloadService.restartAll(posIds.map { dataTransaction.findPostByPostId(it) }.filter { it.isPresent }
.map { it.get() })
}
}
@Synchronized
fun download(posts: List<ThreadPostId>) {
override suspend fun download(posts: List<ThreadPostId>) {
CompletableFuture.runAsync(
AddPostRunnable(posts), GLOBAL_EXECUTOR
)
}
@Synchronized
fun stopAll(postIdList: List<Long> = emptyList()) {
downloadService.stop(postIdList)
override suspend fun stopAll(postIdList: List<Long>) {
lock.withLock {
downloadService.stop(postIdList)
}
}
@Synchronized
fun remove(postIdList: List<Long>) {
downloadService.stop(postIdList)
dataTransaction.removeAll(postIdList)
override suspend fun remove(postIdList: List<Long>) {
lock.withLock {
downloadService.stop(postIdList)
dataTransaction.removeAll(postIdList)
}
}
@Synchronized
fun clearCompleted(): List<Long> {
return dataTransaction.clearCompleted()
override suspend fun clearCompleted(): List<Long> {
lock.withLock {
return dataTransaction.clearCompleted()
}
}
@Synchronized
@Throws(PostParseException::class)
fun grab(threadId: Long): List<PostItem> {
return try {
val thread = dataTransaction.findThreadByThreadId(threadId).orElseThrow {
PostParseException(
String.format(
"Unable to find links for threadId = %s", threadId
override suspend fun grab(threadId: Long): List<PostSelection> {
lock.withLock {
return try {
val thread = dataTransaction.findThreadByThreadId(threadId).orElseThrow {
PostParseException(
String.format(
"Unable to find links for threadId = %s", threadId
)
)
)
}
val threadLookupResult = threadCacheService[thread.threadId]
threadLookupResult.postItemList.ifEmpty {
log.error(
String.format(
"Failed to get links for threadId = %s", threadId
}
val threadLookupResult = threadCacheService[thread.threadId]
threadLookupResult.postItemList.map { postItem ->
PostSelection(
postItem.threadId,
postItem.threadTitle,
postItem.postId,
postItem.number,
postItem.title,
postItem.imageCount,
postItem.url,
postItem.hosts.joinToString(", ") { "${it.first} (${it.second})" },
postItem.forum,
postItem.imageItemList.map { it.thumbLink })
}.ifEmpty {
log.error(
String.format(
"Failed to get links for threadId = %s", threadId
)
)
)
throw PostParseException(
String.format(
"Failed to get links for threadId = %s", threadId
)
)
}
} catch (e: Exception) {
throw PostParseException(
String.format(
"Failed to get links for threadId = %s", threadId
"Failed to get links for threadId = %s, %s", threadId, e.message
)
)
}
} catch (e: Exception) {
throw PostParseException(
String.format(
"Failed to get links for threadId = %s, %s", threadId, e.message
)
)
}
}
@Synchronized
fun threadRemove(threadIdList: List<Long>) {
threadIdList.forEach {
dataTransaction.removeThread(it)
override suspend fun threadRemove(threadIdList: List<Long>) {
lock.withLock {
threadIdList.forEach {
dataTransaction.removeThread(it)
}
}
}
@Synchronized
fun threadClear() {
dataTransaction.clearQueueLinks()
override suspend fun threadClear() {
lock.withLock {
dataTransaction.clearQueueLinks()
}
}
fun logClear() {
dataTransaction.deleteAllLogs()
override suspend fun logClear() {
lock.withLock {
dataTransaction.deleteAllLogs()
}
}
fun rename(postId: Long, name: String) {
override suspend fun renameToFirst(postIds: List<Long>) {
postIds.forEach { postId ->
dataTransaction
.findMetadataByPostId(postId)
.map { it.data.resolvedNames }
.filter { it.isNotEmpty() }
.getOrNull()?.let { rename(postId, it.first()) }
}
}
override suspend fun rename(postId: Long, newName: String) {
CompletableFuture.runAsync({
synchronized(postId.toString().intern()) {
dataTransaction.findPostByPostId(postId).ifPresent { post ->
if (Path(post.downloadDirectory, post.folderName).exists()) {
PathUtils.rename(post.downloadDirectory, post.folderName, name)
PathUtils.rename(
dataTransaction.findImagesByPostId(postId), post.downloadDirectory, post.folderName, newName
)
}
post.folderName = name
post.folderName = PathUtils.sanitize(newName)
dataTransaction.updatePost(post)
}
}
}, GLOBAL_EXECUTOR)
}
override fun onNewPosts(): Flow<Post> =
EventBus.events.filterIsInstance(PostCreateEvent::class).map { it.postEntities.map(::mapper) }
.flatMapConcat { it.asFlow() }
override fun onUpdatePosts() =
EventBus.events.filterIsInstance(PostUpdateEvent::class).map { it.postEntities.map(::mapper) }
.flatMapConcat { it.asFlow() }
override fun onDeletePosts() =
EventBus.events.filterIsInstance(PostDeleteEvent::class).flatMapConcat { it.postIds.asFlow() }
override fun onUpdateMetadata() =
EventBus.events.filterIsInstance(MetadataUpdateEvent::class).map { it.metadataEntity }
override suspend fun findAllPosts(): List<Post> {
return dataTransaction.findAllPosts().map(::mapper)
}
private fun mapper(postEntity: PostEntity): Post {
val metadata: Metadata? = dataTransaction.findMetadataByPostId(postEntity.postId).orElse(null)
val images = dataTransaction.findImagesByPostId(postEntity.postId)
return Post(
postEntity.id,
postEntity.postTitle,
postEntity.threadTitle,
postEntity.forum,
postEntity.url,
postEntity.token,
postEntity.postId,
postEntity.threadId,
postEntity.total,
postEntity.hosts,
postEntity.downloadDirectory,
postEntity.addedOn,
postEntity.folderName,
postEntity.status,
postEntity.done,
postEntity.rank,
postEntity.size,
postEntity.downloaded,
images.take(4).map { it.thumbUrl },
metadata?.data?.postedBy ?: "",
metadata?.data?.resolvedNames ?: emptyList(),
)
}
override suspend fun findPost(postId: Long): Post {
return mapper(dataTransaction.findPostByPostId(postId).orElseThrow())
}
override suspend fun findImagesByPostId(postId: Long): List<Image> {
return dataTransaction.findImagesByPostId(postId)
}
override fun onUpdateImages(postId: Long): Flow<Image> = EventBus.events.filterIsInstance(ImageEvent::class).map {
it.imageEntities.filter { imageEntity: Image -> imageEntity.postId == postId }
}.filter { it.isNotEmpty() }.flatMapConcat { it.asFlow() }
override fun onStopped(): Flow<Long> =
EventBus.events.filterIsInstance(StoppedEvent::class).flatMapConcat { it.postIds.asFlow() }
override suspend fun findAllLogs(): List<LogEntry> {
return dataTransaction.findAllLogs()
}
override fun onNewLog() = EventBus.events.filterIsInstance(LogCreateEvent::class).map { it.logEntryEntity }
override fun onUpdateLog() = EventBus.events.filterIsInstance(LogUpdateEvent::class).map {
it.logEntryEntity
}
override fun onDeleteLogs(): Flow<Long> = EventBus.events.filterIsInstance(LogDeleteEvent::class).flatMapConcat {
it.deleted.asFlow()
}
override fun onNewThread(): Flow<Thread> =
EventBus.events.filterIsInstance(ThreadCreateEvent::class).map { it.threadEntity }
override fun onUpdateThread(): Flow<Thread> =
EventBus.events.filterIsInstance(ThreadUpdateEvent::class).map { it.threadEntity }
override fun onDeleteThread(): Flow<Long> =
EventBus.events.filterIsInstance(ThreadDeleteEvent::class).map { it.threadId }
override fun onClearThreads(): Flow<Unit> = EventBus.events.filterIsInstance(ThreadClearEvent::class).map { }
override suspend fun findAllThreads(): List<Thread> {
return dataTransaction.findAllThreads()
}
override fun onDownloadSpeed(): Flow<Long> =
EventBus.events.filterIsInstance(DownloadSpeedEvent::class).map { it.downloadSpeed.speed }
override fun onVGUserUpdate(): Flow<String> =
EventBus.events.filterIsInstance(VGUserLoginEvent::class).map { it.username }
override fun onQueueStateUpdate(): Flow<QueueState> =
EventBus.events.filterIsInstance(QueueStateEvent::class).map { it.queueState }
override fun onErrorCountUpdate(): Flow<Int> =
EventBus.events.filterIsInstance(ErrorCountEvent::class).map { it.errorCount.count }
override fun onTasksRunning(): Flow<Boolean> =
EventBus.events.filterIsInstance(LoadingTasks::class).sample(Duration.ofMillis(500)).map { it.loading }
override suspend fun getSettings(): Settings = settingsService.settings
override suspend fun saveSettings(settings: Settings) = settingsService.newSettings(settings)
override suspend fun getProxies(): List<String> = settingsService.getProxies()
override fun onUpdateSettings(): Flow<Settings> =
EventBus.events.filterIsInstance(SettingsUpdateEvent::class).map { it.settings }
override suspend fun loggedInUser(): String = vgAuthService.loggedUser
override suspend fun getVersion(): String = ApplicationProperties.VERSION
}
@@ -1,10 +1,14 @@
package me.vripper.services
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import me.vripper.entities.*
import me.vripper.entities.domain.Status
import me.vripper.event.*
import me.vripper.model.ErrorCount
import me.vripper.model.PostItem
import me.vripper.parser.PostItem
import me.vripper.repositories.*
import me.vripper.utilities.PathUtils
import me.vripper.utilities.PathUtils.sanitize
@@ -22,33 +26,52 @@ class DataTransaction(
private val eventBus: EventBus,
) {
private fun save(posts: List<Post>): List<Post> {
return transaction { postDownloadStateRepository.save(posts) }
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private fun save(postEntities: List<PostEntity>): List<PostEntity> {
return transaction { postDownloadStateRepository.save(postEntities) }
}
fun updatePosts(posts: List<Post>) {
transaction { postDownloadStateRepository.update(posts) }
eventBus.publishEvent(PostUpdateEvent(posts))
fun updatePosts(postEntities: List<PostEntity>) {
transaction { postDownloadStateRepository.update(postEntities) }
coroutineScope.launch {
eventBus.publishEvent(PostUpdateEvent(postEntities))
}
}
fun updatePost(post: Post) {
transaction { postDownloadStateRepository.update(post) }
eventBus.publishEvent(PostUpdateEvent(listOf(post)))
fun updatePost(postEntity: PostEntity) {
transaction { postDownloadStateRepository.update(postEntity) }
coroutineScope.launch {
eventBus.publishEvent(PostUpdateEvent(listOf(postEntity)))
}
}
fun save(thread: Thread) {
val savedThread = transaction { threadRepository.save(thread) }
eventBus.publishEvent(ThreadCreateEvent(savedThread))
fun save(threadEntity: ThreadEntity) {
val savedThread = transaction { threadRepository.save(threadEntity) }
coroutineScope.launch {
eventBus.publishEvent(ThreadCreateEvent(savedThread))
}
}
fun updateImages(images: List<Image>) {
transaction { imageRepository.update(images) }
eventBus.publishEvent(ImageEvent(images))
fun update(threadEntity: ThreadEntity) {
transaction { threadRepository.update(threadEntity) }
coroutineScope.launch {
eventBus.publishEvent(ThreadUpdateEvent(threadEntity))
}
}
fun updateImage(image: Image) {
transaction { imageRepository.update(image) }
eventBus.publishEvent(ImageEvent(listOf(image)))
fun updateImages(imageEntities: List<ImageEntity>) {
transaction { imageRepository.update(imageEntities) }
coroutineScope.launch {
eventBus.publishEvent(ImageEvent(imageEntities))
}
}
fun updateImage(imageEntity: ImageEntity) {
transaction { imageRepository.update(imageEntity) }
coroutineScope.launch {
eventBus.publishEvent(ImageEvent(listOf(imageEntity)))
}
}
fun exists(postId: Long): Boolean {
@@ -56,13 +79,13 @@ class DataTransaction(
}
@Synchronized
fun newPosts(postItems: List<PostItem>): List<Post> {
fun newPosts(postItems: List<PostItem>): List<PostEntity> {
var queuePosition = transaction {
getQueuePosition()?.plus(1) ?: 0
}
val posts = postItems.associate { postItem ->
val post = Post(
val postEntity = PostEntity(
postTitle = postItem.title,
url = postItem.url,
token = postItem.securityToken,
@@ -82,8 +105,8 @@ class DataTransaction(
postItem.title
)
)
val images = postItem.imageItemList.mapIndexed { index, imageItem ->
Image(
val imageEntities = postItem.imageItemList.mapIndexed { index, imageItem ->
ImageEntity(
postId = postItem.postId,
url = imageItem.mainLink,
thumbUrl = imageItem.thumbLink,
@@ -91,7 +114,7 @@ class DataTransaction(
index = index,
)
}
Pair(post, images)
Pair(postEntity, imageEntities)
}
@@ -104,7 +127,9 @@ class DataTransaction(
}
savedPosts
}
eventBus.publishEvent(PostCreateEvent(savedPosts))
coroutineScope.launch {
eventBus.publishEvent(PostCreateEvent(savedPosts))
}
return savedPosts
}
@@ -112,8 +137,8 @@ class DataTransaction(
return postDownloadStateRepository.findMaxRank()
}
private fun save(images: List<Image>) {
transaction { imageRepository.save(images) }
private fun save(imageEntities: List<ImageEntity>) {
transaction { imageRepository.save(imageEntities) }
}
fun finishPost(postId: Long, automatic: Boolean = false) {
@@ -138,7 +163,7 @@ class DataTransaction(
}
}
private fun findByPostIdAndIsError(postId: Long): List<Image> {
private fun findByPostIdAndIsError(postId: Long): List<ImageEntity> {
return transaction { imageRepository.findByPostIdAndIsError(postId) }
}
@@ -146,21 +171,25 @@ class DataTransaction(
private fun remove(postIds: List<Long>) {
transaction {
metadataRepository.deleteAllByPostId(postIds)
imageRepository.deleteAllByPostId(postIds)
postDownloadStateRepository.deleteAll(postIds)
sortPostsByRank()
}
eventBus.publishEvent(PostDeleteEvent(postIds = postIds))
eventBus.publishEvent(ErrorCountEvent(ErrorCount(countImagesInError())))
coroutineScope.launch {
eventBus.publishEvent(PostDeleteEvent(postIds = postIds))
}
coroutineScope.launch {
eventBus.publishEvent(ErrorCountEvent(ErrorCount(countImagesInError())))
}
}
fun removeThread(threadId: Long) {
transaction { threadRepository.deleteByThreadId(threadId) }
eventBus.publishEvent(ThreadDeleteEvent(threadId))
coroutineScope.launch {
eventBus.publishEvent(ThreadDeleteEvent(threadId))
}
}
fun clearCompleted(): List<Long> {
@@ -173,7 +202,7 @@ class DataTransaction(
if (postIds.isNotEmpty()) {
remove(postIds)
} else {
remove(findAllPosts().map(Post::postId))
remove(findAllPosts().map(PostEntity::postId))
}
}
@@ -181,59 +210,60 @@ class DataTransaction(
transaction { imageRepository.stopByPostIdAndIsNotCompleted(postId) }
}
@Synchronized
fun setMetadata(post: Post, metadata: Metadata) {
if (metadataRepository.findByPostId(post.postId).isEmpty) {
metadata.postIdRef = post.id
metadataRepository.save(metadata)
fun saveMetadata(metadataEntity: MetadataEntity) {
transaction { metadataRepository.save(metadataEntity) }
coroutineScope.launch {
eventBus.publishEvent(MetadataUpdateEvent(metadataEntity))
}
}
fun clearQueueLinks() {
transaction { threadRepository.deleteAll() }
eventBus.publishEvent(ThreadClearEvent())
coroutineScope.launch {
eventBus.publishEvent(ThreadClearEvent())
}
}
@Synchronized
fun sortPostsByRank() {
val posts = findAllPosts().sortedWith(Comparator.comparing(Post::addedOn))
for (i in posts.indices) {
posts[i].rank = i
val postEntities = findAllPosts().sortedWith(Comparator.comparing(PostEntity::addedOn))
for (i in postEntities.indices) {
postEntities[i].rank = i
}
updatePosts(posts)
updatePosts(postEntities)
}
fun setDownloadingToStopped() {
transaction { postDownloadStateRepository.setDownloadingToStopped() }
}
fun findAllPosts(): List<Post> {
fun findAllPosts(): List<PostEntity> {
return transaction { postDownloadStateRepository.findAll() }
}
fun findPostById(id: Long): Optional<Post> {
fun findPostById(id: Long): Optional<PostEntity> {
return transaction { postDownloadStateRepository.findById(id) }
}
fun findImagesByPostId(postId: Long): List<Image> {
fun findImagesByPostId(postId: Long): List<ImageEntity> {
return transaction { imageRepository.findByPostId(postId) }
}
fun findImageById(id: Long): Optional<Image> {
fun findImageById(id: Long): Optional<ImageEntity> {
return transaction { imageRepository.findById(id) }
}
fun findAllThreads(): List<Thread> {
fun findAllThreads(): List<ThreadEntity> {
return transaction { threadRepository.findAll() }
}
fun findThreadById(id: Long): Optional<Thread> {
fun findThreadById(id: Long): Optional<ThreadEntity> {
return transaction {
threadRepository.findById(id)
}
}
fun findByPostIdAndIsNotCompleted(postId: Long): List<Image> {
fun findByPostIdAndIsNotCompleted(postId: Long): List<ImageEntity> {
return transaction { imageRepository.findByPostIdAndIsNotCompleted(postId) }
}
@@ -241,39 +271,49 @@ class DataTransaction(
return transaction { imageRepository.countError() }
}
fun findPostByPostId(postId: Long): Optional<Post> {
fun findPostByPostId(postId: Long): Optional<PostEntity> {
return transaction { postDownloadStateRepository.findByPostId(postId) }
}
fun findThreadByThreadId(threadId: Long): Optional<Thread> {
fun findThreadByThreadId(threadId: Long): Optional<ThreadEntity> {
return transaction { threadRepository.findByThreadId(threadId) }
}
fun saveLog(logEntry: LogEntry): LogEntry {
fun saveLog(logEntryEntity: LogEntryEntity): LogEntryEntity {
val pair = transaction {
val saved = logRepository.save(logEntry)
val saved = logRepository.save(logEntryEntity)
val deleted = logRepository.deleteOldest()
Pair(saved, deleted)
}
eventBus.publishEvent(LogCreateEvent(pair.first))
eventBus.publishEvent(LogDeleteEvent(pair.second))
coroutineScope.launch {
eventBus.publishEvent(LogCreateEvent(pair.first))
}
coroutineScope.launch {
eventBus.publishEvent(LogDeleteEvent(pair.second))
}
return pair.first
}
fun updateLog(logEntry: LogEntry) {
transaction { logRepository.update(logEntry) }
eventBus.publishEvent(LogUpdateEvent(logEntry))
fun updateLog(logEntryEntity: LogEntryEntity) {
transaction { logRepository.update(logEntryEntity) }
coroutineScope.launch {
eventBus.publishEvent(LogUpdateEvent(logEntryEntity))
}
}
fun deleteAllLogs() {
transaction { logRepository.deleteAll() }
}
fun findAllLogs(): List<LogEntry> {
fun findAllLogs(): List<LogEntryEntity> {
return transaction { logRepository.findAll() }
}
fun findAllNonCompletedPostIds(): List<Long> {
return transaction { postDownloadStateRepository.findAllNonCompletedPostIds() }
}
fun findMetadataByPostId(postId: Long): Optional<MetadataEntity> {
return transaction { metadataRepository.findByPostId(postId) }
}
}
@@ -1,6 +1,7 @@
package me.vripper.services
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.filterIsInstance
import me.vripper.event.DownloadSpeedEvent
import me.vripper.event.EventBus
import me.vripper.event.QueueStateEvent
@@ -19,9 +20,9 @@ class DownloadSpeedService(
private val bytesCount = AtomicLong(0)
private var job: Job? = null
fun init() {
init {
coroutineScope.launch {
eventBus.events.ofType(QueueStateEvent::class.java).subscribe {
eventBus.events.filterIsInstance(QueueStateEvent::class).collect {
if (it.queueState.running + it.queueState.remaining > 0) {
if (job == null || job?.isActive == false) {
job = coroutineScope.launch {
@@ -1,6 +1,7 @@
package me.vripper.services
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.filterIsInstance
import me.vripper.event.EventBus
import me.vripper.event.SettingsUpdateEvent
import org.apache.hc.client5.http.config.ConnectionConfig
@@ -17,7 +18,7 @@ import org.apache.hc.core5.util.TimeValue
import org.apache.hc.core5.util.Timeout
class HTTPService(
val eventBus: EventBus,
private val eventBus: EventBus,
settingsService: SettingsService
) {
@@ -32,9 +33,9 @@ class HTTPService(
private lateinit var rc: RequestConfig
private lateinit var cc: ConnectionConfig
lateinit var client: CloseableHttpClient
private var connectionTimeout: Long = settingsService.settings.connectionSettings.timeout
private var connectionTimeout = settingsService.settings.connectionSettings.timeout
fun init() {
init {
buildRequestConfig()
buildConnectionConfig()
buildConnectionPool()
@@ -43,20 +44,22 @@ class HTTPService(
pcm.closeIdle(TimeValue.ofSeconds(60))
delay(15000)
}
eventBus
.events
.ofType(SettingsUpdateEvent::class.java)
.subscribe {
if (connectionTimeout != it.settings.connectionSettings.timeout) {
connectionTimeout = it.settings.connectionSettings.timeout
client.close()
pcm.close()
buildRequestConfig()
buildConnectionConfig()
buildConnectionPool()
buildClientBuilder()
coroutineScope.launch {
eventBus
.events
.filterIsInstance(SettingsUpdateEvent::class)
.collect {
if (connectionTimeout != it.settings.connectionSettings.timeout) {
connectionTimeout = it.settings.connectionSettings.timeout
client.close()
pcm.close()
buildRequestConfig()
buildConnectionConfig()
buildConnectionPool()
buildClientBuilder()
}
}
}
}
}
private fun buildConnectionPool() {
@@ -71,15 +74,15 @@ class HTTPService(
private fun buildRequestConfig() {
rc = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofSeconds(connectionTimeout))
.setConnectionRequestTimeout(Timeout.ofSeconds(connectionTimeout.toLong()))
.setCookieSpec(StandardCookieSpec.RELAXED)
.build()
}
private fun buildConnectionConfig() {
cc = ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(connectionTimeout))
.setSocketTimeout(Timeout.ofSeconds(connectionTimeout))
.setConnectTimeout(Timeout.ofSeconds(connectionTimeout.toLong()))
.setSocketTimeout(Timeout.ofSeconds(connectionTimeout.toLong()))
.setTimeToLive(TimeValue.ofMinutes(10))
.build()
}
@@ -0,0 +1,48 @@
package me.vripper.services
import kotlinx.coroutines.flow.Flow
import me.vripper.model.*
interface IAppEndpointService {
suspend fun scanLinks(postLinks: String)
suspend fun restartAll(posIds: List<Long> = listOf())
suspend fun remove(postIdList: List<Long>)
suspend fun stopAll(postIdList: List<Long> = emptyList())
suspend fun clearCompleted(): List<Long>
suspend fun findPost(postId: Long): Post
suspend fun findAllPosts(): List<Post>
suspend fun rename(postId: Long, newName: String)
fun onNewPosts(): Flow<Post>
fun onUpdatePosts(): Flow<Post>
fun onDeletePosts(): Flow<Long>
fun onUpdateMetadata(): Flow<Metadata>
suspend fun findImagesByPostId(postId: Long): List<Image>
fun onUpdateImages(postId: Long): Flow<Image>
fun onStopped(): Flow<Long>
suspend fun logClear()
suspend fun findAllLogs(): List<LogEntry>
fun onNewLog(): Flow<LogEntry>
fun onUpdateLog(): Flow<LogEntry>
fun onDeleteLogs(): Flow<Long>
fun onNewThread(): Flow<Thread>
fun onUpdateThread(): Flow<Thread>
fun onDeleteThread(): Flow<Long>
fun onClearThreads(): Flow<Unit>
suspend fun findAllThreads(): List<Thread>
suspend fun threadRemove(threadIdList: List<Long>)
suspend fun threadClear()
suspend fun grab(threadId: Long): List<PostSelection>
suspend fun download(posts: List<ThreadPostId>)
fun onDownloadSpeed(): Flow<Long>
fun onVGUserUpdate(): Flow<String>
fun onQueueStateUpdate(): Flow<QueueState>
fun onErrorCountUpdate(): Flow<Int>
fun onTasksRunning(): Flow<Boolean>
suspend fun getSettings(): Settings
suspend fun saveSettings(settings: Settings)
suspend fun getProxies(): List<String>
fun onUpdateSettings(): Flow<Settings>
suspend fun loggedInUser(): String
suspend fun getVersion(): String
suspend fun renameToFirst(postIds: List<Long>)
}
@@ -0,0 +1,113 @@
package me.vripper.services
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.withPermit
import me.vripper.entities.MetadataEntity
import me.vripper.exception.DownloadException
import me.vripper.exception.VripperException
import me.vripper.utilities.HtmlUtils
import me.vripper.utilities.RequestLimit
import me.vripper.utilities.Tasks
import me.vripper.utilities.XpathUtils
import org.apache.hc.client5.http.classic.methods.HttpGet
import org.apache.hc.core5.net.URIBuilder
import org.w3c.dom.Node
import java.util.concurrent.atomic.AtomicBoolean
import java.util.stream.Collectors
class MetadataService(
private val httpService: HTTPService,
private val settingsService: SettingsService,
private val dataTransaction: DataTransaction,
private val vgAuthService: VGAuthService,
) {
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val dictionary: List<String> = mutableListOf("download", "link", "rapidgator", "filefactory", "filefox")
fun init() {
dataTransaction.findAllPosts().filter { dataTransaction.findMetadataByPostId(it.postId).isEmpty }
.map { it.postId }.forEach(::fetchMetadata)
}
fun fetchMetadata(postId: Long) {
Tasks.increment()
coroutineScope.launch {
RequestLimit.semaphore.withPermit {
try {
val httpGet = HttpGet(URIBuilder(settingsService.settings.viperSettings.host + "/threads/").also {
it.setParameter(
"p", postId.toString()
)
}.build())
val metadataEntity = httpService.client.execute(httpGet, vgAuthService.context) {
if (it.code / 100 != 2) {
throw DownloadException("Unexpected response code '${it.code}' for $httpGet")
}
val document = HtmlUtils.clean(it.entity.content)
val postNode: Node = XpathUtils.getAsNode(
document,
"//li[@id='post_$postId']/div[contains(@class, 'postdetails')]",
) ?: throw VripperException("Unable to find post #'$postId'")
val postedBy: String = XpathUtils.getAsNode(
postNode, "./div[contains(@class, 'userinfo')]//a[contains(@class, 'username')]//font"
)?.textContent?.trim()
?: throw VripperException("Unable to find the poster for post #'$postId'")
val node: Node = XpathUtils.getAsNode(
document, java.lang.String.format("//div[@id='post_message_%s']", postId)
) ?: throw VripperException("Unable to locate post content")
val titles = findTitleInContent(node)
MetadataEntity(postId, MetadataEntity.Data(postedBy, titles))
}
try {
dataTransaction.saveMetadata(metadataEntity)
} catch (e: Exception) {
e.printStackTrace()
}
} finally {
Tasks.decrement()
}
}
}
}
private fun findTitleInContent(node: Node): List<String> {
val altTitle: MutableList<String> = mutableListOf()
findTitle(node, altTitle, AtomicBoolean(true))
return altTitle.stream().distinct().collect(Collectors.toList())
}
private fun findTitle(node: Node, altTitle: MutableList<String>, keepGoing: AtomicBoolean) {
if (!keepGoing.get()) {
return
}
if (node.nodeName == "a" || node.nodeName == "img") {
keepGoing.set(false)
return
}
if (node.nodeType == Node.ELEMENT_NODE) {
for (i in 0 until node.childNodes.length) {
val item = node.childNodes.item(i)
findTitle(item, altTitle, keepGoing)
if (!keepGoing.get()) {
return
}
}
} else if (node.nodeType == Node.TEXT_NODE) {
val text = node.textContent.trim()
if (text.isNotBlank() && dictionary.stream().noneMatch { e ->
text.lowercase().contains(e.lowercase())
}) {
altTitle.add(text)
}
}
}
}
@@ -1,5 +1,10 @@
package me.vripper.services
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.launch
import me.vripper.event.EventBus
import me.vripper.event.SettingsUpdateEvent
import net.jodah.failsafe.RetryPolicy
@@ -11,14 +16,16 @@ class RetryPolicyService(
) {
private val log by me.vripper.delegate.LoggerDelegate()
private var maxAttempts: Int = settingsService.settings.connectionSettings.maxAttempts
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun init() {
eventBus.events.ofType(SettingsUpdateEvent::class.java).subscribe {
if (maxAttempts != it.settings.connectionSettings.maxAttempts) {
maxAttempts = it.settings.connectionSettings.maxAttempts
init {
coroutineScope.launch {
eventBus.events.filterIsInstance(SettingsUpdateEvent::class).collect {
if (maxAttempts != it.settings.connectionSettings.maxAttempts) {
maxAttempts = it.settings.connectionSettings.maxAttempts
}
}
}
}
fun <T> buildRetryPolicyForDownload(): RetryPolicy<T> {
@@ -1,10 +1,12 @@
package me.vripper.services
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import me.vripper.event.EventBus
import me.vripper.event.SettingsUpdateEvent
import me.vripper.exception.ValidationException
@@ -13,44 +15,49 @@ import me.vripper.utilities.ApplicationProperties.VRIPPER_DIR
import org.apache.commons.codec.digest.DigestUtils
import java.io.FileWriter
import java.nio.file.*
import kotlin.io.path.readText
class SettingsService(private val eventBus: EventBus) {
private val log by me.vripper.delegate.LoggerDelegate()
private val configPath = VRIPPER_DIR.resolve("config.yml")
private val configPath = VRIPPER_DIR.resolve("config.json")
private val customProxiesPath = VRIPPER_DIR.resolve("proxies.json")
private val om = ObjectMapper(YAMLFactory())
private val proxies: MutableSet<String> = HashSet()
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val json = Json {
encodeDefaults = true
prettyPrint = true
ignoreUnknownKeys = true
}
var settings = Settings()
init {
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.findAndRegisterModules().registerKotlinModule()
init()
}
private fun init() {
loadViperProxies()
restore()
eventBus.publishEvent(SettingsUpdateEvent(settings))
coroutineScope.launch {
eventBus.publishEvent(SettingsUpdateEvent(settings))
}
}
private fun loadViperProxies() {
try {
SettingsService::class.java.getResourceAsStream("/proxies.json")?.use {
val defaultProxies: List<String> = om.readValue(it)
val defaultProxies: List<String> = json.decodeFromStream(it)
val customProxies: List<String> = if (customProxiesPath.toFile()
.exists() && Files.isRegularFile(customProxiesPath)
) {
try {
om.readValue(
customProxiesPath.toFile()
json.decodeFromString(
customProxiesPath.readText()
)
} catch (e: Exception) {
e.printStackTrace()
emptyList()
}
} else {
@@ -81,36 +88,35 @@ class SettingsService(private val eventBus: EventBus) {
}
fun newSettings(settings: Settings) {
if (settings.viperSettings.login) {
check(settings)
val viperSettings = if (settings.viperSettings.login) {
if (this.settings.viperSettings.password != settings.viperSettings.password) {
settings.viperSettings.password =
DigestUtils.md5Hex(settings.viperSettings.password)
settings.viperSettings.copy(password = DigestUtils.md5Hex(settings.viperSettings.password))
} else {
settings.viperSettings
}
} else {
settings.viperSettings.username = ""
settings.viperSettings.password = ""
settings.viperSettings.thanks = false
settings.viperSettings.login = false
settings.viperSettings.copy(username = "", password = "", thanks = false, login = false)
}
check(settings)
this.settings = settings
this.settings = settings.copy(viperSettings = viperSettings)
save()
eventBus.publishEvent(SettingsUpdateEvent(settings))
coroutineScope.launch {
eventBus.publishEvent(SettingsUpdateEvent(this@SettingsService.settings))
}
}
private fun restore() {
try {
if (configPath.toFile().exists()) {
settings = om.readValue(configPath.toFile())
settings = json.decodeFromString(configPath.readText())
}
} catch (e: Exception) {
log.error("Failed restore user settings", e)
settings = Settings()
}
if (!proxies.contains(settings.viperSettings.host)) {
settings.viperSettings.host = "https://vipergirls.to"
val viperSetting = settings.viperSettings.copy(host = "https://vipergirls.to")
settings = settings.copy(viperSettings = viperSetting)
}
try {
check(settings)
@@ -121,11 +127,11 @@ class SettingsService(private val eventBus: EventBus) {
save()
}
fun save() {
private fun save() {
try {
Files.write(
Files.writeString(
configPath,
om.writeValueAsBytes(settings),
json.encodeToString(settings),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING,
@@ -2,29 +2,45 @@ package me.vripper.services
import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.LoadingCache
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.sync.withPermit
import me.vripper.event.EventBus
import me.vripper.event.SettingsUpdateEvent
import me.vripper.model.ThreadItem
import me.vripper.parser.ThreadItem
import me.vripper.parser.ThreadLookupAPIParser
import me.vripper.utilities.RequestLimit
import java.util.*
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
class ThreadCacheService(val eventBus: EventBus) {
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun init() {
eventBus.events.ofType(SettingsUpdateEvent::class.java).subscribe {
cache.invalidateAll()
coroutineScope.launch {
eventBus.events.filterIsInstance(SettingsUpdateEvent::class).collect {
cache.invalidateAll()
}
}
}
private val cache: LoadingCache<Long, ThreadItem> =
Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build { threadId ->
ThreadLookupAPIParser(threadId).parse()
Caffeine.newBuilder().expireAfterWrite(20, TimeUnit.MINUTES).build { threadId ->
runBlocking {
RequestLimit.semaphore.withPermit {
ThreadLookupAPIParser(threadId).parse()
}
}
}
@Throws(ExecutionException::class)
operator fun get(threadId: Long): ThreadItem {
return cache[threadId] ?: throw NoSuchElementException("$threadId does not exist")
return cache[threadId]
}
fun getIfPresent(threadId: Long): ThreadItem? {
return cache.getIfPresent(threadId)
}
}
@@ -1,6 +1,11 @@
package me.vripper.services
import me.vripper.entities.Post
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.launch
import me.vripper.entities.PostEntity
import me.vripper.event.EventBus
import me.vripper.event.SettingsUpdateEvent
import me.vripper.event.VGUserLoginEvent
@@ -18,18 +23,23 @@ import org.apache.hc.core5.http.message.BasicNameValuePair
import java.util.concurrent.CompletableFuture
class VGAuthService(
private val cm: HTTPService, private val settingsService: SettingsService, private val eventBus: EventBus
private val cm: HTTPService,
private val settingsService: SettingsService,
private val eventBus: EventBus
) {
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val log by me.vripper.delegate.LoggerDelegate()
val context: HttpClientContext = HttpClientContext.create()
var loggedUser = ""
private var authenticated = false
fun init() {
init {
context.cookieStore = BasicCookieStore()
eventBus.events.ofType(SettingsUpdateEvent::class.java).subscribe {
authenticate(it.settings)
coroutineScope.launch {
eventBus.events.filterIsInstance(SettingsUpdateEvent::class).collect {
authenticate(it.settings)
}
}
authenticate(settingsService.settings)
}
@@ -40,7 +50,9 @@ class VGAuthService(
log.debug("Authentication option is disabled")
context.cookieStore.clear()
loggedUser = ""
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
coroutineScope.launch {
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
}
return
}
@@ -51,24 +63,26 @@ class VGAuthService(
context.cookieStore.clear()
loggedUser = ""
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
coroutineScope.launch {
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
}
return
}
val postAuth = HttpPost(settings.viperSettings.host + "/login.php?do=login").also {
it.entity = UrlEncodedFormEntity(
listOf(
BasicNameValuePair("vb_login_username", username),
BasicNameValuePair("cookieuser", "1"),
BasicNameValuePair("do", "login"),
BasicNameValuePair("vb_login_md5password", password)
)
it.entity = UrlEncodedFormEntity(
listOf(
BasicNameValuePair("vb_login_username", username),
BasicNameValuePair("cookieuser", "1"),
BasicNameValuePair("do", "login"),
BasicNameValuePair("vb_login_md5password", password)
)
it.addHeader("Referer", settings.viperSettings.host)
it.addHeader(
"Host", settings.viperSettings.host.replace("https://", "").replace("http://", "")
)
}
)
it.addHeader("Referer", settings.viperSettings.host)
it.addHeader(
"Host", settings.viperSettings.host.replace("https://", "").replace("http://", "")
)
}
try {
cm.client.execute(postAuth, context) { response ->
@@ -81,7 +95,8 @@ class VGAuthService(
if (context.cookieStore.cookies.stream().map { obj: Cookie -> obj.name }
.noneMatch { e: String -> e == "vg_userid" }) {
log.error(
"Failed to authenticate user with {}, missing vg_userid cookie", settings.viperSettings.host
"Failed to authenticate user with {}, missing vg_userid cookie",
settings.viperSettings.host
)
return
}
@@ -89,7 +104,9 @@ class VGAuthService(
context.cookieStore.clear()
loggedUser = ""
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
coroutineScope.launch {
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
}
log.error(
"Failed to authenticate user with " + settings.viperSettings.host, e
@@ -98,13 +115,15 @@ class VGAuthService(
}
authenticated = true
loggedUser = username
log.info(String.format("Authenticated: %s", username))
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
coroutineScope.launch {
eventBus.publishEvent(VGUserLoginEvent(loggedUser))
}
}
fun leaveThanks(post: Post) {
CompletableFuture.runAsync(LeaveThanksRunnable(post, authenticated, context), GLOBAL_EXECUTOR)
fun leaveThanks(postEntity: PostEntity) {
CompletableFuture.runAsync(
LeaveThanksRunnable(postEntity, authenticated, context), GLOBAL_EXECUTOR
)
}
}
@@ -8,6 +8,7 @@ object ImageTable : LongIdTable(name = "IMAGE", columnName = "ID") {
val index = integer("INDEX")
val postId = long("POST_ID")
val status = varchar("STATUS", 15)
val filename = varchar("FILENAME", 260)
val size = long("SIZE")
val url = varchar("URL", 200)
val thumbUrl = varchar("THUMB_URL", 200)
@@ -0,0 +1,8 @@
package me.vripper.tables
import org.jetbrains.exposed.sql.Table
object MetadataTable : Table(name = "METADATA") {
val postId = long("POST_ID")
val data = varchar("DATA", 1_000_000)
}
@@ -1,146 +1,102 @@
package me.vripper.tasks
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.withPermit
import me.vripper.download.DownloadService
import me.vripper.entities.LogEntry.Status.*
import me.vripper.exception.DownloadException
import me.vripper.exception.PostParseException
import me.vripper.model.PostItem
import me.vripper.entities.LogEntryEntity
import me.vripper.model.ThreadPostId
import me.vripper.parser.ThreadLookupAPIResponseHandler
import me.vripper.services.*
import me.vripper.parser.PostItem
import me.vripper.parser.PostLookupAPIParser
import me.vripper.services.DataTransaction
import me.vripper.services.MetadataService
import me.vripper.services.SettingsService
import me.vripper.services.ThreadCacheService
import me.vripper.utilities.RequestLimit
import me.vripper.utilities.Tasks
import net.jodah.failsafe.Failsafe
import net.jodah.failsafe.function.CheckedSupplier
import org.apache.hc.client5.http.classic.HttpClient
import org.apache.hc.client5.http.classic.methods.HttpGet
import org.apache.hc.core5.net.URIBuilder
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.util.*
import javax.xml.parsers.SAXParserFactory
class AddPostRunnable(private val items: List<ThreadPostId>) : KoinComponent, Runnable {
private val log by me.vripper.delegate.LoggerDelegate()
private val dataTransaction: DataTransaction by inject()
private val settingsService: SettingsService by inject()
private val vgAuthService: VGAuthService by inject()
private val httpService: HTTPService by inject()
private val retryPolicyService: RetryPolicyService by inject()
private val downloadService: DownloadService by inject()
private val cacheService: ThreadCacheService by inject()
// private val logEntry: LogEntry
init {
// logEntry = dataTransaction.saveLog(
// LogEntry(
// type = LogEntry.Type.POST, status = PENDING, message = "Processing $link"
// )
// )
}
private val threadCacheService: ThreadCacheService by inject()
private val metadataService: MetadataService by inject()
override fun run() {
try {
Tasks.increment()
val toProcess = mutableListOf<PostItem>()
for ((threadId, postId) in items) {
// dataTransaction.updateLog(logEntry.copy(status = PROCESSING))
if (dataTransaction.exists(postId)) {
log.warn(String.format("skipping %s, already loaded", postId))
continue
}
val threadItem = cacheService[threadId]
// val postItem: PostItem = try {
val postItem: PostItem =
threadItem.postItemList.find { it.postId == postId } ?: parse(postId, threadId)
// } catch (e: PostParseException) {
// val error = String.format("parsing failed for gallery %s", link)
// log.error(error, e)
// dataTransaction.updateLog(
// logEntry.copy(
// status = ERROR, message = """
// $error
// ${e.formatToString()}
// """.trimIndent()
// )
// )
// return@map
// }
// if (postItem.imageItemList.isEmpty()) {
// val error = "Post $link contains no images to download"
// log.error(error)
// dataTransaction.updateLog(logEntry.copy(status = ERROR, message = error))
// return@map
// }
val link =
"https://${settingsService.settings.viperSettings.host}/threads/$threadId?p=$postId&viewfull=1#post$postId"
val cachedThread = threadCacheService.getIfPresent(threadId)
val threadItem = cachedThread ?: runBlocking {
RequestLimit.semaphore.withPermit {
PostLookupAPIParser(
threadId, postId
).parse()
}
}
// dataTransaction.updateLog(
// logEntry.copy(
// status = DONE, message = String.format(
// "Post $link has been successfully added to download queue"
// )
// )
// )
if (threadItem == null) {
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.POST,
status = LogEntryEntity.Status.ERROR,
message = "Failed to load $link"
)
)
continue
} else {
if (threadItem.error.isNotBlank()) {
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.POST,
status = LogEntryEntity.Status.ERROR,
message = "Error loading $link: ${threadItem.error}"
)
)
continue
} else if (threadItem.postItemList.isEmpty()) {
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.POST,
status = LogEntryEntity.Status.ERROR,
message = "Nothing found for $link"
)
)
continue
}
}
val postItem = threadItem.postItemList.first()
toProcess.add(postItem)
}
val posts = dataTransaction.newPosts(toProcess.toList())
// metadataService.startFetchingMetadata(post)
val posts = try {
dataTransaction.newPosts(toProcess.toList())
} catch (e: Exception) {
e.printStackTrace()
emptyList()
}
posts.forEach {
metadataService.fetchMetadata(it.postId)
}
if (settingsService.settings.downloadSettings.autoStart) {
log.debug("Auto start downloads option is enabled")
downloadService.restartAll(posts)
}
} catch (e: Exception) {
val error = String.format("Error when adding galleries")
log.error(error, e)
// dataTransaction.updateLog(
// logEntry.copy(
// status = ERROR, message = """
// $error
// ${e.formatToString()}
// """.trimIndent()
// )
// )
} finally {
Tasks.decrement()
}
}
@Throws(PostParseException::class)
fun parse(postId: Long, threadId: Long): PostItem {
log.debug("Parsing post $postId")
val httpGet =
HttpGet(URIBuilder("${settingsService.settings.viperSettings.host}/vr.php").also {
it.setParameter(
"p", postId.toString()
)
}.build())
val threadLookupAPIResponseHandler = ThreadLookupAPIResponseHandler()
log.debug("Requesting {}", httpGet)
return try {
Failsafe.with(retryPolicyService.buildGenericRetryPolicy<Any>()).onFailure {
log.error(
"parsing failed for thread $threadId, post $postId", it.failure
)
}.get(CheckedSupplier {
val connection: HttpClient = httpService.client
connection.execute(
httpGet, vgAuthService.context
) { response ->
if (response.code / 100 != 2) {
throw DownloadException("Unexpected response code '${response.code}' for $httpGet")
}
factory.newSAXParser()
.parse(response.entity.content, threadLookupAPIResponseHandler)
threadLookupAPIResponseHandler.result.postItemList.first()
}
})
} catch (e: Exception) {
throw PostParseException(e)
}
}
companion object {
private val factory = SAXParserFactory.newInstance()
}
}
@@ -1,8 +1,8 @@
package me.vripper.tasks
import me.vripper.entities.LogEntry
import me.vripper.entities.LogEntry.Status.*
import me.vripper.entities.Post
import me.vripper.entities.LogEntryEntity
import me.vripper.entities.LogEntryEntity.Status.ERROR
import me.vripper.entities.PostEntity
import me.vripper.services.DataTransaction
import me.vripper.services.HTTPService
import me.vripper.services.SettingsService
@@ -16,7 +16,7 @@ import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class LeaveThanksRunnable(
private val post: Post,
private val postEntity: PostEntity,
private val authenticated: Boolean,
private val context: HttpClientContext
) : KoinComponent, Runnable {
@@ -24,47 +24,14 @@ class LeaveThanksRunnable(
private val cm: HTTPService by inject()
private val settingsService: SettingsService by inject()
private val dataTransaction: DataTransaction by inject()
private val logEntry: LogEntry
init {
logEntry = dataTransaction.saveLog(
LogEntry(
type = LogEntry.Type.THANKS,
status = PENDING,
message = "Leaving thanks for ${post.url}"
)
)
}
override fun run() {
try {
Tasks.increment()
dataTransaction.updateLog(logEntry.copy(status = PROCESSING))
if (!settingsService.settings.viperSettings.login) {
dataTransaction.updateLog(
logEntry.copy(
status = DONE,
message = "Will not send a like for ${post.url}\nAuthentication with ViperGirls option is disabled"
)
)
if (!settingsService.settings.viperSettings.login || !authenticated) {
return
}
if (!settingsService.settings.viperSettings.thanks) {
dataTransaction.updateLog(
logEntry.copy(
status = DONE,
message = "Will not send a like for ${post.url}\nLeave thanks option is disabled"
)
)
return
}
if (!authenticated) {
dataTransaction.updateLog(
logEntry.copy(
status = DONE,
message = "Will not send a like for ${post.url}\nYou are not authenticated"
)
)
return
}
@@ -74,8 +41,8 @@ class LeaveThanksRunnable(
listOf(
BasicNameValuePair("do", "post_thanks_add"),
BasicNameValuePair("using_ajax", "1"),
BasicNameValuePair("p", post.postId.toString()),
BasicNameValuePair("securitytoken", post.token)
BasicNameValuePair("p", postEntity.postId.toString()),
BasicNameValuePair("securitytoken", postEntity.token)
)
)
it.addHeader("Referer", settingsService.settings.viperSettings.host)
@@ -86,13 +53,12 @@ class LeaveThanksRunnable(
)
}
cm.client.execute(postThanks, context) { }
dataTransaction.updateLog(logEntry.copy(status = DONE))
} catch (e: Exception) {
val error = "Failed to leave a thanks for $post"
val error = "Failed to leave a thanks for $postEntity"
log.error(error, e)
dataTransaction.updateLog(
logEntry.copy(
status = ERROR, message = """
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.THANKS, status = ERROR, message = """
$error
${e.formatToString()}
""".trimIndent()
@@ -1,12 +1,10 @@
package me.vripper.tasks
import me.vripper.entities.LogEntry
import me.vripper.entities.LogEntry.Status.*
import me.vripper.entities.Thread
import me.vripper.entities.LogEntryEntity
import me.vripper.entities.LogEntryEntity.Status.ERROR
import me.vripper.entities.ThreadEntity
import me.vripper.model.Settings
import me.vripper.model.ThreadItem
import me.vripper.model.ThreadPostId
import me.vripper.services.AppEndpointService
import me.vripper.services.DataTransaction
import me.vripper.services.SettingsService
import me.vripper.services.ThreadCacheService
@@ -17,66 +15,66 @@ import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.util.concurrent.CompletableFuture
class ThreadLookupRunnable(private val threadId: Long, private val settings: Settings) :
KoinComponent, Runnable {
class ThreadLookupRunnable(private val threadId: Long, private val settings: Settings) : KoinComponent, Runnable {
private val log by me.vripper.delegate.LoggerDelegate()
private val dataTransaction by inject<DataTransaction>()
private val settingsService by inject<SettingsService>()
private val threadCacheService by inject<ThreadCacheService>()
private val appEndpointService by inject<AppEndpointService>()
private val link: String = "${settingsService.settings.viperSettings.host}/threads/$threadId"
private val logEntry: LogEntry
init {
logEntry = dataTransaction.saveLog(
LogEntry(
type = LogEntry.Type.THREAD,
status = LogEntry.Status.PENDING,
message = "Processing multi-post link $link"
)
)
}
override fun run() {
try {
Tasks.increment()
dataTransaction.updateLog(logEntry.copy(status = PROCESSING))
if (dataTransaction.findThreadByThreadId(threadId).isEmpty) {
val threadLookupResult = threadCacheService[threadId]
if (threadLookupResult.postItemList.isEmpty()) {
val message = "Nothing found for $link"
dataTransaction.updateLog(logEntry.copy(status = ERROR, message = message))
if (threadLookupResult.error.isNotBlank()) {
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.THREAD,
status = LogEntryEntity.Status.ERROR,
message = "Error loading $link: ${threadLookupResult.error}"
)
)
return
}
dataTransaction.save(
Thread(
title = threadLookupResult.title,
link = link,
threadId = threadId,
total = threadLookupResult.postItemList.size
if (threadLookupResult.postItemList.isEmpty()) {
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.THREAD,
status = LogEntryEntity.Status.ERROR,
message = "Nothing found for $link"
)
)
)
dataTransaction.updateLog(
logEntry.copy(
status = DONE,
message = "Thread scan completed, found ${threadLookupResult.postItemList.size} posts"
)
)
autostart(threadLookupResult)
} else {
log.info("Link $link is already loaded")
dataTransaction.updateLog(
logEntry.copy(
status = DONE, message = "$link has already been scanned"
)
)
return
}
if (threadLookupResult.postItemList.size <= settings.downloadSettings.autoQueueThreshold) {
CompletableFuture.runAsync(AddPostRunnable(threadLookupResult.postItemList.map {
ThreadPostId(
it.threadId, it.postId
)
}), GLOBAL_EXECUTOR)
} else {
try {
dataTransaction.save(
ThreadEntity(
title = threadLookupResult.title,
link = link,
threadId = threadId,
total = threadLookupResult.postItemList.size
)
)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
} catch (e: Exception) {
val error = "Error when adding multi-post link $link"
val error = "Error when processing $link"
log.error(error, e)
dataTransaction.updateLog(
logEntry.copy(
status = ERROR, message = """
dataTransaction.saveLog(
LogEntryEntity(
type = LogEntryEntity.Type.THREAD, status = ERROR, message = """
$error
${e.formatToString()}
""".trimIndent()
@@ -86,16 +84,4 @@ class ThreadLookupRunnable(private val threadId: Long, private val settings: Set
Tasks.decrement()
}
}
private fun autostart(lookupResult: ThreadItem) {
if (lookupResult.postItemList.size <= settings.downloadSettings.autoQueueThreshold) {
appEndpointService.threadRemove(listOf(lookupResult.threadId))
CompletableFuture.runAsync(
AddPostRunnable(
lookupResult.postItemList.map { ThreadPostId(it.threadId, it.postId) }
),
GLOBAL_EXECUTOR
)
}
}
}
@@ -1,22 +1,50 @@
package me.vripper.utilities
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import me.vripper.exception.DownloadException
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.Path
import kotlin.io.path.pathString
object ApplicationProperties {
const val VERSION: String = "5.2.0"
val VERSION: String =
ApplicationProperties.javaClass.getResourceAsStream("/version")
?.use { inputStream -> inputStream.reader().use { it.readText() } } ?: "undefined"
private const val BASE_DIR_NAME: String = "vripper"
private val portable = System.getProperty("vripper.portable", "true").toBoolean()
private val BASE_DIR: String = getBaseDir()
val VRIPPER_DIR: Path = Path(BASE_DIR, BASE_DIR_NAME)
private val json = Json {
ignoreUnknownKeys = true
}
@Serializable
internal data class ReleaseResponse(@SerialName("tag_name") val tagName: String)
init {
Files.createDirectories(VRIPPER_DIR)
System.setProperty("VRIPPER_DIR", VRIPPER_DIR.toRealPath().pathString)
}
fun latestVersion(): String {
val request = HttpRequest.newBuilder()
.uri(URI.create("https://api.github.com/repos/death-claw/vripper-project/releases/latest")).build()
return HttpClient.newHttpClient().use {
val response = it.send(request, HttpResponse.BodyHandlers.ofString())
if (response.statusCode() / 100 != 2) {
throw DownloadException("Unexpected response code '${response.statusCode()}' for $request")
}
json.decodeFromString<ReleaseResponse>(response.body()).tagName
}
}
private fun getBaseDir(): String {
return if (portable) {
System.getProperty("user.dir")
@@ -1,5 +1,6 @@
package me.vripper.utilities
import me.vripper.entities.ImageEntity
import me.vripper.exception.RenameException
import me.vripper.model.Settings
import java.io.IOException
@@ -7,6 +8,7 @@ import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import kotlin.io.path.Path
import kotlin.io.path.listDirectoryEntries
object PathUtils {
@@ -28,15 +30,33 @@ object PathUtils {
}
@Throws(RenameException::class)
fun rename(downloadDirectory: String, oldFolder: String, newFolder: String) {
fun rename(
imageEntityList: List<ImageEntity>,
downloadDirectory: String,
oldFolder: String,
newFolder: String
) {
val currentDownloadDirectory = Path(downloadDirectory, oldFolder)
val newDownloadDirectory = Path(downloadDirectory, sanitize(newFolder))
if (currentDownloadDirectory == newDownloadDirectory) {
return
}
try {
Files.move(
currentDownloadDirectory,
newDownloadDirectory,
StandardCopyOption.ATOMIC_MOVE
)
Files.createDirectories(newDownloadDirectory)
imageEntityList.filter { it.filename.isNotBlank() }.forEach {
Files.move(
currentDownloadDirectory.resolve(it.filename),
newDownloadDirectory.resolve(it.filename),
StandardCopyOption.ATOMIC_MOVE
)
}
if (currentDownloadDirectory.listDirectoryEntries().isEmpty()) {
try {
Files.delete(currentDownloadDirectory)
} catch (e: Exception) {
e.printStackTrace()
}
}
} catch (e: IOException) {
throw RenameException(
String.format(
@@ -0,0 +1,7 @@
package me.vripper.utilities
import kotlinx.coroutines.sync.Semaphore
object RequestLimit {
val semaphore: Semaphore = Semaphore(6)
}
@@ -1,5 +1,9 @@
package me.vripper.utilities
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import me.vripper.event.EventBus
import me.vripper.event.LoadingTasks
import org.koin.core.component.KoinComponent
@@ -9,11 +13,14 @@ object Tasks : KoinComponent {
private val eventBus: EventBus by inject()
private var current = 0
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@Synchronized
fun increment() {
if (current == 0) {
eventBus.publishEvent(LoadingTasks(true))
coroutineScope.launch {
eventBus.publishEvent(LoadingTasks(true))
}
}
current += 1
}
@@ -22,7 +29,9 @@ object Tasks : KoinComponent {
fun decrement() {
current -= 1
if (current == 0) {
eventBus.publishEvent(LoadingTasks(false))
coroutineScope.launch {
eventBus.publishEvent(LoadingTasks(false))
}
}
}
}
@@ -0,0 +1,122 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
import "post.proto";
import "posts.proto";
import "image.proto";
import "images.proto";
import "metadata.proto";
import "log.proto";
import "logs.proto";
import "thread.proto";
import "threads.proto";
import "settings.proto";
message EmptyRequest {}
message EmptyResponse {}
message Links {
string links = 1;
}
message IdList {
repeated int64 ids = 1;
}
message Id {
int64 id = 1;
}
message DownloadSpeed {
int64 speed = 1;
}
message VGUser {
string user = 1;
}
message QueueState {
int32 running = 1;
int32 remaining = 2;
}
message ErrorCount {
int32 count = 1;
}
message TasksRunning {
bool running = 1;
}
message Rename {
int64 postId = 1;
string name = 2;
}
message RenameToFirst {
repeated int64 postIds = 1;
}
message PostSelection {
int64 threadId = 1;
string threadTitle = 2;
int64 postId = 3;
int32 number = 4;
string title = 5;
int32 imageCount = 6;
string url = 7;
string hosts = 8;
string forum = 10;
repeated string previews = 11;
}
message PostSelectionList {
repeated PostSelection postSelectionList = 1;
}
message ThreadPostId {
int64 threadId = 1;
int64 postId = 2;
}
message ThreadPostIdList {
repeated ThreadPostId threadPostIdList = 1;
}
message ProxyList {
repeated string proxies = 1;
}
message LoggedInUser {
string user = 1;
}
message Version {
string version = 1;
}
service EndpointService {
rpc scanLinks (Links) returns (EmptyResponse) {}
rpc onNewPosts (EmptyRequest) returns (stream Post) {}
rpc onUpdatePosts (EmptyRequest) returns (stream Post) {}
rpc onDeletePosts (EmptyRequest) returns (stream Id) {}
rpc findAllPosts (EmptyRequest) returns (Posts) {}
rpc restartAll (IdList) returns (EmptyResponse) {}
rpc stopAll (IdList) returns (EmptyResponse) {}
rpc findPost (Id) returns (Post) {}
rpc findImagesByPostId (Id) returns (Images) {}
rpc onUpdateImages (Id) returns (stream Image) {}
rpc onDownloadSpeed (EmptyRequest) returns (stream DownloadSpeed) {}
rpc onVGUserUpdate (EmptyRequest) returns (stream VGUser) {}
rpc onQueueStateUpdate (EmptyRequest) returns (stream QueueState) {}
rpc onErrorCountUpdate (EmptyRequest) returns (stream ErrorCount) {}
rpc onTasksRunning (EmptyRequest) returns (stream TasksRunning) {}
rpc onUpdateMetadata (EmptyRequest) returns (stream Metadata) {}
rpc remove (IdList) returns (EmptyResponse) {}
rpc clearCompleted (EmptyRequest) returns (IdList) {}
rpc rename (Rename) returns (EmptyResponse) {}
rpc renameToFirst (RenameToFirst) returns (EmptyResponse) {}
rpc onStopped (EmptyRequest) returns (stream Id) {}
rpc logClear (EmptyRequest) returns (EmptyResponse) {}
rpc findAllLogs (EmptyRequest) returns (Logs) {}
rpc onNewLog (EmptyRequest) returns (stream Log) {}
rpc onUpdateLog (EmptyRequest) returns (stream Log) {}
rpc onDeleteLogs (EmptyRequest) returns (stream Id) {}
rpc onNewThread (EmptyRequest) returns (stream Thread) {}
rpc onUpdateThread (EmptyRequest) returns (stream Thread) {}
rpc onDeleteThread (EmptyRequest) returns (stream Id) {}
rpc onClearThreads (EmptyRequest) returns (stream EmptyResponse) {}
rpc findAllThreads (EmptyRequest) returns (Threads) {}
rpc threadRemove (IdList) returns (EmptyResponse) {}
rpc threadClear (EmptyRequest) returns (EmptyResponse) {}
rpc grab (Id) returns (PostSelectionList) {}
rpc download (ThreadPostIdList) returns (EmptyResponse) {}
rpc getSettings (EmptyRequest) returns (Settings) {}
rpc saveSettings (Settings) returns (EmptyResponse) {}
rpc getProxies (EmptyRequest) returns (ProxyList) {}
rpc onUpdateSettings (EmptyRequest) returns (stream Settings) {}
rpc loggedInUser (EmptyRequest) returns (LoggedInUser) {}
rpc getVersion (EmptyRequest) returns (Version) {}
}
+16
View File
@@ -0,0 +1,16 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
message Image {
int64 id = 1;
int64 postId = 2;
string url = 3;
string thumbUrl = 4;
int32 host = 5;
int32 index = 6;
int64 postIdRef = 7;
int64 size = 8;
int64 downloaded = 9;
string status = 10;
string filename = 11;
}
+7
View File
@@ -0,0 +1,7 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
import "image.proto";
message Images {
repeated Image images = 1;
}
+10
View File
@@ -0,0 +1,10 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
message Log {
int64 id = 1;
string type = 2;
string status = 3;
string time = 4;
string message = 5;
}
+7
View File
@@ -0,0 +1,7 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
import "log.proto";
message Logs {
repeated Log logs = 1;
}
@@ -0,0 +1,8 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
message Metadata {
int64 postId = 1;
string postedBy = 2;
repeated string resolvedNames = 3;
}
+26
View File
@@ -0,0 +1,26 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
message Post {
int64 id = 1;
string postTitle = 2;
string threadTitle = 3;
string forum = 4;
string url = 5;
string token = 6;
int64 postId = 7;
int64 threadId = 8;
int32 total = 9;
repeated string hosts = 10;
string downloadDirectory = 11;
string addedOn = 12;
string folderName = 13;
string status = 14;
int32 done = 15;
int32 rank = 16;
int64 size = 17;
int64 downloaded = 18;
repeated string previews = 19;
string postedBy = 20;
repeated string resolvedNames = 21;
}
+7
View File
@@ -0,0 +1,7 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
import "post.proto";
message Posts {
repeated Post posts = 1;
}
@@ -0,0 +1,42 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
message ViperSettings {
bool login = 1;
string username = 2;
string password = 3;
bool thanks = 4;
string host = 5;
}
message DownloadSettings {
string downloadPath = 1;
bool autoStart = 2;
int32 autoQueueThreshold = 3;
bool forceOrder = 4;
bool forumSubDirectory = 5;
bool threadSubLocation = 6;
bool clearCompleted = 7;
bool appendPostId = 8;
}
message ConnectionSettings {
int32 maxConcurrentPerHost = 1;
int32 maxGlobalConcurrent = 2;
int32 timeout = 3;
int32 maxAttempts = 4;
}
message SystemSettings {
string tempPath = 1;
bool enableClipboardMonitoring = 2;
int32 clipboardPollingRate = 3;
int32 maxEventLog = 4;
}
message Settings {
ConnectionSettings connectionSettings = 1;
DownloadSettings downloadSettings = 2;
ViperSettings viperSettings = 3;
SystemSettings systemSettings = 4;
}
+10
View File
@@ -0,0 +1,10 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
message Thread {
int64 id = 1;
string title = 2;
string link = 3;
int64 threadId = 4;
int32 total = 5;
}
@@ -0,0 +1,7 @@
syntax = "proto3";
option java_package = "me.vripper.proto";
import "thread.proto";
message Threads {
repeated Thread threads = 1;
}
@@ -145,9 +145,28 @@
<column name="THREAD_ID"/>
</createIndex>
</changeSet>
<changeSet id="0006" author="vripper">
<addColumn tableName="POST">
<column name="FOLDER_NAME" type="VARCHAR(260)" afterColumn="OUTPUT_PATH" defaultValue=""/>
</addColumn>
</changeSet>
<changeSet id="0006" author="vripper">
<addColumn tableName="POST">
<column name="FOLDER_NAME" type="VARCHAR(260)" afterColumn="OUTPUT_PATH" defaultValue=""/>
</addColumn>
</changeSet>
<changeSet author="vripper" id="0007">
<createTable tableName="METADATA">
<column name="POST_ID" type="BIGINT">
<constraints unique="true" nullable="false"/>
</column>
<column name="DATA" type="VARCHAR">
<constraints nullable="true"/>
</column>
</createTable>
</changeSet>
<changeSet author="vripper" id="0008">
<addColumn tableName="IMAGE">
<column name="FILENAME" type="VARCHAR(260)" afterColumn="STATUS" defaultValue=""/>
</addColumn>
</changeSet>
<changeSet id="0009" author="vripper">
<addUniqueConstraint tableName="POST" columnNames="POST_ID" constraintName="POST__POST_ID_UQ"/>
<addUniqueConstraint tableName="THREAD" columnNames="THREAD_ID" constraintName="THREAD__THREAD_ID_UQ"/>
</changeSet>
</databaseChangeLog>
+25 -23
View File
@@ -1,28 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender class="ch.qos.logback.core.ConsoleAppender" name="STDOUT">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender class="ch.qos.logback.core.ConsoleAppender" name="STDOUT">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender class="ch.qos.logback.core.rolling.RollingFileAppender"
name="FILE">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</encoder>
<file>${VRIPPER_DIR}/vripper.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${VRIPPER_DIR}/vripper.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>7</maxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
</appender>
<appender class="ch.qos.logback.core.rolling.RollingFileAppender"
name="FILE">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</encoder>
<file>${VRIPPER_DIR}/vripper.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${VRIPPER_DIR}/vripper.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>7</maxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
<logger name="Exposed" level="OFF"/>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
@@ -1,6 +1,7 @@
[
"https://planetviper.club",
"https://viperbb.rocks",
"https://viper.to",
"https://viperkats.eu",
"https://viperohilia.art",
"https://viperproxy.org",
+1
View File
@@ -0,0 +1 @@
${project.version}
+80 -26
View File
@@ -16,7 +16,7 @@
<description>vripper-gui</description>
<properties>
<javafx.version>21</javafx.version>
<javafx.version>21.0.2</javafx.version>
</properties>
<dependencies>
@@ -29,6 +29,14 @@
<artifactId>kotlinx-coroutines-core-jvm</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-javafx</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-serialization-json</artifactId>
</dependency>
<dependency>
<artifactId>javafx-base</artifactId>
<groupId>org.openjfx</groupId>
<version>${javafx.version}</version>
@@ -96,12 +104,49 @@
<artifactId>tornadofx</artifactId>
<groupId>no.tornado</groupId>
<version>1.7.20</version>
<exclusions>
<exclusion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.github.mkpaz</groupId>
<artifactId>atlantafx-base</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.kordamp.ikonli</groupId>
<artifactId>ikonli-feather-pack</artifactId>
<version>12.3.1</version>
</dependency>
<dependency>
<groupId>org.kordamp.ikonli</groupId>
<artifactId>ikonli-javafx</artifactId>
<version>12.3.1</version>
</dependency>
<dependency>
<artifactId>vripper-core</artifactId>
<groupId>me.vripper</groupId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-kotlin-stub</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-kotlin</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
</dependency>
</dependencies>
<build>
@@ -119,19 +164,21 @@
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<source>src/main/kotlin</source>
<source>target/generated-sources/annotations</source>
</sourceDirs>
</configuration>
</execution>
</executions>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<jvmTarget>1.8</jvmTarget>
<compilerPlugins>
<plugin>kotlinx-serialization</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-serialization</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
@@ -146,27 +193,34 @@
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>me.vripper.gui.VripperGuiApplicationKt</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<goals>
<goal>single</goal>
</goals>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>jar-with-dependencies</shadedClassifierName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>me.vripper.gui.VripperGuiApplicationKt</mainClass>
<manifestEntries>
<Implementation-Version>${project.version}</Implementation-Version>
<Main-Class>me.vripper.gui.VripperGuiApplicationKt</Main-Class>
</manifestEntries>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
<groupId>org.apache.maven.plugins</groupId>
</plugin>
</plugins>
</build>
@@ -1,12 +1,15 @@
package me.vripper.gui
import me.vripper.gui.clipboard.ClipboardService
import me.vripper.gui.services.GrpcEndpointService
import me.vripper.services.IAppEndpointService
import org.koin.core.qualifier.named
import org.koin.dsl.bind
import org.koin.dsl.module
val guiModule = module {
single<ClipboardService> {
ClipboardService(get(), get(), get())
}
single((named("remoteAppEndpointService"))) {
GrpcEndpointService()
} bind IAppEndpointService::class
}
val modules = module {
@@ -1,33 +0,0 @@
package me.vripper.gui
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import tornadofx.Stylesheet
import tornadofx.box
import tornadofx.cssclass
import tornadofx.px
class Styles : Stylesheet() {
companion object {
val heading by cssclass()
val actionBarButton by cssclass()
}
init {
label and heading {
padding = box(20.px)
fontSize = 20.px
fontWeight = FontWeight.BOLD
}
actionBarButton {
prefWidth = 32.px
prefHeight = 32.px
padding = box(0.px)
backgroundColor += Color.TRANSPARENT
and(hover) {
backgroundColor += Color.LIGHTGREY
}
}
}
}
@@ -1,18 +1,19 @@
package me.vripper.gui
import atlantafx.base.theme.CupertinoDark
import atlantafx.base.theme.CupertinoLight
import javafx.application.Application
import javafx.scene.image.Image
import javafx.stage.Stage
import javafx.stage.WindowEvent
import me.vripper.gui.event.ApplicationInitialized
import me.vripper.gui.listener.GuiStartupLister
import me.vripper.gui.view.LoadingView
import kotlinx.coroutines.*
import me.vripper.gui.components.views.LoadingView
import me.vripper.gui.controller.WidgetsController
import me.vripper.gui.event.GuiEventBus
import me.vripper.listeners.AppLock
import me.vripper.utilities.ApplicationProperties.VRIPPER_DIR
import me.vripper.utilities.DbUtils
import org.jetbrains.exposed.sql.Database
import org.koin.core.context.GlobalContext
import org.koin.core.context.startKoin
import org.koin.core.qualifier.named
import tornadofx.App
import tornadofx.DIContainer
import tornadofx.FX
@@ -21,20 +22,26 @@ import kotlin.system.exitProcess
class VripperGuiApplication : App(
LoadingView::class, Styles::class
) { //The application class must be a TornadoFX application and it must have the main view
LoadingView::class
) {
private var initialized = false
private val startupListener = GuiStartupLister()
private val widgetsController: WidgetsController by inject()
private val coroutineScope = CoroutineScope(SupervisorJob())
init {
APP_INSTANCE = this
}
override fun start(stage: Stage) {
if (widgetsController.currentSettings.darkMode) {
setUserAgentStylesheet(CupertinoDark().userAgentStylesheet)
} else {
setUserAgentStylesheet(CupertinoLight().userAgentStylesheet)
}
with(stage) {
width = 1366.0
height = 768.0
width = widgetsController.currentSettings.width
height = widgetsController.currentSettings.height
minWidth = 800.0
minHeight = 600.0
icons.addAll(
@@ -50,29 +57,42 @@ class VripperGuiApplication : App(
)
)
}
coroutineScope.launch {
while (isActive) {
if (!stage.isMaximized) {
if (widgetsController.currentSettings.width != stage.width || widgetsController.currentSettings.height != stage.height) {
widgetsController.currentSettings.width = stage.width
widgetsController.currentSettings.height = stage.height
widgetsController.update()
}
}
delay(1_000)
}
}
stage.addEventFilter(WindowEvent.WINDOW_SHOWN) {
Database.connect("jdbc:h2:file:$VRIPPER_DIR/vripper;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=30000;")
DbUtils.update()
startKoin {
modules(modules)
}
startupListener.run()
FX.dicontainer =
object : DIContainer {
override fun <T : Any> getInstance(type: KClass<T>): T =
GlobalContext.get().get(type)
override fun <T : Any> getInstance(type: KClass<T>, name: String): T =
GlobalContext.get().get(type, named(name))
}
fire(ApplicationInitialized)
initialized = true
coroutineScope.launch {
GuiEventBus.publishEvent(GuiEventBus.ApplicationInitialized)
initialized = true
}
}
super.start(stage)
}
override fun stop() { // On stop, we have to stop spring as well
override fun stop() {
coroutineScope.cancel()
super.stop()
if (initialized) {
//CLOSE
}
exitProcess(0)
}
@@ -82,6 +102,7 @@ class VripperGuiApplication : App(
}
fun main(args: Array<String>) {
System.setProperty("prism.lcdtext", "false");
AppLock.exclusiveLock()
Application.launch(VripperGuiApplication::class.java, *args)
}
@@ -1,54 +0,0 @@
package me.vripper.gui.clipboard
import javafx.scene.input.Clipboard
import kotlinx.coroutines.*
import me.vripper.event.EventBus
import me.vripper.event.SettingsUpdateEvent
import me.vripper.model.Settings
import me.vripper.services.AppEndpointService
import me.vripper.services.SettingsService
import tornadofx.runLater
class ClipboardService(
private val appEndpointService: AppEndpointService,
private val settingsService: SettingsService,
private val eventBus: EventBus
) {
private var current: String? = null
private var coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private var pollJob: Job? = null
fun init() {
eventBus.events.ofType(SettingsUpdateEvent::class.java).subscribe {
run(it.settings)
}
run(settingsService.settings)
}
private fun run(settings: Settings) {
pollJob?.cancel()
if (settings.systemSettings.enableClipboardMonitoring) {
pollJob = coroutineScope.launch {
while (isActive) {
runLater {
poll()
}
delay(settings.systemSettings.clipboardPollingRate.toLong())
}
}
} else {
current = null
}
}
private fun poll() {
val clipboard = Clipboard.getSystemClipboard()
if (clipboard.hasString()) {
val value: String? = clipboard.string
if (!value.isNullOrBlank() && value != this.current) {
this.current = value
appEndpointService.scanLinks(value)
}
}
}
}
@@ -0,0 +1,22 @@
package me.vripper.gui.components.cells
import javafx.collections.ObservableList
import javafx.geometry.Pos
import javafx.scene.control.TableCell
import org.kordamp.ikonli.feather.Feather
import org.kordamp.ikonli.javafx.FontIcon
class PreviewTableCell<T> : TableCell<T, ObservableList<String>>() {
init {
alignment = Pos.CENTER
}
override fun updateItem(item: ObservableList<String>?, empty: Boolean) {
super.updateItem(item, empty)
graphic = if (!empty) {
FontIcon.of(Feather.IMAGE)
} else {
null
}
}
}
@@ -1,4 +1,4 @@
package me.vripper.gui.view
package me.vripper.gui.components.cells
import javafx.beans.value.ObservableValue
import javafx.event.EventHandler
@@ -1,10 +1,12 @@
package me.vripper.gui.view
package me.vripper.gui.components.cells
import atlantafx.base.theme.Styles
import javafx.geometry.Pos
import javafx.scene.control.TableCell
import javafx.scene.control.Tooltip
import javafx.scene.image.ImageView
import me.vripper.entities.domain.Status
import org.kordamp.ikonli.feather.Feather
import org.kordamp.ikonli.javafx.FontIcon
class StatusTableCell<T> : TableCell<T, String>() {
@@ -22,13 +24,11 @@ class StatusTableCell<T> : TableCell<T, String>() {
val status = Status.valueOf(item)
tooltip = Tooltip(status.stringValue)
graphic = when (status) {
Status.PENDING -> ImageView("pending.png").apply { fitWidth = 25.0; fitHeight = 25.0 }
Status.DOWNLOADING -> ImageView("below.png").apply { fitWidth = 25.0; fitHeight = 25.0 }
Status.FINISHED -> ImageView("ok.png").apply { fitWidth = 25.0; fitHeight = 25.0 }
Status.ERROR -> ImageView("error.png").apply { fitWidth = 25.0; fitHeight = 25.0 }
Status.STOPPED -> ImageView("pause-round.png").apply {
fitWidth = 25.0; fitHeight = 25.0
}
Status.PENDING -> FontIcon.of(Feather.CLOCK)
Status.DOWNLOADING -> FontIcon.of(Feather.DOWNLOAD).apply { styleClass.add(Styles.ACCENT) }
Status.FINISHED -> FontIcon.of(Feather.CHECK).apply { styleClass.add(Styles.SUCCESS) }
Status.ERROR -> FontIcon.of(Feather.ALERT_TRIANGLE).apply { styleClass.add(Styles.DANGER) }
Status.STOPPED -> FontIcon.of(Feather.PAUSE)
}
}
}
@@ -0,0 +1,754 @@
package me.vripper.gui.components.fragments
import javafx.geometry.Insets
import javafx.scene.control.TabPane
import javafx.scene.text.FontWeight
import me.vripper.gui.controller.WidgetsController
import me.vripper.gui.utils.openLink
import me.vripper.utilities.ApplicationProperties
import tornadofx.*
import kotlin.io.path.pathString
class AboutFragment : Fragment("About") {
private val widgetsController: WidgetsController by inject()
override val root = tabpane()
init {
with(root) {
tab("About") {
tabClosingPolicy = TabPane.TabClosingPolicy.UNAVAILABLE
hbox {
padding = Insets(15.0, 15.0, 15.0, 15.0)
spacing = 15.0
imageview("icons/64x64.png")
vbox {
spacing = 5.0
text("VRipper") {
style {
fontWeight = FontWeight.BOLD
fontSize = Dimension(18.0, Dimension.LinearUnits.px)
}
}
text("Version ${ApplicationProperties.VERSION}")
text("Developed by death-claw and VRipper working group")
hyperlink("Home Page") {
action {
openLink("https://github.com/death-claw/vripper-project")
}
}
}
}
}
tab("System") {
form {
fieldset {
field("Application data folder") {
textfield {
text = ApplicationProperties.VRIPPER_DIR.pathString
isEditable = false
}
}
field("Previews Path") {
textfield(widgetsController.currentSettings.cachePathProperty) {
isEditable = false
}
button("Browse") {
action {
val directory = chooseDirectory(title = "Select previews folder")
if (directory != null) {
widgetsController.currentSettings.cachePathProperty.set(directory.path)
}
}
}
}
}
}
}
tab("License") {
textarea(
"""
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>.
""".trimIndent()
).apply {
isEditable = false
}
}
}
}
}
@@ -1,15 +1,21 @@
package me.vripper.gui.view.popup
package me.vripper.gui.components.fragments
import atlantafx.base.theme.Styles
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos
import javafx.scene.control.TextArea
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import me.vripper.gui.controller.PostController
import tornadofx.*
class AddView : Fragment("Add thread links") {
class AddLinksFragment : Fragment("Add thread links") {
private val coroutineScope = CoroutineScope(SupervisorJob())
private val textAreaProperty = SimpleStringProperty()
private val postController: PostController by inject()
lateinit var input: TextArea
@@ -22,15 +28,19 @@ class AddView : Fragment("Add thread links") {
bind(textAreaProperty)
}
button("Scan") {
imageview("search.png") {
fitWidth = 18.0
fitHeight = 18.0
}
isDefaultButton
addClass(Styles.ACCENT)
disableWhen(textAreaProperty.isEmpty)
action {
postController.scan(textAreaProperty.value)
coroutineScope.launch {
postController.scan(textAreaProperty.value)
}
close()
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -0,0 +1,19 @@
package me.vripper.gui.components.fragments
import javafx.beans.property.SimpleBooleanProperty
import javafx.collections.FXCollections
import tornadofx.Fragment
import tornadofx.listview
import tornadofx.useCheckbox
class ColumnSelectionFragment : Fragment("Column Selection") {
val map: MutableMap<String, SimpleBooleanProperty> by param()
override val root = listview<String> {
items = FXCollections.observableArrayList(map.keys)
useCheckbox { listItem ->
map[listItem]!!
}
}
}
@@ -0,0 +1,63 @@
package me.vripper.gui.components.fragments
import javafx.scene.control.Spinner
import kotlinx.coroutines.*
import me.vripper.gui.controller.SettingsController
import me.vripper.gui.model.settings.ConnectionSettingsModel
import me.vripper.model.ConnectionSettings
import tornadofx.*
class ConnectionSettingsFragment : Fragment("Connection Settings") {
private val settingsController: SettingsController by inject()
private val coroutineScope = CoroutineScope(SupervisorJob())
private lateinit var connectionSettings: ConnectionSettings
val connectionSettingsModel = ConnectionSettingsModel()
override val root = vbox {}
init {
coroutineScope.launch {
async { connectionSettings = settingsController.findConnectionSettings() }.await()
runLater {
with(root) {
form {
fieldset {
field("Concurrent downloads per host") {
add(Spinner<Int>(1, 4, connectionSettings.maxConcurrentPerHost).apply {
connectionSettingsModel.maxThreadsProperty.bind(valueProperty())
isEditable = true
atlantafx.base.util.IntegerStringConverter.createFor(this)
})
}
field("Global concurrent downloads") {
add(Spinner<Int>(0, 24, connectionSettings.maxGlobalConcurrent).apply {
connectionSettingsModel.maxTotalThreadsProperty.bind(valueProperty())
isEditable = true
atlantafx.base.util.IntegerStringConverter.createFor(this)
})
}
field("Connection timeout (s)") {
add(Spinner<Int>(1, 300, connectionSettings.timeout).apply {
connectionSettingsModel.timeoutProperty.bind(valueProperty())
isEditable = true
atlantafx.base.util.IntegerStringConverter.createFor(this)
})
}
field("Maximum attempts") {
add(Spinner<Int>(1, 10, connectionSettings.maxAttempts).apply {
connectionSettingsModel.maxAttemptsProperty.bind(valueProperty())
isEditable = true
atlantafx.base.util.IntegerStringConverter.createFor(this)
})
}
}
}
}
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -0,0 +1,100 @@
package me.vripper.gui.components.fragments
import atlantafx.base.util.IntegerStringConverter
import javafx.scene.control.Spinner
import kotlinx.coroutines.*
import me.vripper.gui.controller.SettingsController
import me.vripper.gui.controller.WidgetsController
import me.vripper.gui.model.settings.DownloadSettingsModel
import me.vripper.model.DownloadSettings
import tornadofx.*
class DownloadSettingsFragment : Fragment("Download Settings") {
private val settingsController: SettingsController by inject()
private val widgetsController: WidgetsController by inject()
private val coroutineScope = CoroutineScope(SupervisorJob())
private lateinit var downloadSettings: DownloadSettings
val downloadSettingsModel = DownloadSettingsModel()
override val root = vbox {}
init {
coroutineScope.launch {
async {
downloadSettings = settingsController.findDownloadSettings()
downloadSettingsModel.downloadPath = downloadSettings.downloadPath
downloadSettingsModel.autoStart = downloadSettings.autoStart
downloadSettingsModel.forceOrder = downloadSettings.forceOrder
downloadSettingsModel.forumSubfolder = downloadSettings.forumSubDirectory
downloadSettingsModel.threadSubLocation = downloadSettings.threadSubLocation
downloadSettingsModel.clearCompleted = downloadSettings.clearCompleted
downloadSettingsModel.appendPostId = downloadSettings.appendPostId
}.await()
runLater {
with(root) {
form {
fieldset {
field("Download Path") {
textfield(downloadSettingsModel.downloadPathProperty) {
editableWhen(widgetsController.currentSettings.localSessionProperty.not())
}
button("Browse") {
visibleWhen(widgetsController.currentSettings.localSessionProperty)
action {
val directory = chooseDirectory(title = "Select download folder")
if (directory != null) {
downloadSettingsModel.downloadPathProperty.set(directory.path)
}
}
}
}
field("Auto start downloads") {
checkbox {
bind(downloadSettingsModel.autoStartProperty)
}
}
field("Auto queue thread if post count is below or equal to") {
add(Spinner<Int>(1, Int.MAX_VALUE, downloadSettings.autoQueueThreshold).apply {
downloadSettingsModel.autoQueueThresholdProperty.bind(valueProperty())
isEditable = true
IntegerStringConverter.createFor(this)
})
}
field("Organize by category") {
checkbox {
bind(downloadSettingsModel.forumSubfolderProperty)
}
}
field("Organize by thread") {
checkbox {
bind(downloadSettingsModel.threadSubLocationProperty)
}
}
field("Order images") {
checkbox {
bind(downloadSettingsModel.forceOrderProperty)
}
}
field("Append post id to download folder") {
checkbox {
bind(downloadSettingsModel.appendPostIdProperty)
}
}
field("Clear Finished") {
checkbox {
bind(downloadSettingsModel.clearCompletedProperty)
}
}
}
}
}
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -1,4 +1,4 @@
package me.vripper.gui.view.popup
package me.vripper.gui.components.fragments
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos
@@ -7,7 +7,7 @@ import javafx.scene.layout.VBox
import me.vripper.gui.model.LogModel
import tornadofx.*
class LogMessageView : Fragment("Log message") {
class LogMessageFragment : Fragment("Log message") {
val logModel: LogModel by param()
private val textAreaProperty = SimpleStringProperty(logModel.message)
@@ -0,0 +1,51 @@
package me.vripper.gui.components.fragments
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos
import javafx.scene.control.ComboBox
import kotlinx.coroutines.*
import me.vripper.gui.controller.PostController
import tornadofx.*
class RenameFragment : Fragment("Rename download post") {
val postId: Long by param()
val name: String by param()
val altTitles: List<String> by param()
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val textInputProperty = SimpleStringProperty()
private val postController: PostController by inject()
private lateinit var comboBox: ComboBox<String>
override fun onDock() {
textInputProperty.value = name
}
override val root = vbox(alignment = Pos.CENTER_RIGHT) {
padding = insets(all = 5)
spacing = 5.0
form {
fieldset {
field("Name") {
comboBox = combobox(textInputProperty, altTitles.ifEmpty { listOf(name) }) {
useMaxSize = true
isEditable = true
}
}
}
}
button("Rename") {
disableWhen(comboBox.editor.textProperty().isEmpty)
action {
coroutineScope.launch {
postController.rename(postId, comboBox.editor.text.trim())
}
close()
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -0,0 +1,144 @@
package me.vripper.gui.components.fragments
import atlantafx.base.theme.Styles
import atlantafx.base.util.IntegerStringConverter
import io.grpc.ConnectivityState
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos
import javafx.scene.control.RadioButton
import javafx.scene.control.Spinner
import javafx.scene.control.ToggleGroup
import javafx.scene.layout.VBox
import kotlinx.coroutines.*
import me.vripper.gui.VripperGuiApplication
import me.vripper.gui.components.views.AppView
import me.vripper.gui.controller.WidgetsController
import me.vripper.gui.event.GuiEventBus
import me.vripper.gui.services.DatabaseManager
import me.vripper.gui.services.GrpcEndpointService
import tornadofx.*
class SessionFragment : Fragment("Change Session") {
val component: UIComponent by param()
private val coroutineScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val widgetsController: WidgetsController by inject()
private val grpcEndpointService: GrpcEndpointService by di("remoteAppEndpointService")
private val toggleGroup = ToggleGroup()
private val disableConfirm = SimpleBooleanProperty(false)
private val message = SimpleStringProperty()
override val root = VBox().apply {
alignment = Pos.CENTER
padding = insets(all = 5)
spacing = 5.0
}
init {
with(root) {
form {
fieldset("Source") {
radiobutton(text = "Start Local Session", group = toggleGroup) {
id = "localSession"
isSelected = widgetsController.currentSettings.localSession
}
val remoteRadio = radiobutton(text = "Connect to Remote Session", group = toggleGroup) {
id = "remoteSession"
isSelected = !widgetsController.currentSettings.localSession
}
field("Host") {
enableWhen { remoteRadio.selectedProperty() }
textfield(widgetsController.currentSettings.remoteSessionModel.hostProperty) {}
}
field("Port") {
enableWhen { remoteRadio.selectedProperty() }
add(Spinner<Int>(0, 65535, widgetsController.currentSettings.remoteSessionModel.port).apply {
widgetsController.currentSettings.remoteSessionModel.portProperty.bind(valueProperty())
isEditable = true
IntegerStringConverter.createFor(this)
})
}
}
}
borderpane {
left {
padding = insets(all = 5.0)
label(message) {
disableWhen { message.isBlank() }
}
}
right {
padding = insets(all = 5.0)
button("Ok") {
enableWhen { toggleGroup.selectedToggleProperty().isNotNull.and(disableConfirm.not()) }
addClass(Styles.ACCENT)
isDefaultButton = true
action {
val selectedToggle = toggleGroup.selectedToggle
if (selectedToggle == null) {
VripperGuiApplication.APP_INSTANCE.stop()
}
when ((selectedToggle as RadioButton).id) {
"localSession" -> {
coroutineScope.launch {
runLater {
disableConfirm.set(true)
message.set("Starting...")
}
widgetsController.currentSettings.localSession = true
DatabaseManager.connect()
GuiEventBus.publishEvent(GuiEventBus.ChangingSession)
grpcEndpointService.disconnect()
GuiEventBus.publishEvent(GuiEventBus.LocalSession)
runLater {
component.replaceWith(find<AppView>())
close()
}
}
}
"remoteSession" -> {
coroutineScope.launch {
runLater {
disableConfirm.set(true)
message.set("Connecting...")
}
widgetsController.currentSettings.localSession = false
DatabaseManager.disconnect()
GuiEventBus.publishEvent(GuiEventBus.ChangingSession)
grpcEndpointService.disconnect()
grpcEndpointService.connect(
widgetsController.currentSettings.remoteSessionModel.host,
widgetsController.currentSettings.remoteSessionModel.port
)
repeat(10) {
if (grpcEndpointService.connectionState() == ConnectivityState.READY) {
GuiEventBus.publishEvent(GuiEventBus.RemoteSession)
runLater {
component.replaceWith(find<AppView>())
close()
}
cancel()
}
delay(333)
}
runLater {
disableConfirm.set(false)
message.set("Unable to connect")
}
}
}
else -> VripperGuiApplication.APP_INSTANCE.stop()
}
}
}
}
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -0,0 +1,83 @@
package me.vripper.gui.components.fragments
import atlantafx.base.theme.Styles
import javafx.geometry.Pos
import javafx.scene.control.Alert
import javafx.scene.control.TabPane
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import me.vripper.exception.ValidationException
import me.vripper.gui.controller.SettingsController
import org.kordamp.ikonli.feather.Feather
import org.kordamp.ikonli.javafx.FontIcon
import tornadofx.*
class SettingsFragment : Fragment("Settings") {
private val settingsController: SettingsController by inject()
private val coroutineScope = CoroutineScope(SupervisorJob())
private val downloadSettingsFragment: DownloadSettingsFragment = find()
private val connectionSettingsFragment: ConnectionSettingsFragment = find()
private val viperSettingsFragment: ViperSettingsFragment = find()
private val systemSettingsFragment: SystemSettingsFragment = find()
override val root = vbox(alignment = Pos.CENTER_RIGHT) {
spacing = 5.0
tabpane {
tabClosingPolicy = TabPane.TabClosingPolicy.UNAVAILABLE
VBox.setVgrow(this, Priority.ALWAYS)
tab(downloadSettingsFragment.title) {
add(downloadSettingsFragment)
graphic = FontIcon.of(Feather.FOLDER)
}
tab(connectionSettingsFragment.title) {
add(connectionSettingsFragment)
graphic = FontIcon.of(Feather.ACTIVITY)
}
tab(systemSettingsFragment.title) {
add(systemSettingsFragment)
graphic = FontIcon.of(Feather.CLIPBOARD)
}
tab(viperSettingsFragment.title) {
add(viperSettingsFragment)
graphic = FontIcon.of(Feather.LINK_2)
}
}
borderpane {
right {
padding = insets(all = 5.0)
button("Save") {
graphic = FontIcon.of(Feather.SAVE)
addClass(Styles.ACCENT)
isDefaultButton = true
action {
coroutineScope.launch {
try {
settingsController.saveNewSettings(
downloadSettingsFragment.downloadSettingsModel,
connectionSettingsFragment.connectionSettingsModel,
viperSettingsFragment.viperSettingsModel,
systemSettingsFragment.systemSettingsModel
)
runLater {
close()
}
} catch (e: ValidationException) {
alert(Alert.AlertType.ERROR, "Invalid settings", e.message)
}
}
}
}
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -0,0 +1,86 @@
package me.vripper.gui.components.fragments
import atlantafx.base.controls.ToggleSwitch
import atlantafx.base.util.IntegerStringConverter
import javafx.scene.control.Spinner
import kotlinx.coroutines.*
import me.vripper.gui.controller.SettingsController
import me.vripper.gui.controller.WidgetsController
import me.vripper.gui.model.settings.SystemSettingsModel
import me.vripper.model.SystemSettings
import tornadofx.*
class SystemSettingsFragment : Fragment("System Settings") {
private val settingsController: SettingsController by inject()
private val widgetsController: WidgetsController by inject()
private val coroutineScope = CoroutineScope(SupervisorJob())
private lateinit var systemSettings: SystemSettings
val systemSettingsModel = SystemSettingsModel()
override val root = vbox {}
init {
coroutineScope.launch {
async {
systemSettings = settingsController.findSystemSettings()
systemSettingsModel.tempPath = systemSettings.tempPath
}.await()
runLater {
with(root) {
form {
fieldset {
field("Temporary Path") {
textfield(systemSettingsModel.tempPathProperty) {
editableWhen(widgetsController.currentSettings.localSessionProperty.not())
}
button("Browse") {
visibleWhen(widgetsController.currentSettings.localSessionProperty)
action {
val directory = chooseDirectory(title = "Select temporary folder")
if (directory != null) {
systemSettingsModel.tempPathProperty.set(directory.path)
}
}
}
}
field("Max log entries") {
add(Spinner<Int>(10, 10000, systemSettings.maxEventLog).apply {
systemSettingsModel.logEntriesProperty.bind(valueProperty())
isEditable = true
IntegerStringConverter.createFor(this)
})
}
fieldset {
field("Clipboard monitoring") {
add(ToggleSwitch().apply {
isSelected = systemSettings.enableClipboardMonitoring
systemSettingsModel.enableProperty.bind(selectedProperty())
})
}
fieldset {
visibleWhen(systemSettingsModel.enableProperty)
field("Polling rate (ms)") {
add(
Spinner<Int>(
500,
kotlin.Int.MAX_VALUE,
systemSettings.clipboardPollingRate
).apply {
systemSettingsModel.pollingRateProperty.bind(valueProperty())
isEditable = true
IntegerStringConverter.createFor(this)
})
}
}
}
}
}
}
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -0,0 +1,234 @@
package me.vripper.gui.components.fragments
import atlantafx.base.theme.Styles
import javafx.beans.property.SimpleStringProperty
import javafx.event.EventHandler
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.control.*
import javafx.scene.control.cell.TextFieldTableCell
import javafx.scene.input.MouseButton
import javafx.scene.layout.Priority
import javafx.util.Callback
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.javafx.asFlow
import me.vripper.gui.components.cells.PreviewTableCell
import me.vripper.gui.controller.ThreadController
import me.vripper.gui.controller.WidgetsController
import me.vripper.gui.model.ThreadSelectionModel
import me.vripper.gui.utils.Preview
import me.vripper.gui.utils.openLink
import org.kordamp.ikonli.feather.Feather
import org.kordamp.ikonli.javafx.FontIcon
import tornadofx.*
import kotlin.io.path.Path
class ThreadSelectionTableFragment : Fragment("Thread") {
private lateinit var tableView: TableView<ThreadSelectionModel>
private val threadController: ThreadController by inject()
private val widgetsController: WidgetsController by inject()
private var items = SortedFilteredList<ThreadSelectionModel>()
private var preview: Preview? = null
private val searchInput = SimpleStringProperty()
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
val threadId: Long by param()
override fun onDock() {
tableView.prefWidthProperty().bind(root.widthProperty())
tableView.prefHeightProperty().bind(root.heightProperty())
tableView.placeholder = Label("Loading")
coroutineScope.launch {
val list = async { threadController.grab(threadId) }.await()
runLater {
items.addAll(list)
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
override val root = vbox(alignment = Pos.CENTER_RIGHT, spacing = 15.0) {
hbox(spacing = 5, alignment = Pos.BASELINE_LEFT) {
padding = Insets(10.0, 5.0, 0.0, 5.0)
textfield(searchInput) {
promptText = "Search"
hgrow = Priority.ALWAYS
}
}
tableView = tableview(items) {
addClass(Styles.DENSE)
selectionModel.selectionMode = SelectionMode.MULTIPLE
setRowFactory {
val tableRow = TableRow<ThreadSelectionModel>()
tableRow.setOnMouseClicked {
if (it.button.equals(MouseButton.PRIMARY) && it.clickCount == 2 && tableRow.item != null) {
coroutineScope.launch {
async { threadController.download(listOf(tableRow.item)) }.await()
runLater {
close()
}
}
}
}
val urlItem = MenuItem("Open link").apply {
setOnAction {
openLink(tableRow.item.url)
}
graphic = FontIcon.of(Feather.LINK)
}
val contextMenu = ContextMenu()
contextMenu.items.addAll(urlItem)
tableRow.contextMenuProperty().bind(tableRow.emptyProperty()
.map { empty -> if (empty) null else contextMenu })
tableRow
}
contextMenu = ContextMenu()
contextMenu.items.add(MenuItem("Setup columns").apply {
setOnAction {
find<ColumnSelectionFragment>(
mapOf(
ColumnSelectionFragment::map to mapOf(
Pair(
"Preview",
widgetsController.currentSettings.threadSelectionColumnsModel.previewProperty
),
Pair(
"Post Index",
widgetsController.currentSettings.threadSelectionColumnsModel.indexProperty
),
Pair(
"Title",
widgetsController.currentSettings.threadSelectionColumnsModel.titleProperty
),
Pair(
"URL",
widgetsController.currentSettings.threadSelectionColumnsModel.linkProperty
),
Pair(
"Hosts",
widgetsController.currentSettings.threadSelectionColumnsModel.hostsProperty
),
)
)
).openModal()
}
graphic = FontIcon.of(Feather.COLUMNS)
})
column("Preview", ThreadSelectionModel::previewListProperty) {
prefWidth = 100.0
visibleProperty().bind(widgetsController.currentSettings.threadSelectionColumnsModel.previewProperty)
cellFactory = Callback {
val cell = PreviewTableCell<ThreadSelectionModel>()
cell.onMouseExited = EventHandler {
preview?.hide()
}
cell.onMouseMoved = EventHandler {
preview?.previewPopup?.apply {
x = it.screenX + 20
y = it.screenY + 10
}
}
cell.onMouseEntered = EventHandler { mouseEvent ->
preview?.hide()
if (cell.tableRow.item != null && cell.tableRow.item.previewList.isNotEmpty()) {
preview = Preview(
currentStage!!,
cell.tableRow.item.previewList,
Path(widgetsController.currentSettings.cachePath)
)
preview?.previewPopup?.apply {
x = mouseEvent.screenX + 20
y = mouseEvent.screenY + 10
}
}
}
cell
}
}
column("Post Index", ThreadSelectionModel::indexProperty) {
prefWidth = widgetsController.currentSettings.threadSelectionColumnsWidthModel.index
coroutineScope.launch {
widthProperty().asFlow().debounce(200).collect {
widgetsController.currentSettings.threadSelectionColumnsWidthModel.index = it as Double
}
}
visibleProperty().bind(widgetsController.currentSettings.threadSelectionColumnsModel.indexProperty)
sortOrder.add(this)
cellFactory = Callback {
TextFieldTableCell<ThreadSelectionModel?, Number?>().apply { alignment = Pos.CENTER_LEFT }
}
}
column("Title", ThreadSelectionModel::titleProperty) {
visibleProperty().bind(widgetsController.currentSettings.threadSelectionColumnsModel.titleProperty)
prefWidth = widgetsController.currentSettings.threadSelectionColumnsWidthModel.title
coroutineScope.launch {
widthProperty().asFlow().debounce(200).collect {
widgetsController.currentSettings.threadSelectionColumnsWidthModel.title = it as Double
}
}
cellFactory = Callback {
TextFieldTableCell<ThreadSelectionModel?, String?>().apply { alignment = Pos.CENTER_LEFT }
}
}
column("URL", ThreadSelectionModel::urlProperty) {
visibleProperty().bind(widgetsController.currentSettings.threadSelectionColumnsModel.linkProperty)
prefWidth = widgetsController.currentSettings.threadSelectionColumnsWidthModel.link
coroutineScope.launch {
widthProperty().asFlow().debounce(200).collect {
widgetsController.currentSettings.threadSelectionColumnsWidthModel.link = it as Double
}
}
cellFactory = Callback {
TextFieldTableCell<ThreadSelectionModel?, String?>().apply { alignment = Pos.CENTER_LEFT }
}
}
column("Hosts", ThreadSelectionModel::hostsProperty) {
prefWidth = widgetsController.currentSettings.threadSelectionColumnsWidthModel.hosts
coroutineScope.launch {
widthProperty().asFlow().debounce(200).collect {
widgetsController.currentSettings.threadSelectionColumnsWidthModel.hosts = it as Double
}
}
visibleProperty().bind(widgetsController.currentSettings.threadSelectionColumnsModel.hostsProperty)
cellFactory = Callback {
TextFieldTableCell<ThreadSelectionModel?, String?>().apply { alignment = Pos.CENTER_LEFT }
}
}
}
borderpane {
right {
padding = insets(top = 0, right = 5, bottom = 5, left = 5)
button("Download") {
graphic = FontIcon.of(Feather.DOWNLOAD)
addClass(Styles.ACCENT)
isDefaultButton = true
tooltip("Download selected posts")
enableWhen { tableView.selectionModel.selectedItems.sizeProperty.greaterThan(0) }
action {
coroutineScope.launch {
async { threadController.download(tableView.selectionModel.selectedItems) }.await()
runLater {
close()
}
}
}
}
}
}
searchInput.onChange { search ->
if (search != null) {
items.predicate = { it.title.contains(search, true) }
}
}
items.bindTo(tableView)
}
}
@@ -0,0 +1,67 @@
package me.vripper.gui.components.fragments
import atlantafx.base.controls.ToggleSwitch
import javafx.collections.FXCollections
import kotlinx.coroutines.*
import me.vripper.gui.controller.SettingsController
import me.vripper.gui.model.settings.ViperSettingsModel
import me.vripper.model.ViperSettings
import tornadofx.*
class ViperSettingsFragment : Fragment("Viper Settings") {
private val settingsController: SettingsController by inject()
private val proxies = FXCollections.observableArrayList<String>()
private val coroutineScope = CoroutineScope(SupervisorJob())
private lateinit var viperGirlsSettings: ViperSettings
val viperSettingsModel = ViperSettingsModel()
override val root = vbox {}
init {
coroutineScope.launch {
async {
viperGirlsSettings = settingsController.findViperGirlsSettings()
viperSettingsModel.username = viperGirlsSettings.username
viperSettingsModel.password = viperGirlsSettings.password
viperSettingsModel.thanks = viperGirlsSettings.thanks
viperSettingsModel.host = viperGirlsSettings.host
proxies.addAll(settingsController.getProxies())
}.await()
runLater {
with(root) {
form {
fieldset {
field("Select a proxy") {
combobox(viperSettingsModel.hostProperty, proxies)
}
field("Enable ViperGirls Authentication") {
add(ToggleSwitch().apply {
isSelected = viperGirlsSettings.login
viperSettingsModel.loginProperty.bind(selectedProperty())
})
}
fieldset {
visibleWhen(viperSettingsModel.loginProperty)
field("ViperGirls Username") {
textfield(viperSettingsModel.usernameProperty)
}
field("ViperGirls Password") {
passwordfield(viperSettingsModel.passwordProperty)
}
field("Leave like") {
checkbox {
bind(viperSettingsModel.thanksProperty)
}
}
}
}
}
}
}
}
}
override fun onUndock() {
coroutineScope.cancel()
}
}
@@ -0,0 +1,211 @@
package me.vripper.gui.components.views
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleIntegerProperty
import javafx.geometry.Orientation
import javafx.scene.control.ButtonType
import javafx.scene.control.ContentDisplay
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.catch
import me.vripper.delegate.LoggerDelegate
import me.vripper.gui.components.fragments.AddLinksFragment
import me.vripper.gui.components.fragments.SettingsFragment
import me.vripper.gui.controller.PostController
import me.vripper.gui.event.GuiEventBus
import me.vripper.gui.services.GrpcEndpointService
import me.vripper.services.AppEndpointService
import me.vripper.services.IAppEndpointService
import org.kordamp.ikonli.feather.Feather
import org.kordamp.ikonli.javafx.FontIcon
import tornadofx.*
class ActionBarView : View() {
private val logger by LoggerDelegate()
private val downloadActiveProperty = SimpleBooleanProperty(true)
private val postController: PostController by inject()
private val postsTableView: PostsTableView by inject()
private val coroutineScope = CoroutineScope(SupervisorJob())
private val grpcEndpointService: GrpcEndpointService by di("remoteAppEndpointService")
private val localEndpointService: AppEndpointService by di("localAppEndpointService")
private val running = SimpleIntegerProperty(0)
private val jobs = mutableListOf<Job>()
override val root = toolbar {}
init {
coroutineScope.launch {
GuiEventBus.events.collect { event ->
when (event) {
is GuiEventBus.LocalSession -> {
connect(localEndpointService)
}
is GuiEventBus.RemoteSession -> {
connect(grpcEndpointService)
}
is GuiEventBus.ChangingSession -> {
jobs.forEach { it.cancel() }
jobs.clear()
}
}
}
}
with(root) {
id = "action_toolbar"
padding = insets(all = 5)
button("Add links", FontIcon.of(Feather.PLUS)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Add links [Ctrl+L]")
shortcut(KeyCodeCombination(KeyCode.L, KeyCombination.CONTROL_DOWN))
action {
find<AddLinksFragment>().apply {
input.clear()
}.openModal()
}
}
separator(Orientation.VERTICAL)
button("Start All", FontIcon.of(Feather.SKIP_FORWARD)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Start downloads [Ctrl+S]")
shortcut(KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN))
disableWhen(downloadActiveProperty)
action {
coroutineScope.launch {
postController.startAll()
}
}
}
button("Stop All", FontIcon.of(Feather.SQUARE)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Stops all running downloads [Ctrl+Q]")
shortcut(KeyCodeCombination(KeyCode.Q, KeyCombination.CONTROL_DOWN))
disableWhen(downloadActiveProperty.not())
action {
coroutineScope.launch {
postController.stopAll()
}
}
}
separator(Orientation.VERTICAL)
button("Start", FontIcon.of(Feather.PLAY)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Start downloads for selected [Ctrl+Shift+S]")
shortcut(KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN))
enableWhen(
postsTableView.tableView.selectionModel.selectedItems.sizeProperty.greaterThan(
0
)
)
action {
postsTableView.startSelected()
}
}
button("Stop", FontIcon.of(Feather.SQUARE)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Stop downloads for selected [Ctrl+Shift+Q]")
shortcut(KeyCodeCombination(KeyCode.Q, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN))
enableWhen(
postsTableView.tableView.selectionModel.selectedItems.sizeProperty.greaterThan(
0
)
)
action {
postsTableView.stopSelected()
}
}
button("Rename", FontIcon.of(Feather.EDIT)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Rename selected [Ctrl+R]")
shortcut(KeyCodeCombination(KeyCode.R, KeyCombination.CONTROL_DOWN))
enableWhen(
postsTableView.tableView.selectionModel.selectedItems.sizeProperty.greaterThan(
0
)
)
action {
postsTableView.renameSelected()
}
}
button("Bulk rename", FontIcon.of(Feather.EDIT_3)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Bulk rename selected [Ctrl+Shift+R]")
shortcut(KeyCodeCombination(KeyCode.R, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN))
enableWhen(
postsTableView.tableView.selectionModel.selectedItems.sizeProperty.greaterThan(
0
)
)
action {
postsTableView.bulkRenameSelected()
}
}
button("Delete", FontIcon.of(Feather.TRASH)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Delete selected posts [Del]")
shortcut(KeyCodeCombination(KeyCode.DELETE))
enableWhen(
postsTableView.tableView.selectionModel.selectedItems.sizeProperty.greaterThan(
0
)
)
action {
postsTableView.deleteSelected()
}
}
separator(Orientation.VERTICAL)
button("Clear", FontIcon.of(Feather.TRASH_2)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Clear all finished downloads [Ctrl+Del]")
shortcut(KeyCodeCombination(KeyCode.DELETE, KeyCombination.CONTROL_DOWN))
action {
confirm(
"",
"Confirm removal of finished posts?",
ButtonType.YES,
ButtonType.NO,
owner = primaryStage,
title = "Clean finished posts"
) {
coroutineScope.launch {
val clearPosts = async { postController.clearPosts() }.await()
runLater {
postsTableView.tableView.items.removeIf { clearPosts.contains(it.postId) }
}
}
}
}
}
button("Settings", FontIcon.of(Feather.SETTINGS)) {
contentDisplay = ContentDisplay.GRAPHIC_ONLY
tooltip("Open settings menu [S]")
shortcut(KeyCodeCombination(KeyCode.S))
action {
find<SettingsFragment>().openModal(owner = primaryStage)?.apply {
minWidth = 700.0
minHeight = 400.0
}
}
}
}
downloadActiveProperty.bind(running.greaterThan(0))
}
private fun connect(appEndpointService: IAppEndpointService) {
coroutineScope.launch {
appEndpointService.onQueueStateUpdate().catch {
logger.error("gRPC error", it)
currentCoroutineContext().cancel(null)
}.collect {
runLater {
running.set(it.running)
}
}
}.also { jobs.add(it) }
}
}
@@ -0,0 +1,110 @@
package me.vripper.gui.components.views
import atlantafx.base.theme.CupertinoDark
import atlantafx.base.theme.CupertinoLight
import io.grpc.ConnectivityState
import javafx.application.Application
import kotlinx.coroutines.*
import me.vripper.gui.components.fragments.SessionFragment
import me.vripper.gui.controller.MainController
import me.vripper.gui.controller.WidgetsController
import me.vripper.gui.event.GuiEventBus
import me.vripper.gui.listener.GuiStartupLister
import me.vripper.gui.services.GrpcEndpointService
import tornadofx.View
import tornadofx.onChange
import tornadofx.runLater
import tornadofx.vbox
class AppView : View() {
override val root = vbox { }
private val mainController: MainController by inject()
private val menuBarView: MenuBarView by inject()
private val mainView: MainView by inject()
private val statusBarView: StatusBarView by inject()
private val actionBarView: ActionBarView by inject()
private val widgetsController: WidgetsController by inject()
private val grpcEndpointService: GrpcEndpointService by di("remoteAppEndpointService")
private val coroutineScope: CoroutineScope = CoroutineScope(SupervisorJob())
private var job: Job? = null
init {
title = "VRipper ${mainController.version}"
with(root) {
add(menuBarView)
if (widgetsController.currentSettings.visibleToolbarPanel) {
add(actionBarView)
}
add(mainView)
if (widgetsController.currentSettings.visibleStatusBarPanel) {
add(statusBarView)
}
prefWidth = widgetsController.currentSettings.width
prefHeight = widgetsController.currentSettings.height
}
widgetsController.currentSettings.visibleToolbarPanelProperty.onChange { it ->
if (it) {
root.children.add(1, actionBarView.root)
} else {
root.children.removeIf { it.id == "action_toolbar" }
}
}
widgetsController.currentSettings.visibleStatusBarPanelProperty.onChange { it ->
if (it) {
root.children.add(statusBarView.root)
} else {
root.children.removeIf { it.id == "statusbar" }
}
}
widgetsController.currentSettings.darkModeProperty.onChange {
if (it) {
Application.setUserAgentStylesheet(CupertinoDark().userAgentStylesheet)
} else {
Application.setUserAgentStylesheet(CupertinoLight().userAgentStylesheet)
}
}
coroutineScope.launch {
GuiEventBus.events.collect {
when (it) {
is GuiEventBus.LocalSession -> {
job?.cancel()
GuiStartupLister().run()
}
is GuiEventBus.RemoteSession -> {
job?.cancel()
job = launch {
while (isActive) {
if (grpcEndpointService.connectionState() != ConnectivityState.READY) {
val loadingView = find<LoadingView>()
runLater {
replaceWith(loadingView)
find<SessionFragment>(mapOf(SessionFragment::component to loadingView)).openModal()
}
cancel()
}
delay(1000)
}
}
}
}
}
}
runLater {
if (widgetsController.currentSettings.localSession) {
runBlocking {
GuiEventBus.publishEvent(GuiEventBus.LocalSession)
}
} else {
runBlocking {
GuiEventBus.publishEvent(GuiEventBus.RemoteSession)
}
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More