work branch into the main #8
58 changed files with 5288 additions and 2286 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1,2 +1,3 @@
|
|||
config.json
|
||||
opensearch.xml
|
||||
config.ini
|
674
LICENSE
674
LICENSE
|
@ -1,19 +1,661 @@
|
|||
Copyright (c) 2024
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
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.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
Preamble
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
44
README.md
44
README.md
|
@ -2,14 +2,15 @@
|
|||
|
||||
## Completed Tasks
|
||||
|
||||
- [x] Text results
|
||||
- [x] Image results
|
||||
- [X] Text results
|
||||
- [X] Image results
|
||||
- [X] Video results
|
||||
- [X] Map results
|
||||
- [X] Forums results
|
||||
- [x] HTML+CSS site (no JS version)
|
||||
- [X] HTML+CSS site (no JS version)
|
||||
- [X] Results cache
|
||||
- [X] Torrent results
|
||||
- [X] Better name
|
||||
|
||||
## Pending Tasks
|
||||
|
||||
|
@ -17,31 +18,40 @@
|
|||
- [ ] JS applets for results (such as calculator)
|
||||
- [ ] Dynamic results loading as user scrolls
|
||||
- [ ] Replace fonts, replace icons font for SVG or remove unnecessary icons for faster loading
|
||||
- [ ] Better name
|
||||
- [ ] LXC container
|
||||
- [ ] Docker container
|
||||
- [ ] Automatic updates
|
||||
- [ ] Scalable crawlers and webservers + load balacing
|
||||
- [ ] LibreY-like API
|
||||
- [ ] Music results
|
||||
|
||||
# Ocásek (Warp) Search Engine
|
||||
# Warp (Ocásek) Search Engine
|
||||
|
||||
A self-hosted private and anonymous [metasearch engine](https://en.wikipedia.org/wiki/Metasearch_engine), that aims to be more resource effichent and scalable. Decentralized services are nice, but juming between instances when one just stops working for some reason is just inconvenient. So thats why this engine can do both, you can self-hoste it or use [officiall instance](https://search.spitfirebrowser.com/).
|
||||
A self-hosted private and anonymous [metasearch engine](https://en.wikipedia.org/wiki/Metasearch_engine), that aims to be more resource effichent and scalable than its competetion. Its scalable becouse switching instances when one just decides to not work/is under too much load is just inconvenient. So you can comfortably use [officiall instance](https://search.spitfirebrowser.com/), or self-host your own instance.
|
||||
|
||||
## Comparison to other search engines
|
||||
|
||||
| Name | Works without JS | Privacy frontend redirect | Torrent results | API | No 3rd party libs | Scalable | Not Resource Hungry | Dynamic Page Loading |
|
||||
|------------|----------------------|---------------------------|-----------------|-----|-------------------|----------|---------------------------------------------|----------------------|
|
||||
| Whoogle | ✅ | ❓ Only host can set it | ❌ | ❌ | ❌ | ❌ | ❓ Moderate | ❓ Not specified |
|
||||
| Araa-Search| ✅ | ✅ | ✅ | ✅ | ❓ | ❌ | ❌ Very resource hungry | ❌ |
|
||||
| LibreY | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❓ Moderate | ❌ |
|
||||
| Ocásek | ✅ | ✅ | ✅ | ❌ | ✅ [1] | ✅ | ✅ about 20MiB at idle, 21MiB when searching| ✅ |
|
||||
|
||||
[1]: It does not rely on 3rd-party libs for webscraping like [Selenium](https://www.javatpoint.com/selenium-webdriver), but it uses other search instalces like LibreX as fallback.
|
||||
| Feature | Whoogle | Araa-Search | LibreY | 4get | *Warp* |
|
||||
| :----------------------------------- | ------------------ | ------------------------- | ------------------------ | ------------------------ | ---------------------------------------------------- |
|
||||
| Works without JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| Music search | ❓ | ❌ | ❌ | ✅ | ✅ |
|
||||
| Torrent search | ❌ | ✅ | ✅ | ❌ | ✅ |
|
||||
| API | ❌ | ✅ | ✅ | ✅ | ✅ |
|
||||
| Scalable | ❌ | ❌ | ❌ | ❌ | ✅ |
|
||||
| Not Resource Hungry | ❓ Moderate | ❌ Very resource hungry | ❌ Moderate 200-400mb~ | ❌ Moderate 200-400mb~ | ✅ about 15-20MiB at idle, 17-22MiB when searching |
|
||||
| Dynamic Page Loading | ❓ Not specified | ❌ | ❌ | ❌ | ✅ |
|
||||
| User themable | ❌ | ✅ | ❌ | ❌ | ✅ |
|
||||
| It has dildo as logo, unironically | ❌ | ❌ | ❌ | ✅ | ❌ |
|
||||
|
||||
[1]: I was not able to check this since their site does not work, same for the community instances.
|
||||
|
||||
[2]: In the project repo they specify that it has API, but It looks like they are no loger supporting it. Or just removed "API" button and documentation, since I was not able to find it anymore.
|
||||
|
||||
## Features
|
||||
|
||||
- Text search using Google, Brave, DuckDuckGo and LibreX/Y search results.
|
||||
- Image search using the Qwant/Imgur.
|
||||
- Text search using Google, Brave, DuckDuckGo and LibreX/Y.
|
||||
- Image search using the Qwant, Bing and Imgur.
|
||||
- Video search using Piped API.
|
||||
- Image viewing using proxy and direct links to image source pages for image searches.
|
||||
- Maps using OpenStreetMap
|
||||
|
@ -65,3 +75,7 @@ chmod +x ./run.sh
|
|||
```
|
||||
|
||||
*Its that easy!*
|
||||
|
||||
## License
|
||||
|
||||
[![](https://www.gnu.org/graphics/agplv3-with-text-162x68.png)](https://www.gnu.org/licenses/agpl-3.0.html)
|
2
agent.go
Normal file → Executable file
2
agent.go
Normal file → Executable file
|
@ -260,7 +260,7 @@ func periodicUpdate() {
|
|||
// Fetch the latest browser versions
|
||||
newVersions, err := fetchLatestBrowserVersions()
|
||||
if err != nil {
|
||||
fmt.Println("Error fetching latest browser versions:", err)
|
||||
printWarn("Error fetching latest browser versions: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
5
cache.go
5
cache.go
|
@ -2,7 +2,6 @@ package main
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
|
@ -143,7 +142,7 @@ func (rc *ResultsCache) checkAndCleanCache() {
|
|||
func (rc *ResultsCache) memoryUsage() float64 {
|
||||
v, err := mem.VirtualMemory()
|
||||
if err != nil {
|
||||
log.Printf("Failed to get memory info: %v", err)
|
||||
printErr("Failed to get memory info: %v", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
|
@ -167,7 +166,7 @@ func (rc *ResultsCache) cleanOldestItems() {
|
|||
|
||||
if oldestKey != "" {
|
||||
delete(rc.results, oldestKey)
|
||||
log.Printf("Removed oldest cache item: %s", oldestKey)
|
||||
printDebug("Removed oldest cache item: %s", oldestKey)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
|
34
common.go
Normal file → Executable file
34
common.go
Normal file → Executable file
|
@ -1,11 +1,13 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"html/template"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
debugMode bool = true
|
||||
funcs = template.FuncMap{
|
||||
"sub": func(a, b int) int {
|
||||
return a - b
|
||||
|
@ -15,3 +17,33 @@ var (
|
|||
},
|
||||
}
|
||||
)
|
||||
|
||||
func generateStrongRandomString(length int) string {
|
||||
bytes := make([]byte, length)
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
printErr("Error generating random string: %v", err)
|
||||
}
|
||||
return base64.URLEncoding.EncodeToString(bytes)[:length]
|
||||
}
|
||||
|
||||
// Checks if the URL already includes a protocol
|
||||
func hasProtocol(url string) bool {
|
||||
return strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://")
|
||||
}
|
||||
|
||||
// Checks if the domain is a local address
|
||||
func isLocalAddress(domain string) bool {
|
||||
return domain == "localhost" || strings.HasPrefix(domain, "127.") || strings.HasPrefix(domain, "192.168.") || strings.HasPrefix(domain, "10.")
|
||||
}
|
||||
|
||||
// Ensures that HTTP or HTTPS is befor the adress if needed
|
||||
func addProtocol(domain string) string {
|
||||
if hasProtocol(domain) {
|
||||
return domain
|
||||
}
|
||||
if isLocalAddress(domain) {
|
||||
return "http://" + domain
|
||||
}
|
||||
return "https://" + domain
|
||||
}
|
||||
|
|
183
config.go
Normal file
183
config.go
Normal file
|
@ -0,0 +1,183 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"gopkg.in/ini.v1"
|
||||
)
|
||||
|
||||
func initConfig() error {
|
||||
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
|
||||
return createConfig()
|
||||
}
|
||||
|
||||
printInfo("Configuration file already exists.")
|
||||
config = loadConfig()
|
||||
return nil
|
||||
}
|
||||
|
||||
func createConfig() error {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
printMessage("Configuration file not found.")
|
||||
printMessage("Do you want to use default values? (yes/no): ")
|
||||
useDefaults, _ := reader.ReadString('\n')
|
||||
|
||||
if strings.TrimSpace(useDefaults) != "yes" {
|
||||
printMessage("Enter port (default 5000): ")
|
||||
portStr, _ := reader.ReadString('\n')
|
||||
if portStr != "\n" {
|
||||
port, err := strconv.Atoi(strings.TrimSpace(portStr))
|
||||
if err != nil {
|
||||
config.Port = 5000
|
||||
} else {
|
||||
config.Port = port
|
||||
}
|
||||
}
|
||||
|
||||
printMessage("Enter your domain address (default localhost): ")
|
||||
domain, _ := reader.ReadString('\n')
|
||||
if domain != "\n" {
|
||||
config.Domain = strings.TrimSpace(domain)
|
||||
}
|
||||
} else {
|
||||
config = defaultConfig
|
||||
}
|
||||
|
||||
if config.AuthCode == "" {
|
||||
config.AuthCode = generateStrongRandomString(64)
|
||||
printMessage("Generated connection code: %s\n", config.AuthCode)
|
||||
}
|
||||
|
||||
config.NodesEnabled = len(config.Peers) > 0
|
||||
config.CrawlerEnabled = true
|
||||
config.WebsiteEnabled = true
|
||||
config.LogLevel = 1
|
||||
|
||||
saveConfig(config)
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveConfig(config Config) {
|
||||
cfg := ini.Empty()
|
||||
sec := cfg.Section("")
|
||||
sec.Key("Port").SetValue(strconv.Itoa(config.Port))
|
||||
sec.Key("AuthCode").SetValue(config.AuthCode)
|
||||
sec.Key("PeerID").SetValue(config.PeerID)
|
||||
|
||||
peers := strings.Join(config.Peers, ",")
|
||||
sec.Key("Peers").SetValue(peers)
|
||||
sec.Key("Domain").SetValue(config.Domain)
|
||||
sec.Key("NodesEnabled").SetValue(strconv.FormatBool(config.NodesEnabled))
|
||||
sec.Key("CrawlerEnabled").SetValue(strconv.FormatBool(config.CrawlerEnabled))
|
||||
sec.Key("WebsiteEnabled").SetValue(strconv.FormatBool(config.WebsiteEnabled))
|
||||
sec.Key("LogLevel").SetValue(strconv.Itoa(config.LogLevel))
|
||||
|
||||
err := cfg.SaveTo(configFilePath)
|
||||
if err != nil {
|
||||
printErr("Error writing to config file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func loadConfig() Config {
|
||||
cfg, err := ini.Load(configFilePath)
|
||||
if err != nil {
|
||||
printErr("Error opening config file: %v", err)
|
||||
}
|
||||
|
||||
port, err := cfg.Section("").Key("Port").Int()
|
||||
if err != nil || port == 0 {
|
||||
port = 5000 // Default to 5000 if not set or error
|
||||
}
|
||||
|
||||
peersStr := cfg.Section("").Key("Peers").String()
|
||||
var peers []string
|
||||
if peersStr != "" {
|
||||
peers = strings.Split(peersStr, ",")
|
||||
for i, peer := range peers {
|
||||
peers[i] = addProtocol(peer)
|
||||
}
|
||||
}
|
||||
|
||||
domain := cfg.Section("").Key("Domain").String()
|
||||
if domain == "" {
|
||||
domain = "localhost" // Default to localhost if not set
|
||||
}
|
||||
|
||||
nodesEnabled, err := cfg.Section("").Key("NodesEnabled").Bool()
|
||||
if err != nil { // If NodesEnabled is not found in config
|
||||
nodesEnabled = len(peers) > 0 // Enable nodes if peers are configured
|
||||
}
|
||||
|
||||
crawlerEnabled, err := cfg.Section("").Key("CrawlerEnabled").Bool()
|
||||
if err != nil { // Default to true if not found
|
||||
crawlerEnabled = true
|
||||
}
|
||||
|
||||
websiteEnabled, err := cfg.Section("").Key("WebsiteEnabled").Bool()
|
||||
if err != nil { // Default to true if not found
|
||||
websiteEnabled = true
|
||||
}
|
||||
|
||||
logLevel, err := cfg.Section("").Key("LogLevel").Int()
|
||||
if err != nil || logLevel < 0 || logLevel > 4 { // Default to 1 if not found or out of range
|
||||
logLevel = 1
|
||||
}
|
||||
|
||||
config = Config{
|
||||
Port: port,
|
||||
AuthCode: cfg.Section("").Key("AuthCode").String(),
|
||||
PeerID: cfg.Section("").Key("PeerID").String(),
|
||||
Peers: peers,
|
||||
Domain: domain,
|
||||
NodesEnabled: nodesEnabled,
|
||||
CrawlerEnabled: crawlerEnabled,
|
||||
WebsiteEnabled: websiteEnabled,
|
||||
LogLevel: logLevel,
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
var configLock sync.RWMutex
|
||||
|
||||
func startFileWatcher() {
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
printErr("%v", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer watcher.Close()
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-watcher.Events:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if event.Op&fsnotify.Write == fsnotify.Write {
|
||||
printInfo("Modified file: %v", event.Name)
|
||||
configLock.Lock()
|
||||
config = loadConfig()
|
||||
configLock.Unlock()
|
||||
}
|
||||
case err, ok := <-watcher.Errors:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
printWarn("Error watching configuration file: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
err = watcher.Add(configFilePath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
89
files.go
Normal file → Executable file
89
files.go
Normal file → Executable file
|
@ -3,7 +3,6 @@ package main
|
|||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
|
@ -30,6 +29,8 @@ var (
|
|||
rutor TorrentSite
|
||||
)
|
||||
|
||||
var fileResultsChan = make(chan []TorrentResult)
|
||||
|
||||
func initializeTorrentSites() {
|
||||
torrentGalaxy = NewTorrentGalaxy()
|
||||
// nyaa = NewNyaa()
|
||||
|
@ -37,22 +38,22 @@ func initializeTorrentSites() {
|
|||
// rutor = NewRutor()
|
||||
}
|
||||
|
||||
func handleFileSearch(w http.ResponseWriter, query, safe, lang string, page int) {
|
||||
func handleFileSearch(w http.ResponseWriter, settings UserSettings, query string, page int) {
|
||||
startTime := time.Now()
|
||||
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "file"}
|
||||
combinedResults := getFileResultsFromCacheOrFetch(cacheKey, query, safe, lang, page)
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: settings.SafeSearch == "true", Lang: settings.Language, Type: "file"}
|
||||
combinedResults := getFileResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.Language, page)
|
||||
|
||||
sort.Slice(combinedResults, func(i, j int) bool { return combinedResults[i].Seeders > combinedResults[j].Seeders })
|
||||
|
||||
elapsedTime := time.Since(startTime)
|
||||
funcMap := template.FuncMap{
|
||||
"sub": subtract,
|
||||
"add": add,
|
||||
"sub": func(a, b int) int { return a - b },
|
||||
"add": func(a, b int) int { return a + b },
|
||||
}
|
||||
tmpl, err := template.New("files.html").Funcs(funcMap).ParseFiles("templates/files.html")
|
||||
if err != nil {
|
||||
log.Printf("Failed to load template: %v", err)
|
||||
printErr("Failed to load template: %v", err)
|
||||
http.Error(w, "Failed to load template", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
@ -63,29 +64,35 @@ func handleFileSearch(w http.ResponseWriter, query, safe, lang string, page int)
|
|||
Fetched string
|
||||
Category string
|
||||
Sort string
|
||||
Page int
|
||||
HasPrevPage bool
|
||||
HasNextPage bool
|
||||
Page int
|
||||
Settings Settings
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
Theme string
|
||||
Safe string
|
||||
}{
|
||||
Results: combinedResults,
|
||||
Query: query,
|
||||
Fetched: fmt.Sprintf("%.2f", elapsedTime.Seconds()),
|
||||
Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()),
|
||||
Category: "all",
|
||||
Sort: "seed",
|
||||
Page: page,
|
||||
HasPrevPage: page > 1,
|
||||
HasNextPage: len(combinedResults) > 0,
|
||||
Page: page,
|
||||
Settings: Settings{UxLang: lang, Safe: safe},
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: settings.Language,
|
||||
Theme: settings.Theme,
|
||||
Safe: settings.SafeSearch,
|
||||
}
|
||||
|
||||
// Debugging: Print results before rendering template
|
||||
for _, result := range combinedResults {
|
||||
fmt.Printf("Title: %s, Magnet: %s\n", result.Title, result.Magnet)
|
||||
}
|
||||
// // Debugging: Print results before rendering template
|
||||
// for _, result := range combinedResults {
|
||||
// fmt.Printf("Title: %s, Magnet: %s\n", result.Title, result.Magnet)
|
||||
// }
|
||||
|
||||
if err := tmpl.Execute(w, data); err != nil {
|
||||
log.Printf("Failed to render template: %v", err)
|
||||
printErr("Failed to render template: %v", err)
|
||||
http.Error(w, "Failed to render template", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -97,10 +104,10 @@ func getFileResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string,
|
|||
go func() {
|
||||
results, exists := resultsCache.Get(cacheKey)
|
||||
if exists {
|
||||
log.Println("Cache hit")
|
||||
printInfo("Cache hit")
|
||||
cacheChan <- results
|
||||
} else {
|
||||
log.Println("Cache miss")
|
||||
printInfo("Cache miss")
|
||||
cacheChan <- nil
|
||||
}
|
||||
}()
|
||||
|
@ -108,20 +115,26 @@ func getFileResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string,
|
|||
select {
|
||||
case results := <-cacheChan:
|
||||
if results == nil {
|
||||
combinedResults = fetchAndCacheFileResults(query, safe, lang, page)
|
||||
combinedResults = fetchFileResults(query, safe, lang, page)
|
||||
if len(combinedResults) > 0 {
|
||||
resultsCache.Set(cacheKey, convertToSearchResults(combinedResults))
|
||||
}
|
||||
} else {
|
||||
_, torrentResults, _ := convertToSpecificResults(results)
|
||||
combinedResults = torrentResults
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
log.Println("Cache check timeout")
|
||||
combinedResults = fetchAndCacheFileResults(query, safe, lang, page)
|
||||
printInfo("Cache check timeout")
|
||||
combinedResults = fetchFileResults(query, safe, lang, page)
|
||||
if len(combinedResults) > 0 {
|
||||
resultsCache.Set(cacheKey, convertToSearchResults(combinedResults))
|
||||
}
|
||||
}
|
||||
|
||||
return combinedResults
|
||||
}
|
||||
|
||||
func fetchAndCacheFileResults(query, safe, lang string, page int) []TorrentResult {
|
||||
func fetchFileResults(query, safe, lang string, page int) []TorrentResult {
|
||||
sites := []TorrentSite{torrentGalaxy, nyaa, thePirateBay, rutor}
|
||||
results := []TorrentResult{}
|
||||
|
||||
|
@ -139,9 +152,10 @@ func fetchAndCacheFileResults(query, safe, lang string, page int) []TorrentResul
|
|||
}
|
||||
}
|
||||
|
||||
// Cache the valid results
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "file"}
|
||||
resultsCache.Set(cacheKey, convertToSearchResults(results))
|
||||
if len(results) == 0 {
|
||||
printWarn("No file results found for query: %s, trying other nodes", query)
|
||||
results = tryOtherNodesForFileSearch(query, safe, lang, page, []string{hostID})
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
@ -151,14 +165,6 @@ func removeMagnetLink(magnet string) string {
|
|||
return strings.TrimPrefix(magnet, "magnet:")
|
||||
}
|
||||
|
||||
func subtract(a, b int) int {
|
||||
return a - b
|
||||
}
|
||||
|
||||
func add(a, b int) int {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func parseInt(s string) int {
|
||||
i, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
|
@ -177,7 +183,7 @@ func parseSize(sizeStr string) int64 {
|
|||
re := regexp.MustCompile(`(?i)([\d.]+)\s*([KMGT]?B)`)
|
||||
matches := re.FindStringSubmatch(sizeStr)
|
||||
if len(matches) < 3 {
|
||||
log.Printf("Error parsing size: invalid format %s", sizeStr)
|
||||
printWarn("Error parsing size: invalid format %s", sizeStr)
|
||||
return 0
|
||||
}
|
||||
|
||||
|
@ -195,13 +201,13 @@ func parseSize(sizeStr string) int64 {
|
|||
case "TB":
|
||||
multiplier = 1024 * 1024 * 1024 * 1024
|
||||
default:
|
||||
log.Printf("Unknown unit: %s", unit)
|
||||
printWarn("Unknown unit: %s", unit)
|
||||
return 0
|
||||
}
|
||||
|
||||
size, err := strconv.ParseFloat(sizeStr, 64)
|
||||
if err != nil {
|
||||
log.Printf("Error parsing size: %v", err)
|
||||
printWarn("Error parsing size: %v", err)
|
||||
return 0
|
||||
}
|
||||
return int64(size * float64(multiplier))
|
||||
|
@ -244,3 +250,12 @@ func sanitizeFileName(name string) string {
|
|||
sanitized = regexp.MustCompile(`[^a-zA-Z0-9\-\(\)]`).ReplaceAllString(sanitized, "")
|
||||
return sanitized
|
||||
}
|
||||
|
||||
func contains(slice []string, item string) bool {
|
||||
for _, v := range slice {
|
||||
if v == item {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
23
forums.go
Normal file → Executable file
23
forums.go
Normal file → Executable file
|
@ -4,6 +4,7 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
@ -97,29 +98,33 @@ func PerformRedditSearch(query string, safe string, page int) ([]ForumSearchResu
|
|||
return results, nil
|
||||
}
|
||||
|
||||
func handleForumsSearch(w http.ResponseWriter, query, safe, lang string, page int) {
|
||||
results, err := PerformRedditSearch(query, safe, page)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Error performing search: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
func handleForumsSearch(w http.ResponseWriter, settings UserSettings, query string, page int) {
|
||||
results, err := PerformRedditSearch(query, settings.SafeSearch, page)
|
||||
if err != nil || len(results) == 0 { // 0 == 0 to force search by other node
|
||||
log.Printf("No results from primary search, trying other nodes")
|
||||
results = tryOtherNodesForForumSearch(query, settings.SafeSearch, settings.Language, page)
|
||||
}
|
||||
|
||||
data := struct {
|
||||
Query string
|
||||
Results []ForumSearchResult
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
Page int
|
||||
HasPrevPage bool
|
||||
HasNextPage bool
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
Theme string
|
||||
Safe string
|
||||
}{
|
||||
Query: query,
|
||||
Results: results,
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: lang,
|
||||
Page: page,
|
||||
HasPrevPage: page > 1,
|
||||
HasNextPage: len(results) == 25,
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: settings.Language,
|
||||
Theme: settings.Theme,
|
||||
Safe: settings.SafeSearch,
|
||||
}
|
||||
|
||||
funcMap := template.FuncMap{
|
||||
|
|
9
go.mod
9
go.mod
|
@ -9,15 +9,20 @@ require (
|
|||
github.com/chromedp/cdproto v0.0.0-20240202021202-6d0b6a386732 // indirect
|
||||
github.com/chromedp/chromedp v0.9.5 // indirect
|
||||
github.com/chromedp/sysutil v1.0.0 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/gobwas/ws v1.3.2 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/shirou/gopsutil v3.21.11+incompatible
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
golang.org/x/net v0.21.0 // indirect
|
||||
golang.org/x/sys v0.17.0 // indirect
|
||||
golang.org/x/time v0.5.0 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
)
|
4
go.sum
4
go.sum
|
@ -8,6 +8,8 @@ github.com/chromedp/chromedp v0.9.5 h1:viASzruPJOiThk7c5bueOUY91jGLJVximoEMGoH93
|
|||
github.com/chromedp/chromedp v0.9.5/go.mod h1:D4I2qONslauw/C7INoCir1BJkSwBYMyZgx8X276z3+Y=
|
||||
github.com/chromedp/sysutil v1.0.0 h1:+ZxhTpfpZlmchB58ih/LBHX52ky7w2VhQVKQMucy3Ic=
|
||||
github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww=
|
||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
|
@ -69,3 +71,5 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn
|
|||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
|
@ -14,13 +14,21 @@ func handleImageProxy(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
// Fetch the image from the external URL
|
||||
resp, err := http.Get(imageURL)
|
||||
// Try to fetch the image from Bing first
|
||||
bingURL := fmt.Sprintf("https://tse.mm.bing.net/th?q=%s", imageURL)
|
||||
resp, err := http.Get(bingURL)
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
// If fetching from Bing fails, attempt to fetch from the original image URL
|
||||
printWarn("Error fetching image from Bing, trying original URL.")
|
||||
|
||||
// Attempt to fetch the image directly
|
||||
resp, err = http.Get(imageURL)
|
||||
if err != nil {
|
||||
log.Printf("Error fetching image: %v", err)
|
||||
printWarn("Error fetching image: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Check if the request was successful
|
||||
|
@ -40,7 +48,7 @@ func handleImageProxy(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
// Write the image content to the response
|
||||
if _, err := io.Copy(w, resp.Body); err != nil {
|
||||
log.Printf("Error writing image to response: %v", err)
|
||||
printWarn("Error writing image to response: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
107
images-bing.go
Normal file
107
images-bing.go
Normal file
|
@ -0,0 +1,107 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
)
|
||||
|
||||
func PerformBingImageSearch(query, safe, lang string, page int) ([]ImageSearchResult, time.Duration, error) {
|
||||
startTime := time.Now()
|
||||
|
||||
// Build the search URL
|
||||
searchURL := buildBingSearchURL(query, page)
|
||||
|
||||
// Make the HTTP request
|
||||
resp, err := http.Get(searchURL)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("making request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, 0, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Parse the HTML document
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("loading HTML document: %v", err)
|
||||
}
|
||||
|
||||
// Extract data using goquery
|
||||
var results []ImageSearchResult
|
||||
doc.Find(".imgpt").Each(func(i int, s *goquery.Selection) {
|
||||
imgTag := s.Find("img")
|
||||
imgSrc, exists := imgTag.Attr("src")
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
|
||||
title, _ := imgTag.Attr("alt")
|
||||
|
||||
// Extract width and height if available
|
||||
width, _ := strconv.Atoi(imgTag.AttrOr("width", "0"))
|
||||
height, _ := strconv.Atoi(imgTag.AttrOr("height", "0"))
|
||||
|
||||
// Extract the original image URL from the `mediaurl` parameter in the link
|
||||
pageLink, exists := s.Find("a.iusc").Attr("href")
|
||||
mediaURL := ""
|
||||
if exists {
|
||||
if u, err := url.Parse(pageLink); err == nil {
|
||||
if mediaURLParam := u.Query().Get("mediaurl"); mediaURLParam != "" {
|
||||
mediaURL, _ = url.QueryUnescape(mediaURLParam)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results = append(results, ImageSearchResult{
|
||||
Thumbnail: imgSrc,
|
||||
Title: strings.TrimSpace(title),
|
||||
Media: imgSrc,
|
||||
Width: width,
|
||||
Height: height,
|
||||
Source: mediaURL, // Original image URL
|
||||
ThumbProxy: imgSrc,
|
||||
})
|
||||
})
|
||||
|
||||
duration := time.Since(startTime)
|
||||
|
||||
// Check if the number of results is one or less
|
||||
if len(results) <= 1 {
|
||||
return nil, duration, fmt.Errorf("no images found")
|
||||
}
|
||||
|
||||
return results, duration, nil
|
||||
}
|
||||
|
||||
func buildBingSearchURL(query string, page int) string {
|
||||
baseURL := "https://www.bing.com/images/search"
|
||||
params := url.Values{}
|
||||
params.Add("q", query)
|
||||
params.Add("first", fmt.Sprintf("%d", (page-1)*35+1)) // Pagination, but increasing it doesn't seem to make a difference
|
||||
params.Add("count", "35")
|
||||
params.Add("form", "HDRSC2")
|
||||
return baseURL + "?" + params.Encode()
|
||||
}
|
||||
|
||||
// func main() {
|
||||
// results, duration, err := PerformBingImageSearch("kittens", "false", "en", 1)
|
||||
// if err != nil {
|
||||
// fmt.Println("Error:", err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// fmt.Printf("Search took: %v\n", duration)
|
||||
// fmt.Printf("Total results: %d\n", len(results))
|
||||
// for _, result := range results {
|
||||
// fmt.Printf("Title: %s\nThumbnail: %s\nWidth: %d\nHeight: %d\nThumbProxy: %s\nSource (Original Image URL): %s\n\n",
|
||||
// result.Title, result.Thumbnail, result.Width, result.Height, result.ThumbProxy, result.Source)
|
||||
// }
|
||||
// }
|
38
images.go
Normal file → Executable file
38
images.go
Normal file → Executable file
|
@ -13,15 +13,16 @@ var imageSearchEngines []SearchEngine
|
|||
func init() {
|
||||
imageSearchEngines = []SearchEngine{
|
||||
{Name: "Qwant", Func: wrapImageSearchFunc(PerformQwantImageSearch), Weight: 1},
|
||||
{Name: "Imgur", Func: wrapImageSearchFunc(PerformImgurImageSearch), Weight: 2},
|
||||
{Name: "Bing", Func: wrapImageSearchFunc(PerformBingImageSearch), Weight: 2}, // Bing sometimes returns with low amount of images, this leads to danamica page loading not working
|
||||
{Name: "Imgur", Func: wrapImageSearchFunc(PerformImgurImageSearch), Weight: 3},
|
||||
}
|
||||
}
|
||||
|
||||
func handleImageSearch(w http.ResponseWriter, query, safe, lang string, page int) {
|
||||
func handleImageSearch(w http.ResponseWriter, settings UserSettings, query string, page int) {
|
||||
startTime := time.Now()
|
||||
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "image"}
|
||||
combinedResults := getImageResultsFromCacheOrFetch(cacheKey, query, safe, lang, page)
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: settings.SafeSearch == "true", Lang: settings.Language, Type: "image"}
|
||||
combinedResults := getImageResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.Language, page)
|
||||
|
||||
elapsedTime := time.Since(startTime)
|
||||
tmpl, err := template.New("images.html").Funcs(funcs).ParseFiles("templates/images.html")
|
||||
|
@ -36,24 +37,30 @@ func handleImageSearch(w http.ResponseWriter, query, safe, lang string, page int
|
|||
Query string
|
||||
Page int
|
||||
Fetched string
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
HasPrevPage bool
|
||||
HasNextPage bool
|
||||
NoResults bool
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
Theme string
|
||||
Safe string
|
||||
}{
|
||||
Results: combinedResults,
|
||||
Query: query,
|
||||
Page: page,
|
||||
Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()),
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: lang,
|
||||
HasPrevPage: page > 1,
|
||||
HasNextPage: len(combinedResults) >= 50,
|
||||
NoResults: len(combinedResults) == 0,
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: settings.Language,
|
||||
Theme: settings.Theme,
|
||||
Safe: settings.SafeSearch,
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
log.Printf("Error executing template: %v", err)
|
||||
printErr("Error executing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
@ -65,10 +72,10 @@ func getImageResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string
|
|||
go func() {
|
||||
results, exists := resultsCache.Get(cacheKey)
|
||||
if exists {
|
||||
log.Println("Cache hit")
|
||||
printInfo("Cache hit")
|
||||
cacheChan <- results
|
||||
} else {
|
||||
log.Println("Cache miss")
|
||||
printInfo("Cache miss")
|
||||
cacheChan <- nil
|
||||
}
|
||||
}()
|
||||
|
@ -85,7 +92,7 @@ func getImageResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string
|
|||
combinedResults = imageResults
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
log.Println("Cache check timeout")
|
||||
printInfo("Cache check timeout")
|
||||
combinedResults = fetchImageResults(query, safe, lang, page)
|
||||
if len(combinedResults) > 0 {
|
||||
resultsCache.Set(cacheKey, convertToSearchResults(combinedResults))
|
||||
|
@ -99,12 +106,12 @@ func fetchImageResults(query, safe, lang string, page int) []ImageSearchResult {
|
|||
var results []ImageSearchResult
|
||||
|
||||
for _, engine := range imageSearchEngines {
|
||||
log.Printf("Using image search engine: %s", engine.Name)
|
||||
printInfo("Using image search engine: %s", engine.Name)
|
||||
|
||||
searchResults, duration, err := engine.Func(query, safe, lang, page)
|
||||
updateEngineMetrics(&engine, duration, err == nil)
|
||||
if err != nil {
|
||||
log.Printf("Error performing image search with %s: %v", engine.Name, err)
|
||||
printWarn("Error performing image search with %s: %v", engine.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -120,7 +127,8 @@ func fetchImageResults(query, safe, lang string, page int) []ImageSearchResult {
|
|||
|
||||
// If no results found after trying all engines
|
||||
if len(results) == 0 {
|
||||
log.Printf("No image results found for query: %s", query)
|
||||
printWarn("No image results found for query: %s, trying other nodes", query)
|
||||
results = tryOtherNodesForImageSearch(query, safe, lang, page, []string{hostID})
|
||||
}
|
||||
|
||||
return results
|
||||
|
|
142
init.go
142
init.go
|
@ -1,116 +1,66 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Configuration structure
|
||||
type Config struct {
|
||||
Port int
|
||||
OpenSearch OpenSearchConfig
|
||||
}
|
||||
|
||||
type OpenSearchConfig struct {
|
||||
AuthCode string
|
||||
PeerID string
|
||||
Peers []string
|
||||
Domain string
|
||||
NodesEnabled bool
|
||||
CrawlerEnabled bool
|
||||
WebsiteEnabled bool
|
||||
LogLevel int
|
||||
}
|
||||
|
||||
// Default configuration values
|
||||
var defaultConfig = Config{
|
||||
Port: 5000,
|
||||
OpenSearch: OpenSearchConfig{
|
||||
Domain: "localhost",
|
||||
},
|
||||
Peers: []string{},
|
||||
AuthCode: generateStrongRandomString(64),
|
||||
NodesEnabled: true,
|
||||
CrawlerEnabled: true,
|
||||
WebsiteEnabled: true,
|
||||
LogLevel: 1,
|
||||
}
|
||||
|
||||
const configFilePath = "config.json"
|
||||
|
||||
func main() {
|
||||
// Run the initialization process
|
||||
err := initConfig()
|
||||
if err != nil {
|
||||
fmt.Println("Error during initialization:", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Start the main application
|
||||
runServer()
|
||||
}
|
||||
|
||||
func initConfig() error {
|
||||
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
|
||||
return createConfig()
|
||||
}
|
||||
|
||||
fmt.Println("Configuration file already exists.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func createConfig() error {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
fmt.Println("Configuration file not found.")
|
||||
fmt.Print("Do you want to use default values? (yes/no): ")
|
||||
useDefaults, _ := reader.ReadString('\n')
|
||||
|
||||
config := defaultConfig
|
||||
if useDefaults != "yes\n" {
|
||||
fmt.Print("Enter port (default 5000): ")
|
||||
portStr, _ := reader.ReadString('\n')
|
||||
if portStr != "\n" {
|
||||
port, err := strconv.Atoi(portStr[:len(portStr)-1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
config.Port = port
|
||||
}
|
||||
|
||||
fmt.Print("Enter your domain address (e.g., domain.com): ")
|
||||
domain, _ := reader.ReadString('\n')
|
||||
if domain != "\n" {
|
||||
config.OpenSearch.Domain = domain[:len(domain)-1]
|
||||
}
|
||||
}
|
||||
|
||||
saveConfig(config)
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveConfig(config Config) {
|
||||
file, err := os.Create(configFilePath)
|
||||
if err != nil {
|
||||
fmt.Println("Error creating config file:", err)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
configData, err := json.MarshalIndent(config, "", " ")
|
||||
if err != nil {
|
||||
fmt.Println("Error marshalling config data:", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = file.Write(configData)
|
||||
if err != nil {
|
||||
fmt.Println("Error writing to config file:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func loadConfig() Config {
|
||||
configFile, err := os.Open(configFilePath)
|
||||
if err != nil {
|
||||
log.Fatalf("Error opening config file: %v", err)
|
||||
}
|
||||
defer configFile.Close()
|
||||
const configFilePath = "config.ini"
|
||||
|
||||
var config Config
|
||||
if err := json.NewDecoder(configFile).Decode(&config); err != nil {
|
||||
log.Fatalf("Error decoding config file: %v", err)
|
||||
|
||||
func main() {
|
||||
err := initConfig()
|
||||
if err != nil {
|
||||
printErr("Error during initialization:")
|
||||
return
|
||||
}
|
||||
|
||||
return config
|
||||
loadNodeConfig()
|
||||
go startFileWatcher()
|
||||
go checkMasterHeartbeat()
|
||||
|
||||
if config.AuthCode == "" {
|
||||
config.AuthCode = generateStrongRandomString(64)
|
||||
printInfo("Generated connection code: %s\n", config.AuthCode)
|
||||
saveConfig(config)
|
||||
}
|
||||
|
||||
// Generate Host ID
|
||||
hostID, nodeErr := generateHostID()
|
||||
if nodeErr != nil {
|
||||
printErr("Failed to generate host ID: %v", nodeErr)
|
||||
}
|
||||
config.PeerID = hostID
|
||||
|
||||
if len(config.Peers) > 0 {
|
||||
time.Sleep(2 * time.Second) // Give some time for connections to establish
|
||||
startElection()
|
||||
}
|
||||
|
||||
go startNodeClient()
|
||||
|
||||
runServer()
|
||||
}
|
||||
|
|
67
main.go
Normal file → Executable file
67
main.go
Normal file → Executable file
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
@ -13,6 +14,8 @@ type LanguageOption struct {
|
|||
Name string
|
||||
}
|
||||
|
||||
var settings UserSettings
|
||||
|
||||
var languageOptions = []LanguageOption{
|
||||
{Code: "", Name: "Any Language"},
|
||||
{Code: "lang_en", Name: "English"},
|
||||
|
@ -66,26 +69,65 @@ var languageOptions = []LanguageOption{
|
|||
func handleSearch(w http.ResponseWriter, r *http.Request) {
|
||||
query, safe, lang, searchType, page := parseSearchParams(r)
|
||||
|
||||
// Load user settings
|
||||
settings = loadUserSettings(r)
|
||||
|
||||
// Update the theme, safe search, and language based on query parameters or use existing settings
|
||||
theme := r.URL.Query().Get("theme")
|
||||
if theme != "" {
|
||||
settings.Theme = theme
|
||||
saveUserSettings(w, settings)
|
||||
} else if settings.Theme == "" {
|
||||
settings.Theme = "dark" // Default theme
|
||||
}
|
||||
|
||||
if safe != "" {
|
||||
settings.SafeSearch = safe
|
||||
saveUserSettings(w, settings)
|
||||
}
|
||||
|
||||
if lang != "" {
|
||||
settings.Language = lang
|
||||
saveUserSettings(w, settings)
|
||||
}
|
||||
|
||||
// Render the search page template if no query
|
||||
|
||||
data := struct {
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
Theme string
|
||||
Safe string
|
||||
}{
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: settings.Language,
|
||||
Theme: settings.Theme,
|
||||
Safe: settings.SafeSearch,
|
||||
}
|
||||
if query == "" {
|
||||
http.ServeFile(w, r, "templates/search.html")
|
||||
tmpl := template.Must(template.ParseFiles("templates/search.html"))
|
||||
tmpl.Execute(w, data)
|
||||
return
|
||||
}
|
||||
|
||||
settings := loadUserSettings(r)
|
||||
|
||||
// Handle search based on the type
|
||||
switch searchType {
|
||||
case "image":
|
||||
handleImageSearch(w, query, safe, lang, page)
|
||||
handleImageSearch(w, settings, query, page)
|
||||
case "video":
|
||||
handleVideoSearch(w, query, safe, lang, page)
|
||||
handleVideoSearch(w, settings, query, page)
|
||||
case "map":
|
||||
handleMapSearch(w, query, safe)
|
||||
handleMapSearch(w, settings, query)
|
||||
case "forum":
|
||||
handleForumsSearch(w, query, safe, lang, page)
|
||||
handleForumsSearch(w, settings, query, page)
|
||||
case "file":
|
||||
handleFileSearch(w, query, safe, lang, page)
|
||||
handleFileSearch(w, settings, query, page)
|
||||
case "text":
|
||||
fallthrough
|
||||
default:
|
||||
HandleTextSearch(w, query, safe, lang, page)
|
||||
HandleTextSearch(w, settings, query, page)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -126,9 +168,9 @@ func runServer() {
|
|||
http.HandleFunc("/", handleSearch)
|
||||
http.HandleFunc("/search", handleSearch)
|
||||
http.HandleFunc("/img_proxy", handleImageProxy)
|
||||
http.HandleFunc("/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "templates/settings.html")
|
||||
})
|
||||
http.HandleFunc("/node", handleNodeRequest)
|
||||
http.HandleFunc("/settings", handleSettings)
|
||||
http.HandleFunc("/save-settings", handleSaveSettings)
|
||||
http.HandleFunc("/opensearch.xml", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/opensearchdescription+xml")
|
||||
http.ServeFile(w, r, "static/opensearch.xml")
|
||||
|
@ -138,6 +180,9 @@ func runServer() {
|
|||
config := loadConfig()
|
||||
generateOpenSearchXML(config)
|
||||
|
||||
fmt.Printf("Server is listening on http://localhost:%d\n", config.Port)
|
||||
printMessage("Server is listening on http://localhost:%d", config.Port)
|
||||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil))
|
||||
|
||||
// Start automatic update checker
|
||||
go checkForUpdates()
|
||||
}
|
||||
|
|
9
map.go
Normal file → Executable file
9
map.go
Normal file → Executable file
|
@ -4,7 +4,6 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
@ -44,11 +43,11 @@ func geocodeQuery(query string) (latitude, longitude string, found bool, err err
|
|||
return "", "", false, nil
|
||||
}
|
||||
|
||||
func handleMapSearch(w http.ResponseWriter, query string, lang string) {
|
||||
func handleMapSearch(w http.ResponseWriter, settings UserSettings, query string) {
|
||||
// Geocode the query to get coordinates
|
||||
latitude, longitude, found, err := geocodeQuery(query)
|
||||
if err != nil {
|
||||
log.Printf("Error geocoding query: %s, error: %v", query, err)
|
||||
printDebug("Error geocoding query: %s, error: %v", query, err)
|
||||
http.Error(w, "Failed to find location", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
@ -59,11 +58,13 @@ func handleMapSearch(w http.ResponseWriter, query string, lang string) {
|
|||
"Latitude": latitude,
|
||||
"Longitude": longitude,
|
||||
"Found": found,
|
||||
"Theme": settings.Theme,
|
||||
"Safe": settings.SafeSearch,
|
||||
}
|
||||
|
||||
tmpl, err := template.ParseFiles("templates/map.html")
|
||||
if err != nil {
|
||||
log.Printf("Error loading map template: %v", err)
|
||||
printErr("Error loading map template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
|
219
node-handle-search.go
Executable file
219
node-handle-search.go
Executable file
|
@ -0,0 +1,219 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
)
|
||||
|
||||
func handleSearchTextMessage(msg Message) {
|
||||
var searchParams struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
}
|
||||
err := json.Unmarshal([]byte(msg.Content), &searchParams)
|
||||
if err != nil {
|
||||
printWarn("Error parsing search parameters: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
printDebug("Received search-text request. ResponseAddr: %s", searchParams.ResponseAddr)
|
||||
|
||||
results := fetchTextResults(searchParams.Query, searchParams.Safe, searchParams.Lang, searchParams.Page)
|
||||
resultsJSON, err := json.Marshal(results)
|
||||
if err != nil {
|
||||
printWarn("Error marshalling search results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
responseMsg := Message{
|
||||
ID: hostID,
|
||||
Type: "text-results",
|
||||
Content: string(resultsJSON),
|
||||
}
|
||||
|
||||
// Log the address to be used for sending the response
|
||||
printDebug("Sending text search results to %s", searchParams.ResponseAddr)
|
||||
|
||||
if searchParams.ResponseAddr == "" {
|
||||
printErr("Error: Response address is empty")
|
||||
return
|
||||
}
|
||||
|
||||
err = sendMessage(searchParams.ResponseAddr, responseMsg)
|
||||
if err != nil {
|
||||
printWarn("Error sending text search results to %s: %v", searchParams.ResponseAddr, err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSearchImageMessage(msg Message) {
|
||||
var searchParams struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
}
|
||||
err := json.Unmarshal([]byte(msg.Content), &searchParams)
|
||||
if err != nil {
|
||||
log.Printf("Error parsing search parameters: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Received search-image request. ResponseAddr: %s", searchParams.ResponseAddr)
|
||||
|
||||
results := fetchImageResults(searchParams.Query, searchParams.Safe, searchParams.Lang, searchParams.Page)
|
||||
resultsJSON, err := json.Marshal(results)
|
||||
if err != nil {
|
||||
log.Printf("Error marshalling search results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
responseMsg := Message{
|
||||
ID: hostID,
|
||||
Type: "image-results",
|
||||
Content: string(resultsJSON),
|
||||
}
|
||||
|
||||
// Log the address to be used for sending the response
|
||||
log.Printf("Sending image search results to %s", searchParams.ResponseAddr)
|
||||
|
||||
if searchParams.ResponseAddr == "" {
|
||||
log.Printf("Error: Response address is empty")
|
||||
return
|
||||
}
|
||||
|
||||
err = sendMessage(searchParams.ResponseAddr, responseMsg)
|
||||
if err != nil {
|
||||
log.Printf("Error sending image search results to %s: %v", searchParams.ResponseAddr, err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSearchVideoMessage(msg Message) {
|
||||
var searchParams struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
}
|
||||
err := json.Unmarshal([]byte(msg.Content), &searchParams)
|
||||
if err != nil {
|
||||
log.Printf("Error parsing search parameters: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Received search-video request. ResponseAddr: %s", searchParams.ResponseAddr)
|
||||
|
||||
results := fetchVideoResults(searchParams.Query, searchParams.Safe, searchParams.Lang, searchParams.Page)
|
||||
resultsJSON, err := json.Marshal(results)
|
||||
if err != nil {
|
||||
log.Printf("Error marshalling search results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
responseMsg := Message{
|
||||
ID: hostID,
|
||||
Type: "video-results",
|
||||
Content: string(resultsJSON),
|
||||
}
|
||||
|
||||
log.Printf("Sending video search results to %s", searchParams.ResponseAddr)
|
||||
|
||||
if searchParams.ResponseAddr == "" {
|
||||
log.Printf("Error: Response address is empty")
|
||||
return
|
||||
}
|
||||
|
||||
err = sendMessage(searchParams.ResponseAddr, responseMsg)
|
||||
if err != nil {
|
||||
log.Printf("Error sending video search results to %s: %v", searchParams.ResponseAddr, err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSearchFileMessage(msg Message) {
|
||||
var searchParams struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
}
|
||||
err := json.Unmarshal([]byte(msg.Content), &searchParams)
|
||||
if err != nil {
|
||||
log.Printf("Error parsing search parameters: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Received search-file request. ResponseAddr: %s", searchParams.ResponseAddr)
|
||||
|
||||
results := fetchFileResults(searchParams.Query, searchParams.Safe, searchParams.Lang, searchParams.Page)
|
||||
resultsJSON, err := json.Marshal(results)
|
||||
if err != nil {
|
||||
log.Printf("Error marshalling search results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
responseMsg := Message{
|
||||
ID: hostID,
|
||||
Type: "file-results",
|
||||
Content: string(resultsJSON),
|
||||
}
|
||||
|
||||
log.Printf("Sending file search results to %s", searchParams.ResponseAddr)
|
||||
|
||||
if searchParams.ResponseAddr == "" {
|
||||
log.Printf("Error: Response address is empty")
|
||||
return
|
||||
}
|
||||
|
||||
err = sendMessage(searchParams.ResponseAddr, responseMsg)
|
||||
if err != nil {
|
||||
log.Printf("Error sending file search results to %s: %v", searchParams.ResponseAddr, err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSearchForumMessage(msg Message) {
|
||||
var searchParams struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
}
|
||||
err := json.Unmarshal([]byte(msg.Content), &searchParams)
|
||||
if err != nil {
|
||||
log.Printf("Error parsing search parameters: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Received search-forum request. ResponseAddr: %s", searchParams.ResponseAddr)
|
||||
|
||||
results := fetchForumResults(searchParams.Query, searchParams.Safe, searchParams.Lang, searchParams.Page)
|
||||
resultsJSON, err := json.Marshal(results)
|
||||
if err != nil {
|
||||
log.Printf("Error marshalling search results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
responseMsg := Message{
|
||||
ID: hostID,
|
||||
Type: "forum-results",
|
||||
Content: string(resultsJSON),
|
||||
}
|
||||
|
||||
// Log the address to be used for sending the response
|
||||
log.Printf("Sending forum search results to %s", searchParams.ResponseAddr)
|
||||
|
||||
if searchParams.ResponseAddr == "" {
|
||||
log.Printf("Error: Response address is empty")
|
||||
return
|
||||
}
|
||||
|
||||
err = sendMessage(searchParams.ResponseAddr, responseMsg)
|
||||
if err != nil {
|
||||
log.Printf("Error sending forum search results to %s: %v", searchParams.ResponseAddr, err)
|
||||
}
|
||||
}
|
91
node-master.go
Normal file
91
node-master.go
Normal file
|
@ -0,0 +1,91 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
isMaster bool
|
||||
masterNode string
|
||||
masterNodeMux sync.RWMutex
|
||||
)
|
||||
|
||||
const (
|
||||
heartbeatInterval = 5 * time.Second
|
||||
heartbeatTimeout = 15 * time.Second
|
||||
electionTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
func sendHeartbeats() {
|
||||
for {
|
||||
if !isMaster {
|
||||
return
|
||||
}
|
||||
for _, node := range peers {
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "heartbeat",
|
||||
Content: authCode,
|
||||
}
|
||||
err := sendMessage(node, msg)
|
||||
if err != nil {
|
||||
log.Printf("Error sending heartbeat to %s: %v", node, err)
|
||||
}
|
||||
}
|
||||
time.Sleep(heartbeatInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func checkMasterHeartbeat() {
|
||||
for {
|
||||
time.Sleep(heartbeatTimeout)
|
||||
masterNodeMux.RLock()
|
||||
if masterNode == authCode || masterNode == "" {
|
||||
masterNodeMux.RUnlock()
|
||||
continue
|
||||
}
|
||||
masterNodeMux.RUnlock()
|
||||
|
||||
masterNodeMux.Lock()
|
||||
masterNode = ""
|
||||
masterNodeMux.Unlock()
|
||||
startElection()
|
||||
}
|
||||
}
|
||||
|
||||
func startElection() {
|
||||
masterNodeMux.Lock()
|
||||
defer masterNodeMux.Unlock()
|
||||
|
||||
for _, node := range peers {
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "election",
|
||||
Content: authCode,
|
||||
}
|
||||
err := sendMessage(node, msg)
|
||||
if err != nil {
|
||||
log.Printf("Error sending election message to %s: %v", node, err)
|
||||
}
|
||||
}
|
||||
|
||||
isMaster = true
|
||||
go sendHeartbeats()
|
||||
}
|
||||
|
||||
func handleHeartbeat(content string) {
|
||||
masterNodeMux.Lock()
|
||||
defer masterNodeMux.Unlock()
|
||||
masterNode = content
|
||||
}
|
||||
|
||||
func handleElection(content string) {
|
||||
masterNodeMux.Lock()
|
||||
defer masterNodeMux.Unlock()
|
||||
|
||||
if content < authCode {
|
||||
masterNode = content
|
||||
}
|
||||
}
|
82
node-request-files.go
Executable file
82
node-request-files.go
Executable file
|
@ -0,0 +1,82 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func tryOtherNodesForFileSearch(query, safe, lang string, page int, visitedNodes []string) []TorrentResult {
|
||||
for _, nodeAddr := range peers {
|
||||
if contains(visitedNodes, nodeAddr) {
|
||||
continue // Skip nodes already visited
|
||||
}
|
||||
results, err := sendFileSearchRequestToNode(nodeAddr, query, safe, lang, page, visitedNodes)
|
||||
if err != nil {
|
||||
printWarn("Error contacting node %s: %v", nodeAddr, err)
|
||||
continue
|
||||
}
|
||||
if len(results) > 0 {
|
||||
return results
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendFileSearchRequestToNode(nodeAddr, query, safe, lang string, page int, visitedNodes []string) ([]TorrentResult, error) {
|
||||
visitedNodes = append(visitedNodes, nodeAddr)
|
||||
searchParams := struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
VisitedNodes []string `json:"visitedNodes"`
|
||||
}{
|
||||
Query: query,
|
||||
Safe: safe,
|
||||
Lang: lang,
|
||||
Page: page,
|
||||
ResponseAddr: fmt.Sprintf("http://localhost:%d/node", config.Port),
|
||||
VisitedNodes: visitedNodes,
|
||||
}
|
||||
|
||||
msgBytes, err := json.Marshal(searchParams)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal search parameters: %v", err)
|
||||
}
|
||||
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "search-file",
|
||||
Content: string(msgBytes),
|
||||
}
|
||||
|
||||
err = sendMessage(nodeAddr, msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send search request to node %s: %v", nodeAddr, err)
|
||||
}
|
||||
|
||||
// Wait for results
|
||||
select {
|
||||
case res := <-fileResultsChan:
|
||||
return res, nil
|
||||
case <-time.After(20 * time.Second):
|
||||
return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func handleFileResultsMessage(msg Message) {
|
||||
var results []TorrentResult
|
||||
err := json.Unmarshal([]byte(msg.Content), &results)
|
||||
if err != nil {
|
||||
printWarn("Error unmarshalling file results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
printDebug("Received file results: %+v", results)
|
||||
// Send results to fileResultsChan
|
||||
go func() {
|
||||
fileResultsChan <- results
|
||||
}()
|
||||
}
|
100
node-request-forums.go
Executable file
100
node-request-forums.go
Executable file
|
@ -0,0 +1,100 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var forumResultsChan = make(chan []ForumSearchResult)
|
||||
|
||||
func tryOtherNodesForForumSearch(query, safe, lang string, page int) []ForumSearchResult {
|
||||
for _, nodeAddr := range peers {
|
||||
results, err := sendForumSearchRequestToNode(nodeAddr, query, safe, lang, page, []string{})
|
||||
if err != nil {
|
||||
printWarn("Error contacting node %s: %v", nodeAddr, err)
|
||||
continue
|
||||
}
|
||||
if len(results) > 0 {
|
||||
return results
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendForumSearchRequestToNode(nodeAddr, query, safe, lang string, page int, visitedNodes []string) ([]ForumSearchResult, error) {
|
||||
// Check if the current node has already been visited
|
||||
for _, node := range visitedNodes {
|
||||
if node == hostID {
|
||||
return nil, fmt.Errorf("loop detected: this node (%s) has already been visited", hostID)
|
||||
}
|
||||
}
|
||||
|
||||
// Add current node to the list of visited nodes
|
||||
visitedNodes = append(visitedNodes, hostID)
|
||||
|
||||
searchParams := struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
VisitedNodes []string `json:"visitedNodes"`
|
||||
}{
|
||||
Query: query,
|
||||
Safe: safe,
|
||||
Lang: lang,
|
||||
Page: page,
|
||||
ResponseAddr: fmt.Sprintf("http://localhost:%d/node", config.Port),
|
||||
VisitedNodes: visitedNodes,
|
||||
}
|
||||
|
||||
msgBytes, err := json.Marshal(searchParams)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal search parameters: %v", err)
|
||||
}
|
||||
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "search-forum",
|
||||
Content: string(msgBytes),
|
||||
}
|
||||
|
||||
err = sendMessage(nodeAddr, msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send search request to node %s: %v", nodeAddr, err)
|
||||
}
|
||||
|
||||
// Wait for results
|
||||
select {
|
||||
case res := <-forumResultsChan:
|
||||
return res, nil
|
||||
case <-time.After(20 * time.Second):
|
||||
return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func handleForumResultsMessage(msg Message) {
|
||||
var results []ForumSearchResult
|
||||
err := json.Unmarshal([]byte(msg.Content), &results)
|
||||
if err != nil {
|
||||
printWarn("Error unmarshalling forum results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
printDebug("Received forum results: %+v", results)
|
||||
// Send results to forumResultsChan
|
||||
go func() {
|
||||
forumResultsChan <- results
|
||||
}()
|
||||
}
|
||||
|
||||
// Used only to answer requests
|
||||
func fetchForumResults(query, safe, lang string, page int) []ForumSearchResult {
|
||||
results, err := PerformRedditSearch(query, safe, page)
|
||||
if err != nil {
|
||||
printWarn("Error fetching forum results: %v", err)
|
||||
return nil
|
||||
}
|
||||
return results
|
||||
}
|
84
node-request-images.go
Executable file
84
node-request-images.go
Executable file
|
@ -0,0 +1,84 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var imageResultsChan = make(chan []ImageSearchResult)
|
||||
|
||||
func handleImageResultsMessage(msg Message) {
|
||||
var results []ImageSearchResult
|
||||
err := json.Unmarshal([]byte(msg.Content), &results)
|
||||
if err != nil {
|
||||
printWarn("Error unmarshalling image results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
printDebug("Received image results: %+v", results)
|
||||
// Send results to imageResultsChan
|
||||
go func() {
|
||||
imageResultsChan <- results
|
||||
}()
|
||||
}
|
||||
|
||||
func sendImageSearchRequestToNode(nodeAddr, query, safe, lang string, page int, visitedNodes []string) ([]ImageSearchResult, error) {
|
||||
visitedNodes = append(visitedNodes, nodeAddr)
|
||||
searchParams := struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
VisitedNodes []string `json:"visitedNodes"`
|
||||
}{
|
||||
Query: query,
|
||||
Safe: safe,
|
||||
Lang: lang,
|
||||
Page: page,
|
||||
ResponseAddr: fmt.Sprintf("http://localhost:%d/node", config.Port),
|
||||
VisitedNodes: visitedNodes,
|
||||
}
|
||||
|
||||
msgBytes, err := json.Marshal(searchParams)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal search parameters: %v", err)
|
||||
}
|
||||
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "search-image",
|
||||
Content: string(msgBytes),
|
||||
}
|
||||
|
||||
err = sendMessage(nodeAddr, msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send search request to node %s: %v", nodeAddr, err)
|
||||
}
|
||||
|
||||
// Wait for results
|
||||
select {
|
||||
case res := <-imageResultsChan:
|
||||
return res, nil
|
||||
case <-time.After(30 * time.Second):
|
||||
return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func tryOtherNodesForImageSearch(query, safe, lang string, page int, visitedNodes []string) []ImageSearchResult {
|
||||
for _, nodeAddr := range peers {
|
||||
if contains(visitedNodes, nodeAddr) {
|
||||
continue // Skip nodes already visited
|
||||
}
|
||||
results, err := sendImageSearchRequestToNode(nodeAddr, query, safe, lang, page, visitedNodes)
|
||||
if err != nil {
|
||||
printWarn("Error contacting node %s: %v", nodeAddr, err)
|
||||
continue
|
||||
}
|
||||
if len(results) > 0 {
|
||||
return results
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
84
node-request-text.go
Executable file
84
node-request-text.go
Executable file
|
@ -0,0 +1,84 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var textResultsChan = make(chan []TextSearchResult)
|
||||
|
||||
func tryOtherNodesForTextSearch(query, safe, lang string, page int, visitedNodes []string) []TextSearchResult {
|
||||
for _, nodeAddr := range peers {
|
||||
if contains(visitedNodes, nodeAddr) {
|
||||
continue // Skip nodes already visited
|
||||
}
|
||||
results, err := sendTextSearchRequestToNode(nodeAddr, query, safe, lang, page, visitedNodes)
|
||||
if err != nil {
|
||||
printWarn("Error contacting node %s: %v", nodeAddr, err)
|
||||
continue
|
||||
}
|
||||
if len(results) > 0 {
|
||||
return results
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendTextSearchRequestToNode(nodeAddr, query, safe, lang string, page int, visitedNodes []string) ([]TextSearchResult, error) {
|
||||
visitedNodes = append(visitedNodes, nodeAddr)
|
||||
searchParams := struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
VisitedNodes []string `json:"visitedNodes"`
|
||||
}{
|
||||
Query: query,
|
||||
Safe: safe,
|
||||
Lang: lang,
|
||||
Page: page,
|
||||
ResponseAddr: fmt.Sprintf("http://localhost:%d/node", config.Port),
|
||||
VisitedNodes: visitedNodes,
|
||||
}
|
||||
|
||||
msgBytes, err := json.Marshal(searchParams)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal search parameters: %v", err)
|
||||
}
|
||||
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "search-text",
|
||||
Content: string(msgBytes),
|
||||
}
|
||||
|
||||
err = sendMessage(nodeAddr, msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send search request to node %s: %v", nodeAddr, err)
|
||||
}
|
||||
|
||||
// Wait for results
|
||||
select {
|
||||
case res := <-textResultsChan:
|
||||
return res, nil
|
||||
case <-time.After(20 * time.Second):
|
||||
return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func handleTextResultsMessage(msg Message) {
|
||||
var results []TextSearchResult
|
||||
err := json.Unmarshal([]byte(msg.Content), &results)
|
||||
if err != nil {
|
||||
printWarn("Error unmarshalling text results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
printDebug("Received text results: %+v", results)
|
||||
// Send results to textResultsChan
|
||||
go func() {
|
||||
textResultsChan <- results
|
||||
}()
|
||||
}
|
82
node-request-video.go
Executable file
82
node-request-video.go
Executable file
|
@ -0,0 +1,82 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func tryOtherNodesForVideoSearch(query, safe, lang string, page int, visitedNodes []string) []VideoResult {
|
||||
for _, nodeAddr := range peers {
|
||||
if contains(visitedNodes, nodeAddr) {
|
||||
continue // Skip nodes already visited
|
||||
}
|
||||
results, err := sendVideoSearchRequestToNode(nodeAddr, query, safe, lang, page, visitedNodes)
|
||||
if err != nil {
|
||||
printWarn("Error contacting node %s: %v", nodeAddr, err)
|
||||
continue
|
||||
}
|
||||
if len(results) > 0 {
|
||||
return results
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendVideoSearchRequestToNode(nodeAddr, query, safe, lang string, page int, visitedNodes []string) ([]VideoResult, error) {
|
||||
visitedNodes = append(visitedNodes, nodeAddr)
|
||||
searchParams := struct {
|
||||
Query string `json:"query"`
|
||||
Safe string `json:"safe"`
|
||||
Lang string `json:"lang"`
|
||||
Page int `json:"page"`
|
||||
ResponseAddr string `json:"responseAddr"`
|
||||
VisitedNodes []string `json:"visitedNodes"`
|
||||
}{
|
||||
Query: query,
|
||||
Safe: safe,
|
||||
Lang: lang,
|
||||
Page: page,
|
||||
ResponseAddr: fmt.Sprintf("http://localhost:%d/node", config.Port),
|
||||
VisitedNodes: visitedNodes,
|
||||
}
|
||||
|
||||
msgBytes, err := json.Marshal(searchParams)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal search parameters: %v", err)
|
||||
}
|
||||
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "search-video",
|
||||
Content: string(msgBytes),
|
||||
}
|
||||
|
||||
err = sendMessage(nodeAddr, msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send search request to node %s: %v", nodeAddr, err)
|
||||
}
|
||||
|
||||
// Wait for results
|
||||
select {
|
||||
case res := <-videoResultsChan:
|
||||
return res, nil
|
||||
case <-time.After(20 * time.Second):
|
||||
return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func handleVideoResultsMessage(msg Message) {
|
||||
var results []VideoResult
|
||||
err := json.Unmarshal([]byte(msg.Content), &results)
|
||||
if err != nil {
|
||||
printWarn("Error unmarshalling video results: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
printDebug("Received video results: %+v", results)
|
||||
// Send results to videoResultsChan
|
||||
go func() {
|
||||
videoResultsChan <- results
|
||||
}()
|
||||
}
|
28
node-update.go
Normal file
28
node-update.go
Normal file
|
@ -0,0 +1,28 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Function to sync updates across all nodes
|
||||
func nodeUpdateSync() {
|
||||
fmt.Println("Syncing updates across all nodes...")
|
||||
for _, peerAddr := range peers {
|
||||
fmt.Printf("Notifying node %s about update...\n", peerAddr)
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "update",
|
||||
Content: "Start update process",
|
||||
}
|
||||
err := sendMessage(peerAddr, msg)
|
||||
if err != nil {
|
||||
log.Printf("Failed to notify node %s: %v\n", peerAddr, err)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("Node %s notified. Waiting for it to update...\n", peerAddr)
|
||||
time.Sleep(30 * time.Second) // Adjust sleep time as needed to allow for updates
|
||||
}
|
||||
fmt.Println("All nodes have been updated.")
|
||||
}
|
156
node.go
Normal file
156
node.go
Normal file
|
@ -0,0 +1,156 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
authCode string
|
||||
peers []string
|
||||
hostID string
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Content string `json:"content"`
|
||||
VisitedNodes []string `json:"visitedNodes"`
|
||||
}
|
||||
|
||||
func loadNodeConfig() {
|
||||
config := loadConfig()
|
||||
authCode = config.AuthCode
|
||||
peers = config.Peers
|
||||
}
|
||||
|
||||
func generateHostID() (string, error) {
|
||||
bytes := make([]byte, 16)
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to generate host ID: %v", err)
|
||||
}
|
||||
return fmt.Sprintf("%x", bytes), nil
|
||||
}
|
||||
|
||||
func sendMessage(serverAddr string, msg Message) error {
|
||||
if serverAddr == "" {
|
||||
return fmt.Errorf("server address is empty")
|
||||
}
|
||||
|
||||
msgBytes, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal message: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", serverAddr, bytes.NewBuffer(msgBytes))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", authCode)
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: time.Second * 10,
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to send request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
return fmt.Errorf("server error: %s", body)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleNodeRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth != authCode {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var msg Message
|
||||
err := json.NewDecoder(r.Body).Decode(&msg)
|
||||
if err != nil {
|
||||
http.Error(w, "Error parsing JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
printDebug("Received message: %+v\n", msg)
|
||||
w.Write([]byte("Message received"))
|
||||
|
||||
interpretMessage(msg)
|
||||
}
|
||||
|
||||
func startNodeClient() {
|
||||
for {
|
||||
for _, peerAddr := range peers {
|
||||
msg := Message{
|
||||
ID: hostID,
|
||||
Type: "test",
|
||||
Content: "This is a test message from the client node",
|
||||
}
|
||||
|
||||
err := sendMessage(peerAddr, msg)
|
||||
if err != nil {
|
||||
printWarn("Error sending message to %s: %v", peerAddr, err)
|
||||
} else {
|
||||
printInfo("Message sent successfully to: %s", peerAddr)
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func interpretMessage(msg Message) {
|
||||
switch msg.Type {
|
||||
case "test":
|
||||
printDebug("Received test message: %v", msg.Content)
|
||||
case "update":
|
||||
printDebug("Received update message: %v", msg.Content)
|
||||
go update()
|
||||
case "heartbeat":
|
||||
handleHeartbeat(msg.Content)
|
||||
case "election":
|
||||
handleElection(msg.Content)
|
||||
case "search-text":
|
||||
handleSearchTextMessage(msg)
|
||||
case "search-image":
|
||||
handleSearchImageMessage(msg)
|
||||
case "search-video":
|
||||
handleSearchVideoMessage(msg)
|
||||
case "search-file":
|
||||
handleSearchFileMessage(msg)
|
||||
case "search-forum":
|
||||
handleSearchForumMessage(msg)
|
||||
case "forum-results":
|
||||
handleForumResultsMessage(msg)
|
||||
case "text-results":
|
||||
handleTextResultsMessage(msg)
|
||||
case "image-results":
|
||||
handleImageResultsMessage(msg)
|
||||
case "video-results":
|
||||
handleVideoResultsMessage(msg)
|
||||
case "file-results":
|
||||
handleFileResultsMessage(msg)
|
||||
default:
|
||||
printWarn("Received unknown message type: %v", msg.Type)
|
||||
}
|
||||
}
|
|
@ -21,20 +21,22 @@ type URL struct {
|
|||
}
|
||||
|
||||
func generateOpenSearchXML(config Config) {
|
||||
baseURL := addProtocol(config.Domain)
|
||||
|
||||
opensearch := OpenSearchDescription{
|
||||
Xmlns: "http://a9.com/-/spec/opensearch/1.1/",
|
||||
ShortName: "Ocásek",
|
||||
ShortName: "Search Engine",
|
||||
Description: "Search engine",
|
||||
Tags: "search, engine",
|
||||
URL: URL{
|
||||
Type: "text/html",
|
||||
Template: fmt.Sprintf("https://%s/search?q={searchTerms}", config.OpenSearch.Domain),
|
||||
Template: fmt.Sprintf("%s/search?q={searchTerms}", baseURL),
|
||||
},
|
||||
}
|
||||
|
||||
file, err := os.Create("static/opensearch.xml")
|
||||
if err != nil {
|
||||
fmt.Println("Error creating OpenSearch file:", err)
|
||||
printErr("Error creating OpenSearch file: %v", err)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
@ -42,9 +44,9 @@ func generateOpenSearchXML(config Config) {
|
|||
enc := xml.NewEncoder(file)
|
||||
enc.Indent(" ", " ")
|
||||
if err := enc.Encode(opensearch); err != nil {
|
||||
fmt.Println("Error encoding OpenSearch XML:", err)
|
||||
printErr("Error encoding OpenSearch XML: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("OpenSearch description file generated successfully.")
|
||||
printInfo("OpenSearch description file generated successfully.")
|
||||
}
|
||||
|
|
50
printing.go
Normal file
50
printing.go
Normal file
|
@ -0,0 +1,50 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// printDebug logs debug-level messages when LogLevel is set to 4.
|
||||
func printDebug(format string, args ...interface{}) {
|
||||
if config.LogLevel >= 4 {
|
||||
logMessage("DEBUG", format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// printInfo logs info-level messages when LogLevel is set to 3 or higher.
|
||||
func printInfo(format string, args ...interface{}) {
|
||||
if config.LogLevel >= 3 {
|
||||
logMessage("INFO", format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// printWarn logs warning-level messages when LogLevel is set to 2 or higher.
|
||||
func printWarn(format string, args ...interface{}) {
|
||||
if config.LogLevel >= 2 {
|
||||
logMessage("WARN", format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// printErr logs error-level messages regardless of LogLevel.
|
||||
func printErr(format string, args ...interface{}) {
|
||||
if config.LogLevel >= 1 {
|
||||
logMessage("ERROR", format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// printMessage logs messages without a specific log level (e.g., general output).
|
||||
func printMessage(format string, args ...interface{}) {
|
||||
logMessage("", format, args...)
|
||||
}
|
||||
|
||||
// logMessage handles the actual logging logic without using the default logger's timestamp.
|
||||
func logMessage(level string, format string, args ...interface{}) {
|
||||
timestamp := time.Now().Format("2006-01-02 15:04:05")
|
||||
message := fmt.Sprintf(format, args...)
|
||||
if level != "" {
|
||||
fmt.Printf("[%s %s] %s\n", timestamp, level, message)
|
||||
} else {
|
||||
fmt.Printf("[%s] %s\n", timestamp, message)
|
||||
}
|
||||
}
|
31
run.bat
Executable file
31
run.bat
Executable file
|
@ -0,0 +1,31 @@
|
|||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
rem Directory where the Go files are located
|
||||
set GO_DIR=C:\path\to\your\go\files
|
||||
|
||||
rem Explicitly list the main files in the required order
|
||||
set FILES=main.go init.go search-engine.go text.go text-google.go text-librex.go text-brave.go text-duckduckgo.go common.go cache.go agent.go files.go files-thepiratebay.go files-torrentgalaxy.go forums.go get-searchxng.go imageproxy.go images.go images-imgur.go images-quant.go map.go node.go open-search.go video.go
|
||||
|
||||
rem Change to the directory with the Go files
|
||||
pushd %GO_DIR%
|
||||
|
||||
rem Find all other .go files that were not explicitly listed
|
||||
set OTHER_GO_FILES=
|
||||
|
||||
for %%f in (*.go) do (
|
||||
set file=%%~nxf
|
||||
set found=0
|
||||
for %%i in (%FILES%) do (
|
||||
if /i "%%i"=="!file!" set found=1
|
||||
)
|
||||
if !found!==0 (
|
||||
set OTHER_GO_FILES=!OTHER_GO_FILES! "%%f"
|
||||
)
|
||||
)
|
||||
|
||||
rem Run the Go program with the specified files first, followed by the remaining files
|
||||
go run %FILES% %OTHER_GO_FILES%
|
||||
|
||||
rem Return to the original directory
|
||||
popd
|
36
run.sh
36
run.sh
|
@ -1,7 +1,35 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Find all .go files in the current directory
|
||||
GO_FILES=$(find . -name '*.go' -print)
|
||||
# Explicitly list the main files in the required order
|
||||
FILES="
|
||||
./main.go
|
||||
./init.go
|
||||
./search-engine.go
|
||||
./text.go
|
||||
./text-google.go
|
||||
./text-librex.go
|
||||
./text-brave.go
|
||||
./text-duckduckgo.go
|
||||
./common.go
|
||||
./cache.go
|
||||
./agent.go
|
||||
./files.go
|
||||
./files-thepiratebay.go
|
||||
./files-torrentgalaxy.go
|
||||
./forums.go
|
||||
./get-searchxng.go
|
||||
./imageproxy.go
|
||||
./images.go
|
||||
./images-imgur.go
|
||||
./images-quant.go
|
||||
./map.go
|
||||
./node.go
|
||||
./open-search.go
|
||||
./video.go
|
||||
"
|
||||
|
||||
# Run the Go program
|
||||
go run $GO_FILES
|
||||
# Find all other .go files that were not explicitly listed
|
||||
OTHER_GO_FILES=$(find . -name '*.go' ! -name 'main.go' ! -name 'init.go' ! -name 'search-engine.go' ! -name 'text.go' ! -name 'text-google.go' ! -name 'text-librex.go' ! -name 'text-brave.go' ! -name 'text-duckduckgo.go' ! -name 'common.go' ! -name 'cache.go' ! -name 'agent.go' ! -name 'files.go' ! -name 'files-thepiratebay.go' ! -name 'files-torrentgalaxy.go' ! -name 'forums.go' ! -name 'get-searchxng.go' ! -name 'imageproxy.go' ! -name 'images.go' ! -name 'images-imgur.go' ! -name 'images-quant.go' ! -name 'map.go' ! -name 'node.go' ! -name 'open-search.go' ! -name 'video.go' -print)
|
||||
|
||||
# Run the Go program with the specified files first, followed by the remaining files
|
||||
go run $FILES $OTHER_GO_FILES
|
||||
|
|
|
@ -1,13 +1,18 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
searchEngineLock sync.Mutex
|
||||
searchEngines []SearchEngine // Ensure this variable is defined
|
||||
)
|
||||
|
||||
// SearchEngine struct now includes metrics for calculating reputation.
|
||||
|
@ -19,11 +24,23 @@ type SearchEngine struct {
|
|||
TotalTime time.Duration
|
||||
SuccessfulSearches int
|
||||
FailedSearches int
|
||||
IsCrawler bool // Indicates if this search engine is a crawler
|
||||
Host string // Host of the crawler
|
||||
Port int // Port of the crawler
|
||||
AuthCode string // Auth code for the crawler
|
||||
}
|
||||
|
||||
// init function seeds the random number generator.
|
||||
func init() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
// Initialize the searchEngines list
|
||||
searchEngines = []SearchEngine{
|
||||
{Name: "Google", Func: wrapTextSearchFunc(PerformGoogleTextSearch), Weight: 1},
|
||||
{Name: "LibreX", Func: wrapTextSearchFunc(PerformLibreXTextSearch), Weight: 2},
|
||||
{Name: "Brave", Func: wrapTextSearchFunc(PerformBraveTextSearch), Weight: 2},
|
||||
{Name: "DuckDuckGo", Func: wrapTextSearchFunc(PerformDuckDuckGoTextSearch), Weight: 5},
|
||||
// {Name: "SearXNG", Func: wrapTextSearchFunc(PerformSearXNGTextSearch), Weight: 2}, // Uncomment when implemented
|
||||
}
|
||||
}
|
||||
|
||||
// Selects a search engine based on weighted random selection with dynamic weighting.
|
||||
|
@ -88,3 +105,47 @@ func calculateReputation(engine SearchEngine) int {
|
|||
// Scale reputation for better interpretability (e.g., multiply by 10)
|
||||
return int(reputation * 10)
|
||||
}
|
||||
|
||||
func fetchSearchResults(query, safe, lang, searchType string, page int) []SearchResult {
|
||||
var results []SearchResult
|
||||
|
||||
engine := selectSearchEngine(searchEngines)
|
||||
log.Printf("Using search engine: %s", engine.Name)
|
||||
|
||||
if engine.IsCrawler {
|
||||
searchResults, duration, err := fetchSearchFromCrawler(engine, query, safe, lang, searchType, page)
|
||||
updateEngineMetrics(&engine, duration, err == nil)
|
||||
if err != nil {
|
||||
log.Printf("Error performing search with crawler %s: %v", engine.Name, err)
|
||||
return nil
|
||||
}
|
||||
results = append(results, searchResults...)
|
||||
} else {
|
||||
searchResults, duration, err := engine.Func(query, safe, lang, page)
|
||||
updateEngineMetrics(&engine, duration, err == nil)
|
||||
if err != nil {
|
||||
log.Printf("Error performing search with %s: %v", engine.Name, err)
|
||||
return nil
|
||||
}
|
||||
results = append(results, searchResults...)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func fetchSearchFromCrawler(engine SearchEngine, query, safe, lang, searchType string, page int) ([]SearchResult, time.Duration, error) {
|
||||
url := fmt.Sprintf("http://%s:%d/search?q=%s&safe=%s&lang=%s&t=%s&p=%d", engine.Host, engine.Port, query, safe, lang, searchType, page)
|
||||
start := time.Now()
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var results []SearchResult
|
||||
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return results, time.Since(start), nil
|
||||
}
|
||||
|
|
74
static/css/black.css
Normal file
74
static/css/black.css
Normal file
|
@ -0,0 +1,74 @@
|
|||
:root {
|
||||
--html-bg: #000000;
|
||||
--font-fg: #fafafa;
|
||||
--fg: #BABCBE;
|
||||
|
||||
--search-bg: #000000;
|
||||
--search-bg-input: #000000;
|
||||
--search-bg-input-border: #5f6368;
|
||||
--search-select: #282828;
|
||||
|
||||
--border: #707070;
|
||||
|
||||
--link: #8ab4f8;
|
||||
--link-visited: #c58af9;
|
||||
|
||||
--snip-border: #303134;
|
||||
--snip-background: #282828;
|
||||
--snip-text: #f1f3f4;
|
||||
|
||||
--settings-border: #5f6368;
|
||||
--button: #000000;
|
||||
|
||||
--footer-bg: #161616;
|
||||
--footer-font: #999da2;
|
||||
|
||||
--highlight: #bcc0c3;
|
||||
|
||||
--blue: #8ab4f8;
|
||||
|
||||
--green: #31b06e;
|
||||
|
||||
--search-button: #BABCBE;
|
||||
|
||||
--image-view: #161616;
|
||||
--image-view-titlebar: #161616;
|
||||
--view-image-color: #000000;
|
||||
--image-select: #303030;
|
||||
--fff: #fff;
|
||||
|
||||
--publish-info: #7f869e;
|
||||
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
.calc-btn:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2 {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc-btn {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.view-image-search {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.view-image-search:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
74
static/css/dark.css
Normal file
74
static/css/dark.css
Normal file
|
@ -0,0 +1,74 @@
|
|||
:root {
|
||||
--html-bg: #1c1c1c;
|
||||
--font-fg: #f1f3f4;
|
||||
--fg: #BABCBE;
|
||||
|
||||
--search-bg: #161616;
|
||||
--search-bg-input: #333333;
|
||||
--search-bg-input-border: #3C4043;
|
||||
--search-select: #282828;
|
||||
|
||||
--border: #303134;
|
||||
|
||||
--link: #8ab4f8;
|
||||
--link-visited: #c58af9;
|
||||
|
||||
--snip-border: #303134;
|
||||
--snip-background: #282828;
|
||||
--snip-text: #f1f3f4;
|
||||
|
||||
--settings-border: #5f6368;
|
||||
--button: #333333;
|
||||
|
||||
--footer-bg: #161616;
|
||||
--footer-font: #999da2;
|
||||
|
||||
--highlight: #bcc0c3;
|
||||
|
||||
--blue: #8ab4f8;
|
||||
|
||||
--green: #31b06e;
|
||||
|
||||
--search-button: #BABCBE;
|
||||
|
||||
--image-view: #161616;
|
||||
--image-view-titlebar: #161616;
|
||||
--view-image-color: #000000;
|
||||
--image-select: #303030;
|
||||
--fff: #fff;
|
||||
|
||||
--publish-info: #7f869e;
|
||||
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
.calc-btn:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2 {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc-btn {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.view-image-search {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.view-image-search:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
100
static/css/latte.css
Normal file
100
static/css/latte.css
Normal file
|
@ -0,0 +1,100 @@
|
|||
:root {
|
||||
--rosewater: #f5e0dc;
|
||||
--flamingo: #f2cdcd;
|
||||
--pink: #f5c2e7;
|
||||
--mauve: #cba6f7;
|
||||
--red: #f38ba8;
|
||||
--maroon: #eba0ac;
|
||||
--peach: #fab387;
|
||||
--yellow: #f9e2af;
|
||||
--green: #a6e3a1;
|
||||
--teal: #94e2d5;
|
||||
--sky: #89dceb;
|
||||
--sapphire: #74c7ec;
|
||||
--blue: #89b4fa;
|
||||
--lavender: #b4befe;
|
||||
--text: #cdd6f4;
|
||||
--subtext1: #bac2de;
|
||||
--subtext0: #a6adc8;
|
||||
--overlay2: #9399b2;
|
||||
--overlay1: #7f849c;
|
||||
--overlay0: #6c7086;
|
||||
--surface2: #585b70;
|
||||
--surface1: #45475a;
|
||||
--surface0: #313244;
|
||||
--base: #1e1e2e;
|
||||
--mantle: #181825;
|
||||
--crust: #11111b;
|
||||
|
||||
--html-bg: var(--base);
|
||||
--font-fg: var(--text);
|
||||
--fg: var(--subtext0);
|
||||
|
||||
--search-bg: var(--mantle);
|
||||
--search-bg-input: var(--surface1);
|
||||
--search-bg-input-border: var(--overlay0);
|
||||
--search-select: var(--surface0);
|
||||
|
||||
--border: var(--overlay0);
|
||||
|
||||
--link: var(--blue);
|
||||
--link-visited: var(--mauve);
|
||||
|
||||
--snip-border: var(--surface1);
|
||||
--snip-background: var(--surface0);
|
||||
--snip-text: var(--text);
|
||||
|
||||
--settings-border: var(--overlay1);
|
||||
--button: var(--surface1);
|
||||
|
||||
--footer-bg: var(--mantle);
|
||||
--footer-font: var(--overlay1);
|
||||
|
||||
--highlight: var(--subtext1);
|
||||
|
||||
--blue: var(--blue);
|
||||
--green: var(--green);
|
||||
|
||||
--search-button: var(--subtext0);
|
||||
|
||||
--image-view: var(--mantle);
|
||||
--image-view-titlebar: var(--mantle);
|
||||
--view-image-color: var(--crust);
|
||||
--image-select: var(--surface1);
|
||||
--fff: var(--text);
|
||||
|
||||
--publish-info: var(--overlay2);
|
||||
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
.calc-btn:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2 {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc-btn {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.view-image-search {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.view-image-search:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
72
static/css/light.css
Normal file
72
static/css/light.css
Normal file
|
@ -0,0 +1,72 @@
|
|||
:root {
|
||||
--html-bg: #ffffff;
|
||||
--font-fg: #000000;
|
||||
--fg: #202124;
|
||||
|
||||
--search-bg: #ffffff;
|
||||
--search-bg-input: #f6f6f6;
|
||||
--search-bg-input-border: #dadce0;
|
||||
--search-select: #eeeeee;
|
||||
|
||||
--border: #dadce0;
|
||||
|
||||
--link: #1a0dab;
|
||||
--link-visited: #681da8;
|
||||
|
||||
--snip-border: #dadce0;
|
||||
--snip-background: #ffffff;
|
||||
--snip-text: #000000;
|
||||
|
||||
--settings-border: #5f6368;
|
||||
--button: #f6f6f6;
|
||||
|
||||
--footer-bg: #f6f6f6;
|
||||
--footer-font: #353535;
|
||||
|
||||
--highlight: #202124;
|
||||
|
||||
--blue: #4285f4;
|
||||
|
||||
--green: #202124;
|
||||
|
||||
--image-view: #ffffff;
|
||||
--image-view-titlebar: #ffffff;
|
||||
--view-image-color: #f1f3f4;
|
||||
--image-select: #f6f6f6;
|
||||
--fff: #fff;
|
||||
|
||||
--publish-info: #202124;
|
||||
|
||||
--search-button: #202124;
|
||||
}
|
||||
|
||||
.wrapper-results:hover,
|
||||
.wrapper-results:focus-within,
|
||||
.wrapper:hover,
|
||||
.wrapper:focus-within {
|
||||
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08) !important;
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1) !important;
|
||||
}
|
||||
|
||||
.check p {
|
||||
color: var(--highlight) !important;
|
||||
}
|
||||
|
||||
.image_view {
|
||||
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08) !important;
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1) !important;
|
||||
}
|
||||
|
||||
.search-menu {
|
||||
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08) !important;
|
||||
}
|
||||
|
||||
.view-image-search {
|
||||
box-shadow: none;
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1) !important;
|
||||
}
|
||||
|
||||
.view-image-search:hover {
|
||||
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08) !important;
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1) !important;
|
||||
}
|
100
static/css/mocha.css
Normal file
100
static/css/mocha.css
Normal file
|
@ -0,0 +1,100 @@
|
|||
:root {
|
||||
--rosewater: #dc8a78;
|
||||
--flamingo: #dd7878;
|
||||
--pink: #ea76cb;
|
||||
--mauve: #8839ef;
|
||||
--red: #d20f39;
|
||||
--maroon: #e64553;
|
||||
--peach: #fe640b;
|
||||
--yellow: #df8e1d;
|
||||
--green: #40a02b;
|
||||
--teal: #179299;
|
||||
--sky: #04a5e5;
|
||||
--sapphire: #209fb5;
|
||||
--blue: #1e66f5;
|
||||
--lavender: #7287fd;
|
||||
--text: #4c4f69;
|
||||
--subtext1: #5c5f77;
|
||||
--subtext0: #6c6f85;
|
||||
--overlay2: #7c7f93;
|
||||
--overlay1: #8c8fa1;
|
||||
--overlay0: #9ca0b0;
|
||||
--surface2: #acb0be;
|
||||
--surface1: #bcc0cc;
|
||||
--surface0: #ccd0da;
|
||||
--base: #eff1f5;
|
||||
--mantle: #e6e9ef;
|
||||
--crust: #dce0e8;
|
||||
|
||||
--html-bg: var(--base);
|
||||
--font-fg: var(--text);
|
||||
--fg: var(--subtext0);
|
||||
|
||||
--search-bg: var(--mantle);
|
||||
--search-bg-input: var(--surface1);
|
||||
--search-bg-input-border: var(--overlay0);
|
||||
--search-select: var(--surface0);
|
||||
|
||||
--border: var(--overlay0);
|
||||
|
||||
--link: var(--blue);
|
||||
--link-visited: var(--mauve);
|
||||
|
||||
--snip-border: var(--surface1);
|
||||
--snip-background: var(--surface0);
|
||||
--snip-text: var(--text);
|
||||
|
||||
--settings-border: var(--overlay1);
|
||||
--button: var(--surface1);
|
||||
|
||||
--footer-bg: var(--mantle);
|
||||
--footer-font: var(--overlay1);
|
||||
|
||||
--highlight: var(--subtext1);
|
||||
|
||||
--blue: var(--blue);
|
||||
--green: var(--green);
|
||||
|
||||
--search-button: var(--subtext0);
|
||||
|
||||
--image-view: var(--mantle);
|
||||
--image-view-titlebar: var(--mantle);
|
||||
--view-image-color: var(--crust);
|
||||
--image-select: var(--surface1);
|
||||
--fff: var(--text);
|
||||
|
||||
--publish-info: var(--overlay2);
|
||||
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.calc-btn:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.15), 0 10px 10px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.calc-btn-2:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.15), 0 10px 10px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.calc-btn-2 {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10), 0 1px 2px rgba(0, 0, 0, 0.14);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc-btn {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10), 0 1px 2px rgba(0, 0, 0, 0.14);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.view-image-search {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10), 0 1px 2px rgba(0, 0, 0, 0.14);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.view-image-search:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.15), 0 10px 10px rgba(0, 0, 0, 0.12);
|
||||
}
|
74
static/css/night.css
Normal file
74
static/css/night.css
Normal file
|
@ -0,0 +1,74 @@
|
|||
:root {
|
||||
--html-bg: #171b25;
|
||||
--font-fg: #ebecf7;
|
||||
--fg: #ebecf7;
|
||||
|
||||
--search-bg: #0c0d0f;
|
||||
--search-bg-input: #2e3443;
|
||||
--search-bg-input-border: rgb(46, 52, 67);
|
||||
--search-select: #3a445c;
|
||||
|
||||
--border: rgb(46, 52, 67);
|
||||
|
||||
--link: #a7b1fc;
|
||||
--link-visited: #ad71bc;
|
||||
|
||||
--snip-border: rgb(46, 52, 67);
|
||||
--snip-background: #1e222d;
|
||||
--snip-text: #f1f3f4;
|
||||
|
||||
--settings-border: #5f6368;
|
||||
--button: #0c0d0f;
|
||||
|
||||
--footer-bg: #0c0d0f;
|
||||
--footer-font: #ebecf7;
|
||||
|
||||
--highlight: #ebecf7;
|
||||
|
||||
--blue: #8ab4f8;
|
||||
|
||||
--green: #31b06e;
|
||||
|
||||
--image-view: #0c0d0f;
|
||||
--image-view-titlebar: #0c0d0f;
|
||||
--view-image-color: #000000;
|
||||
--image-select: #303030;
|
||||
--fff: #fff;
|
||||
|
||||
--search-button: #BABCBE;
|
||||
|
||||
--publish-info: #7f869e;
|
||||
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
.calc-btn:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.calc-btn-2 {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc-btn {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.calc {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.view-image-search {
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
|
||||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
|
||||
.view-image-search:hover {
|
||||
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
|
||||
}
|
62
static/css/style-settings.css
Normal file
62
static/css/style-settings.css
Normal file
|
@ -0,0 +1,62 @@
|
|||
|
||||
/* settings.html */
|
||||
|
||||
.theme-link {
|
||||
display: block;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
width: 48%;
|
||||
margin-bottom: 10px;
|
||||
height: 150px;
|
||||
position: relative; /* Make it possible to position the tooltip */
|
||||
}
|
||||
|
||||
.theme-link img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--snip-border);
|
||||
transition: border-color 0.3s ease;
|
||||
}
|
||||
|
||||
/* .theme-link:hover img {
|
||||
border-color: var(--highlight);
|
||||
} */
|
||||
|
||||
.theme-tooltip {
|
||||
display: none; /* Hidden by default */
|
||||
position: absolute;
|
||||
bottom: 10px; /* Position at the bottom of the image */
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background-color: rgba(0, 0, 0, 0.7); /* Semi-transparent background */
|
||||
color: #fff;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.theme-link:hover .theme-tooltip {
|
||||
display: block; /* Show tooltip on hover */
|
||||
}
|
||||
|
||||
.themes-settings-menu {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
background: var(--snip-background);
|
||||
color: var(--fg);
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.theme-link {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- */
|
|
@ -120,6 +120,7 @@
|
|||
}
|
||||
|
||||
.clean {
|
||||
margin-top: 30px;
|
||||
max-width: 775px;
|
||||
}
|
||||
|
||||
|
@ -483,6 +484,16 @@ hr {
|
|||
font-size: 16px;
|
||||
}
|
||||
|
||||
.video_title a {
|
||||
color: var(--link);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.video_title a:hover {
|
||||
color: var(--link);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.video-results-margin {
|
||||
margin-bottom: 0px !important;
|
||||
}
|
||||
|
@ -546,7 +557,7 @@ hr {
|
|||
left: 0;
|
||||
right: 0;
|
||||
z-index: 2;
|
||||
border: 2px solid var(--search-bg-input-border);
|
||||
border: 1px solid var(--search-bg-input-border);
|
||||
}
|
||||
|
||||
.wrapper input {
|
||||
|
@ -680,6 +691,7 @@ hr {
|
|||
|
||||
.kno_wiki_show {
|
||||
display: initial !important;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.open-in-new-tab * {
|
||||
|
@ -786,6 +798,7 @@ form.torrent-sort {
|
|||
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
top: 24px;
|
||||
}
|
||||
|
||||
.search-menu h2 {
|
||||
|
@ -841,7 +854,6 @@ form.torrent-sort {
|
|||
margin: 5px;
|
||||
}
|
||||
|
||||
|
||||
.view-image-search {
|
||||
border: 1px solid var(--snip-border);
|
||||
margin: 0;
|
||||
|
@ -1154,7 +1166,7 @@ p {
|
|||
background-color: inherit;
|
||||
font-size: 14px;
|
||||
font-family: 'Inter';
|
||||
margin-right: 10px;
|
||||
margin-right: 14px;
|
||||
color: var(--search-button);
|
||||
margin-top: 72px;
|
||||
padding-bottom: 11px;
|
||||
|
@ -1208,6 +1220,10 @@ p {
|
|||
margin-top: -2px;
|
||||
}
|
||||
|
||||
.link {
|
||||
color: var(--link);
|
||||
}
|
||||
|
||||
.results a:visited h3,
|
||||
.result_sublink a:visited h3 {
|
||||
color: var(--link-visited);
|
||||
|
@ -1226,6 +1242,7 @@ p {
|
|||
.results p,
|
||||
.result_sublink p {
|
||||
margin-top: 0px;
|
||||
color: var(--font-fg);
|
||||
}
|
||||
|
||||
.results a,
|
||||
|
@ -1235,6 +1252,7 @@ p {
|
|||
.result_sublink a:hover,
|
||||
.result_sublink a:visited {
|
||||
text-decoration: none;
|
||||
/* color: #ebecf7; */
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
|
@ -1277,6 +1295,12 @@ p {
|
|||
font-size: 22px;
|
||||
}
|
||||
|
||||
.wiki_known_for {
|
||||
margin: 0px;
|
||||
font-weight: normal;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.snip img {
|
||||
float: right;
|
||||
max-width: 30%;
|
||||
|
@ -1285,8 +1309,7 @@ p {
|
|||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.snip a {
|
||||
display: block;
|
||||
.snip .wiki_link {
|
||||
margin-top: 10px;
|
||||
text-decoration: none;
|
||||
color: var(--link);
|
||||
|
@ -1300,6 +1323,28 @@ p {
|
|||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.snip .about {
|
||||
font-size: 18px;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.factpoint {
|
||||
color: var(--fg);
|
||||
font-weight: bold;
|
||||
vertical-align: text-top;
|
||||
text-align: left;
|
||||
padding-right: 14px;
|
||||
}
|
||||
|
||||
.fact a {
|
||||
color: var(--link);
|
||||
text-decoration: none;
|
||||
}
|
||||
.fact a:visited {
|
||||
color: var(--link-visited);
|
||||
}
|
||||
|
||||
.snipp {
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
|
@ -1680,6 +1725,7 @@ body, h1, p, a, input, button {
|
|||
margin-top: 0px;
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
/* background-color: var(--search-bg); */
|
||||
}
|
||||
|
||||
.mobile-none {
|
||||
|
@ -1826,8 +1872,6 @@ body, h1, p, a, input, button {
|
|||
|
||||
}
|
||||
|
||||
/* --- */
|
||||
|
||||
/* Ensuring dark theme compliance */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.leaflet-control-locate,
|
||||
|
@ -1849,8 +1893,7 @@ body, h1, p, a, input, button {
|
|||
color: var(--link) !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Variables for light theme */
|
||||
/*
|
||||
:root {
|
||||
--background-color: #ffffff;
|
||||
--text-color: #000000;
|
||||
|
@ -1879,7 +1922,6 @@ body, h1, p, a, input, button {
|
|||
--box-shadow: #00000020;
|
||||
}
|
||||
|
||||
/* Styles for dark theme */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background-color: #202124;
|
||||
|
@ -1908,4 +1950,4 @@ body, h1, p, a, input, button {
|
|||
--green: #8ab4f8;
|
||||
--box-shadow: #ffffff20;
|
||||
}
|
||||
}
|
||||
} */
|
||||
|
|
BIN
static/images/black.webp
Normal file
BIN
static/images/black.webp
Normal file
Binary file not shown.
After Width: | Height: | Size: 11 KiB |
BIN
static/images/dark.webp
Normal file
BIN
static/images/dark.webp
Normal file
Binary file not shown.
After Width: | Height: | Size: 9.5 KiB |
BIN
static/images/latte.webp
Normal file
BIN
static/images/latte.webp
Normal file
Binary file not shown.
After Width: | Height: | Size: 15 KiB |
BIN
static/images/light.webp
Normal file
BIN
static/images/light.webp
Normal file
Binary file not shown.
After Width: | Height: | Size: 10 KiB |
BIN
static/images/mocha.webp
Normal file
BIN
static/images/mocha.webp
Normal file
Binary file not shown.
After Width: | Height: | Size: 14 KiB |
BIN
static/images/night.webp
Normal file
BIN
static/images/night.webp
Normal file
Binary file not shown.
After Width: | Height: | Size: 9.8 KiB |
7
templates/files.html
Normal file → Executable file
7
templates/files.html
Normal file → Executable file
|
@ -4,7 +4,8 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{.Query}} - Ocásek</title>
|
||||
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
</head>
|
||||
<body>
|
||||
|
@ -66,7 +67,7 @@
|
|||
<option value="software" {{ if eq .Category "software" }} selected {{ end }}>Software</option>
|
||||
<option value="anime" {{ if eq .Category "anime" }} selected {{ end }}>Anime</option>
|
||||
<option value="music" {{ if eq .Category "music" }} selected {{ end }}>Music</option>
|
||||
{{ if eq .Settings.Safe "inactive" }}
|
||||
{{ if eq .Safe "disabled" }}
|
||||
<option value="xxx" {{ if eq .Category "xxx" }} selected {{ end }}>XXX (18+)</option>
|
||||
{{ end }}
|
||||
</select>
|
||||
|
@ -74,7 +75,7 @@
|
|||
</form>
|
||||
<div class="clean">
|
||||
{{ range .Results }}
|
||||
<div class="results">
|
||||
<div class="results" id="results">
|
||||
{{ if .Error }}
|
||||
<div class="error">{{ .Error }}</div>
|
||||
{{ else }}
|
||||
|
|
9
templates/forums.html
Normal file → Executable file
9
templates/forums.html
Normal file → Executable file
|
@ -4,7 +4,8 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{.Query}} - Ocásek</title>
|
||||
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
</head>
|
||||
<body>
|
||||
|
@ -47,8 +48,8 @@
|
|||
<form class="results_settings" action="/search" method="get">
|
||||
<input type="hidden" name="q" value="{{ .Query }}">
|
||||
<select class="results-settings" name="safe" id="safeSearchSelect">
|
||||
<option value="">Safe Search Off</option>
|
||||
<option value="active">Safe Search On</option>
|
||||
<option value="disabled" {{if eq .Safe "disabled"}}selected{{end}}>Safe Search Off</option>
|
||||
<option value="active" {{if eq .Safe "active"}}selected{{end}}>Safe Search On</option>
|
||||
</select>
|
||||
<select class="results-settings" name="lang" id="languageSelect">
|
||||
{{range .LanguageOptions}}
|
||||
|
@ -61,7 +62,7 @@
|
|||
{{if .Results}}
|
||||
{{range .Results}}
|
||||
<div class="result_item">
|
||||
<a href="{{.URL}}">{{.URL}}</a>
|
||||
<a id="link" href="{{.URL}}">{{.URL}}</a>
|
||||
<a href="{{.URL}}"><h3>{{.Header}}</h3></a>
|
||||
<p>{{.Description}}</p>
|
||||
</div>
|
||||
|
|
11
templates/images.html
Normal file → Executable file
11
templates/images.html
Normal file → Executable file
|
@ -4,7 +4,8 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{.Query}} - Ocásek</title>
|
||||
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
</head>
|
||||
<body>
|
||||
|
@ -47,8 +48,8 @@
|
|||
<form class="results_settings" action="/search" method="get">
|
||||
<input type="hidden" name="q" value="{{ .Query }}">
|
||||
<select class="results-settings" name="safe" id="safeSearchSelect">
|
||||
<option value="">Safe Search Off</option>
|
||||
<option value="active">Safe Search On</option>
|
||||
<option value="disabled" {{if eq .Safe "disabled"}}selected{{end}}>Safe Search Off</option>
|
||||
<option value="active" {{if eq .Safe "active"}}selected{{end}}>Safe Search On</option>
|
||||
</select>
|
||||
<select class="results-settings" name="lang" id="languageSelect">
|
||||
{{range .LanguageOptions}}
|
||||
|
@ -100,6 +101,10 @@
|
|||
<div class="message-bottom-left" id="message-bottom-left">
|
||||
<span>Searching for new results...</span>
|
||||
</div>
|
||||
<script>
|
||||
// Check if JavaScript is enabled and modify the DOM accordingly
|
||||
document.getElementById('content').classList.remove('js-enabled');
|
||||
</script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
let page = {{ .Page }};
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ .Query }} - Ocásek</title>
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.js"></script>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css" />
|
||||
|
|
69
templates/search.html
Normal file → Executable file
69
templates/search.html
Normal file → Executable file
|
@ -5,11 +5,78 @@
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Search with Ocásek</title>
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
// Define the updateSettings function first
|
||||
function updateSettings(settingKey, settingValue) {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', '/updateSettings', true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
|
||||
xhr.onload = function () {
|
||||
if (this.status >= 200 && this.status < 300) {
|
||||
console.log('Settings updated successfully!');
|
||||
} else {
|
||||
console.log('Failed to update settings.');
|
||||
}
|
||||
};
|
||||
xhr.send(encodeURI(settingKey + '=' + settingValue));
|
||||
}
|
||||
|
||||
const settingsIcon = document.querySelector('.settings-icon-link-search');
|
||||
const searchMenu = document.querySelector('.search-menu');
|
||||
|
||||
settingsIcon.addEventListener('click', function () {
|
||||
searchMenu.classList.toggle('settings-menu-hidden');
|
||||
searchMenu.classList.toggle('settings-menu-visible');
|
||||
});
|
||||
|
||||
// Theme change event listeners
|
||||
document.getElementById('dark_theme').addEventListener('click', function () {
|
||||
window.location.href = '/search?theme=dark';
|
||||
});
|
||||
document.getElementById('light_theme').addEventListener('click', function () {
|
||||
window.location.href = '/search?theme=light';
|
||||
});
|
||||
|
||||
// Event listener for Safe Search Selection
|
||||
document.getElementById('safeSearchSelect').addEventListener('change', function () {
|
||||
updateSettings('safe', this.value);
|
||||
});
|
||||
|
||||
// Event listener for Language Selection
|
||||
document.getElementById('languageSelect').addEventListener('change', function () {
|
||||
updateSettings('lang', this.value);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<div class="settings-search-div settings-search-div-search">
|
||||
<a class="material-icons-round clickable" href="/settings">tune</a>
|
||||
<button class="material-icons-round clickable settings-icon-link settings-icon-link-search">menu</button>
|
||||
</div>
|
||||
<div class="search-menu settings-menu-hidden">
|
||||
<h2>Settings</h2>
|
||||
<div class="settings-content">
|
||||
<button id="settingsButton" onclick="window.location.href='/settings'">All settings</button> <!-- Well its unessesary to use js here but this menu will not work without js anyway -->
|
||||
<div class="theme-settings">
|
||||
<p><span class="highlight">Current theme: </span> <span id="theme_name">{{.Theme}}</span></p>
|
||||
<div class="themes-settings-menu">
|
||||
<div><img class="view-image-search clickable" id="dark_theme" alt="Dark Theme" src="/static/images/dark.webp"></div>
|
||||
<div><img class="view-image-search clickable" id="light_theme" alt="Light Theme" src="/static/images/light.webp"></div>
|
||||
</div>
|
||||
</div>
|
||||
<select class="lang" name="safe" id="safeSearchSelect">
|
||||
<option value="disabled" {{if eq .Safe "disabled"}}selected{{end}}>Safe Search Off</option>
|
||||
<option value="active" {{if eq .Safe "active"}}selected{{end}}>Safe Search On</option>
|
||||
</select>
|
||||
<select class="lang" name="lang" id="languageSelect">
|
||||
{{range .LanguageOptions}}
|
||||
<option value="{{.Code}}" {{if eq .Code $.CurrentLang}}selected{{end}}>{{.Name}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<form action="/search" class="search-container" method="post" autocomplete="off">
|
||||
<h1>Ocásek</h1>
|
||||
|
|
|
@ -4,78 +4,87 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Settings - Ocásek</title>
|
||||
<link rel="stylesheet" type="text/css" href="static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="stylesheet" href="/static/css/style-settings.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
</head>
|
||||
<body>
|
||||
<form action="/search" id="prev-next-form" class="results-search-container" method="GET" autocomplete="off">
|
||||
<h1 class="logomobile"><a class="no-decoration" href="./">Ocásek</a></h1>
|
||||
<div class="wrapper-results">
|
||||
<input type="text" name="q" value="" id="search-input" placeholder="Type to search..." />
|
||||
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="text">search</button>
|
||||
<input type="submit" class="hide" name="t" value="text" />
|
||||
<div class="settings-nav">
|
||||
<h1 class="logomobile"><a class="no-decoration" href="./">Settings</a></h1>
|
||||
</div>
|
||||
<div class="sub-search-button-wrapper">
|
||||
<div class="search-container-results-btn">
|
||||
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="text">search</button>
|
||||
<button name="t" value="text" class="clickable">Web</button>
|
||||
</div>
|
||||
<div class="search-container-results-btn">
|
||||
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="image">image</button>
|
||||
<button name="t" value="image" class="clickable">Images</button>
|
||||
</div>
|
||||
<div class="search-container-results-btn">
|
||||
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="video">movie</button>
|
||||
<button name="t" value="video" class="clickable">Videos</button>
|
||||
</div>
|
||||
<div class="search-container-results-btn">
|
||||
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="forum">forum</button>
|
||||
<button name="t" value="forum" class="clickable">Forums</button>
|
||||
</div>
|
||||
<div id="content" class="js-enabled">
|
||||
<div class="search-container-results-btn">
|
||||
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="map">map</button>
|
||||
<button name="t" value="map" class="clickable">Maps</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="search-container-results-btn">
|
||||
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="torrent">share</button>
|
||||
<button name="t" value="torrent" class="clickable">Torrents</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<div class="results_settings">
|
||||
<form>
|
||||
<h1>SETTINGS ARE NOT IMPLEMENTED YET</h1>
|
||||
<h2>Theme</h2>
|
||||
<label for="theme-dark">Dark Theme:</label>
|
||||
<input type="checkbox" class="results-settings" id="theme-dark" name="theme" value="dark"><br>
|
||||
|
||||
<h2>Language</h2>
|
||||
<label for="ui-language">UI Language:</label>
|
||||
<select id="ui-language" class="results-settings" name="ui_language">
|
||||
<option value="english">English</option>
|
||||
<option value="deutsch">Deutsch</option>
|
||||
</select><br>
|
||||
<label for="search-language">Search Language:</label>
|
||||
<select id="search-language" class="results-settings" name="search_language">
|
||||
<option value="english">English</option>
|
||||
<option value="deutsch">Deutsch</option>
|
||||
<div class="settings-container">
|
||||
<form action="/save-settings" method="post">
|
||||
<div class="settings">
|
||||
<div class="settings-row">
|
||||
<span class="highlight"><p>Theme</p></span>
|
||||
</div>
|
||||
|
||||
<div class="theme-settings">
|
||||
<div class="themes-settings-menu">
|
||||
<a href="/search?theme=dark" class="theme-link">
|
||||
<div class="view-image-search clickable" id="dark">
|
||||
<img src="/static/images/dark.webp" alt="Dark (Default)">
|
||||
<div class="theme-tooltip">Dark (Default)</div>
|
||||
</div>
|
||||
</a>
|
||||
<a href="/search?theme=light" class="theme-link">
|
||||
<div class="view-image-search clickable" id="light">
|
||||
<img src="/static/images/light.webp" alt="Light">
|
||||
<div class="theme-tooltip">Light</div>
|
||||
</div>
|
||||
</a>
|
||||
<a href="/search?theme=night" class="theme-link">
|
||||
<div class="view-image-search clickable" id="night">
|
||||
<img src="/static/images/night.webp" alt="night">
|
||||
<div class="theme-tooltip">Night</div>
|
||||
</div>
|
||||
</a>
|
||||
<a href="/search?theme=black" class="theme-link">
|
||||
<div class="view-image-search clickable" id="black">
|
||||
<img src="/static/images/black.webp" alt="Black">
|
||||
<div class="theme-tooltip">Black</div>
|
||||
</div>
|
||||
</a>
|
||||
<a href="/search?theme=mocha" class="theme-link">
|
||||
<div class="view-image-search clickable" id="mocha">
|
||||
<img src="/static/images/mocha.webp" alt="🌿 Mocha">
|
||||
<div class="theme-tooltip">Mocha</div>
|
||||
</div>
|
||||
</a>
|
||||
<a href="/search?theme=latte" class="theme-link">
|
||||
<div class="view-image-search clickable" id="latte">
|
||||
<img src="/static/images/latte.webp" alt="🌻 Latte">
|
||||
<div class="theme-tooltip">Latte</div>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-row">
|
||||
<p>Safe Search</p>
|
||||
<select class="results-settings" name="safe" id="safeSearchSelect">
|
||||
<option value="disabled" {{if eq .Safe "disabled"}}selected{{end}}>Safe Search Off</option>
|
||||
<option value="active" {{if eq .Safe "active"}}selected{{end}}>Safe Search On</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<h2>Privacy</h2>
|
||||
<label for="theme-dark">Use JavaScript:</label>
|
||||
<input type="checkbox" class="results-settings" id="theme-dark" name="theme" value="dark"><br>
|
||||
<label for="theme-dark">Use search suggestions:</label>
|
||||
<input type="checkbox" class="results-settings" id="theme-dark" name="theme" value="dark"><br><br>
|
||||
<div class="settings-row">
|
||||
<p>Preferred Language</p>
|
||||
<select class="results-settings" name="lang" id="languageSelect">
|
||||
{{range .LanguageOptions}}
|
||||
<option value="{{.Code}}" {{if eq .Code $.CurrentLang}}selected{{end}}>{{.Name}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<input type="submit" class="results-settings" value="Save">
|
||||
<div class="settings-row settings-row2">
|
||||
<p class="font-hide">|</p>
|
||||
<button class="save save-settings-page" type="submit">Save Settings</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<div>
|
||||
<script>
|
||||
// Check if JavaScript is enabled and modify the DOM accordingly
|
||||
document.getElementById('content').classList.remove('js-enabled');
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
|
13
templates/text.html
Normal file → Executable file
13
templates/text.html
Normal file → Executable file
|
@ -4,7 +4,8 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{.Query}} - Ocásek</title>
|
||||
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
</head>
|
||||
<body>
|
||||
|
@ -47,8 +48,8 @@
|
|||
<form class="results_settings" action="/search" method="get">
|
||||
<input type="hidden" name="q" value="{{ .Query }}">
|
||||
<select class="results-settings" name="safe" id="safeSearchSelect">
|
||||
<option value="">Safe Search Off</option>
|
||||
<option value="active">Safe Search On</option>
|
||||
<option value="disabled" {{if eq .Safe "disabled"}}selected{{end}}>Safe Search Off</option>
|
||||
<option value="active" {{if eq .Safe "active"}}selected{{end}}>Safe Search On</option>
|
||||
</select>
|
||||
<select class="results-settings" name="lang" id="languageSelect">
|
||||
{{range .LanguageOptions}}
|
||||
|
@ -61,7 +62,7 @@
|
|||
{{if .Results}}
|
||||
{{range .Results}}
|
||||
<div class="result_item">
|
||||
<a href="{{.URL}}">{{.URL}}</a>
|
||||
<a id="link" href="{{.URL}}">{{.URL}}</a>
|
||||
<a href="{{.URL}}"><h3>{{.Header}}</h3></a>
|
||||
<p>{{.Description}}</p>
|
||||
</div>
|
||||
|
@ -88,6 +89,10 @@
|
|||
{{ end }}
|
||||
</form>
|
||||
</div>
|
||||
<script>
|
||||
// Check if JavaScript is enabled and modify the DOM accordingly
|
||||
document.getElementById('content').classList.remove('js-enabled');
|
||||
</script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
if (document.getElementById('prev-next')) {
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{.Query}} - Ocásek</title>
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<link rel="stylesheet" href="/static/css/{{.Theme}}.css">
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Ocásek" href="/opensearch.xml">
|
||||
</head>
|
||||
<body>
|
||||
|
@ -51,12 +52,15 @@
|
|||
<div>
|
||||
<div class="video__results">
|
||||
<div class="video__img__results">
|
||||
<a href="{{ .Href }}"> <img src="{{ .Image }}">
|
||||
<a href="{{ .Href }}">
|
||||
<img src="{{ .Image }}">
|
||||
<div class="duration">{{ .Duration }}</div>
|
||||
</img></a>
|
||||
</a>
|
||||
</div>
|
||||
<div class="results video-results-margin">
|
||||
<h3 class="video_title" href="{{ .Href }}">{{ .Title }}</h3></a>
|
||||
<h3 class="video_title">
|
||||
<a href="{{ .Href }}">{{ .Title }}</a>
|
||||
</h3>
|
||||
<p class="stats">{{ .Views }} <span class="pipe">|</span> {{ .Date }}</p>
|
||||
<p class="publish__info">YouTube <span class="pipe">|</span> {{ .Creator }}</p>
|
||||
</div>
|
||||
|
|
|
@ -2,7 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
@ -53,9 +53,7 @@ func PerformGoogleTextSearch(query, safe, lang string, page int) ([]TextSearchRe
|
|||
duration := time.Since(startTime) // Calculate the duration
|
||||
|
||||
if len(results) == 0 {
|
||||
if debugMode {
|
||||
log.Println("No results found from Google")
|
||||
}
|
||||
printDebug("No results found from Google Search")
|
||||
}
|
||||
|
||||
return results, duration, nil
|
||||
|
@ -72,8 +70,22 @@ func buildSearchURL(query, safe, lang string, page, resultsPerPage int) string {
|
|||
langParam = "&lr=" + lang
|
||||
}
|
||||
|
||||
// Generate random geolocation
|
||||
glParam, uuleParam := getRandomGeoLocation()
|
||||
|
||||
startIndex := (page - 1) * resultsPerPage
|
||||
return fmt.Sprintf("https://www.google.com/search?q=%s%s%s&udm=14&start=%d", url.QueryEscape(query), safeParam, langParam, startIndex)
|
||||
return fmt.Sprintf("https://www.google.com/search?q=%s%s%s%s%s&start=%d",
|
||||
url.QueryEscape(query), safeParam, langParam, glParam, uuleParam, startIndex)
|
||||
}
|
||||
|
||||
func getRandomGeoLocation() (string, string) {
|
||||
countries := []string{"us", "ca", "gb", "fr", "de", "au", "in", "jp", "br", "za"}
|
||||
randomCountry := countries[rand.Intn(len(countries))]
|
||||
|
||||
glParam := "&gl=" + randomCountry
|
||||
uuleParam := ""
|
||||
|
||||
return glParam, uuleParam
|
||||
}
|
||||
|
||||
func parseResults(doc *goquery.Document) []TextSearchResult {
|
||||
|
@ -83,9 +95,7 @@ func parseResults(doc *goquery.Document) []TextSearchResult {
|
|||
link := s.Find("a")
|
||||
href, exists := link.Attr("href")
|
||||
if !exists {
|
||||
if debugMode {
|
||||
log.Printf("No href attribute found for result %d\n", i)
|
||||
}
|
||||
printDebug("No href attribute found for result %d\n", i)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
124
text.go
Normal file → Executable file
124
text.go
Normal file → Executable file
|
@ -3,7 +3,6 @@ package main
|
|||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
@ -15,26 +14,65 @@ func init() {
|
|||
{Name: "Google", Func: wrapTextSearchFunc(PerformGoogleTextSearch), Weight: 1},
|
||||
{Name: "LibreX", Func: wrapTextSearchFunc(PerformLibreXTextSearch), Weight: 2},
|
||||
{Name: "Brave", Func: wrapTextSearchFunc(PerformBraveTextSearch), Weight: 2},
|
||||
{Name: "DuckDuckGo", Func: wrapTextSearchFunc(PerformDuckDuckGoTextSearch), Weight: 5}, // DuckDuckGo timeouts too fast and search results are trash
|
||||
{Name: "DuckDuckGo", Func: wrapTextSearchFunc(PerformDuckDuckGoTextSearch), Weight: 5},
|
||||
// {Name: "SearXNG", Func: wrapTextSearchFunc(PerformSearXNGTextSearch), Weight: 2}, // Uncomment when implemented
|
||||
}
|
||||
}
|
||||
|
||||
func HandleTextSearch(w http.ResponseWriter, query, safe, lang string, page int) {
|
||||
func HandleTextSearch(w http.ResponseWriter, settings UserSettings, query string, page int) {
|
||||
startTime := time.Now()
|
||||
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"}
|
||||
combinedResults := getTextResultsFromCacheOrFetch(cacheKey, query, safe, lang, page)
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: settings.SafeSearch == "true", Lang: settings.Language, Type: "text"}
|
||||
combinedResults := getTextResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.Language, page)
|
||||
|
||||
hasPrevPage := page > 1
|
||||
hasNextPage := len(combinedResults) > 0
|
||||
hasPrevPage := page > 1 // dupe
|
||||
|
||||
displayResults(w, combinedResults, query, lang, time.Since(startTime).Seconds(), page, hasPrevPage, hasNextPage)
|
||||
//displayResults(w, combinedResults, query, lang, time.Since(startTime).Seconds(), page, hasPrevPage, hasNextPage)
|
||||
|
||||
// Prefetch next and previous pages
|
||||
go prefetchPage(query, safe, lang, page+1)
|
||||
go prefetchPage(query, settings.SafeSearch, settings.Language, page+1)
|
||||
if hasPrevPage {
|
||||
go prefetchPage(query, safe, lang, page-1)
|
||||
go prefetchPage(query, settings.SafeSearch, settings.Language, page-1)
|
||||
}
|
||||
|
||||
elapsedTime := time.Since(startTime)
|
||||
tmpl, err := template.New("text.html").Funcs(funcs).ParseFiles("templates/text.html")
|
||||
if err != nil {
|
||||
printErr("Error parsing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
data := struct {
|
||||
Results []TextSearchResult
|
||||
Query string
|
||||
Page int
|
||||
Fetched string
|
||||
HasPrevPage bool
|
||||
HasNextPage bool
|
||||
NoResults bool
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
Theme string
|
||||
Safe string
|
||||
}{
|
||||
Results: combinedResults,
|
||||
Query: query,
|
||||
Page: page,
|
||||
Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()),
|
||||
HasPrevPage: page > 1,
|
||||
HasNextPage: len(combinedResults) >= 50,
|
||||
NoResults: len(combinedResults) == 0,
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: settings.Language,
|
||||
Theme: settings.Theme,
|
||||
Safe: settings.SafeSearch,
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
printErr("Error executing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -45,10 +83,10 @@ func getTextResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string,
|
|||
go func() {
|
||||
results, exists := resultsCache.Get(cacheKey)
|
||||
if exists {
|
||||
log.Println("Cache hit")
|
||||
printInfo("Cache hit")
|
||||
cacheChan <- results
|
||||
} else {
|
||||
log.Println("Cache miss")
|
||||
printInfo("Cache miss")
|
||||
cacheChan <- nil
|
||||
}
|
||||
}()
|
||||
|
@ -65,7 +103,7 @@ func getTextResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string,
|
|||
combinedResults = textResults
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
log.Println("Cache check timeout")
|
||||
printInfo("Cache check timeout")
|
||||
combinedResults = fetchTextResults(query, safe, lang, page)
|
||||
if len(combinedResults) > 0 {
|
||||
resultsCache.Set(cacheKey, convertToSearchResults(combinedResults))
|
||||
|
@ -78,13 +116,13 @@ func getTextResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string,
|
|||
func prefetchPage(query, safe, lang string, page int) {
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"}
|
||||
if _, exists := resultsCache.Get(cacheKey); !exists {
|
||||
log.Printf("Page %d not cached, caching now...", page)
|
||||
printInfo("Page %d not cached, caching now...", page)
|
||||
pageResults := fetchTextResults(query, safe, lang, page)
|
||||
if len(pageResults) > 0 {
|
||||
resultsCache.Set(cacheKey, convertToSearchResults(pageResults))
|
||||
}
|
||||
} else {
|
||||
log.Printf("Page %d already cached", page)
|
||||
printInfo("Page %d already cached", page)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -92,12 +130,12 @@ func fetchTextResults(query, safe, lang string, page int) []TextSearchResult {
|
|||
var results []TextSearchResult
|
||||
|
||||
for _, engine := range textSearchEngines {
|
||||
log.Printf("Using search engine: %s", engine.Name)
|
||||
printInfo("Using search engine: %s", engine.Name)
|
||||
|
||||
searchResults, duration, err := engine.Func(query, safe, lang, page)
|
||||
updateEngineMetrics(&engine, duration, err == nil)
|
||||
if err != nil {
|
||||
log.Printf("Error performing search with %s: %v", engine.Name, err)
|
||||
printWarn("Error performing search with %s: %v", engine.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -109,6 +147,12 @@ func fetchTextResults(query, safe, lang string, page int) []TextSearchResult {
|
|||
}
|
||||
}
|
||||
|
||||
// If no results found after trying all engines
|
||||
if len(results) == 0 {
|
||||
printWarn("No text results found for query: %s, trying other nodes", query)
|
||||
results = tryOtherNodesForTextSearch(query, safe, lang, page, []string{hostID})
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
|
@ -139,49 +183,3 @@ func wrapTextSearchFunc(f func(string, string, string, int) ([]TextSearchResult,
|
|||
return searchResults, duration, nil
|
||||
}
|
||||
}
|
||||
|
||||
func displayResults(w http.ResponseWriter, results []TextSearchResult, query, lang string, elapsed float64, page int, hasPrevPage, hasNextPage bool) {
|
||||
log.Printf("Displaying results for page %d", page)
|
||||
log.Printf("Total results: %d", len(results))
|
||||
log.Printf("Has previous page: %t, Has next page: %t", hasPrevPage, hasNextPage)
|
||||
|
||||
tmpl, err := template.New("text.html").Funcs(template.FuncMap{
|
||||
"sub": func(a, b int) int {
|
||||
return a - b
|
||||
},
|
||||
"add": func(a, b int) int {
|
||||
return a + b
|
||||
},
|
||||
}).ParseFiles("templates/text.html")
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
data := struct {
|
||||
Results []TextSearchResult
|
||||
Query string
|
||||
Fetched string
|
||||
Page int
|
||||
HasPrevPage bool
|
||||
HasNextPage bool
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
NoResults bool
|
||||
}{
|
||||
Results: results,
|
||||
Query: query,
|
||||
Fetched: fmt.Sprintf("%.2f seconds", elapsed),
|
||||
Page: page,
|
||||
HasPrevPage: hasPrevPage,
|
||||
HasNextPage: hasNextPage,
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: lang,
|
||||
NoResults: len(results) == 0,
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
|
52
update.go
Normal file
52
update.go
Normal file
|
@ -0,0 +1,52 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Function to check for updates and restart the server if an update is found
|
||||
func checkForUpdates() {
|
||||
repoURL := "https://weforgecode.xyz/Spitfire/Search.git"
|
||||
localDir := "." // Assume the repository is cloned in the current directory
|
||||
|
||||
for {
|
||||
err := gitPull(repoURL, localDir)
|
||||
if err != nil {
|
||||
fmt.Println("Error checking for updates:", err)
|
||||
time.Sleep(10 * time.Minute)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Println("Update found. Syncing updates...")
|
||||
nodeUpdateSync()
|
||||
|
||||
fmt.Println("Restarting server to apply updates...")
|
||||
update()
|
||||
time.Sleep(10 * time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
// Function to pull updates from the Git repository
|
||||
func gitPull(repoURL, localDir string) error {
|
||||
cmd := exec.Command("git", "-C", localDir, "pull", repoURL)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
// Function to download updates and restart the server
|
||||
func update() {
|
||||
cmd := exec.Command("sh", "run.sh")
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
fmt.Println("Error starting the server:", err)
|
||||
return
|
||||
}
|
||||
|
||||
os.Exit(0)
|
||||
}
|
122
user-settings.go
Executable file
122
user-settings.go
Executable file
|
@ -0,0 +1,122 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type UserSettings struct {
|
||||
Theme string
|
||||
Language string
|
||||
SafeSearch string
|
||||
}
|
||||
|
||||
func loadUserSettings(r *http.Request) UserSettings {
|
||||
var settings UserSettings
|
||||
|
||||
// Load theme
|
||||
if cookie, err := r.Cookie("theme"); err == nil {
|
||||
settings.Theme = cookie.Value
|
||||
} else {
|
||||
settings.Theme = "dark" // Default theme
|
||||
}
|
||||
|
||||
// Load language
|
||||
if cookie, err := r.Cookie("language"); err == nil {
|
||||
settings.Language = cookie.Value
|
||||
} else {
|
||||
settings.Language = "en" // Default language
|
||||
}
|
||||
|
||||
// Load safe search
|
||||
if cookie, err := r.Cookie("safe"); err == nil {
|
||||
settings.SafeSearch = cookie.Value
|
||||
} else {
|
||||
settings.SafeSearch = "" // Default safe search off
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
func saveUserSettings(w http.ResponseWriter, settings UserSettings) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "theme",
|
||||
Value: settings.Theme,
|
||||
Path: "/",
|
||||
Secure: true, // Ensure cookie is sent over HTTPS only
|
||||
SameSite: http.SameSiteNoneMode, // Set SameSite to None
|
||||
})
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "language",
|
||||
Value: settings.Language,
|
||||
Path: "/",
|
||||
Secure: true, // Ensure cookie is sent over HTTPS only
|
||||
SameSite: http.SameSiteNoneMode, // Set SameSite to None
|
||||
})
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "safe",
|
||||
Value: settings.SafeSearch,
|
||||
Path: "/",
|
||||
Secure: true, // Ensure cookie is sent over HTTPS only
|
||||
SameSite: http.SameSiteNoneMode, // Set SameSite to None
|
||||
})
|
||||
|
||||
printDebug("settings saved: %v", settings)
|
||||
}
|
||||
|
||||
func handleSaveSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "POST" {
|
||||
// Load current settings
|
||||
settings := loadUserSettings(r)
|
||||
|
||||
// Update only the settings that were submitted in the form
|
||||
if theme := r.FormValue("theme"); theme != "" {
|
||||
settings.Theme = theme
|
||||
}
|
||||
if lang := r.FormValue("lang"); lang != "" {
|
||||
settings.Language = lang
|
||||
}
|
||||
if safe := r.FormValue("safe"); safe != "" {
|
||||
settings.SafeSearch = safe
|
||||
}
|
||||
|
||||
// Save the updated settings
|
||||
saveUserSettings(w, settings)
|
||||
|
||||
// Redirect back to the previous page or settings page
|
||||
http.Redirect(w, r, r.FormValue("past"), http.StatusSeeOther)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSettings(w http.ResponseWriter, r *http.Request) {
|
||||
// Load user settings
|
||||
settings = loadUserSettings(r)
|
||||
|
||||
data := struct {
|
||||
LanguageOptions []LanguageOption
|
||||
CurrentLang string
|
||||
Theme string
|
||||
Safe string
|
||||
}{
|
||||
LanguageOptions: languageOptions,
|
||||
CurrentLang: settings.Language,
|
||||
Theme: settings.Theme,
|
||||
Safe: settings.SafeSearch,
|
||||
}
|
||||
|
||||
printDebug("Rendering settings with data: %+v", data)
|
||||
|
||||
tmpl, err := template.ParseFiles("templates/settings.html")
|
||||
if err != nil {
|
||||
printErr("Error parsing template: %s", err)
|
||||
http.Error(w, "Internal Server Error", 500)
|
||||
return
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
printErr("Error executing template: %s", err)
|
||||
http.Error(w, "Internal Server Error", 500)
|
||||
return
|
||||
}
|
||||
}
|
70
video.go
Normal file → Executable file
70
video.go
Normal file → Executable file
|
@ -4,7 +4,6 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
@ -15,10 +14,10 @@ const retryDuration = 12 * time.Hour // Retry duration for unresponding piped in
|
|||
|
||||
var (
|
||||
pipedInstances = []string{
|
||||
"pipedapi.kavin.rocks",
|
||||
"api.piped.yt",
|
||||
"pipedapi.moomoo.me",
|
||||
"pipedapi.darkness.services",
|
||||
"pipedapi.kavin.rocks",
|
||||
"piped-api.hostux.net",
|
||||
"pipedapi.syncpundit.io",
|
||||
"piped-api.cfe.re",
|
||||
|
@ -30,6 +29,7 @@ var (
|
|||
}
|
||||
disabledInstances = make(map[string]bool)
|
||||
mu sync.Mutex
|
||||
videoResultsChan = make(chan []VideoResult) // Channel to receive video results from other nodes
|
||||
)
|
||||
|
||||
// VideoAPIResponse matches the structure of the JSON response from the Piped API
|
||||
|
@ -100,10 +100,10 @@ func checkAndReactivateInstances() {
|
|||
if isDisabled {
|
||||
// Check if the instance is available again
|
||||
if testInstanceAvailability(instance) {
|
||||
log.Printf("Instance %s is now available and reactivated.", instance)
|
||||
printInfo("Instance %s is now available and reactivated.", instance)
|
||||
delete(disabledInstances, instance)
|
||||
} else {
|
||||
log.Printf("Instance %s is still not available.", instance)
|
||||
printInfo("Instance %s is still not available.", instance)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -130,7 +130,7 @@ func makeHTMLRequest(query, safe, lang string, page int) (*VideoAPIResponse, err
|
|||
url := fmt.Sprintf("https://%s/search?q=%s&filter=all&safe=%s&lang=%s&page=%d", instance, url.QueryEscape(query), safe, lang, page)
|
||||
resp, err := http.Get(url)
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
log.Printf("Disabling instance %s due to error or status code: %v", instance, err)
|
||||
printInfo("Disabling instance %s due to error or status code: %v", instance, err)
|
||||
disabledInstances[instance] = true
|
||||
lastError = fmt.Errorf("error making request to %s: %w", instance, err)
|
||||
continue
|
||||
|
@ -148,16 +148,48 @@ func makeHTMLRequest(query, safe, lang string, page int) (*VideoAPIResponse, err
|
|||
}
|
||||
|
||||
// handleVideoSearch adapted from the Python `videoResults`, handles video search requests
|
||||
func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int) {
|
||||
func handleVideoSearch(w http.ResponseWriter, settings UserSettings, query string, page int) {
|
||||
start := time.Now()
|
||||
|
||||
apiResp, err := makeHTMLRequest(query, safe, lang, page)
|
||||
results := fetchVideoResults(query, settings.SafeSearch, settings.Language, page)
|
||||
if len(results) == 0 {
|
||||
printWarn("No results from primary search, trying other nodes")
|
||||
results = tryOtherNodesForVideoSearch(query, settings.SafeSearch, settings.Language, page, []string{hostID})
|
||||
}
|
||||
|
||||
elapsed := time.Since(start)
|
||||
tmpl, err := template.New("videos.html").Funcs(funcs).ParseFiles("templates/videos.html")
|
||||
if err != nil {
|
||||
log.Printf("Error fetching video results: %v", err)
|
||||
printErr("Error parsing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, map[string]interface{}{
|
||||
"Results": results,
|
||||
"Query": query,
|
||||
"Fetched": fmt.Sprintf("%.2f seconds", elapsed.Seconds()),
|
||||
"Page": page,
|
||||
"HasPrevPage": page > 1,
|
||||
"HasNextPage": len(results) > 0,
|
||||
"LanguageOptions": languageOptions,
|
||||
"CurrentLang": settings.Language,
|
||||
"Theme": settings.Theme,
|
||||
"Safe": settings.SafeSearch,
|
||||
})
|
||||
if err != nil {
|
||||
printErr("Error executing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func fetchVideoResults(query, safe, lang string, page int) []VideoResult {
|
||||
apiResp, err := makeHTMLRequest(query, safe, lang, page)
|
||||
if err != nil {
|
||||
printWarn("Error fetching video results: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var results []VideoResult
|
||||
for _, item := range apiResp.Items {
|
||||
if item.Type == "channel" || item.Type == "playlist" {
|
||||
|
@ -178,25 +210,5 @@ func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int
|
|||
Duration: formatDuration(item.Duration),
|
||||
})
|
||||
}
|
||||
|
||||
elapsed := time.Since(start)
|
||||
tmpl, err := template.New("videos.html").Funcs(funcs).ParseFiles("templates/videos.html")
|
||||
if err != nil {
|
||||
log.Printf("Error parsing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, map[string]interface{}{
|
||||
"Results": results,
|
||||
"Query": query,
|
||||
"Fetched": fmt.Sprintf("%.2f seconds", elapsed.Seconds()),
|
||||
"Page": page,
|
||||
"HasPrevPage": page > 1,
|
||||
"HasNextPage": len(results) > 0, // assuming you have a way to determine if there are more pages
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("Error executing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue