Search/text.go

175 lines
5.2 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"
"log"
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},
{Name: "DuckDuckGo", Func: wrapTextSearchFunc(PerformDuckDuckGoTextSearch), Weight: 5}, // DuckDuckGo timeouts too fast and search results are trash
// {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, 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
hasPrevPage := page > 1
2024-06-09 19:44:49 +00:00
hasNextPage := len(combinedResults) > 0
2024-05-21 06:48:09 +00:00
displayResults(w, combinedResults, query, lang, time.Since(startTime).Seconds(), page, hasPrevPage, hasNextPage)
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-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 {
log.Println("Cache hit")
cacheChan <- results
} else {
log.Println("Cache miss")
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):
log.Println("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 {
2024-06-09 19:44:49 +00:00
log.Printf("Page %d not cached, caching now...", page)
pageResults := fetchTextResults(query, safe, lang, page)
if len(pageResults) > 0 {
resultsCache.Set(cacheKey, convertToSearchResults(pageResults))
}
2024-05-21 06:48:09 +00:00
} else {
2024-06-09 19:44:49 +00:00
log.Printf("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 {
log.Printf("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)
continue
}
for _, result := range searchResults {
results = append(results, result.(TextSearchResult))
}
if len(results) > 0 {
break
}
2024-05-21 06:48:09 +00:00
}
2024-06-09 19:44:49 +00:00
return results
}
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
}
func displayResults(w http.ResponseWriter, results []TextSearchResult, query, lang string, elapsed float64, page int, hasPrevPage, hasNextPage bool) {
2024-05-21 06:48:09 +00:00
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")
2024-05-17 12:26:28 +00:00
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
2024-05-17 12:26:28 +00:00
LanguageOptions []LanguageOption
CurrentLang string
NoResults bool
2024-05-17 12:26:28 +00:00
}{
Results: results,
Query: query,
2024-05-17 23:59:29 +00:00
Fetched: fmt.Sprintf("%.2f seconds", elapsed),
Page: page,
HasPrevPage: hasPrevPage,
HasNextPage: hasNextPage,
2024-05-17 12:26:28 +00:00
LanguageOptions: languageOptions,
CurrentLang: lang,
NoResults: len(results) == 0,
2024-05-17 12:26:28 +00:00
}
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
2024-05-16 16:29:26 +00:00
}