Compare commits

...

70 commits
v0.0.1 ... main

Author SHA1 Message Date
aa675170dd Merge pull request 'v0.3.0' (#12) from work into main
Reviewed-on: #12
2024-09-29 18:36:45 +00:00
partisan
18d4f7c6db settings page visual improvements 2024-09-29 08:33:49 +02:00
partisan
83a7726422 aligned logo on results page and made various visual fixes 2024-09-28 20:11:17 +02:00
partisan
3c37bbec87 removed text "Type to search..." from search bar 2024-09-27 17:27:16 +02:00
partisan
9f71666df3 fixed bug for irrelevant results (caused by showing only results in the user's language) 2024-09-27 13:16:36 +02:00
partisan
d780e8210b I hate .css 2024-09-27 12:13:16 +02:00
partisan
bfaf4c1153 mobile button fix 2024-09-26 22:00:27 +02:00
partisan
eabc067429 experimenting with main page redesign 2024-09-26 21:18:52 +02:00
partisan
c094d9e6a1 fixed issue where search suggestions happened twice, causing weird behavior 2024-09-26 19:54:41 +02:00
partisan
afe420a0ed trim search suggestions if there is too many 2024-09-25 18:26:27 +02:00
partisan
2679b04284 added Yahoo to search suggestions 2024-09-25 18:21:06 +02:00
partisan
a5622b9099 improved search-suggestions response time 2024-09-25 14:07:12 +02:00
partisan
6ed06b05b1 i need better way to cache images 2024-09-12 22:11:39 +02:00
partisan
6ce4b888ba fix: remove random location when lang is set 2024-09-11 12:49:06 +02:00
b159980a26 Merge pull request 'v0.2.0' (#11) from work into main
Reviewed-on: #11
2024-09-09 15:32:05 +00:00
partisan
d414cf5ce4 added lang "auto-detect" instead of random lang 2024-09-09 14:14:41 +02:00
partisan
4d6b99c67e added dynamic loading for "forums" 2024-08-31 19:04:41 +02:00
partisan
18fca7dce2 improved dynamic scrolling + fixed bug for dynamic scrolling not working when not enough results 2024-08-30 17:22:07 +02:00
partisan
a02ccaa2f0 fixed quant images, and changed lang code from "lang_en" to "en" 2024-08-29 21:21:36 +02:00
partisan
56ce016db9 images from deviantart 2024-08-29 17:20:47 +02:00
partisan
9aabff0a12 fixed and cleaned autocomplete.js 2024-08-28 23:10:18 +02:00
partisan
da6fae4b4b added support for Dark Reader 2024-08-28 21:31:27 +02:00
partisan
f7df15e47f update style, removed buttons on mobile 2024-08-23 18:12:24 +02:00
partisan
6ef817a2b0 added search suggestions to all pages 2024-08-21 23:23:08 +02:00
partisan
14b4f3aaf5 added search suggestions to opensearch 2024-08-21 22:56:21 +02:00
partisan
980de2b59b added search suggestions 2024-08-21 22:36:45 +02:00
a4285b8939 Merge pull request 'bug fixes' (#10) from work into main
Reviewed-on: #10
2024-08-21 11:08:31 +00:00
partisan
25fb33a725 retrive more images from bing 2024-08-21 12:30:03 +02:00
partisan
32e94d1c2f change cookies from any site to strict 2024-08-21 12:01:19 +02:00
partisan
a7e1ef812e fix user setting expiring immediately 2024-08-21 11:08:37 +02:00
partisan
3b4b9ee83a revert img proxy for video 2024-08-20 18:41:56 +02:00
779aa87636 fix typos 2024-08-20 04:57:31 +00:00
dcf698e99e Merge pull request 'fix getting wrong search results from cache (when using different search settings)' (#9) from work into main
Reviewed-on: #9
2024-08-18 19:08:21 +00:00
partisan
5df9cf1c7a fix getting wrong search results from cache (when using different search settings) 2024-08-18 14:49:42 +02:00
3432880d18 Merge pull request 'work branch into the main' (#8) from work into main
Reviewed-on: #8
2024-08-18 10:08:42 +00:00
34f705f562 Update licence in README 2024-08-15 19:53:53 +00:00
partisan
887b45eb41 fix images 2024-08-15 21:49:07 +02:00
partisan
4bd0a8adc3 revert style.css 2024-08-15 21:42:23 +02:00
60574fbbdd Update README.md 2024-08-15 11:35:35 +00:00
1706b4508a Updated licence to AGPL3 2024-08-15 11:34:36 +00:00
partisan
2f23b32fa7 added working settings page 2024-08-15 13:31:15 +02:00
partisan
7127b3ee88 fix typo 2024-08-13 18:49:26 +02:00
partisan
c00f20860d fix language/safe search gui 2024-08-13 16:38:02 +02:00
partisan
e056832321 cleanup 2024-08-13 16:31:28 +02:00
partisan
04fb0ca629 random geolocation for search, tmp 2024-08-12 17:02:17 +02:00
partisan
5a8da74439 added image fetching using Bing 2024-08-12 12:56:42 +02:00
partisan
e5914a1cd6 better image proxy 2024-08-12 08:29:53 +02:00
partisan
5e84d68b17 updated logging, added theming, added settings button 2024-08-11 21:45:52 +02:00
partisan
f32ddcf13a fix unclickable youtube links 2024-08-10 14:17:15 +02:00
partisan
e1b4f1393c fix logo mobile background overlap 2024-08-10 14:10:38 +02:00
partisan
aa5943cd13 wip new cfg params 2024-08-10 13:27:23 +02:00
partisan
26e404f6bc fix missing "Maps" button 2024-08-09 19:08:02 +02:00
partisan
eea8947ad1 clean up 2024-08-09 15:55:14 +02:00
partisan
bd542b8aa2 added "VisitedNodes" to message, to prevent re-requesting 2024-08-09 12:59:37 +02:00
partisan
1443dec8e2 added node search for video 2024-08-09 10:39:08 +02:00
partisan
4724e84059 added fetch file results from other nodes 2024-08-09 09:55:41 +02:00
partisan
37e9fab9a4 node search for text added 2024-08-08 23:37:58 +02:00
partisan
84bf55ab24 send search request wip 2024-08-08 23:09:07 +02:00
partisan
b9f02e9d1e wip search requests to other nodes 2024-08-08 21:59:10 +02:00
partisan
f31886d715 clean up 2024-08-08 16:49:30 +02:00
partisan
283096d299 stupid proofing missing "http" in config file 2024-08-08 16:23:36 +02:00
17589d51e5 Update README.md 2024-08-08 13:49:06 +00:00
partisan
db96868edd update open-search 2024-08-08 15:05:05 +02:00
partisan
d723b4615b change .json to .ini 2024-08-08 15:03:33 +02:00
partisan
77e1d0681d fix error on run 2024-08-08 13:48:18 +02:00
partisan
ea3092011a remove "libcrypto" since it was not really used 2024-08-08 13:44:13 +02:00
partisan
faa20dc064 code auth added 2024-08-08 13:35:50 +02:00
partisan
f769f70ce7 wip 2024-07-05 03:08:35 +02:00
partisan
9f5ef7a1ef node update sync wip 2024-06-30 23:20:52 +02:00
partisan
f7abef253e test node messages 2024-06-29 21:27:48 +02:00
64 changed files with 6495 additions and 2318 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
config.json
opensearch.xml
config.ini

674
LICENSE
View file

@ -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/>.

View file

@ -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 [1] | Araa-Search | LibreY | 4get | *Warp* |
| :----------------------------------- | ------------------ | ------------------------- | ------------------------ | ------------------------ | ---------------------------------------------------- |
| Works without JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ |
| Music search | ❓ | ❌ | ❌ | ✅ | ✅ |
| Torrent search | ❌ | ✅ | ✅ | ❌ | ✅ |
| API | ❌ | ✅ | ❓ [2] | ✅ | ✅ |
| 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
View 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
}

View file

@ -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
}

36
common.go Normal file → Executable file
View file

@ -1,12 +1,14 @@
package main
import (
"crypto/rand"
"encoding/base64"
"html/template"
"strings"
)
var (
debugMode bool = true
funcs = template.FuncMap{
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
View 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)
}
}

117
files.go Normal file → Executable file
View 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,55 +38,63 @@ 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 == "active", Lang: settings.SearchLanguage, Type: "file"}
combinedResults := getFileResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.SearchLanguage, 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
}
data := struct {
Results []TorrentResult
Query string
Fetched string
Category string
Sort string
HasPrevPage bool
HasNextPage bool
Page int
Settings Settings
Results []TorrentResult
Query string
Fetched string
Category string
Sort string
Page int
HasPrevPage bool
HasNextPage bool
LanguageOptions []LanguageOption
CurrentLang string
Theme string
Safe string
IsThemeDark bool
}{
Results: combinedResults,
Query: query,
Fetched: fmt.Sprintf("%.2f", elapsedTime.Seconds()),
Category: "all",
Sort: "seed",
HasPrevPage: page > 1,
HasNextPage: len(combinedResults) > 0,
Page: page,
Settings: Settings{UxLang: lang, Safe: safe},
Results: combinedResults,
Query: query,
Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()),
Category: "all",
Sort: "seed",
Page: page,
HasPrevPage: page > 1,
HasNextPage: len(combinedResults) > 0,
LanguageOptions: languageOptions,
CurrentLang: settings.SearchLanguage,
Theme: settings.Theme,
Safe: settings.SafeSearch,
IsThemeDark: settings.IsThemeDark,
}
// 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 +106,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 +117,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 +154,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 +167,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 +185,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 +203,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 +252,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
}

25
forums.go Normal file → Executable file
View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"html/template"
"log"
"math"
"net/http"
"net/url"
@ -97,29 +98,35 @@ 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.SearchLanguage, 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
IsThemeDark bool
}{
Query: query,
Results: results,
LanguageOptions: languageOptions,
CurrentLang: lang,
Page: page,
HasPrevPage: page > 1,
HasNextPage: len(results) == 25,
LanguageOptions: languageOptions,
CurrentLang: settings.SearchLanguage,
Theme: settings.Theme,
Safe: settings.SafeSearch,
IsThemeDark: settings.IsThemeDark,
}
funcMap := template.FuncMap{

12
go.mod
View file

@ -9,15 +9,23 @@ 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/chai2010/webp v1.1.1 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
golang.org/x/image v0.20.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)

12
go.sum
View file

@ -2,12 +2,18 @@ github.com/PuerkitoBio/goquery v1.9.1 h1:mTL6XjbJTZdpfL+Gwl5U2h1l9yEkJjhmlTeV9VP
github.com/PuerkitoBio/goquery v1.9.1/go.mod h1:cW1n6TmIMDoORQU5IU/P1T3tGFunOeXEpGP2WHRwkbY=
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
github.com/chai2010/webp v1.1.1 h1:jTRmEccAJ4MGrhFOrPMpNGIJ/eybIgwKpcACsrTEapk=
github.com/chai2010/webp v1.1.1/go.mod h1:0XVwvZWdjjdxpUEIf7b9g9VkHFnInUSYujwqTLEuldU=
github.com/chromedp/cdproto v0.0.0-20240202021202-6d0b6a386732 h1:XYUCaZrW8ckGWlCRJKCSoh/iFwlpX316a8yY9IFEzv8=
github.com/chromedp/cdproto v0.0.0-20240202021202-6d0b6a386732/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
github.com/chromedp/chromedp v0.9.5 h1:viASzruPJOiThk7c5bueOUY91jGLJVximoEMGoH93rg=
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/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
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=
@ -29,6 +35,10 @@ github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.20.0 h1:7cVCUjQwfL18gyBJOmYvptfSHS8Fb3YUDtfLIZ7Nbpw=
golang.org/x/image v0.20.0/go.mod h1:0a88To4CYVBAHp5FXJm8o7QbUl37Vd85ply1vyD8auM=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@ -69,3 +79,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=

View file

@ -2,7 +2,6 @@ package main
import (
"io"
"log"
"net/http"
)
@ -17,7 +16,7 @@ func handleImageProxy(w http.ResponseWriter, r *http.Request) {
// Fetch the image from the external URL
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
}
@ -40,7 +39,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)
}
}

120
images-bing.go Normal file
View file

@ -0,0 +1,120 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
// PerformBingImageSearch performs a Bing image search and returns the results.
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(".iusc").Each(func(i int, s *goquery.Selection) {
// Extract image source
imgTag := s.Find("img")
imgSrc, exists := imgTag.Attr("src")
if !exists {
imgSrc, exists = imgTag.Attr("data-src")
if !exists {
return
}
}
// Extract the image title from `alt` attribute
title := imgTag.AttrOr("alt", "")
// Extract width and height if available
width, _ := strconv.Atoi(imgTag.AttrOr("width", "0"))
height, _ := strconv.Atoi(imgTag.AttrOr("height", "0"))
// Extract the m parameter (JSON-encoded image metadata)
metadata, exists := s.Attr("m")
if !exists {
return
}
// Parse the metadata to get the media URL (the original image source)
var data map[string]interface{}
if err := json.Unmarshal([]byte(metadata), &data); err == nil {
mediaURL, ok := data["murl"].(string)
if ok {
// Apply the image proxy
proxiedURL := "/imgproxy?url=" + mediaURL
results = append(results, ImageSearchResult{
Thumbnail: imgSrc,
Title: strings.TrimSpace(title),
Media: mediaURL,
Source: mediaURL,
ThumbProxy: proxiedURL, // Use the proxied URL
Width: width,
Height: height,
})
}
}
})
duration := time.Since(startTime)
// Check if the number of results is one or less
if len(results) == 0 {
return nil, duration, fmt.Errorf("no images found")
}
return results, duration, nil
}
// buildBingSearchURL constructs the search URL for Bing Image Search
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()
}
// Example usage in main (commented out for clarity)
// 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)
// }
// }

237
images-deviantart.go Normal file
View file

@ -0,0 +1,237 @@
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
)
// NextPageCache is a specialized cache for storing next page links
type NextPageCache struct {
mu sync.Mutex
links map[string]string
expiration time.Duration
}
// NewNextPageCache creates a new NextPageCache with a specified expiration duration
func NewNextPageCache(expiration time.Duration) *NextPageCache {
return &NextPageCache{
links: make(map[string]string),
expiration: expiration,
}
}
// Get retrieves the next page link for a given key from the cache
func (npc *NextPageCache) Get(key CacheKey) (string, bool) {
npc.mu.Lock()
defer npc.mu.Unlock()
link, exists := npc.links[npc.keyToString(key)]
if !exists {
return "", false
}
return link, true
}
// Set stores the next page link for a given key in the cache
// Idk it maybye worth it to use "cache.go" for this
func (npc *NextPageCache) Set(key CacheKey, link string) {
npc.mu.Lock()
defer npc.mu.Unlock()
npc.links[npc.keyToString(key)] = link
}
// keyToString converts a CacheKey to a string representation
func (npc *NextPageCache) keyToString(key CacheKey) string {
return fmt.Sprintf("%s|%d|%t|%s|%s", key.Query, key.Page, key.Safe, key.Lang, key.Type)
}
var (
nextPageCache = NewNextPageCache(6 * time.Hour) // Cache with 6-hour expiration
)
// PerformDeviantArtImageSearch performs a search on DeviantArt and returns a list of image results
func PerformDeviantArtImageSearch(query, safe, lang string, page int) ([]ImageSearchResult, time.Duration, error) {
startTime := time.Now()
cacheKey := CacheKey{
Query: query,
Page: page,
Safe: safe == "active",
Lang: lang,
Type: "deviantart",
}
// Check if the next page link is cached
var searchURL string
if page > 1 {
if nextPageLink, found := nextPageCache.Get(cacheKey); found {
searchURL = nextPageLink
} else {
return nil, 0, fmt.Errorf("next page link not found in cache")
}
} else {
searchURL = buildDeviantArtSearchURL(query, page)
}
// Get the User-Agent string
DeviantArtImageUserAgent, err := GetUserAgent("Image-Search-DeviantArt")
if err != nil {
return nil, 0, err
}
// Make the HTTP request with User-Agent header
client := &http.Client{}
req, err := http.NewRequest("GET", searchURL, nil)
if err != nil {
return nil, 0, fmt.Errorf("creating request: %v", err)
}
req.Header.Set("User-Agent", DeviantArtImageUserAgent)
resp, err := client.Do(req)
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)
}
// Channel to receive valid image results
resultsChan := make(chan ImageSearchResult)
var wg sync.WaitGroup
// Extract data using goquery
doc.Find("div._2pZkk div div a").Each(func(i int, s *goquery.Selection) {
// Skip images that are blurred (premium content)
premiumText := s.Find("../div/div/div").Text()
if strings.Contains(premiumText, "Watch the artist to view this deviation") {
return
}
// Extract image source, fallback on data-src if necessary
imgSrc, exists := s.Find("div img").Attr("srcset")
if !exists {
imgSrc, exists = s.Find("div img").Attr("data-src")
}
if !exists || imgSrc == "" {
return
}
imgSrc = strings.Split(imgSrc, " ")[0]
parsedURL, err := url.Parse(imgSrc)
if err == nil {
parts := strings.Split(parsedURL.Path, "/v1")
parsedURL.Path = parts[0]
imgSrc = parsedURL.String()
}
// Extract URL and title
resultURL := s.AttrOr("href", "")
title := s.AttrOr("aria-label", "")
// Only proceed if title, URL, and img_src are not empty
if title != "" && resultURL != "" && imgSrc != "" {
wg.Add(1)
go func(imgSrc, resultURL, title string) {
defer wg.Done()
// Verify if the image URL is accessible
if isValidImageURL(imgSrc, DeviantArtImageUserAgent, resultURL) {
resultsChan <- ImageSearchResult{
Title: strings.TrimSpace(title),
Media: imgSrc,
Width: 0,
Height: 0,
Source: resultURL,
ThumbProxy: "/imgproxy?url=" + imgSrc,
}
}
}(imgSrc, resultURL, title)
}
})
// Close the results channel when all goroutines are done
go func() {
wg.Wait()
close(resultsChan)
}()
// Collect results from the channel
var results []ImageSearchResult
for result := range resultsChan {
results = append(results, result)
}
// Cache the next page link, if any
nextPageLink := doc.Find("a._1OGeq").Last().AttrOr("href", "")
if nextPageLink != "" {
nextPageCache.Set(cacheKey, nextPageLink)
}
duration := time.Since(startTime)
// Check if the number of results is one or less
if len(results) == 0 {
return nil, duration, fmt.Errorf("no images found")
}
return results, duration, nil
}
// buildDeviantArtSearchURL builds the search URL for DeviantArt
func buildDeviantArtSearchURL(query string, page int) string {
baseURL := "https://www.deviantart.com/search"
params := url.Values{}
params.Add("q", query)
return baseURL + "?" + params.Encode()
}
// isValidImageURL checks if the image URL is accessible with the provided User-Agent
func isValidImageURL(imgSrc, userAgent, referer string) bool {
client := &http.Client{}
req, err := http.NewRequest("HEAD", imgSrc, nil)
if err != nil {
return false
}
// Set headers to mimic a regular browser request
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Referer", referer)
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// // Example usage:
// func main() {
// results, duration, err := PerformDeviantArtImageSearch("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\nMedia: %s\nSource (Original Image URL): %s\n\n",
// result.Title, result.Thumbnail, result.Media, result.Source)
// }
// }

View file

@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"net/url"
"sync"
"time"
)
@ -24,6 +25,64 @@ type QwantAPIResponse struct {
} `json:"data"`
}
func ConvertToQwantLocale(langCode string) string {
langMap := map[string]string{
"en": "en_us", // English
"af": "en_us", // Afrikaans (no direct match, default to English)
"ar": "ar", // Arabic
"hy": "en_us", // Armenian (no direct match, default to English)
"be": "en_us", // Belarusian (no direct match, default to English)
"bg": "bg_bg", // Bulgarian
"ca": "ca_es", // Catalan
"zh-CN": "zh_cn", // Chinese Simplified
"zh-TW": "zh_hk", // Chinese Traditional
"hr": "en_us", // Croatian (no direct match, default to English)
"cs": "cs_cz", // Czech
"da": "da_dk", // Danish
"nl": "nl_nl", // Dutch
"eo": "en_us", // Esperanto (no direct match, default to English)
"et": "et_ee", // Estonian
"tl": "en_us", // Tagalog (no direct match, default to English)
"fi": "fi_fi", // Finnish
"fr": "fr_fr", // French
"de": "de_de", // German
"el": "el_gr", // Greek
"iw": "he_il", // Hebrew
"hi": "en_us", // Hindi (no direct match, default to English)
"hu": "hu_hu", // Hungarian
"is": "en_us", // Icelandic (no direct match, default to English)
"id": "en_us", // Indonesian (no direct match, default to English)
"it": "it_it", // Italian
"ja": "ja_jp", // Japanese
"ko": "ko_kr", // Korean
"lv": "en_us", // Latvian (no direct match, default to English)
"lt": "en_us", // Lithuanian (no direct match, default to English)
"no": "nb_no", // Norwegian
"fa": "en_us", // Persian (no direct match, default to English)
"pl": "pl_pl", // Polish
"pt": "pt_pt", // Portuguese
"ro": "ro_ro", // Romanian
"ru": "ru_ru", // Russian
"sr": "en_us", // Serbian (no direct match, default to English)
"sk": "en_us", // Slovak (no direct match, default to English)
"sl": "en_us", // Slovenian (no direct match, default to English)
"es": "es_es", // Spanish
"sw": "en_us", // Swahili (no direct match, default to English)
"sv": "sv_se", // Swedish
"th": "th_th", // Thai
"tr": "tr_tr", // Turkish
"uk": "en_us", // Ukrainian (no direct match, default to English)
"vi": "en_us", // Vietnamese (no direct match, default to English)
"": "en_us", // Default to English if no language is provided
}
if qwantLocale, exists := langMap[langCode]; exists {
return qwantLocale
}
printWarn("Qwant locale code missing: %v, defaulting to: en_us", langCode)
return "en_us" // Default fallback
}
// PerformQwantImageSearch performs an image search on Qwant and returns the results.
func PerformQwantImageSearch(query, safe, lang string, page int) ([]ImageSearchResult, time.Duration, error) {
startTime := time.Now() // Start the timer
@ -36,13 +95,16 @@ func PerformQwantImageSearch(query, safe, lang string, page int) ([]ImageSearchR
offset = (page - 1) * resultsPerPage
}
// Ensure count + offset is within acceptable limits
if offset+resultsPerPage > 250 {
return nil, 0, fmt.Errorf("count + offset must be lower than 250 for quant")
}
if safe == "" {
safe = "0"
}
if lang == "" {
lang = "en_CA"
}
lang = ConvertToQwantLocale(lang)
apiURL := fmt.Sprintf("https://api.qwant.com/v3/search/images?t=images&q=%s&count=%d&locale=%s&offset=%d&device=desktop&tgp=2&safesearch=%s",
url.QueryEscape(query),
@ -58,7 +120,7 @@ func PerformQwantImageSearch(query, safe, lang string, page int) ([]ImageSearchR
return nil, 0, fmt.Errorf("creating request: %v", err)
}
ImageUserAgent, err := GetUserAgent("Image-Search")
ImageUserAgent, err := GetUserAgent("Image-Search-Quant")
if err != nil {
return nil, 0, err
}
@ -80,19 +142,37 @@ func PerformQwantImageSearch(query, safe, lang string, page int) ([]ImageSearchR
return nil, 0, fmt.Errorf("decoding response: %v", err)
}
var results []ImageSearchResult
for _, item := range apiResp.Data.Result.Items {
results = append(results, ImageSearchResult{
Thumbnail: item.Thumbnail,
Title: item.Title,
Media: item.Media,
Source: item.Url,
ThumbProxy: "/img_proxy?url=" + url.QueryEscape(item.Media),
Width: item.Width,
Height: item.Height,
})
var wg sync.WaitGroup
results := make([]ImageSearchResult, len(apiResp.Data.Result.Items))
for i, item := range apiResp.Data.Result.Items {
wg.Add(1)
go func(i int, item struct {
Media string `json:"media"`
Thumbnail string `json:"thumbnail"`
Title string `json:"title"`
Url string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
}) {
defer wg.Done()
// Populate the result
results[i] = ImageSearchResult{
Thumbnail: item.Thumbnail,
Title: item.Title,
Media: item.Media,
Source: item.Url,
ThumbProxy: "/imgproxy?url=" + item.Media,
Width: item.Width,
Height: item.Height,
}
}(i, item)
}
// Wait for all goroutines to complete
wg.Wait()
duration := time.Since(startTime) // Calculate the duration
return results, duration, nil

41
images.go Normal file → Executable file
View file

@ -13,15 +13,17 @@ 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},
{Name: "DeviantArt", Func: wrapImageSearchFunc(PerformDeviantArtImageSearch), Weight: 3},
//{Name: "Imgur", Func: wrapImageSearchFunc(PerformImgurImageSearch), Weight: 4}, // Image proxy not working
}
}
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 == "active", Lang: settings.SearchLanguage, Type: "image"}
combinedResults := getImageResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.SearchLanguage, page)
elapsedTime := time.Since(startTime)
tmpl, err := template.New("images.html").Funcs(funcs).ParseFiles("templates/images.html")
@ -36,24 +38,32 @@ 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
IsThemeDark bool
}{
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.SearchLanguage,
Theme: settings.Theme,
Safe: settings.SafeSearch,
IsThemeDark: settings.IsThemeDark,
}
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 +75,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 +95,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 +109,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 +130,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
View file

@ -1,116 +1,66 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"time"
)
// Configuration structure
type Config struct {
Port int
OpenSearch OpenSearchConfig
Port int
AuthCode string
PeerID string
Peers []string
Domain string
NodesEnabled bool
CrawlerEnabled bool
WebsiteEnabled bool
LogLevel int
}
type OpenSearchConfig struct {
Domain string
}
// Default configuration values
var defaultConfig = Config{
Port: 5000,
OpenSearch: OpenSearchConfig{
Domain: "localhost",
},
Port: 5000,
Domain: "localhost",
Peers: []string{},
AuthCode: generateStrongRandomString(64),
NodesEnabled: true,
CrawlerEnabled: true,
WebsiteEnabled: true,
LogLevel: 1,
}
const configFilePath = "config.json"
const configFilePath = "config.ini"
var config Config
func main() {
// Run the initialization process
err := initConfig()
if err != nil {
fmt.Println("Error during initialization:", err)
printErr("Error during initialization:")
return
}
// Start the main application
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()
}
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()
var config Config
if err := json.NewDecoder(configFile).Decode(&config); err != nil {
log.Fatalf("Error decoding config file: %v", err)
}
return config
}

178
main.go Normal file → Executable file
View file

@ -2,6 +2,7 @@ package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strconv"
@ -13,79 +14,136 @@ type LanguageOption struct {
Name string
}
var settings UserSettings
var languageOptions = []LanguageOption{
{Code: "", Name: "Any Language"},
{Code: "lang_en", Name: "English"},
{Code: "lang_af", Name: "Afrikaans"},
{Code: "lang_ar", Name: "العربية (Arabic)"},
{Code: "lang_hy", Name: "Հայերեն (Armenian)"},
{Code: "lang_be", Name: "Беларуская (Belarusian)"},
{Code: "lang_bg", Name: "български (Bulgarian)"},
{Code: "lang_ca", Name: "Català (Catalan)"},
{Code: "lang_zh-CN", Name: "中文 (简体) (Chinese Simplified)"},
{Code: "lang_zh-TW", Name: "中文 (繁體) (Chinese Traditional)"},
{Code: "lang_hr", Name: "Hrvatski (Croatian)"},
{Code: "lang_cs", Name: "Čeština (Czech)"},
{Code: "lang_da", Name: "Dansk (Danish)"},
{Code: "lang_nl", Name: "Nederlands (Dutch)"},
{Code: "lang_eo", Name: "Esperanto"},
{Code: "lang_et", Name: "Eesti (Estonian)"},
{Code: "lang_tl", Name: "Filipino (Tagalog)"},
{Code: "lang_fi", Name: "Suomi (Finnish)"},
{Code: "lang_fr", Name: "Français (French)"},
{Code: "lang_de", Name: "Deutsch (German)"},
{Code: "lang_el", Name: "Ελληνικά (Greek)"},
{Code: "lang_iw", Name: "עברית (Hebrew)"},
{Code: "lang_hi", Name: "हिन्दी (Hindi)"},
{Code: "lang_hu", Name: "magyar (Hungarian)"},
{Code: "lang_is", Name: "íslenska (Icelandic)"},
{Code: "lang_id", Name: "Bahasa Indonesia (Indonesian)"},
{Code: "lang_it", Name: "italiano (Italian)"},
{Code: "lang_ja", Name: "日本語 (Japanese)"},
{Code: "lang_ko", Name: "한국어 (Korean)"},
{Code: "lang_lv", Name: "latviešu (Latvian)"},
{Code: "lang_lt", Name: "lietuvių (Lithuanian)"},
{Code: "lang_no", Name: "norsk (Norwegian)"},
{Code: "lang_fa", Name: "فارسی (Persian)"},
{Code: "lang_pl", Name: "polski (Polish)"},
{Code: "lang_pt", Name: "português (Portuguese)"},
{Code: "lang_ro", Name: "română (Romanian)"},
{Code: "lang_ru", Name: "русский (Russian)"},
{Code: "lang_sr", Name: "српски (Serbian)"},
{Code: "lang_sk", Name: "slovenčina (Slovak)"},
{Code: "lang_sl", Name: "slovenščina (Slovenian)"},
{Code: "lang_es", Name: "español (Spanish)"},
{Code: "lang_sw", Name: "Kiswahili (Swahili)"},
{Code: "lang_sv", Name: "svenska (Swedish)"},
{Code: "lang_th", Name: "ไทย (Thai)"},
{Code: "lang_tr", Name: "Türkçe (Turkish)"},
{Code: "lang_uk", Name: "українська (Ukrainian)"},
{Code: "lang_vi", Name: "Tiếng Việt (Vietnamese)"},
{Code: "en", Name: "English"},
{Code: "af", Name: "Afrikaans"},
{Code: "ar", Name: "العربية (Arabic)"},
{Code: "hy", Name: "Հայերեն (Armenian)"},
{Code: "be", Name: "Беларуская (Belarusian)"},
{Code: "bg", Name: "български (Bulgarian)"},
{Code: "ca", Name: "Català (Catalan)"},
{Code: "zh-CN", Name: "中文 (简体) (Chinese Simplified)"},
{Code: "zh-TW", Name: "中文 (繁體) (Chinese Traditional)"},
{Code: "hr", Name: "Hrvatski (Croatian)"},
{Code: "cs", Name: "Čeština (Czech)"},
{Code: "da", Name: "Dansk (Danish)"},
{Code: "nl", Name: "Nederlands (Dutch)"},
{Code: "eo", Name: "Esperanto"},
{Code: "et", Name: "Eesti (Estonian)"},
{Code: "tl", Name: "Filipino (Tagalog)"},
{Code: "fi", Name: "Suomi (Finnish)"},
{Code: "fr", Name: "Français (French)"},
{Code: "de", Name: "Deutsch (German)"},
{Code: "el", Name: "Ελληνικά (Greek)"},
{Code: "iw", Name: "עברית (Hebrew)"},
{Code: "hi", Name: "हिन्दी (Hindi)"},
{Code: "hu", Name: "magyar (Hungarian)"},
{Code: "is", Name: "íslenska (Icelandic)"},
{Code: "id", Name: "Bahasa Indonesia (Indonesian)"},
{Code: "it", Name: "italiano (Italian)"},
{Code: "ja", Name: "日本語 (Japanese)"},
{Code: "ko", Name: "한국어 (Korean)"},
{Code: "lv", Name: "latviešu (Latvian)"},
{Code: "lt", Name: "lietuvių (Lithuanian)"},
{Code: "no", Name: "norsk (Norwegian)"},
{Code: "fa", Name: "فارسی (Persian)"},
{Code: "pl", Name: "polski (Polish)"},
{Code: "pt", Name: "português (Portuguese)"},
{Code: "ro", Name: "română (Romanian)"},
{Code: "ru", Name: "русский (Russian)"},
{Code: "sr", Name: "српски (Serbian)"},
{Code: "sk", Name: "slovenčina (Slovak)"},
{Code: "sl", Name: "slovenščina (Slovenian)"},
{Code: "es", Name: "español (Spanish)"},
{Code: "sw", Name: "Kiswahili (Swahili)"},
{Code: "sv", Name: "svenska (Swedish)"},
{Code: "th", Name: "ไทย (Thai)"},
{Code: "tr", Name: "Türkçe (Turkish)"},
{Code: "uk", Name: "українська (Ukrainian)"},
{Code: "vi", Name: "Tiếng Việt (Vietnamese)"},
}
func handleSearch(w http.ResponseWriter, r *http.Request) {
query, safe, lang, searchType, page := parseSearchParams(r)
settings = loadUserSettings(w, r)
theme := r.URL.Query().Get("theme")
if theme != "" {
settings.Theme = theme
saveUserSettings(w, settings)
} else if settings.Theme == "" {
settings.Theme = "dark"
}
if safe != "" && safe != settings.SafeSearch {
settings.SafeSearch = safe
saveUserSettings(w, settings)
}
// Update site language if provided, or use existing settings
if lang != "" && lang != settings.SiteLanguage {
settings.SiteLanguage = lang
saveUserSettings(w, settings)
} else if settings.SiteLanguage == "" {
settings.SiteLanguage = normalizeLangCode(r.Header.Get("Accept-Language"))
saveUserSettings(w, settings)
}
// Update search language (can be empty)
searchLang := r.URL.Query().Get("search_lang")
if searchLang != settings.SearchLanguage {
settings.SearchLanguage = searchLang
saveUserSettings(w, settings)
}
switch settings.Theme {
case "dark", "black", "night", "latte":
settings.IsThemeDark = true
default:
settings.IsThemeDark = false
}
if query == "" {
http.ServeFile(w, r, "templates/search.html")
data := struct {
LanguageOptions []LanguageOption
CurrentLang string
CurrentSearchLang string
Theme string
Safe string
IsThemeDark bool
}{
LanguageOptions: languageOptions,
CurrentLang: settings.SiteLanguage,
CurrentSearchLang: settings.SearchLanguage,
Theme: settings.Theme,
Safe: settings.SafeSearch,
IsThemeDark: settings.IsThemeDark,
}
tmpl := template.Must(template.ParseFiles("templates/search.html"))
tmpl.Execute(w, data)
return
}
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)
}
}
@ -125,10 +183,11 @@ func runServer() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
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("/suggestions", handleSuggestions)
http.HandleFunc("/imgproxy", handleImageProxy)
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 +197,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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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)
}
}

View file

@ -12,7 +12,7 @@ type OpenSearchDescription struct {
ShortName string `xml:"ShortName"`
Description string `xml:"Description"`
Tags string `xml:"Tags"`
URL URL `xml:"Url"`
URLs []URL `xml:"Url"`
}
type URL struct {
@ -21,20 +21,28 @@ type URL struct {
}
func generateOpenSearchXML(config Config) {
baseURL := addProtocol(config.Domain)
opensearch := OpenSearchDescription{
Xmlns: "http://a9.com/-/spec/opensearch/1.1/",
ShortName: "Ocásek",
Description: "Search engine",
Tags: "search, engine",
URL: URL{
Type: "text/html",
Template: fmt.Sprintf("https://%s/search?q={searchTerms}", config.OpenSearch.Domain),
ShortName: "Warp",
Description: "Warp search engine",
Tags: "search, engine, warp",
URLs: []URL{
{
Type: "text/html",
Template: fmt.Sprintf("%s/search?q={searchTerms}", baseURL),
},
{
Type: "application/x-suggestions+json",
Template: fmt.Sprintf("%s/suggestions?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 +50,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
View 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
View 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
View file

@ -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

View file

@ -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
View 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
View 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
View 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
View 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
View 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
View 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);
}

View file

@ -0,0 +1,61 @@
.search-page-content {
display: flex;
flex-direction: column;
align-items: center;
}
.search-page-content h1 {
text-align: center;
margin-bottom: 20px;
}
#search-input {
width: 100%;
padding: 12px;
font-size: 16px;
}
.search-type-icons {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 30px;
margin-top: 30px;
}
.icon-button {
display: flex;
flex-direction: column;
align-items: center;
background: none;
border: none;
cursor: pointer;
text-align: center;
}
.icon-button .material-icons-round {
font-size: 48px;
color: var(--sub-search-wrapper-ico);
}
.icon-button p {
margin-top: 8px;
font-size: 14px;
color: var(--sub-search-wrapper-ico);
}
.icon-button:hover .material-icons-round {
transition: all .3s ease;
color: var(--blue);
}
.icon-button:hover p {
transition: all .3s ease;
color: var(--blue);
}
.icon-button button:focus {
outline: none;
}

View file

@ -0,0 +1,100 @@
/* 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;
}
#searchLanguageSelect,
#safeSearchSelect,
#siteLanguageSelect {
border-radius: 4px;
padding: 6px;
font-size: 15px;
border: 1px solid var(--border);
color: var(--font-fg);
width: 160px;
background: var(--button);
float: right;
cursor: pointer;
transition: all 0.3s ease;
text-align: center;
box-sizing: border-box; /* Ensures consistent width with padding */
}
#searchLanguageSelect:hover,
#safeSearchSelect:hover,
#siteLanguageSelect:hover {
border: 1px solid #5f6368;
/* background-color: var(--button-hover); */
}
.save.save-settings-page {
padding: 6px;
width: 160px;
height: 40px;
}
/* Ensure correct aligment */
.settings-row {
display: flex;
align-items: center;
justify-content: space-between;
}
.settings-row select,
.settings-row button {
width: 160px;
height: 40px;
box-sizing: border-box;
}
/* --- */

View file

@ -67,13 +67,10 @@
/* Support for all WebKit browsers. */
-webkit-font-feature-settings: 'liga';
-webkit-font-smoothing: antialiased;
/* Support for Safari and Chrome. */
text-rendering: optimizeLegibility;
/* Support for Firefox. */
-moz-osx-font-smoothing: grayscale;
/* Support for IE. */
font-feature-settings: 'liga';
}
@ -120,6 +117,7 @@
}
.clean {
margin-top: 30px;
max-width: 775px;
}
@ -483,6 +481,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;
}
@ -538,15 +546,16 @@ hr {
margin: 0 auto;
background: var(--search-bg-input);
border-radius: 22px;
position: absolute;
width: 520px;
position: relative;
width: 100%;
max-width: 600px;
overflow: hidden;
margin-left: auto;
margin-right: auto;
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 {
@ -643,7 +652,7 @@ hr {
.settings-nav {
max-width: 100%;
height: 40px;
height: 50px;
background-color: var(--search-bg);
border-bottom: 1px solid var(--border);
padding: 10px;
@ -663,6 +672,7 @@ hr {
.settings-row {
display: flex;
align-items: center;
justify-content: flex-end;
padding: 2px;
padding-left: 10px;
padding-right: 10px;
@ -671,7 +681,9 @@ hr {
.settings-row select,
.settings-row button {
margin-left: auto;
width: 160px;
height: 40px;
margin: 0;
}
.kno_wiki {
@ -679,7 +691,8 @@ hr {
}
.kno_wiki_show {
display: initial !important;
display: initial !important;
border-radius: 6px;
}
.open-in-new-tab * {
@ -761,6 +774,8 @@ form.torrent-sort {
#settingsButton {
transition: all .3s ease;
/* width: 283px+6px;
height: 31px; */
}
.settings-icon-link {
@ -786,6 +801,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 {
@ -811,6 +827,12 @@ form.torrent-sort {
cursor: pointer;
}
.search-menu select:hover {
border: 1px solid #5f6368;
cursor: pointer;
transition: all .3s ease;
}
.settings-content {
display: flex;
flex-direction: column;
@ -841,7 +863,6 @@ form.torrent-sort {
margin: 5px;
}
.view-image-search {
border: 1px solid var(--snip-border);
margin: 0;
@ -855,7 +876,7 @@ form.torrent-sort {
.theme-settings {
margin-top: 10px;
width: 90%;
width: 100%-4px;
border: 1px solid var(--snip-border);
background: var(--snip-background);
color: var(--fg);
@ -869,6 +890,10 @@ form.torrent-sort {
margin-left: 3%;
}
.theme-mini-settings {
width: 90%;
}
.settings-search-div:hover p {
color: #8ab4f8;
}
@ -1146,7 +1171,7 @@ p {
position: absolute;
margin-top: 0px;
top: 20px;
left: 38px;
left: 28px;
}
.sub-search-button-wrapper button {
@ -1154,7 +1179,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 +1233,10 @@ p {
margin-top: -2px;
}
.link {
color: var(--link);
}
.results a:visited h3,
.result_sublink a:visited h3 {
color: var(--link-visited);
@ -1226,6 +1255,7 @@ p {
.results p,
.result_sublink p {
margin-top: 0px;
color: var(--font-fg);
}
.results a,
@ -1235,6 +1265,7 @@ p {
.result_sublink a:hover,
.result_sublink a:visited {
text-decoration: none;
/* color: #ebecf7; */
font-size: 14px;
}
@ -1277,6 +1308,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 +1322,7 @@ p {
margin-left: 10px;
}
.snip a {
display: block;
.snip .wiki_link {
margin-top: 10px;
text-decoration: none;
color: var(--link);
@ -1300,6 +1336,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);
@ -1495,6 +1553,20 @@ body, h1, p, a, input, button {
}
}
/*
.material-icons-round {
font-family: 'Material Icons Round';
font-weight: normal;
font-style: normal;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
} */
@media only screen and (max-width: 1220px) {
.snip {
@ -1680,15 +1752,16 @@ body, h1, p, a, input, button {
margin-top: 0px;
top: 0px;
left: 0px;
/* background-color: var(--search-bg); */
}
.mobile-none {
display: none;
}
.search-menu {
/* .search-menu {
display: none;
}
} */
.sub-search-button-wrapper {
margin: 0;
@ -1792,9 +1865,9 @@ body, h1, p, a, input, button {
top: 5px;
}
.settings-search-div {
/* .settings-search-div {
display: none;
}
} */
.search-container h1 {
font-size: 55px;
@ -1815,9 +1888,19 @@ body, h1, p, a, input, button {
}
.search-button-wrapper button {
display: table-row;
margin: 30px 0px 0px 0px;
width: 80%;
display: none;
}
.icon-button {
margin-top: 30px;
}
.icon-button button {
margin-top: 30px;
}
.icon-button p {
margin-top: 30px;
}
#clearSearch {
@ -1826,7 +1909,13 @@ body, h1, p, a, input, button {
}
/* --- */
/* This is really bad */
@media only screen and (max-width: 400px) {
.icon-button {
padding: 5%
}
}
/* Ensuring dark theme compliance */
@media (prefers-color-scheme: dark) {
@ -1850,7 +1939,7 @@ body, h1, p, a, input, button {
}
}
/* Variables for light theme */
/*
:root {
--background-color: #ffffff;
--text-color: #000000;
@ -1879,7 +1968,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 +1996,4 @@ body, h1, p, a, input, button {
--green: #8ab4f8;
--box-shadow: #ffffff20;
}
}
} */

BIN
static/images/black.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
static/images/light.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
static/images/mocha.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
static/images/night.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

180
static/js/autocomplete.js Normal file
View file

@ -0,0 +1,180 @@
/**
* @source: ./script.js (originally from araa-search on Github)
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2023 Extravi
*
* The JavaScript code in this page 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.
*
* The code is distributed 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.
*
* As additional permission under GNU Affero General Public License
* section 7, you may distribute non-source (e.g., minimized or compacted)
* forms of that code without the copy of the GNU Affero General Public
* License normally required by section 4, provided you include this
* license notice and a URL through which recipients can access the
* Corresponding Source.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*/
// Removes the 'Apply Settings' button for Javascript users,
// since changing any of the elements causes the settings to apply
// automatically.
let resultsSave = document.querySelector(".results-save");
if (resultsSave != null) {
resultsSave.style.display = "none";
}
const searchInput = document.getElementById('search-input');
const searchWrapper = document.querySelectorAll('.wrapper, .wrapper-results')[0];
const resultsWrapper = document.querySelector('.autocomplete');
// const clearSearch = document.querySelector("#clearSearch");
async function getSuggestions(query) {
try {
const params = new URLSearchParams({ "q": query }).toString();
const response = await fetch(`/suggestions?${params}`);
const data = await response.json();
return data[1]; // Return only the array of suggestion strings
} catch (error) {
console.error(error);
}
}
let currentIndex = -1; // Keep track of the currently selected suggestion
// Handle click events on the type buttons
let results = [];
searchInput.addEventListener('input', async () => {
let input = searchInput.value;
if (input.length) {
results = await getSuggestions(input);
}
renderResults(results);
currentIndex = -1; // Reset index when we return new results
});
searchInput.addEventListener("focus", async () => {
let input = searchInput.value;
if (results.length === 0 && input.length != 0) {
results = await getSuggestions(input);
}
renderResults(results);
})
// clearSearch.style.visibility = "visible"; // Only show the clear search button for JS users.
// clearSearch.addEventListener("click", () => {
// searchInput.value = "";
// searchInput.focus();
// })
searchInput.addEventListener('keydown', (event) => {
if (event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'Tab') {
event.preventDefault(); // Prevent the default behavior, such as moving the cursor
// Find the currently selected suggestion element
const selectedSuggestion = resultsWrapper.querySelector('.selected');
if (selectedSuggestion) {
selectedSuggestion.classList.remove('selected'); // Deselect the currently selected suggestion
}
// Increment current index when ArrowUp is pressed otherwise hen Tab OR ArrowDown decrement
if (event.key === 'ArrowUp') {
currentIndex--;
} else {
currentIndex++;
}
// Wrap around the index if it goes out of bounds
if (currentIndex < 0) {
currentIndex = resultsWrapper.querySelectorAll('li').length - 1;
} else if (currentIndex >= resultsWrapper.querySelectorAll('li').length) {
currentIndex = 0;
}
// Select the new suggestion
resultsWrapper.querySelectorAll('li')[currentIndex].classList.add('selected');
// Update the value of the search input
searchInput.value = resultsWrapper.querySelectorAll('li')[currentIndex].textContent;
}
});
// Default to the currently selected type or fallback to 'text'
let selectedType = document.querySelector('.search-active')?.value || 'text';
// Function to render results
function renderResults(results) {
if (!results || !results.length || !searchInput.value) {
searchWrapper.classList.remove('show');
return;
}
let content = '';
results.forEach((item) => {
content += `<li>${item}</li>`;
});
if (searchInput.value) {
searchWrapper.classList.add('show');
}
resultsWrapper.innerHTML = `<ul>${content}</ul>`;
}
// Handle click events on the type buttons
const typeButtons = document.querySelectorAll('[name="t"]');
typeButtons.forEach(button => {
button.addEventListener('click', function() {
selectedType = this.value;
typeButtons.forEach(btn => btn.classList.remove('search-active'));
this.classList.add('search-active');
});
});
// Handle clicks on search results
resultsWrapper.addEventListener('click', (event) => {
if (event.target.tagName === 'LI') {
const query = event.target.textContent;
window.location.href = `/search?q=${encodeURIComponent(query)}&t=${encodeURIComponent(selectedType)}`;
}
});
document.addEventListener("keypress", (event) => {
if (document.activeElement == searchInput) {
// Allow the '/' character to be pressed when searchInput is active
} else if (document.querySelector(".calc") != null) {
// Do nothing if the calculator is available, so the division keybinding
// will still work
}
else if (event.key == "/") {
event.preventDefault();
searchInput.focus();
searchInput.selectionStart = searchInput.selectionEnd = searchInput.value.length;
}
})
// Add event listener to hide autocomplete suggestions when clicking outside of search-input or wrapper
document.addEventListener('click', (event) => {
// Check if the target of the event is the search-input or any of its ancestors
if (!searchInput.contains(event.target) && !searchWrapper.contains(event.target)) {
// Remove the show class from the search wrapper
searchWrapper.classList.remove('show');
}
});
// // Update visual feedback for selected type on page load
// document.addEventListener("DOMContentLoaded", () => {
// const activeButton = document.querySelector(`[name="t"][value="${selectedType}"]`);
// if (activeButton) {
// typeButtons.forEach(btn => btn.classList.remove('search-active'));
// activeButton.classList.add('search-active');
// }
// });

View file

@ -0,0 +1,96 @@
document.addEventListener("DOMContentLoaded", function() {
const templateData = document.getElementById('template-data');
let page = parseInt(templateData.getAttribute('data-page')) || 1;
const query = templateData.getAttribute('data-query') || '';
let searchType = templateData.getAttribute('data-type') || 'text'; // Default to 'text' if not provided
let loading = false;
let hasMoreResults = true;
const loadingIndicator = document.getElementById('message-bottom-left');
let loadingTimeout;
function loadResults(newPage) {
if (loading || !hasMoreResults) return;
loading = true;
// Show loading indicator if taking more than 100ms
loadingTimeout = setTimeout(() => {
loadingIndicator.style.display = 'flex';
}, 100);
fetch(`/search?q=${encodeURIComponent(query)}&t=${encodeURIComponent(searchType)}&p=${newPage}`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
clearTimeout(loadingTimeout);
loadingIndicator.style.display = 'none';
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');
const newResults = doc.getElementById('results').innerHTML;
const noResultsMessage = `No results found for '${query}'. Try different keywords.`;
const endOfResultsMessage = "Looks like this is the end of results.";
const serverError = "Internal Server Error";
if (newResults.includes(noResultsMessage) || newResults.includes(endOfResultsMessage) || newResults.includes(serverError)) {
document.getElementById('results').innerHTML += newResults;
hasMoreResults = false;
} else {
document.getElementById('results').innerHTML += newResults;
page = newPage;
// Automatically load more results if content height is less than window height
checkIfMoreResultsNeeded();
}
loading = false;
})
.catch(error => {
clearTimeout(loadingTimeout);
loadingIndicator.style.display = 'none';
console.error('Error loading results:', error);
hasMoreResults = false;
loading = false;
});
}
function checkIfMoreResultsNeeded() {
if (document.body.scrollHeight <= window.innerHeight && hasMoreResults) {
loadResults(page + 1);
}
}
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
loadResults(page + 1);
}
});
// Ensure the correct search button has the active class at load
const buttons = document.querySelectorAll('.search-container-results-btn button');
if (buttons.length === 0) {
console.error("No search buttons found");
} else {
buttons.forEach(btn => {
btn.addEventListener('click', function() {
const activeElement = document.querySelector('.search-container-results-btn .search-active');
if (activeElement) {
activeElement.classList.remove('search-active');
}
this.classList.add('search-active');
// Update search type when button is clicked
searchType = this.getAttribute('value');
});
});
// Ensure one button is active on page load
const initialActiveElement = document.querySelector('.search-container-results-btn .search-active');
if (!initialActiveElement) {
buttons[0].classList.add('search-active');
searchType = buttons[0].getAttribute('value'); // Set default search type
}
}
// Check if more results are needed right after the initial content is loaded
checkIfMoreResultsNeeded();
});

286
suggestions.go Normal file
View file

@ -0,0 +1,286 @@
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"sync"
"time"
)
// SuggestionSource represents a search suggestion source along with its latency.
type SuggestionSource struct {
Name string
FetchFunc func(string) []string
Latency time.Duration
mu sync.Mutex
}
// Initialize suggestion sources with default latency values.
var suggestionSources = []SuggestionSource{
{
Name: "DuckDuckGo",
FetchFunc: fetchDuckDuckGoSuggestions,
Latency: 50 * time.Millisecond,
},
{
Name: "Edge",
FetchFunc: fetchEdgeSuggestions,
Latency: 50 * time.Millisecond,
},
{
Name: "Brave",
FetchFunc: fetchBraveSuggestions,
Latency: 50 * time.Millisecond,
},
{
Name: "Ecosia",
FetchFunc: fetchEcosiaSuggestions,
Latency: 50 * time.Millisecond,
},
// { // Not working with fetchSuggestionsFromURL func
// Name: "Qwant",
// FetchFunc: fetchQwantSuggestions,
// Latency: 50 * time.Millisecond,
// },
{
Name: "Startpage",
FetchFunc: fetchStartpageSuggestions,
Latency: 50 * time.Millisecond,
},
{
Name: "Yahoo",
FetchFunc: fetchYahooSuggestions,
Latency: 50 * time.Millisecond,
},
// I advise against it, but you can use it if you want to
// {
// Name: "Google",
// FetchFunc: fetchGoogleSuggestions,
// Latency: 500 * time.Millisecond,
// },
}
// Mutex to protect the suggestionSources during sorting.
var suggestionsMU sync.Mutex
func handleSuggestions(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
if query == "" {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `["",[]]`)
return
}
// Sort the suggestion sources based on their latency.
suggestionsMU.Lock()
sort.Slice(suggestionSources, func(i, j int) bool {
return suggestionSources[i].Latency < suggestionSources[j].Latency
})
suggestionsMU.Unlock()
var suggestions []string
for i := range suggestionSources {
source := &suggestionSources[i]
start := time.Now()
suggestions = source.FetchFunc(query)
elapsed := time.Since(start)
updateLatency(source, elapsed)
if len(suggestions) > 0 {
printDebug("Suggestions found using %s", source.Name)
break
} else {
printWarn("%s did not return any suggestions or failed.", source.Name)
}
}
// Trim the suggestions to a maximum of 8 items
suggestions = trimSuggestions(suggestions)
if len(suggestions) == 0 {
printErr("All suggestion services failed. Returning empty response.")
}
// Return the final suggestions as JSON.
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `["",%s]`, toJSONStringArray(suggestions))
}
// trimSuggestions trims the suggestion list to a maximum of 8 suggestions.
func trimSuggestions(suggestions []string) []string {
if len(suggestions) > 8 {
return suggestions[:8]
}
return suggestions
}
// updateLatency updates the latency of a suggestion source using an exponential moving average.
func updateLatency(source *SuggestionSource, newLatency time.Duration) {
source.mu.Lock()
defer source.mu.Unlock()
const alpha = 0.5 // Smoothing factor.
source.Latency = time.Duration(float64(source.Latency)*(1-alpha) + float64(newLatency)*alpha)
}
func fetchGoogleSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("http://suggestqueries.google.com/complete/search?client=firefox&q=%s", encodedQuery)
printDebug("Fetching suggestions from Google: %s", url)
return fetchSuggestionsFromURL(url)
}
func fetchDuckDuckGoSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://duckduckgo.com/ac/?q=%s&type=list", encodedQuery)
printDebug("Fetching suggestions from DuckDuckGo: %s", url)
return fetchSuggestionsFromURL(url)
}
func fetchEdgeSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://api.bing.com/osjson.aspx?query=%s", encodedQuery)
printDebug("Fetching suggestions from Edge (Bing): %s", url)
return fetchSuggestionsFromURL(url)
}
func fetchBraveSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://search.brave.com/api/suggest?q=%s", encodedQuery)
printDebug("Fetching suggestions from Brave: %s", url)
return fetchSuggestionsFromURL(url)
}
func fetchEcosiaSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://ac.ecosia.org/?q=%s&type=list", encodedQuery)
printDebug("Fetching suggestions from Ecosia: %s", url)
return fetchSuggestionsFromURL(url)
}
// Is this working?
func fetchQwantSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://api.qwant.com/v3/suggest?q=%s", encodedQuery)
printDebug("Fetching suggestions from Qwant: %s", url)
return fetchSuggestionsFromURL(url)
}
func fetchStartpageSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://startpage.com/suggestions?q=%s", encodedQuery)
printDebug("Fetching suggestions from Startpage: %s", url)
return fetchSuggestionsFromURL(url)
}
func fetchYahooSuggestions(query string) []string {
encodedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://search.yahoo.com/sugg/gossip/gossip-us-ura/?output=fxjson&command=%s", encodedQuery)
printDebug("Fetching suggestions from Yahoo: %s", url)
return fetchSuggestionsFromURL(url)
}
// func fetchBaiduSuggestions(query string) []string {
// encodedQuery := url.QueryEscape(query)
// url := fmt.Sprintf("https://suggestion.baidu.com/su?wd=%s", encodedQuery)
// printDebug("Fetching suggestions from Baidu: %s", url)
// return fetchSuggestionsFromURL(url)
// }
func fetchSuggestionsFromURL(url string) []string {
resp, err := http.Get(url)
if err != nil {
printWarn("Error fetching suggestions from %s: %v", url, err)
return []string{}
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
printWarn("Error reading response body from %s: %v", url, err)
return []string{}
}
// Print the raw HTTP response for debugging
fmt.Printf("Raw response from %s:\n%s\n", url, string(body))
// Log the Content-Type for debugging.
contentType := resp.Header.Get("Content-Type")
printDebug("Response Content-Type from %s: %s", url, contentType)
// Check if the body is non-empty.
if len(body) == 0 {
printWarn("Received empty response body from %s", url)
return []string{}
}
// Attempt to parse the response as JSON regardless of Content-Type.
var parsedResponse []interface{}
if err := json.Unmarshal(body, &parsedResponse); err != nil {
printErr("Error parsing JSON from %s: %v", url, err)
printDebug("Response body: %s", string(body))
return []string{}
}
// Ensure the response structure is as expected.
if len(parsedResponse) < 2 {
printWarn("Unexpected response format from %v: %v", url, string(body))
return []string{}
}
suggestions := []string{}
if items, ok := parsedResponse[1].([]interface{}); ok {
for _, item := range items {
if suggestion, ok := item.(string); ok {
suggestions = append(suggestions, suggestion)
}
}
} else {
printErr("Unexpected suggestions format in response from: %v", url)
}
return suggestions
}
// toJSONStringArray converts a slice of strings to a JSON array string.
func toJSONStringArray(strings []string) string {
result := ""
for i, str := range strings {
result += fmt.Sprintf(`"%s"`, str)
if i < len(strings)-1 {
result += ","
}
}
return "[" + result + "]"
}
// func testSuggestionSources(query string) {
// for _, source := range suggestionSources {
// fmt.Printf("Testing %s...\n", source.Name)
// // Fetch suggestions
// suggestions := source.FetchFunc(query)
// // If we get results, print them
// if len(suggestions) > 0 {
// fmt.Printf("Suggestions from %s:\n", source.Name)
// for i, suggestion := range suggestions {
// fmt.Printf("%d: %s\n", i+1, suggestion)
// }
// } else {
// fmt.Printf("No suggestions from %s.\n", source.Name)
// }
// // Small separator for clarity
// fmt.Println("--------------------------")
// }
// }
// func main() {
// query := "test query"
// testSuggestionSources(query)
// }

17
templates/files.html Normal file → Executable file
View file

@ -3,16 +3,24 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<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>
<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="{{ .Query }}" id="search-input" placeholder="Type to search..." />
<input type="text" name="q" value="{{ .Query }}" id="search-input"/>
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="file">search</button>
<div class="autocomplete">
<ul>
</ul>
</div>
<input type="submit" class="hide" name="t" value="file" />
</div>
<div class="sub-search-button-wrapper">
@ -66,7 +74,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 +82,7 @@
</form>
<div class="clean">
{{ range .Results }}
<div class="results">
<div class="results" id="results">
{{ if .Error }}
<div class="error">{{ .Error }}</div>
{{ else }}
@ -104,6 +112,7 @@
Try rephrasing your search term and/or recorrect any spelling mistakes.
</div>
{{ end }}
<script defer src="/static/js/autocomplete.js"></script>
<script>
// Check if JavaScript is enabled and modify the DOM accordingly
document.getElementById('content').classList.remove('js-enabled');

58
templates/forums.html Normal file → Executable file
View file

@ -3,16 +3,23 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<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>
<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="{{ .Query }}" id="search-input" placeholder="Type to search..." />
<input type="text" name="q" value="{{ .Query }}" id="search-input"/>
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="forum">search</button>
<div class="autocomplete">
<ul></ul>
</div>
<input type="submit" class="hide" name="t" value="forum" />
</div>
<div class="sub-search-button-wrapper">
@ -33,10 +40,10 @@
<button name="t" value="forum" class="clickable search-active">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 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="file">share</button>
@ -47,42 +54,53 @@
<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}}
<option value="{{.Code}}" {{if eq .Code $.CurrentLang}}selected{{end}}>{{.Name}}</option>
{{end}}
</select>
<button class="results-save" name="t" value="text">Apply settings</button>
<button class="results-save" name="t" value="forum">Apply settings</button>
</form>
<div class="results">
<div class="results" id="results">
{{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>
<br>
{{end}}
{{else}}
{{else if .NoResults}}
<div class="no-results">No results found for '{{ .Query }}'. Try different keywords.</div>
{{else}}
<div class="no-more-results">Looks like this is the end of results.</div>
{{end}}
</div>
<div class="prev-next prev-img">
<div class="message-bottom-left" id="message-bottom-left">
<span>Searching for new results...</span>
</div>
<div class="prev-next prev-img" id="prev-next">
<form action="/search" method="get">
<input type="hidden" name="q" value="{{ .Query }}">
<input type="hidden" name="t" value="text">
{{ if .HasPrevPage }}
<button type="submit" name="p" value="{{ sub .Page 1 }}">Previous</button>
{{ end }}
{{ if .HasNextPage }}
<button type="submit" name="p" value="{{ add .Page 1 }}">Next</button>
{{ end }}
<input type="hidden" name="t" value="forum">
<div id="content" class="js-enabled">
{{ if .HasPrevPage }}
<button type="submit" name="p" value="{{ sub .Page 1 }}">Previous</button>
{{ end }}
{{ if .HasNextPage }}
<button type="submit" name="p" value="{{ add .Page 1 }}">Next</button>
{{ end }}
</div>
</form>
</div>
<!-- Pass the relevant data for dynamic scrolling -->
<div id="template-data" data-page="{{ .Page }}" data-query="{{ .Query }}" data-type="forum"></div>
<script defer src="/static/js/dynamicscrolling.js"></script>
<script defer src="/static/js/autocomplete.js"></script>
<script>
// Check if JavaScript is enabled and modify the DOM accordingly
document.getElementById('content').classList.remove('js-enabled');

79
templates/images.html Normal file → Executable file
View file

@ -3,16 +3,24 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<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>
<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="{{ .Query }}" id="search-input" placeholder="Type to search..." />
<input type="text" name="q" value="{{ .Query }}" id="search-input"/>
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="image">search</button>
<div class="autocomplete">
<ul>
</ul>
</div>
<input type="submit" class="hide" name="t" value="image" />
</div>
<div class="sub-search-button-wrapper">
@ -47,8 +55,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,65 +108,12 @@
<div class="message-bottom-left" id="message-bottom-left">
<span>Searching for new results...</span>
</div>
<div id="template-data" data-page="{{ .Page }}" data-query="{{ .Query }}" data-type="image"></div>
<script defer src="/static/js/dynamicscrolling.js"></script>
<script defer src="/static/js/autocomplete.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
let page = {{ .Page }};
const query = "{{ .Query }}";
let loading = false;
let hasMoreResults = true;
const loadingIndicator = document.getElementById('message-bottom-left');
let loadingTimeout;
function loadResults(newPage) {
if (loading || !hasMoreResults) return;
loading = true;
// Show loading indicator if taking more than 100ms
loadingTimeout = setTimeout(() => {
loadingIndicator.style.display = 'flex';
}, 100);
fetch(`/search?q=${encodeURIComponent(query)}&t=image&p=${newPage}`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
clearTimeout(loadingTimeout);
loadingIndicator.style.display = 'none';
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');
const newResults = doc.getElementById('results').innerHTML;
const noResultsMessage = "No results found for '{{ .Query }}'. Try different keywords.";
const endOfResultsMessage = "Looks like this is the end of results.";
const serverError = "Internal Server Error";
if (newResults.includes(noResultsMessage) || newResults.includes(endOfResultsMessage) || newResults.includes(serverError)) {
document.getElementById('results').innerHTML += newResults;
hasMoreResults = false;
} else {
document.getElementById('results').innerHTML += newResults;
page = newPage;
}
loading = false;
})
.catch(error => {
clearTimeout(loadingTimeout);
loadingIndicator.style.display = 'none';
console.error('Error loading results:', error);
hasMoreResults = false; // Stop further attempts
loading = false;
});
}
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
loadResults(page + 1);
}
});
});
// Check if JavaScript is enabled and modify the DOM accordingly
document.getElementById('content').classList.remove('js-enabled');
</script>
</body>
</html>

View file

@ -3,8 +3,12 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<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" />
@ -26,8 +30,12 @@
<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="{{ .Query }}" id="search-input" placeholder="Type to search..." />
<input type="text" name="q" value="{{ .Query }}" id="search-input"/>
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="map">search</button>
<div class="autocomplete">
<ul>
</ul>
</div>
<input type="submit" class="hide" name="t" value="map" />
</div>
<div class="sub-search-button-wrapper">

134
templates/search.html Normal file → Executable file
View file

@ -3,25 +3,137 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<title>Search with Ocásek</title>
<link rel="stylesheet" href="/static/css/style.css">
<link rel="stylesheet" href="/static/css/style-search.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 defer src="/static/js/autocomplete.js"></script>
<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
if (siteLanguageSelect) {
siteLanguageSelect.addEventListener('change', function () {
updateSettings('site_lang', this.value);
});
}
// if (searchLanguageSelect) {
// searchLanguageSelect.addEventListener('change', function () {
// updateSettings('search_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 theme-mini-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="site_lang" id="siteLanguageSelect">
{{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>
<div class="wrapper">
<input type="text" name="q" autofocus id="search-input" placeholder="Type to search..." />
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="text" type="submit">search</button>
<!-- <a id="clearSearch" class="material-icons-round">close</a> -->
</div>
<div class="search-button-wrapper">
<input type="hidden" name="p" value="1">
<button name="t" value="text" type="submit">Search Text</button>
<button name="t" value="image" type="submit">Search Images</button>
<div class="search-page-content">
<h1>Ocásek</h1>
<div class="wrapper">
<input type="text" name="q" autofocus id="search-input"/> <!-- placeholder="Type to search..." -->
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="web" type="submit">search</button>
<div class="autocomplete">
<ul></ul>
</div>
</div>
<div class="search-type-icons">
<input type="hidden" name="p" value="1">
<div class="icon-button">
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="text">search</button>
<p>Web</p>
</div>
<div class="icon-button">
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="image">image</button>
<p>Images</p>
</div>
<div class="icon-button">
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="video">movie</button>
<p>Videos</p>
</div>
<div class="icon-button">
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="forum">forum</button>
<p>Forums</p>
</div>
<div class="icon-button">
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="map">map</button>
<p>Maps</p>
</div>
<div class="icon-button">
<button id="sub-search-wrapper-ico" class="material-icons-round clickable" name="t" value="file">share</button>
<p>Torrents</p>
</div>
</div>
</div>
</form>
</body>

View file

@ -3,79 +3,100 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<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 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>
<div class="settings-row">
<p>Site Language</p>
<select class="results-settings" name="site_lang" id="siteLanguageSelect">
{{range .LanguageOptions}}
<option value="{{.Code}}" {{if eq .Code $.CurrentSiteLang}}selected{{end}}>{{.Name}}</option>
{{end}}
</select>
</div>
<div class="settings-row">
<p>Search Language</p>
<select class="results-settings" name="search_lang" id="searchLanguageSelect">
{{range .LanguageOptions}}
<option value="{{.Code}}" {{if eq .Code $.CurrentSearchLang}}selected{{end}}>{{.Name}}</option>
{{end}}
</select>
</div>
<div class="settings-row">
<p class="font-hide"> </p>
<button class="save save-settings-page" type="submit">Save Settings</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>
</select>
<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>
<input type="submit" class="results-settings" value="Save">
</form>
<div>
<script>
// Check if JavaScript is enabled and modify the DOM accordingly
document.getElementById('content').classList.remove('js-enabled');
</script>
</div>
</body>
</html>

91
templates/text.html Normal file → Executable file
View file

@ -3,16 +3,24 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<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>
<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="{{ .Query }}" id="search-input" placeholder="Type to search..." />
<input type="text" name="q" value="{{ .Query }}" id="search-input"/>
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="text">search</button>
<div class="autocomplete">
<ul>
</ul>
</div>
<input type="submit" class="hide" name="t" value="text" />
</div>
<div class="sub-search-button-wrapper">
@ -47,8 +55,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 +69,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>
@ -80,69 +88,22 @@
<form action="/search" method="get">
<input type="hidden" name="q" value="{{ .Query }}">
<input type="hidden" name="t" value="text">
{{ if .HasPrevPage }}
<button type="submit" name="p" value="{{ sub .Page 1 }}">Previous</button>
{{ end }}
{{ if .HasNextPage }}
<button type="submit" name="p" value="{{ add .Page 1 }}">Next</button>
{{ end }}
<div id="content" class="js-enabled">
{{ if .HasPrevPage }}
<button type="submit" name="p" value="{{ sub .Page 1 }}">Previous</button>
{{ end }}
{{ if .HasNextPage }}
<button type="submit" name="p" value="{{ add .Page 1 }}">Next</button>
{{ end }}
</div>
</form>
</div>
<div id="template-data" data-page="{{ .Page }}" data-query="{{ .Query }}" data-type="text"></div>
<script defer src="/static/js/dynamicscrolling.js"></script>
<script defer src="/static/js/autocomplete.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
if (document.getElementById('prev-next')) {
document.getElementById('prev-next').style.display = 'none';
let page = {{ .Page }};
const query = "{{ .Query }}";
let loading = false;
let hasMoreResults = true;
const loadingIndicator = document.getElementById('message-bottom-left');
let loadingTimeout;
function loadResults(newPage) {
if (loading || !hasMoreResults) return;
loading = true;
// Show loading indicator if taking more than 100ms
loadingTimeout = setTimeout(() => {
loadingIndicator.style.display = 'flex';
}, 100);
fetch(`/search?q=${encodeURIComponent(query)}&t=text&p=${newPage}`)
.then(response => response.text())
.then(data => {
clearTimeout(loadingTimeout);
loadingIndicator.style.display = 'none';
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');
const newResults = doc.getElementById('results').innerHTML;
const noResultsMessage = "No results found for '{{ .Query }}'. Try different keywords.";
if (newResults.includes(noResultsMessage)) {
document.getElementById('results').innerHTML += "<div class='no-more-results'>Looks like this is the end of results.</div>";
hasMoreResults = false;
} else {
document.getElementById('results').innerHTML += newResults;
page = newPage;
}
loading = false;
})
.catch(error => {
clearTimeout(loadingTimeout);
loadingIndicator.style.display = 'none';
console.error('Error loading results:', error);
loading = false;
});
}
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
loadResults(page + 1);
}
});
}
});
// Check if JavaScript is enabled and modify the DOM accordingly
document.getElementById('content').classList.remove('js-enabled');
</script>
</body>
</html>

View file

@ -3,16 +3,24 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ if .IsThemeDark }}
<meta name="darkreader-lock">
{{ end }}
<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>
<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="{{ .Query }}" id="search-input" placeholder="Type to search..." />
<input type="text" name="q" value="{{ .Query }}" id="search-input"/>
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="video">search</button>
<div class="autocomplete">
<ul>
</ul>
</div>
<input type="submit" class="hide" name="t" value="video" />
</div>
<div class="sub-search-button-wrapper">
@ -51,12 +59,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>
@ -78,6 +89,7 @@
{{ end }}
</form>
</div>
<script defer src="/static/js/autocomplete.js"></script>
<script>
// Check if JavaScript is enabled and modify the DOM accordingly
document.getElementById('content').classList.remove('js-enabled');

View file

@ -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
@ -68,12 +66,35 @@ func buildSearchURL(query, safe, lang string, page, resultsPerPage int) string {
}
langParam := ""
var glParam, uuleParam string
if lang != "" {
langParam = "&lr=" + lang
// Use lang as the geolocation
langParam = "&lr=lang_" + lang
glParam = "&gl=" + lang
uuleParam = ""
} else {
// Use 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)
printDebug(fmt.Sprintf("https://www.google.com/search?q=%s%s%s%s%s&start=%d",
url.QueryEscape(query), safeParam, langParam, glParam, uuleParam, 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 +104,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
}

128
text.go Normal file → Executable file
View file

@ -3,7 +3,6 @@ package main
import (
"fmt"
"html/template"
"log"
"net/http"
"time"
)
@ -15,26 +14,67 @@ 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 == "active", Lang: settings.SearchLanguage, Type: "text"}
combinedResults := getTextResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.SearchLanguage, 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.SearchLanguage, page+1)
if hasPrevPage {
go prefetchPage(query, safe, lang, page-1)
go prefetchPage(query, settings.SafeSearch, settings.SearchLanguage, 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
IsThemeDark bool
}{
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.SearchLanguage,
Theme: settings.Theme,
Safe: settings.SafeSearch,
IsThemeDark: settings.IsThemeDark,
}
err = tmpl.Execute(w, data)
if err != nil {
printErr("Error executing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
@ -45,10 +85,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 +105,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))
@ -76,15 +116,15 @@ 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"}
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "active", 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 +132,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 +149,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 +185,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
View 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)
}

213
user-settings.go Executable file
View file

@ -0,0 +1,213 @@
package main
import (
"html/template"
"net/http"
"strings"
"time"
)
type UserSettings struct {
Theme string
SiteLanguage string
SearchLanguage string
SafeSearch string
IsThemeDark bool
}
func loadUserSettings(w http.ResponseWriter, r *http.Request) UserSettings {
var settings UserSettings
saveRequired := false
// Load theme
if cookie, err := r.Cookie("theme"); err == nil {
settings.Theme = cookie.Value
} else {
settings.Theme = "dark"
saveRequired = true
}
// Determine if the selected theme is dark
settings.IsThemeDark = settings.Theme == "dark" || settings.Theme == "night" || settings.Theme == "black" || settings.Theme == "latte"
// Load site language
if cookie, err := r.Cookie("site_language"); err == nil {
settings.SiteLanguage = cookie.Value
} else {
// If no site language is set, use Accept-Language or default to "en"
acceptLang := r.Header.Get("Accept-Language")
if acceptLang != "" {
settings.SiteLanguage = normalizeLangCode(strings.Split(acceptLang, ",")[0])
} else {
settings.SiteLanguage = "en" // Default language
}
saveRequired = true
}
// Load search language (can be empty)
if cookie, err := r.Cookie("search_language"); err == nil {
settings.SearchLanguage = cookie.Value
}
// Load safe search
if cookie, err := r.Cookie("safe"); err == nil {
settings.SafeSearch = cookie.Value
} else {
settings.SafeSearch = ""
saveRequired = true
}
if saveRequired {
saveUserSettings(w, settings)
}
return settings
}
func saveUserSettings(w http.ResponseWriter, settings UserSettings) {
expiration := time.Now().Add(90 * 24 * time.Hour)
http.SetCookie(w, &http.Cookie{
Name: "theme",
Value: settings.Theme,
Path: "/",
Expires: expiration,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
http.SetCookie(w, &http.Cookie{
Name: "site_language",
Value: settings.SiteLanguage,
Path: "/",
Expires: expiration,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
http.SetCookie(w, &http.Cookie{
Name: "search_language",
Value: settings.SearchLanguage,
Path: "/",
Expires: expiration,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
http.SetCookie(w, &http.Cookie{
Name: "safe",
Value: settings.SafeSearch,
Path: "/",
Expires: expiration,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
printDebug("settings saved: %v", settings)
}
func handleSaveSettings(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// Load current settings
settings := loadUserSettings(w, r)
// Update only the settings that were submitted in the form
if theme := r.FormValue("theme"); theme != "" {
settings.Theme = theme
}
// Update site language if provided
if siteLang := r.FormValue("site_lang"); siteLang != "" {
settings.SiteLanguage = siteLang
} else {
// If site_lang is empty, try to get from Accept-Language header
acceptLang := r.Header.Get("Accept-Language")
if acceptLang != "" {
settings.SiteLanguage = strings.Split(acceptLang, ",")[0]
}
}
// Update search language if provided
if searchLang := r.FormValue("search_lang"); searchLang != "" {
settings.SearchLanguage = searchLang
}
// Update safe search if provided
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(w, r)
data := struct {
LanguageOptions []LanguageOption
CurrentSiteLang string
CurrentSearchLang string
Theme string
Safe string
IsThemeDark bool
}{
LanguageOptions: languageOptions,
CurrentSiteLang: settings.SiteLanguage,
CurrentSearchLang: settings.SearchLanguage,
Theme: settings.Theme,
Safe: settings.SafeSearch,
IsThemeDark: settings.IsThemeDark,
}
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
}
}
// Helper function to normalize language codes
func normalizeLangCode(lang string) string {
lang = strings.ToLower(lang)
// First, check if the language code is already valid
if isValidLangCode(lang) {
return lang
}
// Strip regional codes (e.g., en-US -> en)
if strings.Contains(lang, "-") {
lang = strings.Split(lang, "-")[0]
}
// Re-check if the normalized version is valid
if isValidLangCode(lang) {
return lang
}
// If the language is not recognized, default to "en"
return "en"
}
// Helper function to check if a language code exists in the language options
func isValidLangCode(lang string) bool {
for _, opt := range languageOptions {
if opt.Code == lang {
return true
}
}
return false
}

View 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,49 @@ 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.SearchLanguage, page)
if len(results) == 0 {
printWarn("No results from primary search, trying other nodes")
results = tryOtherNodesForVideoSearch(query, settings.SafeSearch, settings.SearchLanguage, 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.SearchLanguage,
"Theme": settings.Theme,
"Safe": settings.SafeSearch,
"IsThemeDark": settings.IsThemeDark,
})
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" {
@ -174,29 +207,9 @@ func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int
Views: formatViews(item.Views),
Creator: item.UploaderName,
Publisher: "Piped",
Image: fmt.Sprintf("/img_proxy?url=%s", url.QueryEscape(item.Thumbnail)),
Image: item.Thumbnail, //fmt.Sprintf("/img_proxy?url=%s", url.QueryEscape(item.Thumbnail)), // Using image proxy is not working, but its not needed here as piped is proxy anyway
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
}