Search/text.go

184 lines
5.5 KiB
Go
Raw Normal View History

2024-05-16 16:29:26 +00:00
package main
import (
2024-05-17 12:26:28 +00:00
"fmt"
"html/template"
2024-05-16 16:29:26 +00:00
"net/http"
2024-05-17 12:26:28 +00:00
"time"
2024-05-16 16:29:26 +00:00
)
var textSearchEngines []SearchEngine
2024-06-09 19:44:49 +00:00
2024-05-17 23:59:29 +00:00
func init() {
textSearchEngines = []SearchEngine{
{Name: "Google", Func: wrapTextSearchFunc(PerformGoogleTextSearch), Weight: 1},
{Name: "LibreX", Func: wrapTextSearchFunc(PerformLibreXTextSearch), Weight: 2},
2024-06-15 16:12:01 +00:00
{Name: "Brave", Func: wrapTextSearchFunc(PerformBraveTextSearch), Weight: 2},
2024-06-29 19:27:48 +00:00
{Name: "DuckDuckGo", Func: wrapTextSearchFunc(PerformDuckDuckGoTextSearch), Weight: 5},
// {Name: "SearXNG", Func: wrapTextSearchFunc(PerformSearXNGTextSearch), Weight: 2}, // Uncomment when implemented
2024-06-09 19:44:49 +00:00
}
2024-05-17 23:59:29 +00:00
}
2024-05-17 12:26:28 +00:00
func HandleTextSearch(w http.ResponseWriter, settings UserSettings, query, safe, lang string, page int) {
2024-05-17 23:59:29 +00:00
startTime := time.Now()
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"}
2024-06-09 19:44:49 +00:00
combinedResults := getTextResultsFromCacheOrFetch(cacheKey, query, safe, lang, page)
2024-05-21 06:48:09 +00:00
2024-08-08 21:37:58 +00:00
hasPrevPage := page > 1 // dupe
2024-05-21 06:48:09 +00:00
2024-08-08 21:37:58 +00:00
//displayResults(w, combinedResults, query, lang, time.Since(startTime).Seconds(), page, hasPrevPage, hasNextPage)
2024-05-21 06:48:09 +00:00
2024-06-09 19:44:49 +00:00
// Prefetch next and previous pages
go prefetchPage(query, safe, lang, page+1)
if hasPrevPage {
go prefetchPage(query, safe, lang, page-1)
2024-05-21 08:19:40 +00:00
}
2024-08-08 21:37:58 +00:00
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)
2024-08-08 21:37:58 +00:00
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
data := struct {
Results []TextSearchResult
Query string
Page int
Fetched string
LanguageOptions []LanguageOption
CurrentLang string
HasPrevPage bool
HasNextPage bool
NoResults bool
Theme string
2024-08-08 21:37:58 +00:00
}{
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,
Theme: settings.Theme,
2024-08-08 21:37:58 +00:00
}
err = tmpl.Execute(w, data)
if err != nil {
printErr("Error executing template: %v", err)
2024-08-08 21:37:58 +00:00
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
2024-05-21 06:48:09 +00:00
}
2024-06-09 19:44:49 +00:00
func getTextResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []TextSearchResult {
cacheChan := make(chan []SearchResult)
2024-05-20 20:14:48 +00:00
var combinedResults []TextSearchResult
2024-05-20 20:14:48 +00:00
go func() {
results, exists := resultsCache.Get(cacheKey)
if exists {
printInfo("Cache hit")
2024-05-20 20:14:48 +00:00
cacheChan <- results
} else {
printInfo("Cache miss")
2024-05-20 20:14:48 +00:00
cacheChan <- nil
}
}()
select {
case results := <-cacheChan:
if results == nil {
2024-06-09 19:44:49 +00:00
combinedResults = fetchTextResults(query, safe, lang, page)
if len(combinedResults) > 0 {
resultsCache.Set(cacheKey, convertToSearchResults(combinedResults))
}
} else {
textResults, _, _ := convertToSpecificResults(results)
combinedResults = textResults
2024-05-20 20:14:48 +00:00
}
case <-time.After(2 * time.Second):
printInfo("Cache check timeout")
2024-06-09 19:44:49 +00:00
combinedResults = fetchTextResults(query, safe, lang, page)
if len(combinedResults) > 0 {
resultsCache.Set(cacheKey, convertToSearchResults(combinedResults))
}
}
2024-05-21 06:48:09 +00:00
return combinedResults
}
2024-06-09 19:44:49 +00:00
func prefetchPage(query, safe, lang string, page int) {
cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"}
2024-05-21 06:48:09 +00:00
if _, exists := resultsCache.Get(cacheKey); !exists {
printInfo("Page %d not cached, caching now...", page)
2024-06-09 19:44:49 +00:00
pageResults := fetchTextResults(query, safe, lang, page)
if len(pageResults) > 0 {
resultsCache.Set(cacheKey, convertToSearchResults(pageResults))
}
2024-05-21 06:48:09 +00:00
} else {
printInfo("Page %d already cached", page)
2024-05-20 20:14:48 +00:00
}
2024-05-21 06:48:09 +00:00
}
2024-06-09 19:44:49 +00:00
func fetchTextResults(query, safe, lang string, page int) []TextSearchResult {
var results []TextSearchResult
for _, engine := range textSearchEngines {
printInfo("Using search engine: %s", engine.Name)
searchResults, duration, err := engine.Func(query, safe, lang, page)
updateEngineMetrics(&engine, duration, err == nil)
if err != nil {
printWarn("Error performing search with %s: %v", engine.Name, err)
continue
}
2024-06-15 23:30:18 +00:00
results = append(results, validateResults(searchResults)...)
// If results are found, break out of the loop
if len(results) > 0 {
break
}
2024-05-21 06:48:09 +00:00
}
2024-08-08 21:37:58 +00:00
// 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})
2024-08-08 21:37:58 +00:00
}
2024-06-09 19:44:49 +00:00
return results
}
2024-06-15 23:30:18 +00:00
func validateResults(searchResults []SearchResult) []TextSearchResult {
var validResults []TextSearchResult
// Remove anything that is missing a URL or Header
for _, result := range searchResults {
textResult := result.(TextSearchResult)
if textResult.URL != "" || textResult.Header != "" {
validResults = append(validResults, textResult)
}
}
return validResults
}
func wrapTextSearchFunc(f func(string, string, string, int) ([]TextSearchResult, time.Duration, error)) func(string, string, string, int) ([]SearchResult, time.Duration, error) {
return func(query, safe, lang string, page int) ([]SearchResult, time.Duration, error) {
textResults, duration, err := f(query, safe, lang, page)
if err != nil {
return nil, duration, err
}
searchResults := make([]SearchResult, len(textResults))
for i, result := range textResults {
searchResults[i] = result
2024-06-09 19:44:49 +00:00
}
return searchResults, duration, nil
2024-05-17 12:26:28 +00:00
}
2024-05-21 06:48:09 +00:00
}