84 lines
2.1 KiB
Go
84 lines
2.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"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 {
|
||
|
log.Printf("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 {
|
||
|
log.Printf("Error unmarshalling file results: %v", err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
log.Printf("Received file results: %+v", results)
|
||
|
// Send results to fileResultsChan
|
||
|
go func() {
|
||
|
fileResultsChan <- results
|
||
|
}()
|
||
|
}
|