send search request wip

This commit is contained in:
partisan 2024-08-08 23:09:07 +02:00
parent 1baa40b620
commit 506107286d
5 changed files with 152 additions and 106 deletions

View file

@ -1,6 +1,7 @@
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
@ -40,6 +41,7 @@ func handleImageSearch(w http.ResponseWriter, query, safe, lang string, page int
CurrentLang string
HasPrevPage bool
HasNextPage bool
NoResults bool
}{
Results: combinedResults,
Query: query,
@ -49,6 +51,7 @@ func handleImageSearch(w http.ResponseWriter, query, safe, lang string, page int
CurrentLang: lang,
HasPrevPage: page > 1,
HasNextPage: len(combinedResults) >= 50,
NoResults: len(combinedResults) == 0,
}
err = tmpl.Execute(w, data)
@ -120,12 +123,67 @@ 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)
log.Printf("No image results found for query: %s, trying other nodes", query)
results = tryOtherNodesForImageSearch(query, safe, lang, page)
}
return results
}
func tryOtherNodesForImageSearch(query, safe, lang string, page int) []ImageSearchResult {
for _, nodeAddr := range peers {
results, err := sendImageSearchRequestToNode(nodeAddr, query, safe, lang, page)
if err != nil {
log.Printf("Error contacting node %s: %v", nodeAddr, err)
continue
}
if len(results) > 0 {
return results
}
}
return nil
}
func sendImageSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]ImageSearchResult, error) {
searchParams := struct {
Query string `json:"query"`
Safe string `json:"safe"`
Lang string `json:"lang"`
Page int `json:"page"`
ResponseAddr string `json:"responseAddr"`
}{
Query: query,
Safe: safe,
Lang: lang,
Page: page,
ResponseAddr: fmt.Sprintf("http://localhost:%d/node", config.Port),
}
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): // Need to handle this better, setting a static number is stupid
return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr)
}
}
func wrapImageSearchFunc(f func(string, string, string, int) ([]ImageSearchResult, time.Duration, error)) func(string, string, string, int) ([]SearchResult, time.Duration, error) {
return func(query, safe, lang string, page int) ([]SearchResult, time.Duration, error) {
imageResults, duration, err := f(query, safe, lang, page)