From f7abef253e430d6dd6f7e60700ac8d75309fc101 Mon Sep 17 00:00:00 2001 From: partisan Date: Sat, 29 Jun 2024 21:27:48 +0200 Subject: [PATCH 01/34] test node messages --- go.mod | 8 +++-- go.sum | 2 ++ main.go | 5 +++ node.go | 89 ++++++++++++++++++++++++++++++++++++++++++++++++ run.sh | 36 +++++++++++++++++--- search-engine.go | 61 +++++++++++++++++++++++++++++++++ text.go | 2 +- 7 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 node.go diff --git a/go.mod b/go.mod index 1b9bbf4..5dcd6b3 100644 --- a/go.mod +++ b/go.mod @@ -9,15 +9,17 @@ 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 -) \ No newline at end of file +) + +require github.com/fsnotify/fsnotify v1.7.0 // indirect diff --git a/go.sum b/go.sum index cef914e..732af13 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,8 @@ github.com/chromedp/chromedp v0.9.5 h1:viASzruPJOiThk7c5bueOUY91jGLJVximoEMGoH93 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/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= diff --git a/main.go b/main.go index a463ba6..98c8eb3 100644 --- a/main.go +++ b/main.go @@ -135,9 +135,14 @@ func runServer() { }) initializeTorrentSites() + http.HandleFunc("/node", handleNodeRequest) // Handle node requests + config := loadConfig() generateOpenSearchXML(config) + // Start node communication client + go startNodeClient(peers) + fmt.Printf("Server is listening on http://localhost:%d\n", config.Port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil)) } diff --git a/node.go b/node.go new file mode 100644 index 0000000..afe9f1d --- /dev/null +++ b/node.go @@ -0,0 +1,89 @@ +package main + +import ( + "fmt" + "io/ioutil" + "net/http" + "strings" + "sync" + "time" +) + +const ( + connCode = "secretcode123" + testMsg = "This is a test message" +) + +var connCodeMutex sync.Mutex +var peers = []string{"localhost:50002", "localhost:5000"} // Example peer addresses + +func handleNodeRequest(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) + return + } + + connCodeMutex.Lock() + defer connCodeMutex.Unlock() + + body, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error reading request body", http.StatusInternalServerError) + return + } + defer r.Body.Close() + + receivedCode := strings.TrimSpace(string(body)) + + if receivedCode != connCode { + http.Error(w, "Authentication failed", http.StatusUnauthorized) + return + } + + fmt.Println("Authentication successful") + fmt.Fprintln(w, testMsg) +} + +func startNodeClient(addresses []string) { + for _, address := range addresses { + go func(addr string) { + for { + url := fmt.Sprintf("http://%s/node", addr) + req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(connCode)) + if err != nil { + fmt.Println("Error creating request:", err) + time.Sleep(5 * time.Second) + continue + } + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + fmt.Println("Error connecting to", addr, ":", err) + time.Sleep(5 * time.Second) + continue + } + + if resp.StatusCode != http.StatusOK { + fmt.Println("Authentication failed:", resp.Status) + resp.Body.Close() + time.Sleep(5 * time.Second) + continue + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println("Error reading response:", err) + resp.Body.Close() + time.Sleep(5 * time.Second) + continue + } + resp.Body.Close() + + testMsg := strings.TrimSpace(string(body)) + fmt.Println("Received test message from", addr, ":", testMsg) + time.Sleep(10 * time.Second) + } + }(address) + } +} diff --git a/run.sh b/run.sh index da5bcae..6aa8efa 100755 --- a/run.sh +++ b/run.sh @@ -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 diff --git a/search-engine.go b/search-engine.go index 36dde9a..1396b4e 100644 --- a/search-engine.go +++ b/search-engine.go @@ -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 +} diff --git a/text.go b/text.go index ce021ba..a6d67cc 100644 --- a/text.go +++ b/text.go @@ -15,7 +15,7 @@ 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 } } -- 2.40.1 From 9f5ef7a1ef3ff0d2236e4495753ba5608f3b5d9a Mon Sep 17 00:00:00 2001 From: partisan Date: Sun, 30 Jun 2024 23:20:52 +0200 Subject: [PATCH 02/34] node update sync wip --- init.go | 36 ++++++++++++++- main.go | 7 ++- node-update.go | 23 ++++++++++ node.go | 116 ++++++++++++++++++++++++++++++++----------------- update.go | 52 ++++++++++++++++++++++ 5 files changed, 189 insertions(+), 45 deletions(-) create mode 100644 node-update.go create mode 100644 update.go diff --git a/init.go b/init.go index b3129a4..873b077 100644 --- a/init.go +++ b/init.go @@ -2,17 +2,22 @@ package main import ( "bufio" + "crypto/rand" + "encoding/base64" "encoding/json" "fmt" "log" "os" "strconv" + "strings" ) // Configuration structure type Config struct { - Port int - OpenSearch OpenSearchConfig + Port int + ConnectionCode string + Peers []string + OpenSearch OpenSearchConfig } type OpenSearchConfig struct { @@ -37,6 +42,9 @@ func main() { return } + // This is stupid + loadNodeConfig() + // Start the main application runServer() } @@ -74,6 +82,21 @@ func createConfig() error { if domain != "\n" { config.OpenSearch.Domain = domain[:len(domain)-1] } + + fmt.Print("Do you want to connect to other nodes? (yes/no): ") + connectNodes, _ := reader.ReadString('\n') + if strings.TrimSpace(connectNodes) == "yes" { + fmt.Println("Enter peer addresses (comma separated, e.g., http://localhost:5000,http://localhost:5001): ") + peersStr, _ := reader.ReadString('\n') + if peersStr != "\n" { + config.Peers = strings.Split(strings.TrimSpace(peersStr), ",") + } + } + } + + if config.ConnectionCode == "" { + config.ConnectionCode = generateStrongRandomString(32) + fmt.Printf("Generated connection code: %s\n", config.ConnectionCode) } saveConfig(config) @@ -114,3 +137,12 @@ func loadConfig() Config { return config } + +func generateStrongRandomString(length int) string { + bytes := make([]byte, length) + _, err := rand.Read(bytes) + if err != nil { + log.Fatalf("Error generating random string: %v", err) + } + return base64.URLEncoding.EncodeToString(bytes)[:length] +} diff --git a/main.go b/main.go index 98c8eb3..f05108a 100644 --- a/main.go +++ b/main.go @@ -140,9 +140,12 @@ func runServer() { config := loadConfig() generateOpenSearchXML(config) + fmt.Printf("Server is listening on http://localhost:%d\n", config.Port) + log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil)) + // Start node communication client go startNodeClient(peers) - fmt.Printf("Server is listening on http://localhost:%d\n", config.Port) - log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil)) + // Start automatic update checker + go checkForUpdates() } diff --git a/node-update.go b/node-update.go new file mode 100644 index 0000000..e67a160 --- /dev/null +++ b/node-update.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "log" + "time" +) + +// Function to sync updates across all nodes +func nodeUpdateSync() { + fmt.Println("Syncing updates across all nodes...") + for _, peer := range peers { + fmt.Printf("Notifying node %s about update...\n", peer) + err := sendMessage(peer, connCode, "update", "Start update process") + if err != nil { + log.Printf("Failed to notify node %s: %v\n", peer, err) + continue + } + fmt.Printf("Node %s notified. Waiting for it to update...\n", peer) + time.Sleep(30 * time.Second) // Adjust sleep time as needed to allow for updates + } + fmt.Println("All nodes have been updated.") +} diff --git a/node.go b/node.go index afe9f1d..5c04e18 100644 --- a/node.go +++ b/node.go @@ -1,21 +1,32 @@ package main import ( + "bytes" + "encoding/json" "fmt" "io/ioutil" "net/http" - "strings" "sync" "time" ) -const ( - connCode = "secretcode123" - testMsg = "This is a test message" +var ( + connCode string + peers []string + connCodeMutex sync.Mutex ) -var connCodeMutex sync.Mutex -var peers = []string{"localhost:50002", "localhost:5000"} // Example peer addresses +type Message struct { + ID string `json:"id"` + Type string `json:"type"` + Content string `json:"content"` +} + +func loadNodeConfig() { + config := loadConfig() + connCode = config.ConnectionCode + peers = config.Peers +} func handleNodeRequest(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { @@ -33,55 +44,78 @@ func handleNodeRequest(w http.ResponseWriter, r *http.Request) { } defer r.Body.Close() - receivedCode := strings.TrimSpace(string(body)) + var msg Message + if err := json.Unmarshal(body, &msg); err != nil { + http.Error(w, "Error parsing JSON", http.StatusBadRequest) + return + } - if receivedCode != connCode { + if msg.ID != connCode { http.Error(w, "Authentication failed", http.StatusUnauthorized) return } - fmt.Println("Authentication successful") - fmt.Fprintln(w, testMsg) + interpretMessage(msg) + fmt.Fprintln(w, "Message received") +} + +func interpretMessage(msg Message) { + switch msg.Type { + case "test": + fmt.Println("Received test message:", msg.Content) + case "get-version": + fmt.Println("Received get-version message") + // Handle get-version logic here + case "update": + fmt.Println("Received update message:", msg.Content) + // Handle update logic here + go update() + default: + fmt.Println("Received unknown message type:", msg.Type) + } +} + +func sendMessage(address, id, msgType, content string) error { + msg := Message{ + ID: id, + Type: msgType, + Content: content, + } + msgBytes, err := json.Marshal(msg) + if err != nil { + return err + } + + req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/node", address), bytes.NewBuffer(msgBytes)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := ioutil.ReadAll(resp.Body) + return fmt.Errorf("failed to send message: %s", body) + } + + return nil } func startNodeClient(addresses []string) { for _, address := range addresses { go func(addr string) { for { - url := fmt.Sprintf("http://%s/node", addr) - req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(connCode)) + err := sendMessage(addr, connCode, "test", "This is a test message") if err != nil { - fmt.Println("Error creating request:", err) - time.Sleep(5 * time.Second) + fmt.Println("Error sending test message to", addr, ":", err) continue } - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - fmt.Println("Error connecting to", addr, ":", err) - time.Sleep(5 * time.Second) - continue - } - - if resp.StatusCode != http.StatusOK { - fmt.Println("Authentication failed:", resp.Status) - resp.Body.Close() - time.Sleep(5 * time.Second) - continue - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println("Error reading response:", err) - resp.Body.Close() - time.Sleep(5 * time.Second) - continue - } - resp.Body.Close() - - testMsg := strings.TrimSpace(string(body)) - fmt.Println("Received test message from", addr, ":", testMsg) time.Sleep(10 * time.Second) } }(address) diff --git a/update.go b/update.go new file mode 100644 index 0000000..3e31ba0 --- /dev/null +++ b/update.go @@ -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) +} -- 2.40.1 From f769f70ce77082dab7de3bee2abc58b87ed7a697 Mon Sep 17 00:00:00 2001 From: partisan Date: Fri, 5 Jul 2024 03:08:35 +0200 Subject: [PATCH 03/34] wip --- init.go | 73 +++++++++++++++++++++++++++++++++------ main.go | 24 ++++++------- node-master.go | 81 +++++++++++++++++++++++++++++++++++++++++++ node-update.go | 2 +- node.go | 93 +++++++++++++++++++++++++++++++++++++++++++------- 5 files changed, 237 insertions(+), 36 deletions(-) create mode 100644 node-master.go diff --git a/init.go b/init.go index 873b077..b3df270 100644 --- a/init.go +++ b/init.go @@ -10,14 +10,17 @@ import ( "os" "strconv" "strings" + "sync" + + "github.com/fsnotify/fsnotify" ) // Configuration structure type Config struct { - Port int - ConnectionCode string - Peers []string - OpenSearch OpenSearchConfig + Port int + AuthCode string + Peers []string + OpenSearch OpenSearchConfig } type OpenSearchConfig struct { @@ -34,18 +37,31 @@ var defaultConfig = Config{ const configFilePath = "config.json" +var config Config +var configLock sync.RWMutex + func main() { - // Run the initialization process err := initConfig() if err != nil { fmt.Println("Error during initialization:", err) return } - // This is stupid loadNodeConfig() + go startFileWatcher() + go checkMasterHeartbeat() + + if config.AuthCode == "" { + config.AuthCode = generateStrongRandomString(64) + fmt.Printf("Generated connection code: %s\n", config.AuthCode) + saveConfig(config) + } + + if len(config.Peers) > 0 { + go startNodeClient(config.Peers) + startElection() + } - // Start the main application runServer() } @@ -55,6 +71,7 @@ func initConfig() error { } fmt.Println("Configuration file already exists.") + config = loadConfig() return nil } @@ -94,9 +111,9 @@ func createConfig() error { } } - if config.ConnectionCode == "" { - config.ConnectionCode = generateStrongRandomString(32) - fmt.Printf("Generated connection code: %s\n", config.ConnectionCode) + if config.AuthCode == "" { + config.AuthCode = generateStrongRandomString(64) + fmt.Printf("Generated connection code: %s\n", config.AuthCode) } saveConfig(config) @@ -146,3 +163,39 @@ func generateStrongRandomString(length int) string { } return base64.URLEncoding.EncodeToString(bytes)[:length] } + +func startFileWatcher() { + watcher, err := fsnotify.NewWatcher() + if err != nil { + log.Fatal(err) + } + + go func() { + defer watcher.Close() + for { + select { + case event, ok := <-watcher.Events: + if !ok { + return + } + if event.Op&fsnotify.Write == fsnotify.Write { + log.Println("Modified file:", event.Name) + configLock.Lock() + config = loadConfig() + configLock.Unlock() + // Perform your logic here to handle the changes in the config file + } + case err, ok := <-watcher.Errors: + if !ok { + return + } + log.Println("Error:", err) + } + } + }() + + err = watcher.Add(configFilePath) + if err != nil { + log.Fatal(err) + } +} diff --git a/main.go b/main.go index f05108a..0d9ac33 100644 --- a/main.go +++ b/main.go @@ -122,18 +122,18 @@ func parsePageParameter(pageStr string) int { } 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("/opensearch.xml", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/opensearchdescription+xml") - http.ServeFile(w, r, "static/opensearch.xml") - }) - initializeTorrentSites() + // 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("/opensearch.xml", func(w http.ResponseWriter, r *http.Request) { + // w.Header().Set("Content-Type", "application/opensearchdescription+xml") + // http.ServeFile(w, r, "static/opensearch.xml") + // }) + // initializeTorrentSites() http.HandleFunc("/node", handleNodeRequest) // Handle node requests diff --git a/node-master.go b/node-master.go new file mode 100644 index 0000000..4f5155b --- /dev/null +++ b/node-master.go @@ -0,0 +1,81 @@ +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 { + err := sendMessage(node, authCode, "heartbeat", authCode) + 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 { + err := sendMessage(node, authCode, "election", authCode) + 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 + } +} diff --git a/node-update.go b/node-update.go index e67a160..0ef63f6 100644 --- a/node-update.go +++ b/node-update.go @@ -11,7 +11,7 @@ func nodeUpdateSync() { fmt.Println("Syncing updates across all nodes...") for _, peer := range peers { fmt.Printf("Notifying node %s about update...\n", peer) - err := sendMessage(peer, connCode, "update", "Start update process") + err := sendMessage(peer, authCode, "update", "Start update process") if err != nil { log.Printf("Failed to notify node %s: %v\n", peer, err) continue diff --git a/node.go b/node.go index 5c04e18..97862c7 100644 --- a/node.go +++ b/node.go @@ -2,18 +2,22 @@ package main import ( "bytes" + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" "io/ioutil" + "log" "net/http" "sync" "time" ) var ( - connCode string + authCode string peers []string - connCodeMutex sync.Mutex + authMutex sync.Mutex + authenticated = make(map[string]bool) ) type Message struct { @@ -22,9 +26,16 @@ type Message struct { Content string `json:"content"` } +type CrawlerConfig struct { + ID string + Host string + Port int + AuthCode string +} + func loadNodeConfig() { config := loadConfig() - connCode = config.ConnectionCode + authCode = config.AuthCode // nuh uh peers = config.Peers } @@ -34,9 +45,6 @@ func handleNodeRequest(w http.ResponseWriter, r *http.Request) { return } - connCodeMutex.Lock() - defer connCodeMutex.Unlock() - body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Error reading request body", http.StatusInternalServerError) @@ -50,8 +58,8 @@ func handleNodeRequest(w http.ResponseWriter, r *http.Request) { return } - if msg.ID != connCode { - http.Error(w, "Authentication failed", http.StatusUnauthorized) + if !isAuthenticated(msg.ID) { + http.Error(w, "Authentication required", http.StatusUnauthorized) return } @@ -59,17 +67,55 @@ func handleNodeRequest(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Message received") } +func handleAuth(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) + return + } + + body, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error reading request body", http.StatusInternalServerError) + return + } + defer r.Body.Close() + + var authRequest CrawlerConfig + if err := json.Unmarshal(body, &authRequest); err != nil { + http.Error(w, "Error parsing JSON", http.StatusBadRequest) + return + } + + expectedCode := GenerateRegistrationCode(authRequest.Host, authRequest.Port, authCode) + if authRequest.AuthCode != expectedCode { + http.Error(w, "Invalid auth code", http.StatusUnauthorized) + return + } + + authMutex.Lock() + authenticated[authRequest.ID] = true + authMutex.Unlock() + + fmt.Fprintln(w, "Authenticated successfully") +} + +func isAuthenticated(id string) bool { + authMutex.Lock() + defer authMutex.Unlock() + return authenticated[id] +} + func interpretMessage(msg Message) { switch msg.Type { case "test": fmt.Println("Received test message:", msg.Content) - case "get-version": - fmt.Println("Received get-version message") - // Handle get-version logic here case "update": fmt.Println("Received update message:", msg.Content) - // Handle update logic here go update() + case "heartbeat": + handleHeartbeat(msg.Content) + case "election": + handleElection(msg.Content) default: fmt.Println("Received unknown message type:", msg.Type) } @@ -111,7 +157,7 @@ func startNodeClient(addresses []string) { for _, address := range addresses { go func(addr string) { for { - err := sendMessage(addr, connCode, "test", "This is a test message") + err := sendMessage(addr, authCode, "test", "This is a test message") if err != nil { fmt.Println("Error sending test message to", addr, ":", err) continue @@ -121,3 +167,24 @@ func startNodeClient(addresses []string) { }(address) } } + +func GenerateRegistrationCode(host string, port int, authCode string) string { + data := fmt.Sprintf("%s:%d:%s", host, port, authCode) + hash := sha256.Sum256([]byte(data)) + return hex.EncodeToString(hash[:]) +} + +func ParseRegistrationCode(code string, host string, port int, authCode string) (string, int, string, error) { + data := fmt.Sprintf("%s:%d:%s", host, port, authCode) + hash := sha256.Sum256([]byte(data)) + expectedCode := hex.EncodeToString(hash[:]) + + log.Printf("Parsing registration code: %s", code) + log.Printf("Expected registration code: %s", expectedCode) + + if expectedCode != code { + return "", 0, "", fmt.Errorf("invalid registration code") + } + + return host, port, authCode, nil +} -- 2.40.1 From faa20dc064541eedc978f58a29ea62e59665eefa Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 13:35:50 +0200 Subject: [PATCH 04/34] code auth added --- init.go | 18 ++++- main.go | 30 ++++---- node-master.go | 14 +++- node-update.go | 15 ++-- node.go | 195 ++++++++++++++++++++----------------------------- 5 files changed, 127 insertions(+), 145 deletions(-) diff --git a/init.go b/init.go index b3df270..91ffd05 100644 --- a/init.go +++ b/init.go @@ -11,15 +11,16 @@ import ( "strconv" "strings" "sync" + "time" "github.com/fsnotify/fsnotify" ) -// Configuration structure type Config struct { Port int AuthCode string Peers []string + PeerID string OpenSearch OpenSearchConfig } @@ -27,7 +28,6 @@ type OpenSearchConfig struct { Domain string } -// Default configuration values var defaultConfig = Config{ Port: 5000, OpenSearch: OpenSearchConfig{ @@ -57,11 +57,21 @@ func main() { saveConfig(config) } + // Initialize P2P + var nodeErr error + hostID, nodeErr = initP2P() + if nodeErr != nil { + log.Fatalf("Failed to initialize P2P: %v", nodeErr) + } + config.PeerID = hostID.String() + if len(config.Peers) > 0 { - go startNodeClient(config.Peers) + time.Sleep(2 * time.Second) // Give some time for connections to establish startElection() } + go startNodeClient() + runServer() } @@ -103,7 +113,7 @@ func createConfig() error { fmt.Print("Do you want to connect to other nodes? (yes/no): ") connectNodes, _ := reader.ReadString('\n') if strings.TrimSpace(connectNodes) == "yes" { - fmt.Println("Enter peer addresses (comma separated, e.g., http://localhost:5000,http://localhost:5001): ") + fmt.Println("Enter peer addresses (comma separated, e.g., /ip4/127.0.0.1/tcp/5000,/ip4/127.0.0.1/tcp/5001): ") peersStr, _ := reader.ReadString('\n') if peersStr != "\n" { config.Peers = strings.Split(strings.TrimSpace(peersStr), ",") diff --git a/main.go b/main.go index 0d9ac33..f79eef2 100644 --- a/main.go +++ b/main.go @@ -122,20 +122,19 @@ func parsePageParameter(pageStr string) int { } 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("/opensearch.xml", func(w http.ResponseWriter, r *http.Request) { - // w.Header().Set("Content-Type", "application/opensearchdescription+xml") - // http.ServeFile(w, r, "static/opensearch.xml") - // }) - // initializeTorrentSites() - - http.HandleFunc("/node", handleNodeRequest) // Handle node requests + 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("/node", handleNodeRequest) + http.HandleFunc("/settings", func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, "templates/settings.html") + }) + 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") + }) + initializeTorrentSites() config := loadConfig() generateOpenSearchXML(config) @@ -143,9 +142,6 @@ func runServer() { fmt.Printf("Server is listening on http://localhost:%d\n", config.Port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil)) - // Start node communication client - go startNodeClient(peers) - // Start automatic update checker go checkForUpdates() } diff --git a/node-master.go b/node-master.go index 4f5155b..0cfa7ae 100644 --- a/node-master.go +++ b/node-master.go @@ -24,7 +24,12 @@ func sendHeartbeats() { return } for _, node := range peers { - err := sendMessage(node, authCode, "heartbeat", authCode) + msg := Message{ + ID: hostID.Pretty(), + Type: "heartbeat", + Content: authCode, + } + err := sendMessage(node, msg) if err != nil { log.Printf("Error sending heartbeat to %s: %v", node, err) } @@ -55,7 +60,12 @@ func startElection() { defer masterNodeMux.Unlock() for _, node := range peers { - err := sendMessage(node, authCode, "election", authCode) + msg := Message{ + ID: hostID.Pretty(), + Type: "election", + Content: authCode, + } + err := sendMessage(node, msg) if err != nil { log.Printf("Error sending election message to %s: %v", node, err) } diff --git a/node-update.go b/node-update.go index 0ef63f6..555b16a 100644 --- a/node-update.go +++ b/node-update.go @@ -9,14 +9,19 @@ import ( // Function to sync updates across all nodes func nodeUpdateSync() { fmt.Println("Syncing updates across all nodes...") - for _, peer := range peers { - fmt.Printf("Notifying node %s about update...\n", peer) - err := sendMessage(peer, authCode, "update", "Start update process") + for _, peerAddr := range peers { + fmt.Printf("Notifying node %s about update...\n", peerAddr) + msg := Message{ + ID: hostID.Pretty(), + Type: "update", + Content: "Start update process", + } + err := sendMessage(peerAddr, msg) if err != nil { - log.Printf("Failed to notify node %s: %v\n", peer, err) + log.Printf("Failed to notify node %s: %v\n", peerAddr, err) continue } - fmt.Printf("Node %s notified. Waiting for it to update...\n", peer) + 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.") diff --git a/node.go b/node.go index 97862c7..a397c78 100644 --- a/node.go +++ b/node.go @@ -2,8 +2,7 @@ package main import ( "bytes" - "crypto/sha256" - "encoding/hex" + "crypto/rand" "encoding/json" "fmt" "io/ioutil" @@ -11,6 +10,10 @@ import ( "net/http" "sync" "time" + + libp2p "github.com/libp2p/go-libp2p" + crypto "github.com/libp2p/go-libp2p-core/crypto" + "github.com/libp2p/go-libp2p-core/peer" ) var ( @@ -18,6 +21,7 @@ var ( peers []string authMutex sync.Mutex authenticated = make(map[string]bool) + hostID peer.ID ) type Message struct { @@ -35,74 +39,99 @@ type CrawlerConfig struct { func loadNodeConfig() { config := loadConfig() - authCode = config.AuthCode // nuh uh + authCode = config.AuthCode peers = config.Peers } +func initP2P() (peer.ID, error) { + priv, _, err := crypto.GenerateKeyPairWithReader(crypto.Ed25519, 2048, rand.Reader) + if err != nil { + return "", fmt.Errorf("failed to generate key pair: %v", err) + } + + h, err := libp2p.New(libp2p.Identity(priv)) + if err != nil { + return "", fmt.Errorf("failed to create libp2p host: %v", err) + } + + return h.ID(), nil +} + +func sendMessage(serverAddr string, msg Message) error { + 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 } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - http.Error(w, "Error reading request body", http.StatusInternalServerError) + auth := r.Header.Get("Authorization") + if auth != authCode { + http.Error(w, "Unauthorized", http.StatusUnauthorized) return } - defer r.Body.Close() var msg Message - if err := json.Unmarshal(body, &msg); err != nil { - http.Error(w, "Error parsing JSON", http.StatusBadRequest) - return - } - - if !isAuthenticated(msg.ID) { - http.Error(w, "Authentication required", http.StatusUnauthorized) - return - } - - interpretMessage(msg) - fmt.Fprintln(w, "Message received") -} - -func handleAuth(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) - return - } - - body, err := ioutil.ReadAll(r.Body) + err := json.NewDecoder(r.Body).Decode(&msg) if err != nil { - http.Error(w, "Error reading request body", http.StatusInternalServerError) + http.Error(w, "Error parsing JSON", http.StatusBadRequest) return } defer r.Body.Close() - var authRequest CrawlerConfig - if err := json.Unmarshal(body, &authRequest); err != nil { - http.Error(w, "Error parsing JSON", http.StatusBadRequest) - return - } + log.Printf("Received message: %+v\n", msg) + w.Write([]byte("Message received")) - expectedCode := GenerateRegistrationCode(authRequest.Host, authRequest.Port, authCode) - if authRequest.AuthCode != expectedCode { - http.Error(w, "Invalid auth code", http.StatusUnauthorized) - return - } - - authMutex.Lock() - authenticated[authRequest.ID] = true - authMutex.Unlock() - - fmt.Fprintln(w, "Authenticated successfully") + interpretMessage(msg) } -func isAuthenticated(id string) bool { - authMutex.Lock() - defer authMutex.Unlock() - return authenticated[id] +func startNodeClient() { + for { + for _, peerAddr := range peers { + msg := Message{ + ID: hostID.Pretty(), + Type: "test", + Content: "This is a test message from the client node", + } + + err := sendMessage(peerAddr, msg) + if err != nil { + log.Printf("Error sending message to %s: %v", peerAddr, err) + } else { + log.Println("Message sent successfully to", peerAddr) + } + } + time.Sleep(10 * time.Second) + } } func interpretMessage(msg Message) { @@ -120,71 +149,3 @@ func interpretMessage(msg Message) { fmt.Println("Received unknown message type:", msg.Type) } } - -func sendMessage(address, id, msgType, content string) error { - msg := Message{ - ID: id, - Type: msgType, - Content: content, - } - msgBytes, err := json.Marshal(msg) - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/node", address), bytes.NewBuffer(msgBytes)) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json") - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - body, _ := ioutil.ReadAll(resp.Body) - return fmt.Errorf("failed to send message: %s", body) - } - - return nil -} - -func startNodeClient(addresses []string) { - for _, address := range addresses { - go func(addr string) { - for { - err := sendMessage(addr, authCode, "test", "This is a test message") - if err != nil { - fmt.Println("Error sending test message to", addr, ":", err) - continue - } - time.Sleep(10 * time.Second) - } - }(address) - } -} - -func GenerateRegistrationCode(host string, port int, authCode string) string { - data := fmt.Sprintf("%s:%d:%s", host, port, authCode) - hash := sha256.Sum256([]byte(data)) - return hex.EncodeToString(hash[:]) -} - -func ParseRegistrationCode(code string, host string, port int, authCode string) (string, int, string, error) { - data := fmt.Sprintf("%s:%d:%s", host, port, authCode) - hash := sha256.Sum256([]byte(data)) - expectedCode := hex.EncodeToString(hash[:]) - - log.Printf("Parsing registration code: %s", code) - log.Printf("Expected registration code: %s", expectedCode) - - if expectedCode != code { - return "", 0, "", fmt.Errorf("invalid registration code") - } - - return host, port, authCode, nil -} -- 2.40.1 From ea3092011aa66b6b150a4a1ae9704f9bf1fbdda0 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 13:44:13 +0200 Subject: [PATCH 05/34] remove "libcrypto" since it was not really used --- init.go | 9 ++++----- node.go | 23 +++++++---------------- 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/init.go b/init.go index 91ffd05..8872f57 100644 --- a/init.go +++ b/init.go @@ -57,13 +57,12 @@ func main() { saveConfig(config) } - // Initialize P2P - var nodeErr error - hostID, nodeErr = initP2P() + // Generate Host ID + hostID, nodeErr := generateHostID() if nodeErr != nil { - log.Fatalf("Failed to initialize P2P: %v", nodeErr) + log.Fatalf("Failed to generate host ID: %v", nodeErr) } - config.PeerID = hostID.String() + config.PeerID = hostID if len(config.Peers) > 0 { time.Sleep(2 * time.Second) // Give some time for connections to establish diff --git a/node.go b/node.go index a397c78..ed1d86f 100644 --- a/node.go +++ b/node.go @@ -10,10 +10,6 @@ import ( "net/http" "sync" "time" - - libp2p "github.com/libp2p/go-libp2p" - crypto "github.com/libp2p/go-libp2p-core/crypto" - "github.com/libp2p/go-libp2p-core/peer" ) var ( @@ -21,7 +17,7 @@ var ( peers []string authMutex sync.Mutex authenticated = make(map[string]bool) - hostID peer.ID + hostID string ) type Message struct { @@ -43,18 +39,13 @@ func loadNodeConfig() { peers = config.Peers } -func initP2P() (peer.ID, error) { - priv, _, err := crypto.GenerateKeyPairWithReader(crypto.Ed25519, 2048, rand.Reader) +func generateHostID() (string, error) { + bytes := make([]byte, 16) + _, err := rand.Read(bytes) if err != nil { - return "", fmt.Errorf("failed to generate key pair: %v", err) + return "", fmt.Errorf("failed to generate host ID: %v", err) } - - h, err := libp2p.New(libp2p.Identity(priv)) - if err != nil { - return "", fmt.Errorf("failed to create libp2p host: %v", err) - } - - return h.ID(), nil + return fmt.Sprintf("%x", bytes), nil } func sendMessage(serverAddr string, msg Message) error { @@ -118,7 +109,7 @@ func startNodeClient() { for { for _, peerAddr := range peers { msg := Message{ - ID: hostID.Pretty(), + ID: hostID, Type: "test", Content: "This is a test message from the client node", } -- 2.40.1 From 77e1d0681da3e34302328bb09b33e871597f1b90 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 13:48:18 +0200 Subject: [PATCH 06/34] fix error on run --- node-master.go | 4 ++-- node-update.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/node-master.go b/node-master.go index 0cfa7ae..133f72e 100644 --- a/node-master.go +++ b/node-master.go @@ -25,7 +25,7 @@ func sendHeartbeats() { } for _, node := range peers { msg := Message{ - ID: hostID.Pretty(), + ID: hostID, Type: "heartbeat", Content: authCode, } @@ -61,7 +61,7 @@ func startElection() { for _, node := range peers { msg := Message{ - ID: hostID.Pretty(), + ID: hostID, Type: "election", Content: authCode, } diff --git a/node-update.go b/node-update.go index 555b16a..f433eb4 100644 --- a/node-update.go +++ b/node-update.go @@ -12,7 +12,7 @@ func nodeUpdateSync() { for _, peerAddr := range peers { fmt.Printf("Notifying node %s about update...\n", peerAddr) msg := Message{ - ID: hostID.Pretty(), + ID: hostID, Type: "update", Content: "Start update process", } -- 2.40.1 From d723b4615b8b585053126f120224654ac4818610 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 15:03:33 +0200 Subject: [PATCH 07/34] change .json to .ini --- .gitignore | 3 +- go.mod | 5 ++- go.sum | 2 + init.go | 99 +++++++++++++++++++++++++------------------------- open-search.go | 2 +- 5 files changed, 59 insertions(+), 52 deletions(-) diff --git a/.gitignore b/.gitignore index 0034634..41819de 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ config.json -opensearch.xml \ No newline at end of file +opensearch.xml +config.ini \ No newline at end of file diff --git a/go.mod b/go.mod index 5dcd6b3..f6755b1 100644 --- a/go.mod +++ b/go.mod @@ -22,4 +22,7 @@ require ( golang.org/x/time v0.5.0 // indirect ) -require github.com/fsnotify/fsnotify v1.7.0 // indirect +require ( + github.com/fsnotify/fsnotify v1.7.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect +) diff --git a/go.sum b/go.sum index 732af13..7fab23f 100644 --- a/go.sum +++ b/go.sum @@ -71,3 +71,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= diff --git a/init.go b/init.go index 8872f57..915bd3c 100644 --- a/init.go +++ b/init.go @@ -4,7 +4,6 @@ import ( "bufio" "crypto/rand" "encoding/base64" - "encoding/json" "fmt" "log" "os" @@ -14,28 +13,23 @@ import ( "time" "github.com/fsnotify/fsnotify" + "gopkg.in/ini.v1" ) type Config struct { - Port int - AuthCode string - Peers []string - PeerID string - OpenSearch OpenSearchConfig -} - -type OpenSearchConfig struct { - Domain string + Port int + AuthCode string + Peers []string + PeerID string + Domain string } var defaultConfig = Config{ - Port: 5000, - OpenSearch: OpenSearchConfig{ - Domain: "localhost", - }, + Port: 5000, + Domain: "localhost", } -const configFilePath = "config.json" +const configFilePath = "config.ini" var config Config var configLock sync.RWMutex @@ -91,33 +85,25 @@ func createConfig() error { fmt.Print("Do you want to use default values? (yes/no): ") useDefaults, _ := reader.ReadString('\n') - config := defaultConfig - if useDefaults != "yes\n" { + if strings.TrimSpace(useDefaults) != "yes" { fmt.Print("Enter port (default 5000): ") portStr, _ := reader.ReadString('\n') if portStr != "\n" { - port, err := strconv.Atoi(portStr[:len(portStr)-1]) + port, err := strconv.Atoi(strings.TrimSpace(portStr)) if err != nil { - return err + config.Port = 5000 + } else { + config.Port = port } - config.Port = port } - fmt.Print("Enter your domain address (e.g., domain.com): ") + fmt.Print("Enter your domain address (default localhost): ") domain, _ := reader.ReadString('\n') if domain != "\n" { - config.OpenSearch.Domain = domain[:len(domain)-1] - } - - fmt.Print("Do you want to connect to other nodes? (yes/no): ") - connectNodes, _ := reader.ReadString('\n') - if strings.TrimSpace(connectNodes) == "yes" { - fmt.Println("Enter peer addresses (comma separated, e.g., /ip4/127.0.0.1/tcp/5000,/ip4/127.0.0.1/tcp/5001): ") - peersStr, _ := reader.ReadString('\n') - if peersStr != "\n" { - config.Peers = strings.Split(strings.TrimSpace(peersStr), ",") - } + config.Domain = strings.TrimSpace(domain) } + } else { + config = defaultConfig } if config.AuthCode == "" { @@ -130,35 +116,50 @@ func createConfig() error { } func saveConfig(config Config) { - file, err := os.Create(configFilePath) - if err != nil { - fmt.Println("Error creating config file:", err) - return - } - defer file.Close() + 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) - configData, err := json.MarshalIndent(config, "", " ") - if err != nil { - fmt.Println("Error marshalling config data:", err) - return - } + peers := strings.Join(config.Peers, ",") + sec.Key("Peers").SetValue(peers) + sec.Key("Domain").SetValue(config.Domain) - _, err = file.Write(configData) + err := cfg.SaveTo(configFilePath) if err != nil { fmt.Println("Error writing to config file:", err) } } func loadConfig() Config { - configFile, err := os.Open(configFilePath) + cfg, err := ini.Load(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) + 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, ",") + } + + domain := cfg.Section("").Key("Domain").String() + if domain == "" { + domain = "localhost" // Default to localhost if not set + } + + config = Config{ + Port: port, + AuthCode: cfg.Section("").Key("AuthCode").String(), + PeerID: cfg.Section("").Key("PeerID").String(), + Peers: peers, + Domain: domain, } return config diff --git a/open-search.go b/open-search.go index b685e42..2d5d0b4 100644 --- a/open-search.go +++ b/open-search.go @@ -28,7 +28,7 @@ func generateOpenSearchXML(config Config) { Tags: "search, engine", URL: URL{ Type: "text/html", - Template: fmt.Sprintf("https://%s/search?q={searchTerms}", config.OpenSearch.Domain), + Template: fmt.Sprintf("https://%s/search?q={searchTerms}", config.Domain), }, } -- 2.40.1 From db96868edd2d4b5526927b45ba4aa3fa3052a06d Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 15:05:05 +0200 Subject: [PATCH 08/34] update open-search --- open-search.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/open-search.go b/open-search.go index 2d5d0b4..138020f 100644 --- a/open-search.go +++ b/open-search.go @@ -4,6 +4,7 @@ import ( "encoding/xml" "fmt" "os" + "strings" ) type OpenSearchDescription struct { @@ -20,7 +21,17 @@ type URL struct { Template string `xml:"template,attr"` } +// isLocalAddress 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.") +} + func generateOpenSearchXML(config Config) { + protocol := "https://" + if isLocalAddress(config.Domain) { + protocol = "http://" + } + opensearch := OpenSearchDescription{ Xmlns: "http://a9.com/-/spec/opensearch/1.1/", ShortName: "Ocásek", @@ -28,7 +39,7 @@ func generateOpenSearchXML(config Config) { Tags: "search, engine", URL: URL{ Type: "text/html", - Template: fmt.Sprintf("https://%s/search?q={searchTerms}", config.Domain), + Template: fmt.Sprintf("%s%s/search?q={searchTerms}", protocol, config.Domain), }, } -- 2.40.1 From 17589d51e5d052def86215e8301e71419130a5ba Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 13:49:06 +0000 Subject: [PATCH 09/34] Update README.md --- README.md | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index e0df49c..0f55f01 100644 --- a/README.md +++ b/README.md @@ -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,30 +18,35 @@ - [ ] 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. +| Name | Works without JavaScript | Music search | Torrent search | API | Scalable | Not Resource Hungry | Dynamic Page Loading | +| ------------- | ------------------ | --------------------------- | ----------------- | ------ | ------------------- | ---------------------------------------------- | ---------------------- | +| Whoogle [1] | ✅ | ❓ | ❌ | ❌ | ❌ | ❓ Moderate | ❓ Not specified | +| Araa-Search | ✅ | ❌ | ✅ | ✅ [2] | ❌ | ❌ Very resource hungry | ❌ | +| LibreY | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ Moderate 200-400mb~ | ❌ | +| 4get | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ Moderate 200-400mb~ | ❌ | +| Warp | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ about 15-20MiB at idle, 17-22MiB when searching | ✅ | + +[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. +- Text search using Google, Brave, DuckDuckGo and LibreX/Y. - Image search using the Qwant/Imgur. - Video search using Piped API. - Image viewing using proxy and direct links to image source pages for image searches. -- 2.40.1 From 283096d2999ded96c1576226f640ace2560f2828 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 16:23:36 +0200 Subject: [PATCH 10/34] stupid proofing missing "http" in config file --- open-search.go | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/open-search.go b/open-search.go index 138020f..f6214a5 100644 --- a/open-search.go +++ b/open-search.go @@ -21,25 +21,38 @@ type URL struct { Template string `xml:"template,attr"` } -// isLocalAddress checks if the domain is a local address +// 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.") } -func generateOpenSearchXML(config Config) { - protocol := "https://" - if isLocalAddress(config.Domain) { - protocol = "http://" +// 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 +} + +func generateOpenSearchXML(config Config) { + baseURL := addProtocol(config.Domain) opensearch := OpenSearchDescription{ Xmlns: "http://a9.com/-/spec/opensearch/1.1/", - ShortName: "Ocásek", + ShortName: "Search Engine", Description: "Search engine", Tags: "search, engine", URL: URL{ Type: "text/html", - Template: fmt.Sprintf("%s%s/search?q={searchTerms}", protocol, config.Domain), + Template: fmt.Sprintf("%s/search?q={searchTerms}", baseURL), }, } -- 2.40.1 From f31886d7159dea96ccf1aafa016718b51ab7929c Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 16:49:30 +0200 Subject: [PATCH 11/34] clean up --- common.go | 34 +++++++++++ config.go | 149 ++++++++++++++++++++++++++++++++++++++++++++++++ init.go | 151 ------------------------------------------------- open-search.go | 22 ------- 4 files changed, 183 insertions(+), 173 deletions(-) create mode 100644 config.go diff --git a/common.go b/common.go index 7d30861..4a0beae 100644 --- a/common.go +++ b/common.go @@ -1,7 +1,11 @@ package main import ( + "crypto/rand" + "encoding/base64" "html/template" + "log" + "strings" ) var ( @@ -15,3 +19,33 @@ var ( }, } ) + +func generateStrongRandomString(length int) string { + bytes := make([]byte, length) + _, err := rand.Read(bytes) + if err != nil { + log.Fatalf("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 +} diff --git a/config.go b/config.go new file mode 100644 index 0000000..a004359 --- /dev/null +++ b/config.go @@ -0,0 +1,149 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "os" + "strconv" + "strings" + + "github.com/fsnotify/fsnotify" + "gopkg.in/ini.v1" +) + +func initConfig() error { + if _, err := os.Stat(configFilePath); os.IsNotExist(err) { + return createConfig() + } + + fmt.Println("Configuration file already exists.") + config = loadConfig() + 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') + + if strings.TrimSpace(useDefaults) != "yes" { + fmt.Print("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 + } + } + + fmt.Print("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) + fmt.Printf("Generated connection code: %s\n", config.AuthCode) + } + + 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) + + err := cfg.SaveTo(configFilePath) + if err != nil { + fmt.Println("Error writing to config file:", err) + } +} + +func loadConfig() Config { + cfg, err := ini.Load(configFilePath) + if err != nil { + log.Fatalf("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 + } + + config = Config{ + Port: port, + AuthCode: cfg.Section("").Key("AuthCode").String(), + PeerID: cfg.Section("").Key("PeerID").String(), + Peers: peers, + Domain: domain, + } + + return config +} + +func startFileWatcher() { + watcher, err := fsnotify.NewWatcher() + if err != nil { + log.Fatal(err) + } + + go func() { + defer watcher.Close() + for { + select { + case event, ok := <-watcher.Events: + if !ok { + return + } + if event.Op&fsnotify.Write == fsnotify.Write { + log.Println("Modified file:", event.Name) + configLock.Lock() + config = loadConfig() + configLock.Unlock() + // Perform your logic here to handle the changes in the config file + } + case err, ok := <-watcher.Errors: + if !ok { + return + } + log.Println("Error:", err) + } + } + }() + + err = watcher.Add(configFilePath) + if err != nil { + log.Fatal(err) + } +} diff --git a/init.go b/init.go index 915bd3c..c807cfe 100644 --- a/init.go +++ b/init.go @@ -1,19 +1,10 @@ package main import ( - "bufio" - "crypto/rand" - "encoding/base64" "fmt" "log" - "os" - "strconv" - "strings" "sync" "time" - - "github.com/fsnotify/fsnotify" - "gopkg.in/ini.v1" ) type Config struct { @@ -67,145 +58,3 @@ func main() { runServer() } - -func initConfig() error { - if _, err := os.Stat(configFilePath); os.IsNotExist(err) { - return createConfig() - } - - fmt.Println("Configuration file already exists.") - config = loadConfig() - 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') - - if strings.TrimSpace(useDefaults) != "yes" { - fmt.Print("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 - } - } - - fmt.Print("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) - fmt.Printf("Generated connection code: %s\n", config.AuthCode) - } - - 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) - - err := cfg.SaveTo(configFilePath) - if err != nil { - fmt.Println("Error writing to config file:", err) - } -} - -func loadConfig() Config { - cfg, err := ini.Load(configFilePath) - if err != nil { - log.Fatalf("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, ",") - } - - domain := cfg.Section("").Key("Domain").String() - if domain == "" { - domain = "localhost" // Default to localhost if not set - } - - config = Config{ - Port: port, - AuthCode: cfg.Section("").Key("AuthCode").String(), - PeerID: cfg.Section("").Key("PeerID").String(), - Peers: peers, - Domain: domain, - } - - return config -} - -func generateStrongRandomString(length int) string { - bytes := make([]byte, length) - _, err := rand.Read(bytes) - if err != nil { - log.Fatalf("Error generating random string: %v", err) - } - return base64.URLEncoding.EncodeToString(bytes)[:length] -} - -func startFileWatcher() { - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - - go func() { - defer watcher.Close() - for { - select { - case event, ok := <-watcher.Events: - if !ok { - return - } - if event.Op&fsnotify.Write == fsnotify.Write { - log.Println("Modified file:", event.Name) - configLock.Lock() - config = loadConfig() - configLock.Unlock() - // Perform your logic here to handle the changes in the config file - } - case err, ok := <-watcher.Errors: - if !ok { - return - } - log.Println("Error:", err) - } - } - }() - - err = watcher.Add(configFilePath) - if err != nil { - log.Fatal(err) - } -} diff --git a/open-search.go b/open-search.go index f6214a5..86d7e4e 100644 --- a/open-search.go +++ b/open-search.go @@ -4,7 +4,6 @@ import ( "encoding/xml" "fmt" "os" - "strings" ) type OpenSearchDescription struct { @@ -21,27 +20,6 @@ type URL struct { Template string `xml:"template,attr"` } -// 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 -} - func generateOpenSearchXML(config Config) { baseURL := addProtocol(config.Domain) -- 2.40.1 From b9f02e9d1e1cf2d4f2a4934620d21c6908469d04 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 21:59:10 +0200 Subject: [PATCH 12/34] wip search requests to other nodes --- config.go | 3 +- files.go | 6 ++ forums.go | 87 +++++++++++++++++++- node-handle-search.go | 183 +++++++++++++++++++++++++++++++++++++++++ node-request-search.go | 80 ++++++++++++++++++ node.go | 23 ++++++ video.go | 38 ++++++++- 7 files changed, 411 insertions(+), 9 deletions(-) create mode 100644 node-handle-search.go create mode 100644 node-request-search.go diff --git a/config.go b/config.go index a004359..d2a0857 100644 --- a/config.go +++ b/config.go @@ -131,13 +131,12 @@ func startFileWatcher() { configLock.Lock() config = loadConfig() configLock.Unlock() - // Perform your logic here to handle the changes in the config file } case err, ok := <-watcher.Errors: if !ok { return } - log.Println("Error:", err) + log.Println("Error watching configuration file:", err) } } }() diff --git a/files.go b/files.go index bce60b0..1ef1276 100644 --- a/files.go +++ b/files.go @@ -146,6 +146,12 @@ func fetchAndCacheFileResults(query, safe, lang string, page int) []TorrentResul return results } +func fetchFileResults(query, safe, lang string, page int) []TorrentResult { + cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "file"} + results := getFileResultsFromCacheOrFetch(cacheKey, query, safe, lang, page) + return results +} + func removeMagnetLink(magnet string) string { // Remove the magnet: prefix unconditionally return strings.TrimPrefix(magnet, "magnet:") diff --git a/forums.go b/forums.go index dc32012..7f13fed 100644 --- a/forums.go +++ b/forums.go @@ -4,12 +4,15 @@ import ( "encoding/json" "fmt" "html/template" + "log" "math" "net/http" "net/url" "time" ) +var resultsChan = make(chan []ForumSearchResult) + func PerformRedditSearch(query string, safe string, page int) ([]ForumSearchResult, error) { const ( pageSize = 25 @@ -99,9 +102,9 @@ func PerformRedditSearch(query string, safe string, page int) ([]ForumSearchResu 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 + if err != nil || len(results) == 0 || 0 == 0 { // 0 == 0 to force search by other node + log.Printf("No results from primary search, trying other nodes") + results = tryOtherNodesForForumSearch(query, safe, lang, page) } data := struct { @@ -137,3 +140,81 @@ func handleForumsSearch(w http.ResponseWriter, query, safe, lang string, page in http.Error(w, fmt.Sprintf("Error rendering template: %v", err), http.StatusInternalServerError) } } + +func tryOtherNodesForForumSearch(query, safe, lang string, page int) []ForumSearchResult { + for _, nodeAddr := range peers { + results, err := sendSearchRequestToNode(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 sendSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]ForumSearchResult, 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-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 := <-resultsChan: + return res, nil + case <-time.After(20 * time.Second): // Increased timeout duration + 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 { + log.Printf("Error unmarshalling forum results: %v", err) + return + } + + log.Printf("Received forum results: %+v", results) + // Send results to resultsChan + go func() { + resultsChan <- results + }() +} + +func fetchForumResults(query, safe, lang string, page int) []ForumSearchResult { + results, err := PerformRedditSearch(query, safe, page) + if err != nil { + log.Printf("Error fetching forum results: %v", err) + return nil + } + return results +} diff --git a/node-handle-search.go b/node-handle-search.go new file mode 100644 index 0000000..248adba --- /dev/null +++ b/node-handle-search.go @@ -0,0 +1,183 @@ +package main + +import ( + "encoding/json" + "log" + "sync" +) + +var ( + forumResults = make(map[string][]ForumSearchResult) + forumResultsMutex sync.Mutex +) + +func handleSearchTextMessage(msg Message) { + var searchParams struct { + Query string `json:"query"` + Safe string `json:"safe"` + Lang string `json:"lang"` + Page int `json:"page"` + } + err := json.Unmarshal([]byte(msg.Content), &searchParams) + if err != nil { + log.Printf("Error parsing search parameters: %v", err) + return + } + + results := fetchTextResults(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: "search-results", + Content: string(resultsJSON), + } + + err = sendMessage(msg.ID, responseMsg) + if err != nil { + log.Printf("Error sending search results to %s: %v", msg.ID, err) + } +} + +func handleSearchImageMessage(msg Message) { + var searchParams struct { + Query string `json:"query"` + Safe string `json:"safe"` + Lang string `json:"lang"` + Page int `json:"page"` + } + err := json.Unmarshal([]byte(msg.Content), &searchParams) + if err != nil { + log.Printf("Error parsing search parameters: %v", err) + return + } + + 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), + } + + err = sendMessage(msg.ID, responseMsg) + if err != nil { + log.Printf("Error sending image search results to %s: %v", msg.ID, err) + } +} + +func handleSearchVideoMessage(msg Message) { + var searchParams struct { + Query string `json:"query"` + Safe string `json:"safe"` + Lang string `json:"lang"` + Page int `json:"page"` + } + err := json.Unmarshal([]byte(msg.Content), &searchParams) + if err != nil { + log.Printf("Error parsing search parameters: %v", err) + return + } + + 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), + } + + err = sendMessage(msg.ID, responseMsg) + if err != nil { + log.Printf("Error sending video search results to %s: %v", msg.ID, err) + } +} + +func handleSearchFileMessage(msg Message) { + var searchParams struct { + Query string `json:"query"` + Safe string `json:"safe"` + Lang string `json:"lang"` + Page int `json:"page"` + } + err := json.Unmarshal([]byte(msg.Content), &searchParams) + if err != nil { + log.Printf("Error parsing search parameters: %v", err) + return + } + + 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), + } + + err = sendMessage(msg.ID, responseMsg) + if err != nil { + log.Printf("Error sending file search results to %s: %v", msg.ID, 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) + } +} diff --git a/node-request-search.go b/node-request-search.go new file mode 100644 index 0000000..18cf03b --- /dev/null +++ b/node-request-search.go @@ -0,0 +1,80 @@ +package main + +import ( + "encoding/json" +) + +// func sendSearchRequestToNode(nodeAddr, query, safe, lang string, page int, requestID string) ([]ForumSearchResult, 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: "http://localhost:5000/node", // Node 1's address +// } + +// msg := Message{ +// ID: requestID, +// Type: "search-forum", +// Content: toJSON(searchParams), +// } + +// msgBytes, err := json.Marshal(msg) +// if err != nil { +// return nil, fmt.Errorf("failed to marshal search request: %v", err) +// } + +// req, err := http.NewRequest("POST", nodeAddr, bytes.NewBuffer(msgBytes)) +// if err != nil { +// return nil, fmt.Errorf("failed to create search 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 nil, fmt.Errorf("failed to send search request: %v", err) +// } +// defer resp.Body.Close() + +// if resp.StatusCode != http.StatusOK { +// body, _ := ioutil.ReadAll(resp.Body) +// return nil, fmt.Errorf("server error: %s", body) +// } + +// var responseMsg Message +// err = json.NewDecoder(resp.Body).Decode(&responseMsg) +// if err != nil { +// return nil, fmt.Errorf("failed to decode search response: %v", err) +// } + +// if responseMsg.Type != "forum-results" { +// return nil, fmt.Errorf("unexpected message type: %s", responseMsg.Type) +// } + +// var results []ForumSearchResult +// err = json.Unmarshal([]byte(responseMsg.Content), &results) +// if err != nil { +// return nil, fmt.Errorf("failed to unmarshal search results: %v", err) +// } + +// return results, nil +// } + +func toJSON(v interface{}) string { + data, err := json.Marshal(v) + if err != nil { + return "" + } + return string(data) +} diff --git a/node.go b/node.go index ed1d86f..5fe0774 100644 --- a/node.go +++ b/node.go @@ -49,6 +49,10 @@ func generateHostID() (string, error) { } 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) @@ -136,7 +140,26 @@ func interpretMessage(msg Message) { 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": + log.Println("Received search-forum message:", msg.Content) + handleSearchForumMessage(msg) + case "forum-results": + handleForumResultsMessage(msg) default: fmt.Println("Received unknown message type:", msg.Type) } } + +func generateRequestID() string { + bytes := make([]byte, 16) + rand.Read(bytes) + return fmt.Sprintf("%x", bytes) +} diff --git a/video.go b/video.go index 4aa1ec3..36d0613 100644 --- a/video.go +++ b/video.go @@ -188,10 +188,10 @@ func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int } err = tmpl.Execute(w, map[string]interface{}{ - "Results": results, - "Query": query, - "Fetched": fmt.Sprintf("%.2f seconds", elapsed.Seconds()), - "Page": page, + "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 }) @@ -200,3 +200,33 @@ func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int 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 { + log.Printf("Error fetching video results: %v", err) + return nil + } + + var results []VideoResult + for _, item := range apiResp.Items { + if item.Type == "channel" || item.Type == "playlist" { + continue + } + if item.UploadedDate == "" { + item.UploadedDate = "Now" + } + + results = append(results, VideoResult{ + Href: fmt.Sprintf("https://youtube.com%s", item.URL), + Title: item.Title, + Date: item.UploadedDate, + Views: formatViews(item.Views), + Creator: item.UploaderName, + Publisher: "Piped", + Image: fmt.Sprintf("/img_proxy?url=%s", url.QueryEscape(item.Thumbnail)), + Duration: formatDuration(item.Duration), + }) + } + return results +} -- 2.40.1 From 84bf55ab24de50bd9d9f5734cacb3c5d3f2d0779 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 23:09:07 +0200 Subject: [PATCH 13/34] send search request wip --- forums.go | 26 -------- images.go | 60 +++++++++++++++++- node-handle-search.go | 23 +++++-- node-request-search.go | 135 +++++++++++++++++++++-------------------- node.go | 14 +++-- 5 files changed, 152 insertions(+), 106 deletions(-) diff --git a/forums.go b/forums.go index 7f13fed..7c4b6c6 100644 --- a/forums.go +++ b/forums.go @@ -11,8 +11,6 @@ import ( "time" ) -var resultsChan = make(chan []ForumSearchResult) - func PerformRedditSearch(query string, safe string, page int) ([]ForumSearchResult, error) { const ( pageSize = 25 @@ -194,27 +192,3 @@ func sendSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]Fo 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 { - log.Printf("Error unmarshalling forum results: %v", err) - return - } - - log.Printf("Received forum results: %+v", results) - // Send results to resultsChan - go func() { - resultsChan <- results - }() -} - -func fetchForumResults(query, safe, lang string, page int) []ForumSearchResult { - results, err := PerformRedditSearch(query, safe, page) - if err != nil { - log.Printf("Error fetching forum results: %v", err) - return nil - } - return results -} diff --git a/images.go b/images.go index 84c1366..429b4df 100644 --- a/images.go +++ b/images.go @@ -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) diff --git a/node-handle-search.go b/node-handle-search.go index 248adba..d489a08 100644 --- a/node-handle-search.go +++ b/node-handle-search.go @@ -45,10 +45,11 @@ func handleSearchTextMessage(msg Message) { func handleSearchImageMessage(msg Message) { var searchParams struct { - Query string `json:"query"` - Safe string `json:"safe"` - Lang string `json:"lang"` - Page int `json:"page"` + 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 { @@ -56,6 +57,8 @@ func handleSearchImageMessage(msg Message) { 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 { @@ -69,9 +72,17 @@ func handleSearchImageMessage(msg Message) { Content: string(resultsJSON), } - err = sendMessage(msg.ID, responseMsg) + // 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", msg.ID, err) + log.Printf("Error sending image search results to %s: %v", searchParams.ResponseAddr, err) } } diff --git a/node-request-search.go b/node-request-search.go index 18cf03b..2d61c1b 100644 --- a/node-request-search.go +++ b/node-request-search.go @@ -2,79 +2,80 @@ package main import ( "encoding/json" + "log" ) -// func sendSearchRequestToNode(nodeAddr, query, safe, lang string, page int, requestID string) ([]ForumSearchResult, 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: "http://localhost:5000/node", // Node 1's address -// } +////// FORUMS ///// -// msg := Message{ -// ID: requestID, -// Type: "search-forum", -// Content: toJSON(searchParams), -// } +var resultsChan = make(chan []ForumSearchResult) -// msgBytes, err := json.Marshal(msg) -// if err != nil { -// return nil, fmt.Errorf("failed to marshal search request: %v", err) -// } +func sendForumResults(responseAddr string, results []ForumSearchResult) { + resultsMsg := Message{ + ID: hostID, + Type: "forum-results", + Content: marshalResults(results), + } -// req, err := http.NewRequest("POST", nodeAddr, bytes.NewBuffer(msgBytes)) -// if err != nil { -// return nil, fmt.Errorf("failed to create search 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 nil, fmt.Errorf("failed to send search request: %v", err) -// } -// defer resp.Body.Close() - -// if resp.StatusCode != http.StatusOK { -// body, _ := ioutil.ReadAll(resp.Body) -// return nil, fmt.Errorf("server error: %s", body) -// } - -// var responseMsg Message -// err = json.NewDecoder(resp.Body).Decode(&responseMsg) -// if err != nil { -// return nil, fmt.Errorf("failed to decode search response: %v", err) -// } - -// if responseMsg.Type != "forum-results" { -// return nil, fmt.Errorf("unexpected message type: %s", responseMsg.Type) -// } - -// var results []ForumSearchResult -// err = json.Unmarshal([]byte(responseMsg.Content), &results) -// if err != nil { -// return nil, fmt.Errorf("failed to unmarshal search results: %v", err) -// } - -// return results, nil -// } - -func toJSON(v interface{}) string { - data, err := json.Marshal(v) + err := sendMessage(responseAddr, resultsMsg) if err != nil { + log.Printf("Error sending forum search results to %s: %v", responseAddr, err) + } else { + log.Printf("Forum search results sent successfully to %s", responseAddr) + } +} + +func marshalResults(results []ForumSearchResult) string { + content, err := json.Marshal(results) + if err != nil { + log.Printf("Error marshalling forum results: %v", err) return "" } - return string(data) + return string(content) } + +func handleForumResultsMessage(msg Message) { + var results []ForumSearchResult + err := json.Unmarshal([]byte(msg.Content), &results) + if err != nil { + log.Printf("Error unmarshalling forum results: %v", err) + return + } + + log.Printf("Received forum results: %+v", results) + // Send results to resultsChan + go func() { + resultsChan <- results + }() +} + +func fetchForumResults(query, safe, lang string, page int) []ForumSearchResult { + results, err := PerformRedditSearch(query, safe, page) + if err != nil { + log.Printf("Error fetching forum results: %v", err) + return nil + } + return results +} + +////// FORUMS ////// + +////// IMAGES ///// + +var imageResultsChan = make(chan []ImageSearchResult) + +func handleImageResultsMessage(msg Message) { + var results []ImageSearchResult + err := json.Unmarshal([]byte(msg.Content), &results) + if err != nil { + log.Printf("Error unmarshalling image results: %v", err) + return + } + + log.Printf("Received image results: %+v", results) + // Send results to imageResultsChan + go func() { + imageResultsChan <- results + }() +} + +////// IMAGES ///// diff --git a/node.go b/node.go index 5fe0774..6f927d3 100644 --- a/node.go +++ b/node.go @@ -153,13 +153,15 @@ func interpretMessage(msg Message) { handleSearchForumMessage(msg) case "forum-results": handleForumResultsMessage(msg) + // case "text-results": + // handleTextResultsMessage(msg) // need to implement + case "image-results": + handleImageResultsMessage(msg) // need to implement + // case "video-results": + // handleVideoResultsMessage(msg) // need to implement + // case "file-results": + // handleFileResultsMessage(msg) // need to implement default: fmt.Println("Received unknown message type:", msg.Type) } } - -func generateRequestID() string { - bytes := make([]byte, 16) - rand.Read(bytes) - return fmt.Sprintf("%x", bytes) -} -- 2.40.1 From 37e9fab9a4cf4819a15c5f05bdc53b16a2156df3 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 8 Aug 2024 23:37:58 +0200 Subject: [PATCH 14/34] node search for text added --- node-handle-search.go | 25 +++++-- node.go | 4 +- text.go | 150 ++++++++++++++++++++++++++++++------------ 3 files changed, 128 insertions(+), 51 deletions(-) diff --git a/node-handle-search.go b/node-handle-search.go index d489a08..d83f545 100644 --- a/node-handle-search.go +++ b/node-handle-search.go @@ -13,10 +13,11 @@ var ( func handleSearchTextMessage(msg Message) { var searchParams struct { - Query string `json:"query"` - Safe string `json:"safe"` - Lang string `json:"lang"` - Page int `json:"page"` + 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 { @@ -24,6 +25,8 @@ func handleSearchTextMessage(msg Message) { return } + log.Printf("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 { @@ -33,13 +36,21 @@ func handleSearchTextMessage(msg Message) { responseMsg := Message{ ID: hostID, - Type: "search-results", + Type: "text-results", Content: string(resultsJSON), } - err = sendMessage(msg.ID, responseMsg) + // Log the address to be used for sending the response + log.Printf("Sending text 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 search results to %s: %v", msg.ID, err) + log.Printf("Error sending text search results to %s: %v", searchParams.ResponseAddr, err) } } diff --git a/node.go b/node.go index 6f927d3..824577f 100644 --- a/node.go +++ b/node.go @@ -153,8 +153,8 @@ func interpretMessage(msg Message) { handleSearchForumMessage(msg) case "forum-results": handleForumResultsMessage(msg) - // case "text-results": - // handleTextResultsMessage(msg) // need to implement + case "text-results": + handleTextResultsMessage(msg) // need to implement case "image-results": handleImageResultsMessage(msg) // need to implement // case "video-results": diff --git a/text.go b/text.go index a6d67cc..a6c3283 100644 --- a/text.go +++ b/text.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "fmt" "html/template" "log" @@ -9,6 +10,7 @@ import ( ) var textSearchEngines []SearchEngine +var textResultsChan = make(chan []TextSearchResult) func init() { textSearchEngines = []SearchEngine{ @@ -26,16 +28,51 @@ func HandleTextSearch(w http.ResponseWriter, query, safe, lang string, page int) cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"} combinedResults := getTextResultsFromCacheOrFetch(cacheKey, query, safe, lang, 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) if hasPrevPage { go prefetchPage(query, safe, lang, page-1) } + + elapsedTime := time.Since(startTime) + tmpl, err := template.New("text.html").Funcs(funcs).ParseFiles("templates/text.html") + if err != nil { + log.Printf("Error parsing template: %v", err) + 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 + }{ + 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, + } + + err = tmpl.Execute(w, data) + if err != nil { + log.Printf("Error executing template: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } } func getTextResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []TextSearchResult { @@ -109,6 +146,12 @@ func fetchTextResults(query, safe, lang string, page int) []TextSearchResult { } } + // If no results found after trying all engines + if len(results) == 0 { + log.Printf("No text results found for query: %s, trying other nodes", query) + results = tryOtherNodesForTextSearch(query, safe, lang, page) + } + return results } @@ -140,48 +183,71 @@ func wrapTextSearchFunc(f func(string, string, string, int) ([]TextSearchResult, } } -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) +func tryOtherNodesForTextSearch(query, safe, lang string, page int) []TextSearchResult { + for _, nodeAddr := range peers { + results, err := sendTextSearchRequestToNode(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 +} - 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") +func sendTextSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]TextSearchResult, 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 { - http.Error(w, "Internal Server Error", http.StatusInternalServerError) + 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): // Increased timeout duration + 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 { + log.Printf("Error unmarshalling text results: %v", err) 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) - } + log.Printf("Received text results: %+v", results) + // Send results to textResultsChan + go func() { + textResultsChan <- results + }() } -- 2.40.1 From 4724e840595126f199c97572ec4a2a8580cd00e1 Mon Sep 17 00:00:00 2001 From: partisan Date: Fri, 9 Aug 2024 09:55:41 +0200 Subject: [PATCH 15/34] added fetch file results from other nodes --- files.go | 93 ++++++++++++++++++++++++++++++++++++++----- node-handle-search.go | 22 +++++++--- 2 files changed, 99 insertions(+), 16 deletions(-) diff --git a/files.go b/files.go index 1ef1276..35c227c 100644 --- a/files.go +++ b/files.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "fmt" "html/template" "log" @@ -30,6 +31,8 @@ var ( rutor TorrentSite ) +var fileResultsChan = make(chan []TorrentResult) + func initializeTorrentSites() { torrentGalaxy = NewTorrentGalaxy() // nyaa = NewNyaa() @@ -108,20 +111,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) + 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,17 +148,81 @@ 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 { + log.Printf("No file results found for query: %s, trying other nodes", query) + results = tryOtherNodesForFileSearch(query, safe, lang, page) + } return results } -func fetchFileResults(query, safe, lang string, page int) []TorrentResult { - cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "file"} - results := getFileResultsFromCacheOrFetch(cacheKey, query, safe, lang, page) - return results +func tryOtherNodesForFileSearch(query, safe, lang string, page int) []TorrentResult { + for _, nodeAddr := range peers { + results, err := sendFileSearchRequestToNode(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 sendFileSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]TorrentResult, 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-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 + }() } func removeMagnetLink(magnet string) string { diff --git a/node-handle-search.go b/node-handle-search.go index d83f545..3992de0 100644 --- a/node-handle-search.go +++ b/node-handle-search.go @@ -131,10 +131,11 @@ func handleSearchVideoMessage(msg Message) { func handleSearchFileMessage(msg Message) { var searchParams struct { - Query string `json:"query"` - Safe string `json:"safe"` - Lang string `json:"lang"` - Page int `json:"page"` + 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 { @@ -142,6 +143,8 @@ func handleSearchFileMessage(msg Message) { 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 { @@ -155,9 +158,16 @@ func handleSearchFileMessage(msg Message) { Content: string(resultsJSON), } - err = sendMessage(msg.ID, responseMsg) + 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", msg.ID, err) + log.Printf("Error sending file search results to %s: %v", searchParams.ResponseAddr, err) } } -- 2.40.1 From 1443dec8e27ea12d499302db9f953ff4a653ca97 Mon Sep 17 00:00:00 2001 From: partisan Date: Fri, 9 Aug 2024 10:39:08 +0200 Subject: [PATCH 16/34] added node search for video --- node-handle-search.go | 22 +++++++--- node.go | 8 ++-- video.go | 100 +++++++++++++++++++++++++++++++----------- 3 files changed, 94 insertions(+), 36 deletions(-) diff --git a/node-handle-search.go b/node-handle-search.go index 3992de0..77819be 100644 --- a/node-handle-search.go +++ b/node-handle-search.go @@ -99,10 +99,11 @@ func handleSearchImageMessage(msg Message) { func handleSearchVideoMessage(msg Message) { var searchParams struct { - Query string `json:"query"` - Safe string `json:"safe"` - Lang string `json:"lang"` - Page int `json:"page"` + 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 { @@ -110,6 +111,8 @@ func handleSearchVideoMessage(msg Message) { 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 { @@ -123,9 +126,16 @@ func handleSearchVideoMessage(msg Message) { Content: string(resultsJSON), } - err = sendMessage(msg.ID, responseMsg) + 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", msg.ID, err) + log.Printf("Error sending video search results to %s: %v", searchParams.ResponseAddr, err) } } diff --git a/node.go b/node.go index 824577f..56ffd82 100644 --- a/node.go +++ b/node.go @@ -157,10 +157,10 @@ func interpretMessage(msg Message) { handleTextResultsMessage(msg) // need to implement case "image-results": handleImageResultsMessage(msg) // need to implement - // case "video-results": - // handleVideoResultsMessage(msg) // need to implement - // case "file-results": - // handleFileResultsMessage(msg) // need to implement + case "video-results": + handleVideoResultsMessage(msg) // need to implement + case "file-results": + handleFileResultsMessage(msg) // need to implement default: fmt.Println("Received unknown message type:", msg.Type) } diff --git a/video.go b/video.go index 36d0613..697f3c7 100644 --- a/video.go +++ b/video.go @@ -30,6 +30,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 @@ -151,32 +152,10 @@ func makeHTMLRequest(query, safe, lang string, page int) (*VideoAPIResponse, err func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int) { start := time.Now() - apiResp, err := makeHTMLRequest(query, safe, lang, page) - if err != nil { - log.Printf("Error fetching video results: %v", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - - var results []VideoResult - for _, item := range apiResp.Items { - if item.Type == "channel" || item.Type == "playlist" { - continue - } - if item.UploadedDate == "" { - item.UploadedDate = "Now" - } - - results = append(results, VideoResult{ - Href: fmt.Sprintf("https://youtube.com%s", item.URL), - Title: item.Title, - Date: item.UploadedDate, - Views: formatViews(item.Views), - Creator: item.UploaderName, - Publisher: "Piped", - Image: fmt.Sprintf("/img_proxy?url=%s", url.QueryEscape(item.Thumbnail)), - Duration: formatDuration(item.Duration), - }) + results := fetchVideoResults(query, safe, lang, page) + if len(results) == 0 { + log.Printf("No results from primary search, trying other nodes") + results = tryOtherNodesForVideoSearch(query, safe, lang, page) } elapsed := time.Since(start) @@ -230,3 +209,72 @@ func fetchVideoResults(query, safe, lang string, page int) []VideoResult { } return results } + +func tryOtherNodesForVideoSearch(query, safe, lang string, page int) []VideoResult { + for _, nodeAddr := range peers { + results, err := sendVideoSearchRequestToNode(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 sendVideoSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]VideoResult, 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-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 { + log.Printf("Error unmarshalling video results: %v", err) + return + } + + log.Printf("Received video results: %+v", results) + // Send results to videoResultsChan + go func() { + videoResultsChan <- results + }() +} -- 2.40.1 From bd542b8aa2a9fe7287ae9bcdd98945e9d2360c74 Mon Sep 17 00:00:00 2001 From: partisan Date: Fri, 9 Aug 2024 12:59:37 +0200 Subject: [PATCH 17/34] added "VisitedNodes" to message, to prevent re-requesting --- files.go | 41 ++++++++++++++++++++++++++++------------- forums.go | 30 +++++++++++++++++++++--------- images.go | 42 ++++++++++++++++++++++++++++++++---------- node-request-search.go | 17 ----------------- node.go | 16 ++++++++-------- text.go | 26 ++++++++++++++++---------- video.go | 24 +++++++++++++++--------- 7 files changed, 120 insertions(+), 76 deletions(-) diff --git a/files.go b/files.go index 35c227c..a331623 100644 --- a/files.go +++ b/files.go @@ -82,10 +82,10 @@ func handleFileSearch(w http.ResponseWriter, query, safe, lang string, page int) Settings: Settings{UxLang: lang, Safe: safe}, } - // 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) @@ -150,15 +150,18 @@ func fetchFileResults(query, safe, lang string, page int) []TorrentResult { if len(results) == 0 { log.Printf("No file results found for query: %s, trying other nodes", query) - results = tryOtherNodesForFileSearch(query, safe, lang, page) + results = tryOtherNodesForFileSearch(query, safe, lang, page, []string{hostID}) } return results } -func tryOtherNodesForFileSearch(query, safe, lang string, page int) []TorrentResult { +func tryOtherNodesForFileSearch(query, safe, lang string, page int, visitedNodes []string) []TorrentResult { for _, nodeAddr := range peers { - results, err := sendFileSearchRequestToNode(nodeAddr, query, safe, lang, page) + 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 @@ -170,19 +173,22 @@ func tryOtherNodesForFileSearch(query, safe, lang string, page int) []TorrentRes return nil } -func sendFileSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]TorrentResult, error) { +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"` + 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) @@ -323,3 +329,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 +} diff --git a/forums.go b/forums.go index 7c4b6c6..9d643a3 100644 --- a/forums.go +++ b/forums.go @@ -100,7 +100,7 @@ func PerformRedditSearch(query string, safe string, page int) ([]ForumSearchResu func handleForumsSearch(w http.ResponseWriter, query, safe, lang string, page int) { results, err := PerformRedditSearch(query, safe, page) - if err != nil || len(results) == 0 || 0 == 0 { // 0 == 0 to force search by other node + 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, safe, lang, page) } @@ -141,7 +141,7 @@ func handleForumsSearch(w http.ResponseWriter, query, safe, lang string, page in func tryOtherNodesForForumSearch(query, safe, lang string, page int) []ForumSearchResult { for _, nodeAddr := range peers { - results, err := sendSearchRequestToNode(nodeAddr, query, safe, lang, page) + results, err := sendSearchRequestToNode(nodeAddr, query, safe, lang, page, []string{}) if err != nil { log.Printf("Error contacting node %s: %v", nodeAddr, err) continue @@ -153,19 +153,31 @@ func tryOtherNodesForForumSearch(query, safe, lang string, page int) []ForumSear return nil } -func sendSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]ForumSearchResult, error) { +func sendSearchRequestToNode(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"` + 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) @@ -188,7 +200,7 @@ func sendSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]Fo select { case res := <-resultsChan: return res, nil - case <-time.After(20 * time.Second): // Increased timeout duration + case <-time.After(20 * time.Second): return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr) } } diff --git a/images.go b/images.go index 429b4df..b78cac7 100644 --- a/images.go +++ b/images.go @@ -10,6 +10,7 @@ import ( ) var imageSearchEngines []SearchEngine +var imageResultsChan = make(chan []ImageSearchResult) func init() { imageSearchEngines = []SearchEngine{ @@ -124,15 +125,18 @@ 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, trying other nodes", query) - results = tryOtherNodesForImageSearch(query, safe, lang, page) + results = tryOtherNodesForImageSearch(query, safe, lang, page, []string{hostID}) } return results } -func tryOtherNodesForImageSearch(query, safe, lang string, page int) []ImageSearchResult { +func tryOtherNodesForImageSearch(query, safe, lang string, page int, visitedNodes []string) []ImageSearchResult { for _, nodeAddr := range peers { - results, err := sendImageSearchRequestToNode(nodeAddr, query, safe, lang, page) + if contains(visitedNodes, nodeAddr) { + continue // Skip nodes already visited + } + results, err := sendImageSearchRequestToNode(nodeAddr, query, safe, lang, page, visitedNodes) if err != nil { log.Printf("Error contacting node %s: %v", nodeAddr, err) continue @@ -144,19 +148,22 @@ func tryOtherNodesForImageSearch(query, safe, lang string, page int) []ImageSear return nil } -func sendImageSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]ImageSearchResult, error) { +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"` + 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) @@ -179,7 +186,7 @@ func sendImageSearchRequestToNode(nodeAddr, query, safe, lang string, page int) select { case res := <-imageResultsChan: return res, nil - case <-time.After(30 * time.Second): // Need to handle this better, setting a static number is stupid + case <-time.After(30 * time.Second): return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr) } } @@ -197,3 +204,18 @@ func wrapImageSearchFunc(f func(string, string, string, int) ([]ImageSearchResul return searchResults, duration, nil } } + +func handleImageResultsMessage(msg Message) { + var results []ImageSearchResult + err := json.Unmarshal([]byte(msg.Content), &results) + if err != nil { + log.Printf("Error unmarshalling image results: %v", err) + return + } + + log.Printf("Received image results: %+v", results) + // Send results to imageResultsChan + go func() { + imageResultsChan <- results + }() +} diff --git a/node-request-search.go b/node-request-search.go index 2d61c1b..5bc331e 100644 --- a/node-request-search.go +++ b/node-request-search.go @@ -61,21 +61,4 @@ func fetchForumResults(query, safe, lang string, page int) []ForumSearchResult { ////// IMAGES ///// -var imageResultsChan = make(chan []ImageSearchResult) - -func handleImageResultsMessage(msg Message) { - var results []ImageSearchResult - err := json.Unmarshal([]byte(msg.Content), &results) - if err != nil { - log.Printf("Error unmarshalling image results: %v", err) - return - } - - log.Printf("Received image results: %+v", results) - // Send results to imageResultsChan - go func() { - imageResultsChan <- results - }() -} - ////// IMAGES ///// diff --git a/node.go b/node.go index 56ffd82..dc0a4eb 100644 --- a/node.go +++ b/node.go @@ -21,9 +21,10 @@ var ( ) type Message struct { - ID string `json:"id"` - Type string `json:"type"` - Content string `json:"content"` + ID string `json:"id"` + Type string `json:"type"` + Content string `json:"content"` + VisitedNodes []string `json:"visitedNodes"` } type CrawlerConfig struct { @@ -149,18 +150,17 @@ func interpretMessage(msg Message) { case "search-file": handleSearchFileMessage(msg) case "search-forum": - log.Println("Received search-forum message:", msg.Content) handleSearchForumMessage(msg) case "forum-results": handleForumResultsMessage(msg) case "text-results": - handleTextResultsMessage(msg) // need to implement + handleTextResultsMessage(msg) case "image-results": - handleImageResultsMessage(msg) // need to implement + handleImageResultsMessage(msg) case "video-results": - handleVideoResultsMessage(msg) // need to implement + handleVideoResultsMessage(msg) case "file-results": - handleFileResultsMessage(msg) // need to implement + handleFileResultsMessage(msg) default: fmt.Println("Received unknown message type:", msg.Type) } diff --git a/text.go b/text.go index a6c3283..a0ab6bf 100644 --- a/text.go +++ b/text.go @@ -149,7 +149,7 @@ func fetchTextResults(query, safe, lang string, page int) []TextSearchResult { // If no results found after trying all engines if len(results) == 0 { log.Printf("No text results found for query: %s, trying other nodes", query) - results = tryOtherNodesForTextSearch(query, safe, lang, page) + results = tryOtherNodesForTextSearch(query, safe, lang, page, []string{hostID}) } return results @@ -183,9 +183,12 @@ func wrapTextSearchFunc(f func(string, string, string, int) ([]TextSearchResult, } } -func tryOtherNodesForTextSearch(query, safe, lang string, page int) []TextSearchResult { +func tryOtherNodesForTextSearch(query, safe, lang string, page int, visitedNodes []string) []TextSearchResult { for _, nodeAddr := range peers { - results, err := sendTextSearchRequestToNode(nodeAddr, query, safe, lang, page) + if contains(visitedNodes, nodeAddr) { + continue // Skip nodes already visited + } + results, err := sendTextSearchRequestToNode(nodeAddr, query, safe, lang, page, visitedNodes) if err != nil { log.Printf("Error contacting node %s: %v", nodeAddr, err) continue @@ -197,19 +200,22 @@ func tryOtherNodesForTextSearch(query, safe, lang string, page int) []TextSearch return nil } -func sendTextSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]TextSearchResult, error) { +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"` + 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) @@ -232,7 +238,7 @@ func sendTextSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ( select { case res := <-textResultsChan: return res, nil - case <-time.After(20 * time.Second): // Increased timeout duration + case <-time.After(20 * time.Second): return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr) } } diff --git a/video.go b/video.go index 697f3c7..974705d 100644 --- a/video.go +++ b/video.go @@ -155,7 +155,7 @@ func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int results := fetchVideoResults(query, safe, lang, page) if len(results) == 0 { log.Printf("No results from primary search, trying other nodes") - results = tryOtherNodesForVideoSearch(query, safe, lang, page) + results = tryOtherNodesForVideoSearch(query, safe, lang, page, []string{hostID}) } elapsed := time.Since(start) @@ -210,9 +210,12 @@ func fetchVideoResults(query, safe, lang string, page int) []VideoResult { return results } -func tryOtherNodesForVideoSearch(query, safe, lang string, page int) []VideoResult { +func tryOtherNodesForVideoSearch(query, safe, lang string, page int, visitedNodes []string) []VideoResult { for _, nodeAddr := range peers { - results, err := sendVideoSearchRequestToNode(nodeAddr, query, safe, lang, page) + if contains(visitedNodes, nodeAddr) { + continue // Skip nodes already visited + } + results, err := sendVideoSearchRequestToNode(nodeAddr, query, safe, lang, page, visitedNodes) if err != nil { log.Printf("Error contacting node %s: %v", nodeAddr, err) continue @@ -224,19 +227,22 @@ func tryOtherNodesForVideoSearch(query, safe, lang string, page int) []VideoResu return nil } -func sendVideoSearchRequestToNode(nodeAddr, query, safe, lang string, page int) ([]VideoResult, error) { +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"` + 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) -- 2.40.1 From eea8947ad15fa2a992ea2202fa2916aa3609e6dc Mon Sep 17 00:00:00 2001 From: partisan Date: Fri, 9 Aug 2024 15:55:14 +0200 Subject: [PATCH 18/34] clean up --- config.go | 22 +++++++-- files.go | 88 +---------------------------------- forums.go | 66 --------------------------- images.go | 77 ------------------------------- init.go | 19 ++++---- node-handle-search.go | 6 --- node-request-files.go | 83 +++++++++++++++++++++++++++++++++ node-request-forums.go | 101 +++++++++++++++++++++++++++++++++++++++++ node-request-images.go | 85 ++++++++++++++++++++++++++++++++++ node-request-search.go | 64 -------------------------- node-request-text.go | 85 ++++++++++++++++++++++++++++++++++ node-request-video.go | 83 +++++++++++++++++++++++++++++++++ text.go | 77 ------------------------------- video.go | 75 ------------------------------ 14 files changed, 466 insertions(+), 465 deletions(-) create mode 100644 node-request-files.go create mode 100644 node-request-forums.go create mode 100644 node-request-images.go delete mode 100644 node-request-search.go create mode 100644 node-request-text.go create mode 100644 node-request-video.go diff --git a/config.go b/config.go index d2a0857..14d9808 100644 --- a/config.go +++ b/config.go @@ -7,6 +7,7 @@ import ( "os" "strconv" "strings" + "sync" "github.com/fsnotify/fsnotify" "gopkg.in/ini.v1" @@ -55,6 +56,8 @@ func createConfig() error { fmt.Printf("Generated connection code: %s\n", config.AuthCode) } + config.NodesEnabled = len(config.Peers) > 0 + saveConfig(config) return nil } @@ -69,6 +72,7 @@ func saveConfig(config Config) { peers := strings.Join(config.Peers, ",") sec.Key("Peers").SetValue(peers) sec.Key("Domain").SetValue(config.Domain) + sec.Key("NodesEnabled").SetValue(strconv.FormatBool(config.NodesEnabled)) err := cfg.SaveTo(configFilePath) if err != nil { @@ -101,17 +105,25 @@ func loadConfig() Config { 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 + } + config = Config{ - Port: port, - AuthCode: cfg.Section("").Key("AuthCode").String(), - PeerID: cfg.Section("").Key("PeerID").String(), - Peers: peers, - Domain: domain, + Port: port, + AuthCode: cfg.Section("").Key("AuthCode").String(), + PeerID: cfg.Section("").Key("PeerID").String(), + Peers: peers, + Domain: domain, + NodesEnabled: nodesEnabled, } return config } +var configLock sync.RWMutex + func startFileWatcher() { watcher, err := fsnotify.NewWatcher() if err != nil { diff --git a/files.go b/files.go index a331623..0308b56 100644 --- a/files.go +++ b/files.go @@ -1,7 +1,6 @@ package main import ( - "encoding/json" "fmt" "html/template" "log" @@ -50,8 +49,8 @@ func handleFileSearch(w http.ResponseWriter, query, safe, lang string, page int) 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 { @@ -156,94 +155,11 @@ func fetchFileResults(query, safe, lang string, page int) []TorrentResult { return results } -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 - }() -} - func removeMagnetLink(magnet string) string { // Remove the magnet: prefix unconditionally 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 { diff --git a/forums.go b/forums.go index 9d643a3..b358acd 100644 --- a/forums.go +++ b/forums.go @@ -138,69 +138,3 @@ func handleForumsSearch(w http.ResponseWriter, query, safe, lang string, page in http.Error(w, fmt.Sprintf("Error rendering template: %v", err), http.StatusInternalServerError) } } - -func tryOtherNodesForForumSearch(query, safe, lang string, page int) []ForumSearchResult { - for _, nodeAddr := range peers { - results, err := sendSearchRequestToNode(nodeAddr, query, safe, lang, page, []string{}) - if err != nil { - log.Printf("Error contacting node %s: %v", nodeAddr, err) - continue - } - if len(results) > 0 { - return results - } - } - return nil -} - -func sendSearchRequestToNode(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 := <-resultsChan: - return res, nil - case <-time.After(20 * time.Second): - return nil, fmt.Errorf("timeout waiting for results from node %s", nodeAddr) - } -} diff --git a/images.go b/images.go index b78cac7..38eed51 100644 --- a/images.go +++ b/images.go @@ -1,7 +1,6 @@ package main import ( - "encoding/json" "fmt" "html/template" "log" @@ -10,7 +9,6 @@ import ( ) var imageSearchEngines []SearchEngine -var imageResultsChan = make(chan []ImageSearchResult) func init() { imageSearchEngines = []SearchEngine{ @@ -131,66 +129,6 @@ func fetchImageResults(query, safe, lang string, page int) []ImageSearchResult { return results } -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 { - 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, 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 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) @@ -204,18 +142,3 @@ func wrapImageSearchFunc(f func(string, string, string, int) ([]ImageSearchResul return searchResults, duration, nil } } - -func handleImageResultsMessage(msg Message) { - var results []ImageSearchResult - err := json.Unmarshal([]byte(msg.Content), &results) - if err != nil { - log.Printf("Error unmarshalling image results: %v", err) - return - } - - log.Printf("Received image results: %+v", results) - // Send results to imageResultsChan - go func() { - imageResultsChan <- results - }() -} diff --git a/init.go b/init.go index c807cfe..2f6d273 100644 --- a/init.go +++ b/init.go @@ -3,27 +3,28 @@ package main import ( "fmt" "log" - "sync" "time" ) type Config struct { - Port int - AuthCode string - Peers []string - PeerID string - Domain string + Port int + AuthCode string + PeerID string + Peers []string + Domain string + NodesEnabled bool } var defaultConfig = Config{ - Port: 5000, - Domain: "localhost", + Port: 5000, + Domain: "localhost", + Peers: []string{}, + AuthCode: generateStrongRandomString(64), } const configFilePath = "config.ini" var config Config -var configLock sync.RWMutex func main() { err := initConfig() diff --git a/node-handle-search.go b/node-handle-search.go index 77819be..bfa8f6a 100644 --- a/node-handle-search.go +++ b/node-handle-search.go @@ -3,12 +3,6 @@ package main import ( "encoding/json" "log" - "sync" -) - -var ( - forumResults = make(map[string][]ForumSearchResult) - forumResultsMutex sync.Mutex ) func handleSearchTextMessage(msg Message) { diff --git a/node-request-files.go b/node-request-files.go new file mode 100644 index 0000000..2c9a28b --- /dev/null +++ b/node-request-files.go @@ -0,0 +1,83 @@ +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 + }() +} diff --git a/node-request-forums.go b/node-request-forums.go new file mode 100644 index 0000000..921f2fb --- /dev/null +++ b/node-request-forums.go @@ -0,0 +1,101 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "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 { + log.Printf("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 { + log.Printf("Error unmarshalling forum results: %v", err) + return + } + + log.Printf("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 { + log.Printf("Error fetching forum results: %v", err) + return nil + } + return results +} diff --git a/node-request-images.go b/node-request-images.go new file mode 100644 index 0000000..0fb8eae --- /dev/null +++ b/node-request-images.go @@ -0,0 +1,85 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "time" +) + +var imageResultsChan = make(chan []ImageSearchResult) + +func handleImageResultsMessage(msg Message) { + var results []ImageSearchResult + err := json.Unmarshal([]byte(msg.Content), &results) + if err != nil { + log.Printf("Error unmarshalling image results: %v", err) + return + } + + log.Printf("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 { + log.Printf("Error contacting node %s: %v", nodeAddr, err) + continue + } + if len(results) > 0 { + return results + } + } + return nil +} diff --git a/node-request-search.go b/node-request-search.go deleted file mode 100644 index 5bc331e..0000000 --- a/node-request-search.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "encoding/json" - "log" -) - -////// FORUMS ///// - -var resultsChan = make(chan []ForumSearchResult) - -func sendForumResults(responseAddr string, results []ForumSearchResult) { - resultsMsg := Message{ - ID: hostID, - Type: "forum-results", - Content: marshalResults(results), - } - - err := sendMessage(responseAddr, resultsMsg) - if err != nil { - log.Printf("Error sending forum search results to %s: %v", responseAddr, err) - } else { - log.Printf("Forum search results sent successfully to %s", responseAddr) - } -} - -func marshalResults(results []ForumSearchResult) string { - content, err := json.Marshal(results) - if err != nil { - log.Printf("Error marshalling forum results: %v", err) - return "" - } - return string(content) -} - -func handleForumResultsMessage(msg Message) { - var results []ForumSearchResult - err := json.Unmarshal([]byte(msg.Content), &results) - if err != nil { - log.Printf("Error unmarshalling forum results: %v", err) - return - } - - log.Printf("Received forum results: %+v", results) - // Send results to resultsChan - go func() { - resultsChan <- results - }() -} - -func fetchForumResults(query, safe, lang string, page int) []ForumSearchResult { - results, err := PerformRedditSearch(query, safe, page) - if err != nil { - log.Printf("Error fetching forum results: %v", err) - return nil - } - return results -} - -////// FORUMS ////// - -////// IMAGES ///// - -////// IMAGES ///// diff --git a/node-request-text.go b/node-request-text.go new file mode 100644 index 0000000..6f4596e --- /dev/null +++ b/node-request-text.go @@ -0,0 +1,85 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "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 { + log.Printf("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 { + log.Printf("Error unmarshalling text results: %v", err) + return + } + + log.Printf("Received text results: %+v", results) + // Send results to textResultsChan + go func() { + textResultsChan <- results + }() +} diff --git a/node-request-video.go b/node-request-video.go new file mode 100644 index 0000000..209b84c --- /dev/null +++ b/node-request-video.go @@ -0,0 +1,83 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "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 { + log.Printf("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 { + log.Printf("Error unmarshalling video results: %v", err) + return + } + + log.Printf("Received video results: %+v", results) + // Send results to videoResultsChan + go func() { + videoResultsChan <- results + }() +} diff --git a/text.go b/text.go index a0ab6bf..6b26f24 100644 --- a/text.go +++ b/text.go @@ -1,7 +1,6 @@ package main import ( - "encoding/json" "fmt" "html/template" "log" @@ -10,7 +9,6 @@ import ( ) var textSearchEngines []SearchEngine -var textResultsChan = make(chan []TextSearchResult) func init() { textSearchEngines = []SearchEngine{ @@ -182,78 +180,3 @@ func wrapTextSearchFunc(f func(string, string, string, int) ([]TextSearchResult, return searchResults, duration, nil } } - -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 { - log.Printf("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 { - log.Printf("Error unmarshalling text results: %v", err) - return - } - - log.Printf("Received text results: %+v", results) - // Send results to textResultsChan - go func() { - textResultsChan <- results - }() -} diff --git a/video.go b/video.go index 974705d..0e2da9d 100644 --- a/video.go +++ b/video.go @@ -209,78 +209,3 @@ func fetchVideoResults(query, safe, lang string, page int) []VideoResult { } return results } - -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 { - log.Printf("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 { - log.Printf("Error unmarshalling video results: %v", err) - return - } - - log.Printf("Received video results: %+v", results) - // Send results to videoResultsChan - go func() { - videoResultsChan <- results - }() -} -- 2.40.1 From 26e404f6bc5ec5e6b013469f2c37702b61a20f2b Mon Sep 17 00:00:00 2001 From: partisan Date: Fri, 9 Aug 2024 19:08:02 +0200 Subject: [PATCH 19/34] fix missing "Maps" button --- templates/images.html | 4 ++++ templates/text.html | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/templates/images.html b/templates/images.html index 9ef54fe..54e3687 100644 --- a/templates/images.html +++ b/templates/images.html @@ -100,6 +100,10 @@
Searching for new results...
+ diff --git a/templates/search.html b/templates/search.html index 4cc6ab8..f82599a 100644 --- a/templates/search.html +++ b/templates/search.html @@ -5,11 +5,56 @@ Search with Ocásek + + +
+

Settings

+
+ +
+

Theme: Default Theme

+
+
Dark Theme
+
Light Theme
+
+
+ + + +

Ocásek

diff --git a/templates/settings.html b/templates/settings.html index b484e7e..d106af3 100644 --- a/templates/settings.html +++ b/templates/settings.html @@ -4,7 +4,8 @@ Settings - Ocásek - + + diff --git a/templates/text.html b/templates/text.html index f7607b7..6dccaa7 100644 --- a/templates/text.html +++ b/templates/text.html @@ -4,7 +4,8 @@ {{.Query}} - Ocásek - + + @@ -61,7 +62,7 @@ {{if .Results}} {{range .Results}}
- {{.URL}} + {{.URL}}

{{.Header}}

{{.Description}}

diff --git a/templates/videos.html b/templates/videos.html index 5b2cefc..d03b984 100644 --- a/templates/videos.html +++ b/templates/videos.html @@ -5,6 +5,7 @@ {{.Query}} - Ocásek + diff --git a/text.go b/text.go index 6b26f24..471d0ed 100644 --- a/text.go +++ b/text.go @@ -3,7 +3,6 @@ package main import ( "fmt" "html/template" - "log" "net/http" "time" ) @@ -20,7 +19,7 @@ func init() { } } -func HandleTextSearch(w http.ResponseWriter, query, safe, lang string, page int) { +func HandleTextSearch(w http.ResponseWriter, settings UserSettings, query, safe, lang string, page int) { startTime := time.Now() cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"} @@ -39,7 +38,7 @@ func HandleTextSearch(w http.ResponseWriter, query, safe, lang string, page int) elapsedTime := time.Since(startTime) tmpl, err := template.New("text.html").Funcs(funcs).ParseFiles("templates/text.html") if err != nil { - log.Printf("Error parsing template: %v", err) + printErr("Error parsing template: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } @@ -54,6 +53,7 @@ func HandleTextSearch(w http.ResponseWriter, query, safe, lang string, page int) HasPrevPage bool HasNextPage bool NoResults bool + Theme string }{ Results: combinedResults, Query: query, @@ -64,11 +64,12 @@ func HandleTextSearch(w http.ResponseWriter, query, safe, lang string, page int) HasPrevPage: page > 1, HasNextPage: len(combinedResults) >= 50, NoResults: len(combinedResults) == 0, + Theme: settings.Theme, } 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) } } @@ -80,10 +81,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 } }() @@ -100,7 +101,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)) @@ -113,13 +114,13 @@ 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"} 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) } } @@ -127,12 +128,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 } @@ -146,7 +147,7 @@ func fetchTextResults(query, safe, lang string, page int) []TextSearchResult { // If no results found after trying all engines if len(results) == 0 { - log.Printf("No text results found for query: %s, trying other nodes", query) + printWarn("No text results found for query: %s, trying other nodes", query) results = tryOtherNodesForTextSearch(query, safe, lang, page, []string{hostID}) } diff --git a/user-settings.go b/user-settings.go new file mode 100644 index 0000000..41960a7 --- /dev/null +++ b/user-settings.go @@ -0,0 +1,54 @@ +package main + +import "net/http" + +type UserSettings struct { + Theme string + Language string + SafeSearch string +} + +func loadUserSettings(r *http.Request) UserSettings { + var settings UserSettings + + // Load theme + if cookie, err := r.Cookie("theme"); err == nil { + settings.Theme = cookie.Value + } else { + settings.Theme = "dark" // Default theme + } + + // Load language + if cookie, err := r.Cookie("language"); err == nil { + settings.Language = cookie.Value + } else { + settings.Language = "en" // Default language + } + + // Load safe search + if cookie, err := r.Cookie("safe"); err == nil { + settings.SafeSearch = cookie.Value + } else { + settings.SafeSearch = "" // Default safe search off + } + + return settings +} + +func saveUserSettings(w http.ResponseWriter, settings UserSettings) { + http.SetCookie(w, &http.Cookie{ + Name: "theme", + Value: settings.Theme, + Path: "/", + }) + http.SetCookie(w, &http.Cookie{ + Name: "language", + Value: settings.Language, + Path: "/", + }) + http.SetCookie(w, &http.Cookie{ + Name: "safe", + Value: settings.SafeSearch, + Path: "/", + }) +} diff --git a/video.go b/video.go index 0e2da9d..5b09276 100644 --- a/video.go +++ b/video.go @@ -149,13 +149,13 @@ 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, safe, lang string, page int) { start := time.Now() - results := fetchVideoResults(query, safe, lang, page) + results := fetchVideoResults(query, settings.SafeSearch, settings.Language, page) if len(results) == 0 { log.Printf("No results from primary search, trying other nodes") - results = tryOtherNodesForVideoSearch(query, safe, lang, page, []string{hostID}) + results = tryOtherNodesForVideoSearch(query, settings.SafeSearch, settings.Language, page, []string{hostID}) } elapsed := time.Since(start) @@ -172,7 +172,8 @@ func handleVideoSearch(w http.ResponseWriter, query, safe, lang string, page int "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 + "HasNextPage": len(results) > 0, // no + "Theme": settings.Theme, }) if err != nil { log.Printf("Error executing template: %v", err) -- 2.40.1 From e5914a1cd61171eee0c4925e506260ed66eb36d8 Mon Sep 17 00:00:00 2001 From: partisan Date: Mon, 12 Aug 2024 08:29:53 +0200 Subject: [PATCH 24/34] better image proxy --- imageproxy.go | 21 +++++++++++++++------ video.go | 17 ++++++++--------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/imageproxy.go b/imageproxy.go index 4dd7478..74a1cbb 100644 --- a/imageproxy.go +++ b/imageproxy.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "io" "net/http" ) @@ -13,12 +14,20 @@ func handleImageProxy(w http.ResponseWriter, r *http.Request) { return } - // Fetch the image from the external URL - resp, err := http.Get(imageURL) - if err != nil { - printWarn("Error fetching image: %v", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return + // Try to fetch the image from Bing first + bingURL := fmt.Sprintf("https://tse.mm.bing.net/th?q=%s", imageURL) + resp, err := http.Get(bingURL) + if err != nil || resp.StatusCode != http.StatusOK { + // If fetching from Bing fails, attempt to fetch from the original image URL + printWarn("Error fetching image from Bing, trying original URL.") + + // Attempt to fetch the image directly + resp, err = http.Get(imageURL) + if err != nil { + printWarn("Error fetching image: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } } defer resp.Body.Close() diff --git a/video.go b/video.go index 5b09276..0a87f1f 100644 --- a/video.go +++ b/video.go @@ -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", @@ -101,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) } } } @@ -131,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 @@ -154,14 +153,14 @@ func handleVideoSearch(w http.ResponseWriter, settings UserSettings, query, safe results := fetchVideoResults(query, settings.SafeSearch, settings.Language, page) if len(results) == 0 { - log.Printf("No results from primary search, trying other nodes") + printWarn("No results from primary search, trying other nodes") results = tryOtherNodesForVideoSearch(query, settings.SafeSearch, settings.Language, 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 parsing template: %v", err) + printErr("Error parsing template: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } @@ -176,7 +175,7 @@ func handleVideoSearch(w http.ResponseWriter, settings UserSettings, query, safe "Theme": settings.Theme, }) if err != nil { - log.Printf("Error executing template: %v", err) + printErr("Error executing template: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) } } @@ -184,7 +183,7 @@ func handleVideoSearch(w http.ResponseWriter, settings UserSettings, query, safe func fetchVideoResults(query, safe, lang string, page int) []VideoResult { apiResp, err := makeHTMLRequest(query, safe, lang, page) if err != nil { - log.Printf("Error fetching video results: %v", err) + printWarn("Error fetching video results: %v", err) return nil } -- 2.40.1 From 5a8da744395dfdf652db5f0a00540ea82154a708 Mon Sep 17 00:00:00 2001 From: partisan Date: Mon, 12 Aug 2024 12:56:42 +0200 Subject: [PATCH 25/34] added image fetching using Bing --- README.md | 2 +- images-bing.go | 107 +++++++++++++++++++++++++++++++++++++++++++++++++ images.go | 3 +- 3 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 images-bing.go diff --git a/README.md b/README.md index 0f55f01..f6b7546 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ A self-hosted private and anonymous [metasearch engine](https://en.wikipedia.org ## Features - Text search using Google, Brave, DuckDuckGo and LibreX/Y. -- Image search using the Qwant/Imgur. +- 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 diff --git a/images-bing.go b/images-bing.go new file mode 100644 index 0000000..a9f8717 --- /dev/null +++ b/images-bing.go @@ -0,0 +1,107 @@ +package main + +import ( + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/PuerkitoBio/goquery" +) + +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(".imgpt").Each(func(i int, s *goquery.Selection) { + imgTag := s.Find("img") + imgSrc, exists := imgTag.Attr("src") + if !exists { + return + } + + title, _ := imgTag.Attr("alt") + + // Extract width and height if available + width, _ := strconv.Atoi(imgTag.AttrOr("width", "0")) + height, _ := strconv.Atoi(imgTag.AttrOr("height", "0")) + + // Extract the original image URL from the `mediaurl` parameter in the link + pageLink, exists := s.Find("a.iusc").Attr("href") + mediaURL := "" + if exists { + if u, err := url.Parse(pageLink); err == nil { + if mediaURLParam := u.Query().Get("mediaurl"); mediaURLParam != "" { + mediaURL, _ = url.QueryUnescape(mediaURLParam) + } + } + } + + results = append(results, ImageSearchResult{ + Thumbnail: imgSrc, + Title: strings.TrimSpace(title), + Media: imgSrc, + Width: width, + Height: height, + Source: mediaURL, // Original image URL + ThumbProxy: imgSrc, + }) + }) + + duration := time.Since(startTime) + + // Check if the number of results is one or less + if len(results) <= 1 { + return nil, duration, fmt.Errorf("no images found") + } + + return results, duration, nil +} + +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() +} + +// 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) +// } +// } diff --git a/images.go b/images.go index 13873af..d159165 100644 --- a/images.go +++ b/images.go @@ -13,7 +13,8 @@ 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}, // Bing sometimes returns with low amount of images, this leads to danamica page loading not working + {Name: "Imgur", Func: wrapImageSearchFunc(PerformImgurImageSearch), Weight: 3}, } } -- 2.40.1 From 04fb0ca62938053ae42cb7a91a36107eaa3bcfcd Mon Sep 17 00:00:00 2001 From: partisan Date: Mon, 12 Aug 2024 17:02:17 +0200 Subject: [PATCH 26/34] random geolocation for search, tmp --- text-google.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/text-google.go b/text-google.go index ce7646f..98cf897 100644 --- a/text-google.go +++ b/text-google.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "math/rand" "net/http" "net/url" "strings" @@ -69,8 +70,22 @@ func buildSearchURL(query, safe, lang string, page, resultsPerPage int) string { langParam = "&lr=" + lang } + // Generate 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) + 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 { -- 2.40.1 From e0568323214edda8beafc6e48753a1bb950fe506 Mon Sep 17 00:00:00 2001 From: partisan Date: Tue, 13 Aug 2024 16:31:28 +0200 Subject: [PATCH 27/34] cleanup --- agent.go | 710 ++++++++++++++++++++--------------------- common.go | 99 +++--- files.go | 515 +++++++++++++++--------------- forums.go | 284 ++++++++--------- images.go | 294 ++++++++--------- main.go | 355 ++++++++++----------- map.go | 144 ++++----- node-handle-search.go | 438 ++++++++++++------------- node-request-files.go | 165 +++++----- node-request-forums.go | 201 ++++++------ node-request-images.go | 169 +++++----- node-request-text.go | 169 +++++----- node-request-video.go | 165 +++++----- run.bat | 31 ++ text.go | 366 ++++++++++----------- video.go | 422 ++++++++++++------------ 16 files changed, 2275 insertions(+), 2252 deletions(-) mode change 100644 => 100755 agent.go mode change 100644 => 100755 common.go mode change 100644 => 100755 files.go mode change 100644 => 100755 forums.go mode change 100644 => 100755 images.go mode change 100644 => 100755 main.go mode change 100644 => 100755 map.go mode change 100644 => 100755 node-handle-search.go mode change 100644 => 100755 node-request-files.go mode change 100644 => 100755 node-request-forums.go mode change 100644 => 100755 node-request-images.go mode change 100644 => 100755 node-request-text.go mode change 100644 => 100755 node-request-video.go create mode 100755 run.bat mode change 100644 => 100755 text.go mode change 100644 => 100755 video.go diff --git a/agent.go b/agent.go old mode 100644 new mode 100755 index 172b209..296b4e4 --- a/agent.go +++ b/agent.go @@ -1,355 +1,355 @@ -package main - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "math/rand" - "net/http" - "sort" - "sync" - "time" -) - -type BrowserVersion struct { - Version string `json:"version"` - Global float64 `json:"global"` -} - -type BrowserData struct { - Firefox []BrowserVersion `json:"firefox"` - Chromium []BrowserVersion `json:"chrome"` -} - -var ( - cache = struct { - sync.RWMutex - data map[string]string - }{ - data: make(map[string]string), - } - browserCache = struct { - sync.RWMutex - data BrowserData - expires time.Time - }{ - expires: time.Now(), - } -) - -func fetchLatestBrowserVersions() (BrowserData, error) { - url := "https://raw.githubusercontent.com/Fyrd/caniuse/master/fulldata-json/data-2.0.json" - - resp, err := http.Get(url) - if err != nil { - return BrowserData{}, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return BrowserData{}, err - } - - var rawData map[string]interface{} - if err := json.Unmarshal(body, &rawData); err != nil { - return BrowserData{}, err - } - - stats := rawData["agents"].(map[string]interface{}) - - var data BrowserData - - if firefoxData, ok := stats["firefox"].(map[string]interface{}); ok { - for version, usage := range firefoxData["usage_global"].(map[string]interface{}) { - data.Firefox = append(data.Firefox, BrowserVersion{ - Version: version, - Global: usage.(float64), - }) - } - } - - if chromeData, ok := stats["chrome"].(map[string]interface{}); ok { - for version, usage := range chromeData["usage_global"].(map[string]interface{}) { - data.Chromium = append(data.Chromium, BrowserVersion{ - Version: version, - Global: usage.(float64), - }) - } - } - - return data, nil -} - -func getLatestBrowserVersions() (BrowserData, error) { - browserCache.RLock() - if time.Now().Before(browserCache.expires) { - data := browserCache.data - browserCache.RUnlock() - return data, nil - } - browserCache.RUnlock() - - data, err := fetchLatestBrowserVersions() - if err != nil { - return BrowserData{}, err - } - - browserCache.Lock() - browserCache.data = data - browserCache.expires = time.Now().Add(24 * time.Hour) - browserCache.Unlock() - - return data, nil -} - -func randomUserAgent() (string, error) { - browsers, err := getLatestBrowserVersions() - if err != nil { - return "", err - } - - rand.Seed(time.Now().UnixNano()) - - // Simulated browser usage statistics (in percentages) - usageStats := map[string]float64{ - "Firefox": 30.0, - "Chromium": 70.0, - } - - // Calculate the probabilities for the versions - probabilities := []float64{0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625} - - // Select a browser based on usage statistics - browserType := "" - randVal := rand.Float64() * 100 - cumulative := 0.0 - for browser, usage := range usageStats { - cumulative += usage - if randVal < cumulative { - browserType = browser - break - } - } - - var versions []BrowserVersion - switch browserType { - case "Firefox": - versions = browsers.Firefox - case "Chromium": - versions = browsers.Chromium - } - - if len(versions) == 0 { - return "", fmt.Errorf("no versions found for browser: %s", browserType) - } - - // Sort versions by usage (descending order) - sort.Slice(versions, func(i, j int) bool { - return versions[i].Global > versions[j].Global - }) - - // Select a version based on the probabilities - version := "" - randVal = rand.Float64() - cumulative = 0.0 - for i, p := range probabilities { - cumulative += p - if randVal < cumulative && i < len(versions) { - version = versions[i].Version - break - } - } - - if version == "" { - version = versions[len(versions)-1].Version - } - - // Generate the user agent string - userAgent := generateUserAgent(browserType, version) - return userAgent, nil -} - -func generateUserAgent(browser, version string) string { - oses := []struct { - os string - probability float64 - }{ - {"Windows NT 10.0; Win64; x64", 44.0}, - {"Windows NT 11.0; Win64; x64", 44.0}, - {"X11; Linux x86_64", 1.0}, - {"X11; Ubuntu; Linux x86_64", 1.0}, - {"Macintosh; Intel Mac OS X 10_15_7", 10.0}, - } - - // Select an OS based on probabilities - randVal := rand.Float64() * 100 - cumulative := 0.0 - selectedOS := "" - for _, os := range oses { - cumulative += os.probability - if randVal < cumulative { - selectedOS = os.os - break - } - } - - switch browser { - case "Firefox": - return fmt.Sprintf("Mozilla/5.0 (%s; rv:%s) Gecko/20100101 Firefox/%s", selectedOS, version, version) - case "Chromium": - return fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", selectedOS, version) - } - return "" -} - -func updateCachedUserAgents(newVersions BrowserData) { - cache.Lock() - defer cache.Unlock() - for key, userAgent := range cache.data { - randVal := rand.Float64() - if randVal < 0.5 { - updatedUserAgent := updateUserAgentVersion(userAgent, newVersions) - cache.data[key] = updatedUserAgent - } - } -} - -func updateUserAgentVersion(userAgent string, newVersions BrowserData) string { - // Parse the current user agent to extract browser and version - var browserType, version string - if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { - browserType = "Chromium" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { - browserType = "Chromium" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { - browserType = "Chromium" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { - browserType = "Chromium" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { - browserType = "Chromium" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { - browserType = "Firefox" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 11.0; Win64; x64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { - browserType = "Firefox" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { - browserType = "Firefox" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { - browserType = "Firefox" - } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { - browserType = "Firefox" - } - - // Get the latest version for the browser type - var latestVersion string - if browserType == "Firefox" { - latestVersion = newVersions.Firefox[0].Version - } else if browserType == "Chromium" { - latestVersion = newVersions.Chromium[0].Version - } - - // Update the user agent string with the new version - return generateUserAgent(browserType, latestVersion) -} - -func periodicUpdate() { - for { - // Sleep for a random interval between 1 and 2 days - time.Sleep(time.Duration(24+rand.Intn(24)) * time.Hour) - - // Fetch the latest browser versions - newVersions, err := fetchLatestBrowserVersions() - if err != nil { - fmt.Println("Error fetching latest browser versions:", err) - continue - } - - // Update the browser version cache - browserCache.Lock() - browserCache.data = newVersions - browserCache.expires = time.Now().Add(24 * time.Hour) - browserCache.Unlock() - - // Update the cached user agents - updateCachedUserAgents(newVersions) - } -} - -func GetUserAgent(cacheKey string) (string, error) { - cache.RLock() - userAgent, found := cache.data[cacheKey] - cache.RUnlock() - - if found { - return userAgent, nil - } - - userAgent, err := randomUserAgent() - if err != nil { - return "", err - } - - cache.Lock() - cache.data[cacheKey] = userAgent - cache.Unlock() - - return userAgent, nil -} - -func GetNewUserAgent(cacheKey string) (string, error) { - userAgent, err := randomUserAgent() - if err != nil { - return "", err - } - - cache.Lock() - cache.data[cacheKey] = userAgent - cache.Unlock() - - return userAgent, nil -} - -func init() { - go periodicUpdate() -} - -// func main() { -// go periodicUpdate() // not needed here - -// cacheKey := "image-search" -// userAgent, err := GetUserAgent(cacheKey) -// if err != nil { -// fmt.Println("Error:", err) -// return -// } - -// fmt.Println("Generated User Agent:", userAgent) - -// // Request a new user agent for the same key -// newUserAgent, err := GetNewUserAgent(cacheKey) -// if err != nil { -// fmt.Println("Error:", err) -// return -// } - -// fmt.Println("New User Agent:", newUserAgent) - -// AcacheKey := "image-search" -// AuserAgent, err := GetUserAgent(AcacheKey) -// if err != nil { -// fmt.Println("Error:", err) -// return -// } - -// fmt.Println("Generated User Agent:", AuserAgent) - -// DcacheKey := "image-search" -// DuserAgent, err := GetUserAgent(DcacheKey) -// if err != nil { -// fmt.Println("Error:", err) -// return -// } - -// fmt.Println("Generated User Agent:", DuserAgent) - -// } +package main + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "math/rand" + "net/http" + "sort" + "sync" + "time" +) + +type BrowserVersion struct { + Version string `json:"version"` + Global float64 `json:"global"` +} + +type BrowserData struct { + Firefox []BrowserVersion `json:"firefox"` + Chromium []BrowserVersion `json:"chrome"` +} + +var ( + cache = struct { + sync.RWMutex + data map[string]string + }{ + data: make(map[string]string), + } + browserCache = struct { + sync.RWMutex + data BrowserData + expires time.Time + }{ + expires: time.Now(), + } +) + +func fetchLatestBrowserVersions() (BrowserData, error) { + url := "https://raw.githubusercontent.com/Fyrd/caniuse/master/fulldata-json/data-2.0.json" + + resp, err := http.Get(url) + if err != nil { + return BrowserData{}, err + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return BrowserData{}, err + } + + var rawData map[string]interface{} + if err := json.Unmarshal(body, &rawData); err != nil { + return BrowserData{}, err + } + + stats := rawData["agents"].(map[string]interface{}) + + var data BrowserData + + if firefoxData, ok := stats["firefox"].(map[string]interface{}); ok { + for version, usage := range firefoxData["usage_global"].(map[string]interface{}) { + data.Firefox = append(data.Firefox, BrowserVersion{ + Version: version, + Global: usage.(float64), + }) + } + } + + if chromeData, ok := stats["chrome"].(map[string]interface{}); ok { + for version, usage := range chromeData["usage_global"].(map[string]interface{}) { + data.Chromium = append(data.Chromium, BrowserVersion{ + Version: version, + Global: usage.(float64), + }) + } + } + + return data, nil +} + +func getLatestBrowserVersions() (BrowserData, error) { + browserCache.RLock() + if time.Now().Before(browserCache.expires) { + data := browserCache.data + browserCache.RUnlock() + return data, nil + } + browserCache.RUnlock() + + data, err := fetchLatestBrowserVersions() + if err != nil { + return BrowserData{}, err + } + + browserCache.Lock() + browserCache.data = data + browserCache.expires = time.Now().Add(24 * time.Hour) + browserCache.Unlock() + + return data, nil +} + +func randomUserAgent() (string, error) { + browsers, err := getLatestBrowserVersions() + if err != nil { + return "", err + } + + rand.Seed(time.Now().UnixNano()) + + // Simulated browser usage statistics (in percentages) + usageStats := map[string]float64{ + "Firefox": 30.0, + "Chromium": 70.0, + } + + // Calculate the probabilities for the versions + probabilities := []float64{0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625} + + // Select a browser based on usage statistics + browserType := "" + randVal := rand.Float64() * 100 + cumulative := 0.0 + for browser, usage := range usageStats { + cumulative += usage + if randVal < cumulative { + browserType = browser + break + } + } + + var versions []BrowserVersion + switch browserType { + case "Firefox": + versions = browsers.Firefox + case "Chromium": + versions = browsers.Chromium + } + + if len(versions) == 0 { + return "", fmt.Errorf("no versions found for browser: %s", browserType) + } + + // Sort versions by usage (descending order) + sort.Slice(versions, func(i, j int) bool { + return versions[i].Global > versions[j].Global + }) + + // Select a version based on the probabilities + version := "" + randVal = rand.Float64() + cumulative = 0.0 + for i, p := range probabilities { + cumulative += p + if randVal < cumulative && i < len(versions) { + version = versions[i].Version + break + } + } + + if version == "" { + version = versions[len(versions)-1].Version + } + + // Generate the user agent string + userAgent := generateUserAgent(browserType, version) + return userAgent, nil +} + +func generateUserAgent(browser, version string) string { + oses := []struct { + os string + probability float64 + }{ + {"Windows NT 10.0; Win64; x64", 44.0}, + {"Windows NT 11.0; Win64; x64", 44.0}, + {"X11; Linux x86_64", 1.0}, + {"X11; Ubuntu; Linux x86_64", 1.0}, + {"Macintosh; Intel Mac OS X 10_15_7", 10.0}, + } + + // Select an OS based on probabilities + randVal := rand.Float64() * 100 + cumulative := 0.0 + selectedOS := "" + for _, os := range oses { + cumulative += os.probability + if randVal < cumulative { + selectedOS = os.os + break + } + } + + switch browser { + case "Firefox": + return fmt.Sprintf("Mozilla/5.0 (%s; rv:%s) Gecko/20100101 Firefox/%s", selectedOS, version, version) + case "Chromium": + return fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", selectedOS, version) + } + return "" +} + +func updateCachedUserAgents(newVersions BrowserData) { + cache.Lock() + defer cache.Unlock() + for key, userAgent := range cache.data { + randVal := rand.Float64() + if randVal < 0.5 { + updatedUserAgent := updateUserAgentVersion(userAgent, newVersions) + cache.data[key] = updatedUserAgent + } + } +} + +func updateUserAgentVersion(userAgent string, newVersions BrowserData) string { + // Parse the current user agent to extract browser and version + var browserType, version string + if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { + browserType = "Chromium" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { + browserType = "Chromium" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { + browserType = "Chromium" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { + browserType = "Chromium" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", &version); err == nil { + browserType = "Chromium" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { + browserType = "Firefox" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Windows NT 11.0; Win64; x64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { + browserType = "Firefox" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { + browserType = "Firefox" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { + browserType = "Firefox" + } else if _, err := fmt.Sscanf(userAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7; rv:%s) Gecko/20100101 Firefox/%s", &version, &version); err == nil { + browserType = "Firefox" + } + + // Get the latest version for the browser type + var latestVersion string + if browserType == "Firefox" { + latestVersion = newVersions.Firefox[0].Version + } else if browserType == "Chromium" { + latestVersion = newVersions.Chromium[0].Version + } + + // Update the user agent string with the new version + return generateUserAgent(browserType, latestVersion) +} + +func periodicUpdate() { + for { + // Sleep for a random interval between 1 and 2 days + time.Sleep(time.Duration(24+rand.Intn(24)) * time.Hour) + + // Fetch the latest browser versions + newVersions, err := fetchLatestBrowserVersions() + if err != nil { + printWarn("Error fetching latest browser versions: %v", err) + continue + } + + // Update the browser version cache + browserCache.Lock() + browserCache.data = newVersions + browserCache.expires = time.Now().Add(24 * time.Hour) + browserCache.Unlock() + + // Update the cached user agents + updateCachedUserAgents(newVersions) + } +} + +func GetUserAgent(cacheKey string) (string, error) { + cache.RLock() + userAgent, found := cache.data[cacheKey] + cache.RUnlock() + + if found { + return userAgent, nil + } + + userAgent, err := randomUserAgent() + if err != nil { + return "", err + } + + cache.Lock() + cache.data[cacheKey] = userAgent + cache.Unlock() + + return userAgent, nil +} + +func GetNewUserAgent(cacheKey string) (string, error) { + userAgent, err := randomUserAgent() + if err != nil { + return "", err + } + + cache.Lock() + cache.data[cacheKey] = userAgent + cache.Unlock() + + return userAgent, nil +} + +func init() { + go periodicUpdate() +} + +// func main() { +// go periodicUpdate() // not needed here + +// cacheKey := "image-search" +// userAgent, err := GetUserAgent(cacheKey) +// if err != nil { +// fmt.Println("Error:", err) +// return +// } + +// fmt.Println("Generated User Agent:", userAgent) + +// // Request a new user agent for the same key +// newUserAgent, err := GetNewUserAgent(cacheKey) +// if err != nil { +// fmt.Println("Error:", err) +// return +// } + +// fmt.Println("New User Agent:", newUserAgent) + +// AcacheKey := "image-search" +// AuserAgent, err := GetUserAgent(AcacheKey) +// if err != nil { +// fmt.Println("Error:", err) +// return +// } + +// fmt.Println("Generated User Agent:", AuserAgent) + +// DcacheKey := "image-search" +// DuserAgent, err := GetUserAgent(DcacheKey) +// if err != nil { +// fmt.Println("Error:", err) +// return +// } + +// fmt.Println("Generated User Agent:", DuserAgent) + +// } diff --git a/common.go b/common.go old mode 100644 new mode 100755 index 33d3ee9..3915f24 --- a/common.go +++ b/common.go @@ -1,50 +1,49 @@ -package main - -import ( - "crypto/rand" - "encoding/base64" - "html/template" - "log" - "strings" -) - -var ( - funcs = template.FuncMap{ - "sub": func(a, b int) int { - return a - b - }, - "add": func(a, b int) int { - return a + b - }, - } -) - -func generateStrongRandomString(length int) string { - bytes := make([]byte, length) - _, err := rand.Read(bytes) - if err != nil { - log.Fatalf("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 -} +package main + +import ( + "crypto/rand" + "encoding/base64" + "html/template" + "strings" +) + +var ( + funcs = template.FuncMap{ + "sub": func(a, b int) int { + return a - b + }, + "add": func(a, b int) int { + return a + b + }, + } +) + +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 +} diff --git a/files.go b/files.go old mode 100644 new mode 100755 index 65dee0a..b397a99 --- a/files.go +++ b/files.go @@ -1,258 +1,257 @@ -package main - -import ( - "fmt" - "html/template" - "log" - "net/http" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - "time" -) - -type Settings struct { - UxLang string - Safe string -} - -type TorrentSite interface { - Name() string - Search(query string, category string) ([]TorrentResult, error) -} - -var ( - torrentGalaxy TorrentSite - nyaa TorrentSite - thePirateBay TorrentSite - rutor TorrentSite -) - -var fileResultsChan = make(chan []TorrentResult) - -func initializeTorrentSites() { - torrentGalaxy = NewTorrentGalaxy() - // nyaa = NewNyaa() - thePirateBay = NewThePirateBay() - // rutor = NewRutor() -} - -func handleFileSearch(w http.ResponseWriter, settings UserSettings, query, safe, lang 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) - - sort.Slice(combinedResults, func(i, j int) bool { return combinedResults[i].Seeders > combinedResults[j].Seeders }) - - elapsedTime := time.Since(startTime) - funcMap := template.FuncMap{ - "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) - 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 - Theme string - }{ - 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}, // Now this is painful, are there two Settings variables?? - Theme: settings.Theme, - } - - // // 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) - http.Error(w, "Failed to render template", http.StatusInternalServerError) - } -} - -func getFileResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []TorrentResult { - cacheChan := make(chan []SearchResult) - var combinedResults []TorrentResult - - 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 { - 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 = fetchFileResults(query, safe, lang, page) - if len(combinedResults) > 0 { - resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) - } - } - - return combinedResults -} - -func fetchFileResults(query, safe, lang string, page int) []TorrentResult { - sites := []TorrentSite{torrentGalaxy, nyaa, thePirateBay, rutor} - results := []TorrentResult{} - - for _, site := range sites { - if site == nil { - continue - } - res, err := site.Search(query, "all") - if err != nil { - continue - } - for _, r := range res { - r.Magnet = removeMagnetLink(r.Magnet) // Remove "magnet:", prehaps usless now? - results = append(results, r) - } - } - - if len(results) == 0 { - log.Printf("No file results found for query: %s, trying other nodes", query) - results = tryOtherNodesForFileSearch(query, safe, lang, page, []string{hostID}) - } - - return results -} - -func removeMagnetLink(magnet string) string { - // Remove the magnet: prefix unconditionally - return strings.TrimPrefix(magnet, "magnet:") -} - -func parseInt(s string) int { - i, err := strconv.Atoi(s) - if err != nil { - return 0 - } - return i -} - -func parseSize(sizeStr string) int64 { - sizeStr = strings.TrimSpace(sizeStr) - if sizeStr == "" { - return 0 - } - - // Use regex to extract numeric value and unit separately - 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) - return 0 - } - - sizeStr = matches[1] - unit := strings.ToUpper(matches[2]) - - var multiplier int64 = 1 - switch unit { - case "KB": - multiplier = 1024 - case "MB": - multiplier = 1024 * 1024 - case "GB": - multiplier = 1024 * 1024 * 1024 - case "TB": - multiplier = 1024 * 1024 * 1024 * 1024 - default: - log.Printf("Unknown unit: %s", unit) - return 0 - } - - size, err := strconv.ParseFloat(sizeStr, 64) - if err != nil { - log.Printf("Error parsing size: %v", err) - return 0 - } - return int64(size * float64(multiplier)) -} - -// apparently this is needed so it can announce that magnet link is being used and people start seeding it, but I dont like the fact that I add trackers purposefully -func applyTrackers(magnetLink string) string { - if magnetLink == "" { - return "" - } - trackers := []string{ - "udp://tracker.openbittorrent.com:80/announce", - "udp://tracker.opentrackr.org:1337/announce", - "udp://tracker.coppersurfer.tk:6969/announce", - "udp://tracker.leechers-paradise.org:6969/announce", - } - for _, tracker := range trackers { - magnetLink += "&tr=" + url.QueryEscape(tracker) - } - return magnetLink -} - -func formatSize(size int64) string { - if size >= 1024*1024*1024*1024 { - return fmt.Sprintf("%.2f TB", float64(size)/(1024*1024*1024*1024)) - } else if size >= 1024*1024*1024 { - return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024)) - } else if size >= 1024*1024 { - return fmt.Sprintf("%.2f MB", float64(size)/(1024*1024)) - } else if size >= 1024 { - return fmt.Sprintf("%.2f KB", float64(size)/1024) - } - return fmt.Sprintf("%d B", size) -} - -func sanitizeFileName(name string) string { - // Replace spaces with dashes - sanitized := regexp.MustCompile(`\s+`).ReplaceAllString(name, "-") - // Remove any characters that are not alphanumeric, dashes, or parentheses - 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 -} +package main + +import ( + "fmt" + "html/template" + "net/http" + "net/url" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +type Settings struct { + UxLang string + Safe string +} + +type TorrentSite interface { + Name() string + Search(query string, category string) ([]TorrentResult, error) +} + +var ( + torrentGalaxy TorrentSite + nyaa TorrentSite + thePirateBay TorrentSite + rutor TorrentSite +) + +var fileResultsChan = make(chan []TorrentResult) + +func initializeTorrentSites() { + torrentGalaxy = NewTorrentGalaxy() + // nyaa = NewNyaa() + thePirateBay = NewThePirateBay() + // rutor = NewRutor() +} + +func handleFileSearch(w http.ResponseWriter, settings UserSettings, query string, page int) { + startTime := time.Now() + + cacheKey := CacheKey{Query: query, Page: page, Safe: settings.SafeSearch == "true", Lang: settings.Language, Type: "file"} + combinedResults := getFileResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.Language, page) + + sort.Slice(combinedResults, func(i, j int) bool { return combinedResults[i].Seeders > combinedResults[j].Seeders }) + + elapsedTime := time.Since(startTime) + funcMap := template.FuncMap{ + "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 { + 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 + Theme string + }{ + 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: settings.Language, Safe: settings.SafeSearch}, // Now this is painful, are there two Settings variables?? + Theme: settings.Theme, + } + + // // 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 { + printErr("Failed to render template: %v", err) + http.Error(w, "Failed to render template", http.StatusInternalServerError) + } +} + +func getFileResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []TorrentResult { + cacheChan := make(chan []SearchResult) + var combinedResults []TorrentResult + + go func() { + results, exists := resultsCache.Get(cacheKey) + if exists { + printInfo("Cache hit") + cacheChan <- results + } else { + printInfo("Cache miss") + cacheChan <- nil + } + }() + + select { + case results := <-cacheChan: + if results == nil { + 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): + printInfo("Cache check timeout") + combinedResults = fetchFileResults(query, safe, lang, page) + if len(combinedResults) > 0 { + resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) + } + } + + return combinedResults +} + +func fetchFileResults(query, safe, lang string, page int) []TorrentResult { + sites := []TorrentSite{torrentGalaxy, nyaa, thePirateBay, rutor} + results := []TorrentResult{} + + for _, site := range sites { + if site == nil { + continue + } + res, err := site.Search(query, "all") + if err != nil { + continue + } + for _, r := range res { + r.Magnet = removeMagnetLink(r.Magnet) // Remove "magnet:", prehaps usless now? + results = append(results, r) + } + } + + 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 +} + +func removeMagnetLink(magnet string) string { + // Remove the magnet: prefix unconditionally + return strings.TrimPrefix(magnet, "magnet:") +} + +func parseInt(s string) int { + i, err := strconv.Atoi(s) + if err != nil { + return 0 + } + return i +} + +func parseSize(sizeStr string) int64 { + sizeStr = strings.TrimSpace(sizeStr) + if sizeStr == "" { + return 0 + } + + // Use regex to extract numeric value and unit separately + re := regexp.MustCompile(`(?i)([\d.]+)\s*([KMGT]?B)`) + matches := re.FindStringSubmatch(sizeStr) + if len(matches) < 3 { + printWarn("Error parsing size: invalid format %s", sizeStr) + return 0 + } + + sizeStr = matches[1] + unit := strings.ToUpper(matches[2]) + + var multiplier int64 = 1 + switch unit { + case "KB": + multiplier = 1024 + case "MB": + multiplier = 1024 * 1024 + case "GB": + multiplier = 1024 * 1024 * 1024 + case "TB": + multiplier = 1024 * 1024 * 1024 * 1024 + default: + printWarn("Unknown unit: %s", unit) + return 0 + } + + size, err := strconv.ParseFloat(sizeStr, 64) + if err != nil { + printWarn("Error parsing size: %v", err) + return 0 + } + return int64(size * float64(multiplier)) +} + +// apparently this is needed so it can announce that magnet link is being used and people start seeding it, but I dont like the fact that I add trackers purposefully +func applyTrackers(magnetLink string) string { + if magnetLink == "" { + return "" + } + trackers := []string{ + "udp://tracker.openbittorrent.com:80/announce", + "udp://tracker.opentrackr.org:1337/announce", + "udp://tracker.coppersurfer.tk:6969/announce", + "udp://tracker.leechers-paradise.org:6969/announce", + } + for _, tracker := range trackers { + magnetLink += "&tr=" + url.QueryEscape(tracker) + } + return magnetLink +} + +func formatSize(size int64) string { + if size >= 1024*1024*1024*1024 { + return fmt.Sprintf("%.2f TB", float64(size)/(1024*1024*1024*1024)) + } else if size >= 1024*1024*1024 { + return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024)) + } else if size >= 1024*1024 { + return fmt.Sprintf("%.2f MB", float64(size)/(1024*1024)) + } else if size >= 1024 { + return fmt.Sprintf("%.2f KB", float64(size)/1024) + } + return fmt.Sprintf("%d B", size) +} + +func sanitizeFileName(name string) string { + // Replace spaces with dashes + sanitized := regexp.MustCompile(`\s+`).ReplaceAllString(name, "-") + // Remove any characters that are not alphanumeric, dashes, or parentheses + 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 +} diff --git a/forums.go b/forums.go old mode 100644 new mode 100755 index e3fbed5..69f911e --- a/forums.go +++ b/forums.go @@ -1,142 +1,142 @@ -package main - -import ( - "encoding/json" - "fmt" - "html/template" - "log" - "math" - "net/http" - "net/url" - "time" -) - -func PerformRedditSearch(query string, safe string, page int) ([]ForumSearchResult, error) { - const ( - pageSize = 25 - baseURL = "https://www.reddit.com" - maxRetries = 5 - initialBackoff = 2 * time.Second - ) - var results []ForumSearchResult - - searchURL := fmt.Sprintf("%s/search.json?q=%s&limit=%d&start=%d", baseURL, url.QueryEscape(query), pageSize, page*pageSize) - var resp *http.Response - var err error - - // Retry logic with exponential backoff - for i := 0; i <= maxRetries; i++ { - resp, err = http.Get(searchURL) - if err != nil { - return nil, fmt.Errorf("making request: %v", err) - } - if resp.StatusCode != http.StatusTooManyRequests { - break - } - - // Wait for some time before retrying - backoff := time.Duration(math.Pow(2, float64(i))) * initialBackoff - time.Sleep(backoff) - } - - if err != nil { - return nil, fmt.Errorf("making request: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) - } - - var searchResults map[string]interface{} - if err := json.NewDecoder(resp.Body).Decode(&searchResults); err != nil { - return nil, fmt.Errorf("decoding response: %v", err) - } - - data, ok := searchResults["data"].(map[string]interface{}) - if !ok { - return nil, fmt.Errorf("no data field in response") - } - - posts, ok := data["children"].([]interface{}) - if !ok { - return nil, fmt.Errorf("no children field in data") - } - - for _, post := range posts { - postData := post.(map[string]interface{})["data"].(map[string]interface{}) - - if safe == "active" && postData["over_18"].(bool) { - continue - } - - header := postData["title"].(string) - description := postData["selftext"].(string) - if len(description) > 500 { - description = description[:500] + "..." - } - publishedDate := time.Unix(int64(postData["created_utc"].(float64)), 0) - permalink := postData["permalink"].(string) - resultURL := fmt.Sprintf("%s%s", baseURL, permalink) - - result := ForumSearchResult{ - URL: resultURL, - Header: header, - Description: description, - PublishedDate: publishedDate, - } - - thumbnail := postData["thumbnail"].(string) - if parsedURL, err := url.Parse(thumbnail); err == nil && parsedURL.Scheme != "" { - result.ImgSrc = postData["url"].(string) - result.ThumbnailSrc = thumbnail - } - - results = append(results, result) - } - - return results, nil -} - -func handleForumsSearch(w http.ResponseWriter, settings UserSettings, query, safe, lang string, page int) { - results, err := PerformRedditSearch(query, safe, 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, safe, lang, page) - } - - data := struct { - Query string - Results []ForumSearchResult - LanguageOptions []LanguageOption - CurrentLang string - Page int - HasPrevPage bool - HasNextPage bool - Theme string - }{ - Query: query, - Results: results, - LanguageOptions: languageOptions, - CurrentLang: lang, - Page: page, - HasPrevPage: page > 1, - HasNextPage: len(results) == 25, - Theme: settings.Theme, - } - - funcMap := template.FuncMap{ - "sub": func(a, b int) int { return a - b }, - "add": func(a, b int) int { return a + b }, - } - - tmpl, err := template.New("forums.html").Funcs(funcMap).ParseFiles("templates/forums.html") - if err != nil { - http.Error(w, fmt.Sprintf("Error loading template: %v", err), http.StatusInternalServerError) - return - } - - if err := tmpl.Execute(w, data); err != nil { - http.Error(w, fmt.Sprintf("Error rendering template: %v", err), http.StatusInternalServerError) - } -} +package main + +import ( + "encoding/json" + "fmt" + "html/template" + "log" + "math" + "net/http" + "net/url" + "time" +) + +func PerformRedditSearch(query string, safe string, page int) ([]ForumSearchResult, error) { + const ( + pageSize = 25 + baseURL = "https://www.reddit.com" + maxRetries = 5 + initialBackoff = 2 * time.Second + ) + var results []ForumSearchResult + + searchURL := fmt.Sprintf("%s/search.json?q=%s&limit=%d&start=%d", baseURL, url.QueryEscape(query), pageSize, page*pageSize) + var resp *http.Response + var err error + + // Retry logic with exponential backoff + for i := 0; i <= maxRetries; i++ { + resp, err = http.Get(searchURL) + if err != nil { + return nil, fmt.Errorf("making request: %v", err) + } + if resp.StatusCode != http.StatusTooManyRequests { + break + } + + // Wait for some time before retrying + backoff := time.Duration(math.Pow(2, float64(i))) * initialBackoff + time.Sleep(backoff) + } + + if err != nil { + return nil, fmt.Errorf("making request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) + } + + var searchResults map[string]interface{} + if err := json.NewDecoder(resp.Body).Decode(&searchResults); err != nil { + return nil, fmt.Errorf("decoding response: %v", err) + } + + data, ok := searchResults["data"].(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("no data field in response") + } + + posts, ok := data["children"].([]interface{}) + if !ok { + return nil, fmt.Errorf("no children field in data") + } + + for _, post := range posts { + postData := post.(map[string]interface{})["data"].(map[string]interface{}) + + if safe == "active" && postData["over_18"].(bool) { + continue + } + + header := postData["title"].(string) + description := postData["selftext"].(string) + if len(description) > 500 { + description = description[:500] + "..." + } + publishedDate := time.Unix(int64(postData["created_utc"].(float64)), 0) + permalink := postData["permalink"].(string) + resultURL := fmt.Sprintf("%s%s", baseURL, permalink) + + result := ForumSearchResult{ + URL: resultURL, + Header: header, + Description: description, + PublishedDate: publishedDate, + } + + thumbnail := postData["thumbnail"].(string) + if parsedURL, err := url.Parse(thumbnail); err == nil && parsedURL.Scheme != "" { + result.ImgSrc = postData["url"].(string) + result.ThumbnailSrc = thumbnail + } + + results = append(results, result) + } + + return results, nil +} + +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.Language, page) + } + + data := struct { + Query string + Results []ForumSearchResult + LanguageOptions []LanguageOption + CurrentLang string + Page int + HasPrevPage bool + HasNextPage bool + Theme string + }{ + Query: query, + Results: results, + LanguageOptions: languageOptions, + CurrentLang: settings.Language, + Page: page, + HasPrevPage: page > 1, + HasNextPage: len(results) == 25, + Theme: settings.Theme, + } + + funcMap := template.FuncMap{ + "sub": func(a, b int) int { return a - b }, + "add": func(a, b int) int { return a + b }, + } + + tmpl, err := template.New("forums.html").Funcs(funcMap).ParseFiles("templates/forums.html") + if err != nil { + http.Error(w, fmt.Sprintf("Error loading template: %v", err), http.StatusInternalServerError) + return + } + + if err := tmpl.Execute(w, data); err != nil { + http.Error(w, fmt.Sprintf("Error rendering template: %v", err), http.StatusInternalServerError) + } +} diff --git a/images.go b/images.go old mode 100644 new mode 100755 index d159165..bf1a840 --- a/images.go +++ b/images.go @@ -1,147 +1,147 @@ -package main - -import ( - "fmt" - "html/template" - "log" - "net/http" - "time" -) - -var imageSearchEngines []SearchEngine - -func init() { - imageSearchEngines = []SearchEngine{ - {Name: "Qwant", Func: wrapImageSearchFunc(PerformQwantImageSearch), Weight: 1}, - {Name: "Bing", Func: wrapImageSearchFunc(PerformBingImageSearch), Weight: 2}, // Bing sometimes returns with low amount of images, this leads to danamica page loading not working - {Name: "Imgur", Func: wrapImageSearchFunc(PerformImgurImageSearch), Weight: 3}, - } -} - -func handleImageSearch(w http.ResponseWriter, settings UserSettings, query, safe, lang 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) - - elapsedTime := time.Since(startTime) - tmpl, err := template.New("images.html").Funcs(funcs).ParseFiles("templates/images.html") - if err != nil { - log.Printf("Error parsing template: %v", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - - data := struct { - Results []ImageSearchResult - Query string - Page int - Fetched string - LanguageOptions []LanguageOption - CurrentLang string - HasPrevPage bool - HasNextPage bool - NoResults bool - Theme string - }{ - 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, - } - - err = tmpl.Execute(w, data) - if err != nil { - log.Printf("Error executing template: %v", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - } -} - -func getImageResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []ImageSearchResult { - cacheChan := make(chan []SearchResult) - var combinedResults []ImageSearchResult - - 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 { - combinedResults = fetchImageResults(query, safe, lang, page) - if len(combinedResults) > 0 { - resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) - } - } else { - _, _, imageResults := convertToSpecificResults(results) - combinedResults = imageResults - } - case <-time.After(2 * time.Second): - log.Println("Cache check timeout") - combinedResults = fetchImageResults(query, safe, lang, page) - if len(combinedResults) > 0 { - resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) - } - } - - return combinedResults -} - -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) - - 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) - continue - } - - for _, result := range searchResults { - results = append(results, result.(ImageSearchResult)) - } - - // If results are found, break out of the loop - if len(results) > 0 { - break - } - } - - // If no results found after trying all engines - if len(results) == 0 { - log.Printf("No image results found for query: %s, trying other nodes", query) - results = tryOtherNodesForImageSearch(query, safe, lang, page, []string{hostID}) - } - - return results -} - -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) - if err != nil { - return nil, duration, err - } - searchResults := make([]SearchResult, len(imageResults)) - for i, result := range imageResults { - searchResults[i] = result - } - return searchResults, duration, nil - } -} +package main + +import ( + "fmt" + "html/template" + "log" + "net/http" + "time" +) + +var imageSearchEngines []SearchEngine + +func init() { + imageSearchEngines = []SearchEngine{ + {Name: "Qwant", Func: wrapImageSearchFunc(PerformQwantImageSearch), Weight: 1}, + {Name: "Bing", Func: wrapImageSearchFunc(PerformBingImageSearch), Weight: 2}, // Bing sometimes returns with low amount of images, this leads to danamica page loading not working + {Name: "Imgur", Func: wrapImageSearchFunc(PerformImgurImageSearch), Weight: 3}, + } +} + +func handleImageSearch(w http.ResponseWriter, settings UserSettings, query string, page int) { + startTime := time.Now() + + cacheKey := CacheKey{Query: query, Page: page, Safe: settings.SafeSearch == "true", Lang: settings.Language, Type: "image"} + combinedResults := getImageResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.Language, page) + + elapsedTime := time.Since(startTime) + tmpl, err := template.New("images.html").Funcs(funcs).ParseFiles("templates/images.html") + if err != nil { + log.Printf("Error parsing template: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + data := struct { + Results []ImageSearchResult + Query string + Page int + Fetched string + LanguageOptions []LanguageOption + CurrentLang string + HasPrevPage bool + HasNextPage bool + NoResults bool + Theme string + }{ + Results: combinedResults, + Query: query, + Page: page, + Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()), + LanguageOptions: languageOptions, + CurrentLang: settings.Language, + HasPrevPage: page > 1, + HasNextPage: len(combinedResults) >= 50, + NoResults: len(combinedResults) == 0, + Theme: settings.Theme, + } + + err = tmpl.Execute(w, data) + if err != nil { + printErr("Error executing template: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } +} + +func getImageResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []ImageSearchResult { + cacheChan := make(chan []SearchResult) + var combinedResults []ImageSearchResult + + go func() { + results, exists := resultsCache.Get(cacheKey) + if exists { + printInfo("Cache hit") + cacheChan <- results + } else { + printInfo("Cache miss") + cacheChan <- nil + } + }() + + select { + case results := <-cacheChan: + if results == nil { + combinedResults = fetchImageResults(query, safe, lang, page) + if len(combinedResults) > 0 { + resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) + } + } else { + _, _, imageResults := convertToSpecificResults(results) + combinedResults = imageResults + } + case <-time.After(2 * time.Second): + printInfo("Cache check timeout") + combinedResults = fetchImageResults(query, safe, lang, page) + if len(combinedResults) > 0 { + resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) + } + } + + return combinedResults +} + +func fetchImageResults(query, safe, lang string, page int) []ImageSearchResult { + var results []ImageSearchResult + + for _, engine := range imageSearchEngines { + 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 { + printWarn("Error performing image search with %s: %v", engine.Name, err) + continue + } + + for _, result := range searchResults { + results = append(results, result.(ImageSearchResult)) + } + + // If results are found, break out of the loop + if len(results) > 0 { + break + } + } + + // If no results found after trying all engines + if len(results) == 0 { + printWarn("No image results found for query: %s, trying other nodes", query) + results = tryOtherNodesForImageSearch(query, safe, lang, page, []string{hostID}) + } + + return results +} + +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) + if err != nil { + return nil, duration, err + } + searchResults := make([]SearchResult, len(imageResults)) + for i, result := range imageResults { + searchResults[i] = result + } + return searchResults, duration, nil + } +} diff --git a/main.go b/main.go old mode 100644 new mode 100755 index fb12b70..6c9cb2c --- a/main.go +++ b/main.go @@ -1,178 +1,177 @@ -package main - -import ( - "fmt" - "html/template" - "log" - "net/http" - "strconv" -) - -// LanguageOption represents a language option for search -type LanguageOption struct { - Code string - 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)"}, -} - -func handleSearch(w http.ResponseWriter, r *http.Request) { - query, safe, lang, searchType, page := parseSearchParams(r) - - // Load user settings - settings = loadUserSettings(r) - - // Update the theme, safe search, and language based on query parameters or use existing settings - theme := r.URL.Query().Get("theme") - if theme != "" { - settings.Theme = theme - saveUserSettings(w, settings) - } else if settings.Theme == "" { - settings.Theme = "dark" // Default theme - } - - if safe != "" { - settings.SafeSearch = safe - saveUserSettings(w, settings) - } - - if lang != "" { - settings.Language = lang - saveUserSettings(w, settings) - } - - // Render the search page template if no query - if query == "" { - tmpl := template.Must(template.ParseFiles("templates/search.html")) - tmpl.Execute(w, settings) - return - } - - settings := loadUserSettings(r) - - // Handle search based on the type - switch searchType { - case "image": - handleImageSearch(w, settings, query, safe, lang, page) - case "video": - handleVideoSearch(w, settings, query, safe, lang, page) - case "map": - handleMapSearch(w, settings, query, safe) - case "forum": - handleForumsSearch(w, settings, query, safe, lang, page) - case "file": - handleFileSearch(w, settings, query, safe, lang, page) - case "text": - fallthrough - default: - HandleTextSearch(w, settings, query, safe, lang, page) - } - // This is immeasurably stupid it passes safe and language then it passes settings with safe and lang again -} - -func parseSearchParams(r *http.Request) (query, safe, lang, searchType string, page int) { - if r.Method == "GET" { - query = r.URL.Query().Get("q") - safe = r.URL.Query().Get("safe") - lang = r.URL.Query().Get("lang") - searchType = r.URL.Query().Get("t") - pageStr := r.URL.Query().Get("p") - page = parsePageParameter(pageStr) - } else if r.Method == "POST" { - query = r.FormValue("q") - safe = r.FormValue("safe") - lang = r.FormValue("lang") - searchType = r.FormValue("t") - pageStr := r.FormValue("p") - page = parsePageParameter(pageStr) - } - - if searchType == "" { - searchType = "text" - } - - return -} - -func parsePageParameter(pageStr string) int { - page, err := strconv.Atoi(pageStr) - if err != nil || page < 1 { - page = 1 - } - return page -} - -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("/node", handleNodeRequest) - http.HandleFunc("/settings", func(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, "templates/settings.html") - }) - 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") - }) - initializeTorrentSites() - - config := loadConfig() - generateOpenSearchXML(config) - - 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() -} +package main + +import ( + "fmt" + "html/template" + "log" + "net/http" + "strconv" +) + +// LanguageOption represents a language option for search +type LanguageOption struct { + Code string + 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)"}, +} + +func handleSearch(w http.ResponseWriter, r *http.Request) { + query, safe, lang, searchType, page := parseSearchParams(r) + + // Load user settings + settings = loadUserSettings(r) + + // Update the theme, safe search, and language based on query parameters or use existing settings + theme := r.URL.Query().Get("theme") + if theme != "" { + settings.Theme = theme + saveUserSettings(w, settings) + } else if settings.Theme == "" { + settings.Theme = "dark" // Default theme + } + + if safe != "" { + settings.SafeSearch = safe + saveUserSettings(w, settings) + } + + if lang != "" { + settings.Language = lang + saveUserSettings(w, settings) + } + + // Render the search page template if no query + if query == "" { + tmpl := template.Must(template.ParseFiles("templates/search.html")) + tmpl.Execute(w, settings) + return + } + + settings := loadUserSettings(r) + + // Handle search based on the type + switch searchType { + case "image": + handleImageSearch(w, settings, query, page) + case "video": + handleVideoSearch(w, settings, query, page) + case "map": + handleMapSearch(w, settings, query) + case "forum": + handleForumsSearch(w, settings, query, page) + case "file": + handleFileSearch(w, settings, query, page) + case "text": + fallthrough + default: + HandleTextSearch(w, settings, query, page) + } +} + +func parseSearchParams(r *http.Request) (query, safe, lang, searchType string, page int) { + if r.Method == "GET" { + query = r.URL.Query().Get("q") + safe = r.URL.Query().Get("safe") + lang = r.URL.Query().Get("lang") + searchType = r.URL.Query().Get("t") + pageStr := r.URL.Query().Get("p") + page = parsePageParameter(pageStr) + } else if r.Method == "POST" { + query = r.FormValue("q") + safe = r.FormValue("safe") + lang = r.FormValue("lang") + searchType = r.FormValue("t") + pageStr := r.FormValue("p") + page = parsePageParameter(pageStr) + } + + if searchType == "" { + searchType = "text" + } + + return +} + +func parsePageParameter(pageStr string) int { + page, err := strconv.Atoi(pageStr) + if err != nil || page < 1 { + page = 1 + } + return page +} + +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("/node", handleNodeRequest) + http.HandleFunc("/settings", func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, "templates/settings.html") + }) + 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") + }) + initializeTorrentSites() + + config := loadConfig() + generateOpenSearchXML(config) + + 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() +} diff --git a/map.go b/map.go old mode 100644 new mode 100755 index 9ec879e..8981d65 --- a/map.go +++ b/map.go @@ -1,72 +1,72 @@ -package main - -import ( - "encoding/json" - "fmt" - "html/template" - "net/http" - "net/url" -) - -type NominatimResponse struct { - Lat string `json:"lat"` - Lon string `json:"lon"` -} - -func geocodeQuery(query string) (latitude, longitude string, found bool, err error) { - // URL encode the query - query = url.QueryEscape(query) - - // Construct the request URL - urlString := fmt.Sprintf("https://nominatim.openstreetmap.org/search?format=json&q=%s", query) - - // Make the HTTP GET request - resp, err := http.Get(urlString) - if err != nil { - return "", "", false, err - } - defer resp.Body.Close() - - // Read the response - var result []NominatimResponse - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return "", "", false, err - } - - // Check if there are any results - if len(result) > 0 { - latitude = result[0].Lat - longitude = result[0].Lon - return latitude, longitude, true, nil - } - - return "", "", false, nil -} - -func handleMapSearch(w http.ResponseWriter, settings UserSettings, query string, lang string) { - // Geocode the query to get coordinates - latitude, longitude, found, err := geocodeQuery(query) - if err != nil { - printDebug("Error geocoding query: %s, error: %v", query, err) - http.Error(w, "Failed to find location", http.StatusInternalServerError) - return - } - - // Use a template to serve the map page - data := map[string]interface{}{ - "Query": query, - "Latitude": latitude, - "Longitude": longitude, - "Found": found, - "Theme": settings.Theme, - } - - tmpl, err := template.ParseFiles("templates/map.html") - if err != nil { - printErr("Error loading map template: %v", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - - tmpl.Execute(w, data) -} +package main + +import ( + "encoding/json" + "fmt" + "html/template" + "net/http" + "net/url" +) + +type NominatimResponse struct { + Lat string `json:"lat"` + Lon string `json:"lon"` +} + +func geocodeQuery(query string) (latitude, longitude string, found bool, err error) { + // URL encode the query + query = url.QueryEscape(query) + + // Construct the request URL + urlString := fmt.Sprintf("https://nominatim.openstreetmap.org/search?format=json&q=%s", query) + + // Make the HTTP GET request + resp, err := http.Get(urlString) + if err != nil { + return "", "", false, err + } + defer resp.Body.Close() + + // Read the response + var result []NominatimResponse + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return "", "", false, err + } + + // Check if there are any results + if len(result) > 0 { + latitude = result[0].Lat + longitude = result[0].Lon + return latitude, longitude, true, nil + } + + return "", "", false, nil +} + +func handleMapSearch(w http.ResponseWriter, settings UserSettings, query string) { + // Geocode the query to get coordinates + latitude, longitude, found, err := geocodeQuery(query) + if err != nil { + printDebug("Error geocoding query: %s, error: %v", query, err) + http.Error(w, "Failed to find location", http.StatusInternalServerError) + return + } + + // Use a template to serve the map page + data := map[string]interface{}{ + "Query": query, + "Latitude": latitude, + "Longitude": longitude, + "Found": found, + "Theme": settings.Theme, + } + + tmpl, err := template.ParseFiles("templates/map.html") + if err != nil { + printErr("Error loading map template: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + tmpl.Execute(w, data) +} diff --git a/node-handle-search.go b/node-handle-search.go old mode 100644 new mode 100755 index bfa8f6a..8591b65 --- a/node-handle-search.go +++ b/node-handle-search.go @@ -1,219 +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 { - log.Printf("Error parsing search parameters: %v", err) - return - } - - log.Printf("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 { - log.Printf("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 - log.Printf("Sending text 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 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) - } -} +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) + } +} diff --git a/node-request-files.go b/node-request-files.go old mode 100644 new mode 100755 index 2c9a28b..0cabf32 --- a/node-request-files.go +++ b/node-request-files.go @@ -1,83 +1,82 @@ -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 - }() -} +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 + }() +} diff --git a/node-request-forums.go b/node-request-forums.go old mode 100644 new mode 100755 index 921f2fb..ff6ed2e --- a/node-request-forums.go +++ b/node-request-forums.go @@ -1,101 +1,100 @@ -package main - -import ( - "encoding/json" - "fmt" - "log" - "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 { - log.Printf("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 { - log.Printf("Error unmarshalling forum results: %v", err) - return - } - - log.Printf("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 { - log.Printf("Error fetching forum results: %v", err) - return nil - } - return results -} +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 +} diff --git a/node-request-images.go b/node-request-images.go old mode 100644 new mode 100755 index 0fb8eae..4e3e9e3 --- a/node-request-images.go +++ b/node-request-images.go @@ -1,85 +1,84 @@ -package main - -import ( - "encoding/json" - "fmt" - "log" - "time" -) - -var imageResultsChan = make(chan []ImageSearchResult) - -func handleImageResultsMessage(msg Message) { - var results []ImageSearchResult - err := json.Unmarshal([]byte(msg.Content), &results) - if err != nil { - log.Printf("Error unmarshalling image results: %v", err) - return - } - - log.Printf("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 { - log.Printf("Error contacting node %s: %v", nodeAddr, err) - continue - } - if len(results) > 0 { - return results - } - } - return nil -} +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 +} diff --git a/node-request-text.go b/node-request-text.go old mode 100644 new mode 100755 index 6f4596e..ebe6041 --- a/node-request-text.go +++ b/node-request-text.go @@ -1,85 +1,84 @@ -package main - -import ( - "encoding/json" - "fmt" - "log" - "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 { - log.Printf("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 { - log.Printf("Error unmarshalling text results: %v", err) - return - } - - log.Printf("Received text results: %+v", results) - // Send results to textResultsChan - go func() { - textResultsChan <- results - }() -} +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 + }() +} diff --git a/node-request-video.go b/node-request-video.go old mode 100644 new mode 100755 index 209b84c..d965a7d --- a/node-request-video.go +++ b/node-request-video.go @@ -1,83 +1,82 @@ -package main - -import ( - "encoding/json" - "fmt" - "log" - "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 { - log.Printf("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 { - log.Printf("Error unmarshalling video results: %v", err) - return - } - - log.Printf("Received video results: %+v", results) - // Send results to videoResultsChan - go func() { - videoResultsChan <- results - }() -} +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 + }() +} diff --git a/run.bat b/run.bat new file mode 100755 index 0000000..2709b17 --- /dev/null +++ b/run.bat @@ -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 diff --git a/text.go b/text.go old mode 100644 new mode 100755 index 471d0ed..f7be586 --- a/text.go +++ b/text.go @@ -1,183 +1,183 @@ -package main - -import ( - "fmt" - "html/template" - "net/http" - "time" -) - -var textSearchEngines []SearchEngine - -func init() { - textSearchEngines = []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 - } -} - -func HandleTextSearch(w http.ResponseWriter, settings UserSettings, query, safe, lang 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) - - hasPrevPage := page > 1 // dupe - - //displayResults(w, combinedResults, query, lang, time.Since(startTime).Seconds(), page, hasPrevPage, hasNextPage) - - // Prefetch next and previous pages - go prefetchPage(query, safe, lang, page+1) - if hasPrevPage { - go prefetchPage(query, safe, lang, 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 - LanguageOptions []LanguageOption - CurrentLang string - HasPrevPage bool - HasNextPage bool - NoResults bool - Theme string - }{ - 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, - } - - err = tmpl.Execute(w, data) - if err != nil { - printErr("Error executing template: %v", err) - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - } -} - -func getTextResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []TextSearchResult { - cacheChan := make(chan []SearchResult) - var combinedResults []TextSearchResult - - go func() { - results, exists := resultsCache.Get(cacheKey) - if exists { - printInfo("Cache hit") - cacheChan <- results - } else { - printInfo("Cache miss") - cacheChan <- nil - } - }() - - select { - case results := <-cacheChan: - if results == nil { - combinedResults = fetchTextResults(query, safe, lang, page) - if len(combinedResults) > 0 { - resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) - } - } else { - textResults, _, _ := convertToSpecificResults(results) - combinedResults = textResults - } - case <-time.After(2 * time.Second): - printInfo("Cache check timeout") - combinedResults = fetchTextResults(query, safe, lang, page) - if len(combinedResults) > 0 { - resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) - } - } - - return combinedResults -} - -func prefetchPage(query, safe, lang string, page int) { - cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"} - if _, exists := resultsCache.Get(cacheKey); !exists { - printInfo("Page %d not cached, caching now...", page) - pageResults := fetchTextResults(query, safe, lang, page) - if len(pageResults) > 0 { - resultsCache.Set(cacheKey, convertToSearchResults(pageResults)) - } - } else { - printInfo("Page %d already cached", page) - } -} - -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 - } - - results = append(results, validateResults(searchResults)...) - - // If results are found, break out of the loop - if len(results) > 0 { - break - } - } - - // 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 -} - -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 - } - return searchResults, duration, nil - } -} +package main + +import ( + "fmt" + "html/template" + "net/http" + "time" +) + +var textSearchEngines []SearchEngine + +func init() { + textSearchEngines = []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 + } +} + +func HandleTextSearch(w http.ResponseWriter, settings UserSettings, query string, page int) { + startTime := time.Now() + + cacheKey := CacheKey{Query: query, Page: page, Safe: settings.SafeSearch == "true", Lang: settings.Language, Type: "text"} + combinedResults := getTextResultsFromCacheOrFetch(cacheKey, query, settings.SafeSearch, settings.Language, page) + + hasPrevPage := page > 1 // dupe + + //displayResults(w, combinedResults, query, lang, time.Since(startTime).Seconds(), page, hasPrevPage, hasNextPage) + + // Prefetch next and previous pages + go prefetchPage(query, settings.SafeSearch, settings.Language, page+1) + if hasPrevPage { + go prefetchPage(query, settings.SafeSearch, settings.Language, 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 + LanguageOptions []LanguageOption + CurrentLang string + HasPrevPage bool + HasNextPage bool + NoResults bool + Theme string + }{ + Results: combinedResults, + Query: query, + Page: page, + Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()), + LanguageOptions: languageOptions, + CurrentLang: settings.Language, + HasPrevPage: page > 1, + HasNextPage: len(combinedResults) >= 50, + NoResults: len(combinedResults) == 0, + Theme: settings.Theme, + } + + err = tmpl.Execute(w, data) + if err != nil { + printErr("Error executing template: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } +} + +func getTextResultsFromCacheOrFetch(cacheKey CacheKey, query, safe, lang string, page int) []TextSearchResult { + cacheChan := make(chan []SearchResult) + var combinedResults []TextSearchResult + + go func() { + results, exists := resultsCache.Get(cacheKey) + if exists { + printInfo("Cache hit") + cacheChan <- results + } else { + printInfo("Cache miss") + cacheChan <- nil + } + }() + + select { + case results := <-cacheChan: + if results == nil { + combinedResults = fetchTextResults(query, safe, lang, page) + if len(combinedResults) > 0 { + resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) + } + } else { + textResults, _, _ := convertToSpecificResults(results) + combinedResults = textResults + } + case <-time.After(2 * time.Second): + printInfo("Cache check timeout") + combinedResults = fetchTextResults(query, safe, lang, page) + if len(combinedResults) > 0 { + resultsCache.Set(cacheKey, convertToSearchResults(combinedResults)) + } + } + + return combinedResults +} + +func prefetchPage(query, safe, lang string, page int) { + cacheKey := CacheKey{Query: query, Page: page, Safe: safe == "true", Lang: lang, Type: "text"} + if _, exists := resultsCache.Get(cacheKey); !exists { + printInfo("Page %d not cached, caching now...", page) + pageResults := fetchTextResults(query, safe, lang, page) + if len(pageResults) > 0 { + resultsCache.Set(cacheKey, convertToSearchResults(pageResults)) + } + } else { + printInfo("Page %d already cached", page) + } +} + +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 + } + + results = append(results, validateResults(searchResults)...) + + // If results are found, break out of the loop + if len(results) > 0 { + break + } + } + + // 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 +} + +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 + } + return searchResults, duration, nil + } +} diff --git a/video.go b/video.go old mode 100644 new mode 100755 index 0a87f1f..45af48e --- a/video.go +++ b/video.go @@ -1,211 +1,211 @@ -package main - -import ( - "encoding/json" - "fmt" - "html/template" - "net/http" - "net/url" - "sync" - "time" -) - -const retryDuration = 12 * time.Hour // Retry duration for unresponding piped instances - -var ( - pipedInstances = []string{ - "api.piped.yt", - "pipedapi.moomoo.me", - "pipedapi.darkness.services", - "pipedapi.kavin.rocks", - "piped-api.hostux.net", - "pipedapi.syncpundit.io", - "piped-api.cfe.re", - "pipedapi.in.projectsegfau.lt", - "piapi.ggtyler.dev", - "piped-api.codespace.cz", - "pipedapi.coldforge.xyz", - "pipedapi.osphost.fi", - } - 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 -type VideoAPIResponse struct { - Items []struct { - URL string `json:"url"` - Title string `json:"title"` - UploaderName string `json:"uploaderName"` - Views int `json:"views"` - Thumbnail string `json:"thumbnail"` - Duration int `json:"duration"` - UploadedDate string `json:"uploadedDate"` - Type string `json:"type"` - } `json:"items"` -} - -// Function to format views similarly to the Python code -func formatViews(views int) string { - switch { - case views >= 1_000_000_000: - return fmt.Sprintf("%.1fB views", float64(views)/1_000_000_000) - case views >= 1_000_000: - return fmt.Sprintf("%.1fM views", float64(views)/1_000_000) - case views >= 10_000: - return fmt.Sprintf("%.1fK views", float64(views)/1_000) - case views == 1: - return fmt.Sprintf("%d view", views) - default: - return fmt.Sprintf("%d views", views) - } -} - -// formatDuration formats video duration as done in the Python code -func formatDuration(seconds int) string { - if 0 > seconds { - return "Live" - } - - hours := seconds / 3600 - minutes := (seconds % 3600) / 60 - seconds = seconds % 60 - - if hours > 0 { - return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds) - } - return fmt.Sprintf("%02d:%02d", minutes, seconds) -} - -func init() { - go checkDisabledInstancesPeriodically() -} - -func checkDisabledInstancesPeriodically() { - checkAndReactivateInstances() // Initial immediate check - ticker := time.NewTicker(retryDuration) - defer ticker.Stop() - - for range ticker.C { - checkAndReactivateInstances() - } -} - -func checkAndReactivateInstances() { - mu.Lock() - defer mu.Unlock() - - for instance, isDisabled := range disabledInstances { - if isDisabled { - // Check if the instance is available again - if testInstanceAvailability(instance) { - printInfo("Instance %s is now available and reactivated.", instance) - delete(disabledInstances, instance) - } else { - printInfo("Instance %s is still not available.", instance) - } - } - } -} - -func testInstanceAvailability(instance string) bool { - resp, err := http.Get(fmt.Sprintf("https://%s/search?q=%s&filter=all", instance, url.QueryEscape("test"))) - if err != nil || resp.StatusCode != http.StatusOK { - return false - } - return true -} - -func makeHTMLRequest(query, safe, lang string, page int) (*VideoAPIResponse, error) { - var lastError error - mu.Lock() - defer mu.Unlock() - - for _, instance := range pipedInstances { - if disabledInstances[instance] { - continue // Skip this instance because it's still disabled - } - - 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 { - 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 - } - - defer resp.Body.Close() - var apiResp VideoAPIResponse - if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { - lastError = fmt.Errorf("error decoding response from %s: %w", instance, err) - continue - } - return &apiResp, nil - } - return nil, fmt.Errorf("all instances failed, last error: %v", lastError) -} - -// handleVideoSearch adapted from the Python `videoResults`, handles video search requests -func handleVideoSearch(w http.ResponseWriter, settings UserSettings, query, safe, lang string, page int) { - start := time.Now() - - results := fetchVideoResults(query, settings.SafeSearch, settings.Language, page) - if len(results) == 0 { - printWarn("No results from primary search, trying other nodes") - results = tryOtherNodesForVideoSearch(query, settings.SafeSearch, settings.Language, page, []string{hostID}) - } - - elapsed := time.Since(start) - tmpl, err := template.New("videos.html").Funcs(funcs).ParseFiles("templates/videos.html") - if err != nil { - 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, // no - "Theme": settings.Theme, - }) - 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" { - continue - } - if item.UploadedDate == "" { - item.UploadedDate = "Now" - } - - results = append(results, VideoResult{ - Href: fmt.Sprintf("https://youtube.com%s", item.URL), - Title: item.Title, - Date: item.UploadedDate, - Views: formatViews(item.Views), - Creator: item.UploaderName, - Publisher: "Piped", - Image: fmt.Sprintf("/img_proxy?url=%s", url.QueryEscape(item.Thumbnail)), - Duration: formatDuration(item.Duration), - }) - } - return results -} +package main + +import ( + "encoding/json" + "fmt" + "html/template" + "net/http" + "net/url" + "sync" + "time" +) + +const retryDuration = 12 * time.Hour // Retry duration for unresponding piped instances + +var ( + pipedInstances = []string{ + "api.piped.yt", + "pipedapi.moomoo.me", + "pipedapi.darkness.services", + "pipedapi.kavin.rocks", + "piped-api.hostux.net", + "pipedapi.syncpundit.io", + "piped-api.cfe.re", + "pipedapi.in.projectsegfau.lt", + "piapi.ggtyler.dev", + "piped-api.codespace.cz", + "pipedapi.coldforge.xyz", + "pipedapi.osphost.fi", + } + 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 +type VideoAPIResponse struct { + Items []struct { + URL string `json:"url"` + Title string `json:"title"` + UploaderName string `json:"uploaderName"` + Views int `json:"views"` + Thumbnail string `json:"thumbnail"` + Duration int `json:"duration"` + UploadedDate string `json:"uploadedDate"` + Type string `json:"type"` + } `json:"items"` +} + +// Function to format views similarly to the Python code +func formatViews(views int) string { + switch { + case views >= 1_000_000_000: + return fmt.Sprintf("%.1fB views", float64(views)/1_000_000_000) + case views >= 1_000_000: + return fmt.Sprintf("%.1fM views", float64(views)/1_000_000) + case views >= 10_000: + return fmt.Sprintf("%.1fK views", float64(views)/1_000) + case views == 1: + return fmt.Sprintf("%d view", views) + default: + return fmt.Sprintf("%d views", views) + } +} + +// formatDuration formats video duration as done in the Python code +func formatDuration(seconds int) string { + if 0 > seconds { + return "Live" + } + + hours := seconds / 3600 + minutes := (seconds % 3600) / 60 + seconds = seconds % 60 + + if hours > 0 { + return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds) + } + return fmt.Sprintf("%02d:%02d", minutes, seconds) +} + +func init() { + go checkDisabledInstancesPeriodically() +} + +func checkDisabledInstancesPeriodically() { + checkAndReactivateInstances() // Initial immediate check + ticker := time.NewTicker(retryDuration) + defer ticker.Stop() + + for range ticker.C { + checkAndReactivateInstances() + } +} + +func checkAndReactivateInstances() { + mu.Lock() + defer mu.Unlock() + + for instance, isDisabled := range disabledInstances { + if isDisabled { + // Check if the instance is available again + if testInstanceAvailability(instance) { + printInfo("Instance %s is now available and reactivated.", instance) + delete(disabledInstances, instance) + } else { + printInfo("Instance %s is still not available.", instance) + } + } + } +} + +func testInstanceAvailability(instance string) bool { + resp, err := http.Get(fmt.Sprintf("https://%s/search?q=%s&filter=all", instance, url.QueryEscape("test"))) + if err != nil || resp.StatusCode != http.StatusOK { + return false + } + return true +} + +func makeHTMLRequest(query, safe, lang string, page int) (*VideoAPIResponse, error) { + var lastError error + mu.Lock() + defer mu.Unlock() + + for _, instance := range pipedInstances { + if disabledInstances[instance] { + continue // Skip this instance because it's still disabled + } + + 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 { + 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 + } + + defer resp.Body.Close() + var apiResp VideoAPIResponse + if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { + lastError = fmt.Errorf("error decoding response from %s: %w", instance, err) + continue + } + return &apiResp, nil + } + return nil, fmt.Errorf("all instances failed, last error: %v", lastError) +} + +// handleVideoSearch adapted from the Python `videoResults`, handles video search requests +func handleVideoSearch(w http.ResponseWriter, settings UserSettings, query string, page int) { + start := time.Now() + + results := fetchVideoResults(query, settings.SafeSearch, settings.Language, page) + if len(results) == 0 { + printWarn("No results from primary search, trying other nodes") + results = tryOtherNodesForVideoSearch(query, settings.SafeSearch, settings.Language, page, []string{hostID}) + } + + elapsed := time.Since(start) + tmpl, err := template.New("videos.html").Funcs(funcs).ParseFiles("templates/videos.html") + if err != nil { + 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, // no + "Theme": settings.Theme, + }) + 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" { + continue + } + if item.UploadedDate == "" { + item.UploadedDate = "Now" + } + + results = append(results, VideoResult{ + Href: fmt.Sprintf("https://youtube.com%s", item.URL), + Title: item.Title, + Date: item.UploadedDate, + Views: formatViews(item.Views), + Creator: item.UploaderName, + Publisher: "Piped", + Image: fmt.Sprintf("/img_proxy?url=%s", url.QueryEscape(item.Thumbnail)), + Duration: formatDuration(item.Duration), + }) + } + return results +} -- 2.40.1 From c00f20860d1a9c9b73d96ce95c99f8d8766326b4 Mon Sep 17 00:00:00 2001 From: partisan Date: Tue, 13 Aug 2024 16:38:02 +0200 Subject: [PATCH 28/34] fix language/safe search gui --- files.go | 44 +++--- forums.go | 10 +- images.go | 10 +- main.go | 14 +- map.go | 1 + templates/files.html | 226 ++++++++++++++-------------- templates/forums.html | 184 +++++++++++------------ templates/images.html | 338 +++++++++++++++++++++--------------------- templates/search.html | 168 ++++++++++++--------- templates/text.html | 306 +++++++++++++++++++------------------- text.go | 10 +- user-settings.go | 114 +++++++------- video.go | 17 ++- 13 files changed, 748 insertions(+), 694 deletions(-) mode change 100644 => 100755 templates/files.html mode change 100644 => 100755 templates/forums.html mode change 100644 => 100755 templates/images.html mode change 100644 => 100755 templates/search.html mode change 100644 => 100755 templates/text.html mode change 100644 => 100755 user-settings.go diff --git a/files.go b/files.go index b397a99..cbafb66 100755 --- a/files.go +++ b/files.go @@ -59,27 +59,31 @@ func handleFileSearch(w http.ResponseWriter, settings UserSettings, query string } data := struct { - Results []TorrentResult - Query string - Fetched string - Category string - Sort string - HasPrevPage bool - HasNextPage bool - Page int - Settings Settings - Theme string + Results []TorrentResult + Query string + Fetched string + Category string + Sort string + Page int + HasPrevPage bool + HasNextPage bool + LanguageOptions []LanguageOption + CurrentLang string + Theme string + Safe string }{ - 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: settings.Language, Safe: settings.SafeSearch}, // Now this is painful, are there two Settings variables?? - Theme: settings.Theme, + 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.Language, + Theme: settings.Theme, + Safe: settings.SafeSearch, } // // Debugging: Print results before rendering template diff --git a/forums.go b/forums.go index 69f911e..d0be4f6 100755 --- a/forums.go +++ b/forums.go @@ -108,21 +108,23 @@ func handleForumsSearch(w http.ResponseWriter, settings UserSettings, query stri data := struct { Query string Results []ForumSearchResult - LanguageOptions []LanguageOption - CurrentLang string Page int HasPrevPage bool HasNextPage bool + LanguageOptions []LanguageOption + CurrentLang string Theme string + Safe string }{ Query: query, Results: results, - LanguageOptions: languageOptions, - CurrentLang: settings.Language, Page: page, HasPrevPage: page > 1, HasNextPage: len(results) == 25, + LanguageOptions: languageOptions, + CurrentLang: settings.Language, Theme: settings.Theme, + Safe: settings.SafeSearch, } funcMap := template.FuncMap{ diff --git a/images.go b/images.go index bf1a840..bdac1cd 100755 --- a/images.go +++ b/images.go @@ -37,23 +37,25 @@ func handleImageSearch(w http.ResponseWriter, settings UserSettings, query strin Query string Page int Fetched string - LanguageOptions []LanguageOption - CurrentLang string HasPrevPage bool HasNextPage bool NoResults bool + LanguageOptions []LanguageOption + CurrentLang string Theme string + Safe string }{ Results: combinedResults, Query: query, Page: page, Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()), - LanguageOptions: languageOptions, - CurrentLang: settings.Language, HasPrevPage: page > 1, HasNextPage: len(combinedResults) >= 50, NoResults: len(combinedResults) == 0, + LanguageOptions: languageOptions, + CurrentLang: settings.Language, Theme: settings.Theme, + Safe: settings.SafeSearch, } err = tmpl.Execute(w, data) diff --git a/main.go b/main.go index 6c9cb2c..392aab8 100755 --- a/main.go +++ b/main.go @@ -92,9 +92,21 @@ func handleSearch(w http.ResponseWriter, r *http.Request) { } // Render the search page template if no query + + data := struct { + LanguageOptions []LanguageOption + CurrentLang string + Theme string + Safe string + }{ + LanguageOptions: languageOptions, + CurrentLang: settings.Language, + Theme: settings.Theme, + Safe: settings.SafeSearch, + } if query == "" { tmpl := template.Must(template.ParseFiles("templates/search.html")) - tmpl.Execute(w, settings) + tmpl.Execute(w, data) return } diff --git a/map.go b/map.go index 8981d65..df3c7e8 100755 --- a/map.go +++ b/map.go @@ -59,6 +59,7 @@ func handleMapSearch(w http.ResponseWriter, settings UserSettings, query string) "Longitude": longitude, "Found": found, "Theme": settings.Theme, + "Safe": settings.SafeSearch, } tmpl, err := template.ParseFiles("templates/map.html") diff --git a/templates/files.html b/templates/files.html old mode 100644 new mode 100755 index b1fc4cb..af39437 --- a/templates/files.html +++ b/templates/files.html @@ -1,113 +1,113 @@ - - - - - - {{.Query}} - Ocásek - - - - - - -

Ocásek

-
- - - -
-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- - -
-
-
- - -
-
- - -

Fetched in {{ .Fetched }} seconds

- - {{ if .Results }} -
- - - - - -
-
- {{ range .Results }} -
- {{ if .Error }} -
{{ .Error }}
- {{ else }} - {{ .URL }} -

{{ .Title }}

-

{{ if .Views }}{{ .Views }} views • {{ end }}{{ .Size }}

-

Seeders: {{ .Seeders }} | Leechers: {{ .Leechers }}

- {{ end }} -
- {{ end }} -
-
-
- - - {{ if .HasPrevPage }} - - {{ end }} - {{ if .HasNextPage }} - - {{ end }} -
-
- {{ else }} -
- Your search '{{ .Query }}' came back with no results.
- Try rephrasing your search term and/or recorrect any spelling mistakes. -
- {{ end }} - - - + + + + + + {{.Query}} - Ocásek + + + + + +
+

Ocásek

+
+ + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
+ +

Fetched in {{ .Fetched }} seconds

+ + {{ if .Results }} +
+ + + + + +
+
+ {{ range .Results }} +
+ {{ if .Error }} +
{{ .Error }}
+ {{ else }} + {{ .URL }} +

{{ .Title }}

+

{{ if .Views }}{{ .Views }} views • {{ end }}{{ .Size }}

+

Seeders: {{ .Seeders }} | Leechers: {{ .Leechers }}

+ {{ end }} +
+ {{ end }} +
+
+
+ + + {{ if .HasPrevPage }} + + {{ end }} + {{ if .HasNextPage }} + + {{ end }} +
+
+ {{ else }} +
+ Your search '{{ .Query }}' came back with no results.
+ Try rephrasing your search term and/or recorrect any spelling mistakes. +
+ {{ end }} + + + diff --git a/templates/forums.html b/templates/forums.html old mode 100644 new mode 100755 index 6d04557..0246110 --- a/templates/forums.html +++ b/templates/forums.html @@ -1,92 +1,92 @@ - - - - - - {{.Query}} - Ocásek - - - - - -
-

Ocásek

-
- - - -
-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- - -
-
-
- - -
-
-
-
- - - - -
-
- {{if .Results}} - {{range .Results}} -
- {{.URL}} -

{{.Header}}

-

{{.Description}}

-
-
- {{end}} - {{else}} -
No results found for '{{ .Query }}'. Try different keywords.
- {{end}} -
-
-
- - - {{ if .HasPrevPage }} - - {{ end }} - {{ if .HasNextPage }} - - {{ end }} -
-
- - - + + + + + + {{.Query}} - Ocásek + + + + + +
+

Ocásek

+
+ + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
+
+ + + + +
+
+ {{if .Results}} + {{range .Results}} +
+ {{.URL}} +

{{.Header}}

+

{{.Description}}

+
+
+ {{end}} + {{else}} +
No results found for '{{ .Query }}'. Try different keywords.
+ {{end}} +
+
+
+ + + {{ if .HasPrevPage }} + + {{ end }} + {{ if .HasNextPage }} + + {{ end }} +
+
+ + + diff --git a/templates/images.html b/templates/images.html old mode 100644 new mode 100755 index 7a7e07d..ee3794a --- a/templates/images.html +++ b/templates/images.html @@ -1,169 +1,169 @@ - - - - - - {{.Query}} - Ocásek - - - - - -
-

Ocásek

-
- - - -
-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- - -
-
-
- - -
-
-
-
- - - - -
-
- - {{ if .Results }} -
- - {{ range .Results }} - - {{ end }} -
- - {{ else if .NoResults }} -
No results found for '{{ .Query }}'. Try different keywords.
- {{ else }} -
Looks like this is the end of results.
- {{ end }} -
-
- Searching for new results... -
- - - - + + + + + + {{.Query}} - Ocásek + + + + + +
+

Ocásek

+
+ + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
+
+ + + + +
+
+ + {{ if .Results }} +
+ + {{ range .Results }} + + {{ end }} +
+ + {{ else if .NoResults }} +
No results found for '{{ .Query }}'. Try different keywords.
+ {{ else }} +
Looks like this is the end of results.
+ {{ end }} +
+
+ Searching for new results... +
+ + + + diff --git a/templates/search.html b/templates/search.html old mode 100644 new mode 100755 index f82599a..aa425a2 --- a/templates/search.html +++ b/templates/search.html @@ -1,73 +1,95 @@ - - - - - - Search with Ocásek - - - - - - - -
-

Settings

-
- -
-

Theme: Default Theme

-
-
Dark Theme
-
Light Theme
-
-
- - - -
-
-
-

Ocásek

-
- - - -
-
- - - -
-
- - + + + + + + Search with Ocásek + + + + + + + +
+

Settings

+
+ +
+

Current theme: {{.Theme}}

+
+
Dark Theme
+
Light Theme
+
+
+ + +
+
+
+

Ocásek

+
+ + + +
+
+ + + +
+
+ + diff --git a/templates/text.html b/templates/text.html old mode 100644 new mode 100755 index 6dccaa7..12cfe53 --- a/templates/text.html +++ b/templates/text.html @@ -1,153 +1,153 @@ - - - - - - {{.Query}} - Ocásek - - - - - -
-

Ocásek

-
- - - -
-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- - -
-
-
- - -
-
-
-
- - - - -
-
- {{if .Results}} - {{range .Results}} -
- {{.URL}} -

{{.Header}}

-

{{.Description}}

-
-
- {{end}} - {{else if .NoResults}} -
No results found for '{{ .Query }}'. Try different keywords.
- {{else}} -
Looks like this is the end of results.
- {{end}} -
-
- Searching for new results... -
-
-
- - - {{ if .HasPrevPage }} - - {{ end }} - {{ if .HasNextPage }} - - {{ end }} -
-
- - - - + + + + + + {{.Query}} - Ocásek + + + + + +
+

Ocásek

+
+ + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
+
+ + + + +
+
+ {{if .Results}} + {{range .Results}} +
+ {{.URL}} +

{{.Header}}

+

{{.Description}}

+
+
+ {{end}} + {{else if .NoResults}} +
No results found for '{{ .Query }}'. Try different keywords.
+ {{else}} +
Looks like this is the end of results.
+ {{end}} +
+
+ Searching for new results... +
+
+
+ + + {{ if .HasPrevPage }} + + {{ end }} + {{ if .HasNextPage }} + + {{ end }} +
+
+ + + + diff --git a/text.go b/text.go index f7be586..d088a07 100755 --- a/text.go +++ b/text.go @@ -48,23 +48,25 @@ func HandleTextSearch(w http.ResponseWriter, settings UserSettings, query string Query string Page int Fetched string - LanguageOptions []LanguageOption - CurrentLang string HasPrevPage bool HasNextPage bool NoResults bool + LanguageOptions []LanguageOption + CurrentLang string Theme string + Safe string }{ Results: combinedResults, Query: query, Page: page, Fetched: fmt.Sprintf("%.2f seconds", elapsedTime.Seconds()), - LanguageOptions: languageOptions, - CurrentLang: settings.Language, HasPrevPage: page > 1, HasNextPage: len(combinedResults) >= 50, NoResults: len(combinedResults) == 0, + LanguageOptions: languageOptions, + CurrentLang: settings.Language, Theme: settings.Theme, + Safe: settings.SafeSearch, } err = tmpl.Execute(w, data) diff --git a/user-settings.go b/user-settings.go old mode 100644 new mode 100755 index 41960a7..80b8b04 --- a/user-settings.go +++ b/user-settings.go @@ -1,54 +1,60 @@ -package main - -import "net/http" - -type UserSettings struct { - Theme string - Language string - SafeSearch string -} - -func loadUserSettings(r *http.Request) UserSettings { - var settings UserSettings - - // Load theme - if cookie, err := r.Cookie("theme"); err == nil { - settings.Theme = cookie.Value - } else { - settings.Theme = "dark" // Default theme - } - - // Load language - if cookie, err := r.Cookie("language"); err == nil { - settings.Language = cookie.Value - } else { - settings.Language = "en" // Default language - } - - // Load safe search - if cookie, err := r.Cookie("safe"); err == nil { - settings.SafeSearch = cookie.Value - } else { - settings.SafeSearch = "" // Default safe search off - } - - return settings -} - -func saveUserSettings(w http.ResponseWriter, settings UserSettings) { - http.SetCookie(w, &http.Cookie{ - Name: "theme", - Value: settings.Theme, - Path: "/", - }) - http.SetCookie(w, &http.Cookie{ - Name: "language", - Value: settings.Language, - Path: "/", - }) - http.SetCookie(w, &http.Cookie{ - Name: "safe", - Value: settings.SafeSearch, - Path: "/", - }) -} +package main + +import "net/http" + +type UserSettings struct { + Theme string + Language string + SafeSearch string +} + +func loadUserSettings(r *http.Request) UserSettings { + var settings UserSettings + + // Load theme + if cookie, err := r.Cookie("theme"); err == nil { + settings.Theme = cookie.Value + } else { + settings.Theme = "dark" // Default theme + } + + // Load language + if cookie, err := r.Cookie("language"); err == nil { + settings.Language = cookie.Value + } else { + settings.Language = "en" // Default language + } + + // Load safe search + if cookie, err := r.Cookie("safe"); err == nil { + settings.SafeSearch = cookie.Value + } else { + settings.SafeSearch = "" // Default safe search off + } + + return settings +} + +func saveUserSettings(w http.ResponseWriter, settings UserSettings) { + http.SetCookie(w, &http.Cookie{ + Name: "theme", + Value: settings.Theme, + Path: "/", + Secure: true, // Ensure cookie is sent over HTTPS only + SameSite: http.SameSiteNoneMode, // Set SameSite to None + }) + http.SetCookie(w, &http.Cookie{ + Name: "language", + Value: settings.Language, + Path: "/", + Secure: true, // Ensure cookie is sent over HTTPS only + SameSite: http.SameSiteNoneMode, // Set SameSite to None + }) + http.SetCookie(w, &http.Cookie{ + Name: "safe", + Value: settings.SafeSearch, + Path: "/", + Secure: true, // Ensure cookie is sent over HTTPS only + SameSite: http.SameSiteNoneMode, // Set SameSite to None + }) +} diff --git a/video.go b/video.go index 45af48e..1633853 100755 --- a/video.go +++ b/video.go @@ -166,13 +166,16 @@ func handleVideoSearch(w http.ResponseWriter, settings UserSettings, query strin } 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, // no - "Theme": settings.Theme, + "Results": results, + "Query": query, + "Fetched": fmt.Sprintf("%.2f seconds", elapsed.Seconds()), + "Page": page, + "HasPrevPage": page > 1, + "HasNextPage": len(results) > 0, + "LanguageOptions": languageOptions, + "CurrentLang": settings.Language, + "Theme": settings.Theme, + "Safe": settings.SafeSearch, }) if err != nil { printErr("Error executing template: %v", err) -- 2.40.1 From 7127b3ee8871c4514ac400864e97de271c9dcfca Mon Sep 17 00:00:00 2001 From: partisan Date: Tue, 13 Aug 2024 18:49:26 +0200 Subject: [PATCH 29/34] fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f6b7546..5bc3b1c 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ A self-hosted private and anonymous [metasearch engine](https://en.wikipedia.org ## Features - Text search using Google, Brave, DuckDuckGo and LibreX/Y. -- Image search using the Qwant,Bing and Imgur. +- 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 -- 2.40.1 From 2f23b32fa7ae0e60b80462a571c4cfc1aa413aa3 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 15 Aug 2024 13:31:15 +0200 Subject: [PATCH 30/34] added working settings page --- README.md | 20 +++-- main.go | 5 +- static/css/black.css | 74 ++++++++++++++++++ static/css/latte.css | 100 ++++++++++++++++++++++++ static/css/mocha.css | 100 ++++++++++++++++++++++++ static/css/night.css | 74 ++++++++++++++++++ static/css/style-settings.css | 62 +++++++++++++++ static/css/style.css | 19 ----- static/images/black.webp | Bin 0 -> 10936 bytes static/images/dark.webp | Bin 9050 -> 9692 bytes static/images/latte.webp | Bin 0 -> 9016 bytes static/images/light.webp | Bin 10008 -> 10608 bytes static/images/mocha.webp | Bin 0 -> 9566 bytes static/images/night.webp | Bin 0 -> 10006 bytes templates/search.html | 2 +- templates/settings.html | 138 ++++++++++++++++++---------------- user-settings.go | 64 +++++++++++++++- 17 files changed, 561 insertions(+), 97 deletions(-) create mode 100644 static/css/black.css create mode 100644 static/css/latte.css create mode 100644 static/css/mocha.css create mode 100644 static/css/night.css create mode 100644 static/css/style-settings.css create mode 100644 static/images/black.webp create mode 100644 static/images/latte.webp create mode 100644 static/images/mocha.webp create mode 100644 static/images/night.webp diff --git a/README.md b/README.md index 5bc3b1c..af1d11e 100644 --- a/README.md +++ b/README.md @@ -32,13 +32,17 @@ A self-hosted private and anonymous [metasearch engine](https://en.wikipedia.org ## Comparison to other search engines -| Name | Works without JavaScript | Music search | Torrent search | API | Scalable | Not Resource Hungry | Dynamic Page Loading | -| ------------- | ------------------ | --------------------------- | ----------------- | ------ | ------------------- | ---------------------------------------------- | ---------------------- | -| Whoogle [1] | ✅ | ❓ | ❌ | ❌ | ❌ | ❓ Moderate | ❓ Not specified | -| Araa-Search | ✅ | ❌ | ✅ | ✅ [2] | ❌ | ❌ Very resource hungry | ❌ | -| LibreY | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ Moderate 200-400mb~ | ❌ | -| 4get | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ Moderate 200-400mb~ | ❌ | -| Warp | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ about 15-20MiB at idle, 17-22MiB when searching | ✅ | +| Feature | Whoogle | Araa-Search | LibreY | 4get | *Warp* | +| :----------------------------------- | ------------------ | ------------------------- | ------------------------ | ------------------------ | ---------------------------------------------------- | +| Works without JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ | +| Music search | ❓ | ❌ | ❌ | ✅ | ✅ | +| Torrent search | ❌ | ✅ | ✅ | ❌ | ✅ | +| API | ❌ | ✅ | ✅ | ✅ | ✅ | +| 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. @@ -70,4 +74,4 @@ chmod +x ./run.sh ./run.sh ``` -*Its that easy!* \ No newline at end of file +*Its that easy!* diff --git a/main.go b/main.go index 392aab8..65c272b 100755 --- a/main.go +++ b/main.go @@ -169,9 +169,8 @@ func runServer() { http.HandleFunc("/search", handleSearch) http.HandleFunc("/img_proxy", handleImageProxy) http.HandleFunc("/node", handleNodeRequest) - http.HandleFunc("/settings", func(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, "templates/settings.html") - }) + 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") diff --git a/static/css/black.css b/static/css/black.css new file mode 100644 index 0000000..9661246 --- /dev/null +++ b/static/css/black.css @@ -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); +} diff --git a/static/css/latte.css b/static/css/latte.css new file mode 100644 index 0000000..b217da7 --- /dev/null +++ b/static/css/latte.css @@ -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); +} diff --git a/static/css/mocha.css b/static/css/mocha.css new file mode 100644 index 0000000..543332f --- /dev/null +++ b/static/css/mocha.css @@ -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); +} diff --git a/static/css/night.css b/static/css/night.css new file mode 100644 index 0000000..0676672 --- /dev/null +++ b/static/css/night.css @@ -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); +} diff --git a/static/css/style-settings.css b/static/css/style-settings.css new file mode 100644 index 0000000..0dda333 --- /dev/null +++ b/static/css/style-settings.css @@ -0,0 +1,62 @@ + +/* 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; +} + +@media (max-width: 600px) { + .theme-link { + width: 100%; + } +} + +/* --- */ diff --git a/static/css/style.css b/static/css/style.css index 48d9127..e9cd93c 100644 --- a/static/css/style.css +++ b/static/css/style.css @@ -838,23 +838,6 @@ form.torrent-sort { display: initial; } -.themes-settings-menu { - background: var(--snip-background); - color: var(--fg); - border-radius: 4px; - height: 100%; - margin: 5px; - display: flex; - flex-wrap: wrap; - justify-content: space-between; -} - -.themes-settings-menu>div { - width: calc(50% - 10px); - margin: 5px; -} - - .view-image-search { border: 1px solid var(--snip-border); margin: 0; @@ -1873,8 +1856,6 @@ body, h1, p, a, input, button { } -/* --- */ - /* Ensuring dark theme compliance */ @media (prefers-color-scheme: dark) { .leaflet-control-locate, diff --git a/static/images/black.webp b/static/images/black.webp new file mode 100644 index 0000000000000000000000000000000000000000..44386b541e2f571eb93eb1a16261f75f72690fd3 GIT binary patch literal 10936 zcmeHrWmH_m;BNiB+pqhL zH{Q7SrT_G}-Q%7gXPvQsoHO@abFDS^(NvI?tz!lN^kgK}b=CQ)i~o8)m4M3uG6x~^ zBZwx;=PQ>K)6r6U@blNs{qNb$`Emy3bpdx~si$eiVu9_7=$p zj0b_LL}CR!4(H2MbN=aqoN$+k`>VnKV_;dQHJ;dEVD7I0M1hU!8%2rLH8wf*t2=lA&)X!b*HU4mtHCB|xM5%a zSm|9F=G#Lb^aFcDVYHelJWh6mkSX^344OoZPy0A=a7%5fNkO|pEp>jcx;mGHBqMB% zUGU)H$U9b(7>pt{rG5efu5(Iq)El@z{b_YMHzuQv1$&^ed_A)S{LbzLuu>YsaAYOb zX3lRk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gQBjKHQ~^U`zcv0DVJ+Z;pTdbgcLR^Rg$Dtpoypo^v9d7x#SF&+ z#^1i4pFEo*P~SlhUe`%srRNUE%X3-p_K+S3sRgQ*Pd_R*H_3`3X@At`UuMmtwrgNZ z+BaZE2$U9+bJIQ4?t9k0!G*QK2ABnRul9IxKN*RGai8I3q@q)+E^jeTU zIpSSYvpVfZ+9=M-_2?7edVMjnePBHG(RG%*%f1>2`dY(&89Y2iH zY#H(^O$Ih=F<_Wpm){{a;hN2mY* diff --git a/static/images/mocha.webp b/static/images/mocha.webp new file mode 100644 index 0000000000000000000000000000000000000000..d6369586f9f1661140bcc3d3601910b4d288ccc8 GIT binary patch literal 9566 zcmeHLWl&t(mTnqr+$}f+f=jT*JrJ~UO9%va2=0w*a0%}25L^Nz1P{V%C$Vx%9Az&JXU*B=Q|v4#^oCP`hL^rpR4Dv{ls$dCjK)U{?qwS@Aj9&@1pt}L7w>5neg6U zQF#<{QN8E%Q~RoE8>}Q}n+y@fuF|jWt{KV*k=Of;b^iW~6TBwH2`AF*5wHix+VyVu zo*L#Nu}K}eT2EJKSLrwY3!|)QY>$mQ$s=#pUs{-wo{4(n3ROHRAIW5;{7SD(r-*?GhDmaLtD8LYIf+pB_+s_CW~ zKPrnrSM%BNnl4_1jS{zUV*j^dP<(Z?<(a&H{o+uY%~OtnTbaQj_b6smtbrHx>qad? z(p%O($;!uv-AT^Pr!F;~-%iLV<0P4l?D_=Uh#gQ~DQjBHMI& z%(JsJdV;mE# z#4XOk**eF1H0{%5KmXH(71y?!Mj`-+1j7AyHPA;vGhcY+U`sfb8bUb@pA1SVbQB*38xQdPF-2V)xCkarmXT~{O+X(WN^Z`#+7m`>>v+WUc4bWC`kKZ= zMKd;1{VK4?D>L;hlm9UDlnpBit-m^~x~D`T`={SwHrBLfFW){YSMK4B6e{&UuIt)S z8SnM#$u9#}3%9{k^`zqY)*c~(MsQRF<--j@>Ql)5Hkw)f2rkNjixdIz2|d5 zIcAyTuZAg}WQO9m{1K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C)6XQm3mibpX~8Bj z9vV%?9f!fr-mqL#&HzSQgWm6?P-kF3RPIk-v7~Af+r$F%UZwrTZyvr-^7YZIJ4K&? zcALJ=7Q8u5L9ztq?7dcwN>#||q~Xt{fC7L$7r$G= zjROu<0V&sPT@XckWz5V$#0m*c4Y_&bywel@A2Ld-**h6CYHVoe1n&FxwZp10PVbjz(tG801Sb`;!TOJ!)rG^{?uxPq z+HRR_t*qX&hT;hR>|V@E`s;g!u_L0=rPR(?92zCyPPVBmhq*9C@_9wONtX-kr-5aP zdBrmn4wF_S8wOg|sHBKdZ3`&g8qzakJZp{RWbqWp)&$WHJT){^5EvUQIhS5mudmA( zD>^h*(2?Fdx>zHe{d7ftoe{B^#(ikKnwfn(&Q(tShw|u=Lcph(Jp#q~JHg2zX74(Z zjI>O;EyfEA#pVU~b1ppbzO`?aY{!xktmk>ngNd(aE|YLsUBnsdl%v4?-GJU@Q4hu_-q z?bf8N!UiT|yX`PL4-gsfQOdKYNvEH_C$HTP_l6H8@)FVg0@~zUq1hAe2VoR0T~JDa`iA|q)y9| z^9vn?UtM=uop_(~5+5^xPVRa5Y6xy~9#Q!m$Cx~B!7Zs)#*nM5PPO)VL;UO|e^9br zMi{KR>a@EymtN*sagIv;`VDI}O34q1FY*^eOPsix`4}Fe78ntIYLPby-yH5HnNrkN zBaZ@biYvpU-p>8OcsyK=VfEFwM8AA=0CMgp6{bZ~gHe&^R)X)C1D(}YTJidST`2XA isA?}leJCC^w)%>aJQYC)Y|_ceh@42Ee^k={b@LxYt$KO@ literal 0 HcmV?d00001 diff --git a/static/images/night.webp b/static/images/night.webp new file mode 100644 index 0000000000000000000000000000000000000000..332926842c48257868d19250bdfd0dd182a5f60c GIT binary patch literal 10006 zcmeHKWl$W-M?loYqp5lfz~N0Q6*KG;}qDsNnyYUvR?b!Lfv(2q8)& zD-@}eme3Ya=@1jw^Zp0yM=La+C106C?D@?i6(t>Zf&1!+fa}s3m)NuDsP;g4`6j! zoHb8jJ$bO;>*Z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VAzp*0##9S#w!Wj;vUDkkAoJ7z`G9N)gRsEi-Ja9TS$G80+fBh!aRY?U|bLb zR+Egh$phlL!vYqTDs)j0Ki|eVlRzxrSt03fQ9X77-dzqM??EK?ThnWU0$!IQr){x* zZFIxYBM7osqyI@i0bL{uJb$aCG-#v6Y)5xFVSsvkn}CjRifatte_9xvFtgw~{qvkj zNwu{=<(A|1&-l%ImN)8X$nEQuJSWC$L$fH)y&@Gw(gtfPl!D1y&2RgK6);EO$;Cd3 zYo}vB2p@YPve|~`l}N4!BGF0Ft2JU7eXNzz?wu>9n6kM>H^6_I>m%WpkQ5452l=(m zzYD90+e}-Z&dgV|3JG&*{@|$Gj(JCfO}P_?HMV=bamD92;u-5*mrR*|Dh6AKrY4*c zK5u6~x{WS37<#|i@5eSdt)wr;%CU;)bi%641Fm+#S$Iu!`9oxeho5wd7PIS`pELM- zJ#S`~9+lffGS#FK#yJGbUX6OtC=EH8<6|H3&=i&7Rf#XEv z8O@+}?G5Kkz?OUa6p+jeKr&WU>wL(4QNVt#rdYxklejum9c{qfK}(2~4yrtBBp?r( gaF@@&_6*&-kv*MHo>#~AMQMuVp!l2O{V$FG0OP@h>Hq)$ literal 0 HcmV?d00001 diff --git a/templates/search.html b/templates/search.html index aa425a2..1300d4e 100755 --- a/templates/search.html +++ b/templates/search.html @@ -59,7 +59,7 @@

Settings

- +

Current theme: {{.Theme}}

diff --git a/templates/settings.html b/templates/settings.html index d106af3..73843f6 100644 --- a/templates/settings.html +++ b/templates/settings.html @@ -6,77 +6,85 @@ Settings - Ocásek + -
-

Ocásek

-
- - - + -
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- - + +
+ +
+
+

Theme

+
+ + + +
+

Safe Search

+ +
+ +
+

Preferred Language

+ +
+ +
+

|

+
-
- - -
-
-
- -
-
-

SETTINGS ARE NOT IMPLEMENTED YET

-

Theme

- -
- -

Language

- -
- - - -

Privacy

- -
- -

- -
-
- +
diff --git a/user-settings.go b/user-settings.go index 80b8b04..9b7b5ee 100755 --- a/user-settings.go +++ b/user-settings.go @@ -1,6 +1,9 @@ package main -import "net/http" +import ( + "html/template" + "net/http" +) type UserSettings struct { Theme string @@ -57,4 +60,63 @@ func saveUserSettings(w http.ResponseWriter, settings UserSettings) { Secure: true, // Ensure cookie is sent over HTTPS only SameSite: http.SameSiteNoneMode, // Set SameSite to None }) + + printDebug("settings saved: %v", settings) +} + +func handleSaveSettings(w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" { + // Load current settings + settings := loadUserSettings(r) + + // Update only the settings that were submitted in the form + if theme := r.FormValue("theme"); theme != "" { + settings.Theme = theme + } + if lang := r.FormValue("lang"); lang != "" { + settings.Language = lang + } + 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(r) + + data := struct { + LanguageOptions []LanguageOption + CurrentLang string + Theme string + Safe string + }{ + LanguageOptions: languageOptions, + CurrentLang: settings.Language, + Theme: settings.Theme, + Safe: settings.SafeSearch, + } + + 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 + } } -- 2.40.1 From 1706b4508acc25242c8e9daddaeca4a2e918f7f7 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 15 Aug 2024 11:34:36 +0000 Subject: [PATCH 31/34] Updated licence to AGPL3 --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 658 insertions(+), 16 deletions(-) diff --git a/LICENSE b/LICENSE index 193ebf9..8410c20 100644 --- a/LICENSE +++ b/LICENSE @@ -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. + 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. \ No newline at end of file + 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. + + + Copyright (C) + + 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 . + +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 +. \ No newline at end of file -- 2.40.1 From 4bd0a8adc3ada7e43d4baafff0e4990b342dcdb7 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 15 Aug 2024 21:42:23 +0200 Subject: [PATCH 32/34] revert style.css --- static/css/style.css | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/static/css/style.css b/static/css/style.css index e9cd93c..a132aaa 100644 --- a/static/css/style.css +++ b/static/css/style.css @@ -838,6 +838,22 @@ form.torrent-sort { display: initial; } +.themes-settings-menu { + background: var(--snip-background); + color: var(--fg); + border-radius: 4px; + height: 100%; + margin: 5px; + display: flex; + flex-wrap: wrap; + justify-content: space-between; +} + +.themes-settings-menu>div { + width: calc(50% - 10px); + margin: 5px; +} + .view-image-search { border: 1px solid var(--snip-border); margin: 0; -- 2.40.1 From 887b45eb4169eeb03770fd7510b7b9cc696a9134 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 15 Aug 2024 21:49:07 +0200 Subject: [PATCH 33/34] fix images --- static/images/latte.webp | Bin 9016 -> 15018 bytes static/images/mocha.webp | Bin 9566 -> 14402 bytes 2 files changed, 0 insertions(+), 0 deletions(-) diff --git a/static/images/latte.webp b/static/images/latte.webp index 2a8f8d989902d1e8b1e7c2405930a3a60c1f1d2d..146d583b8e211990927ea45ae768ae79fee9ffee 100644 GIT binary patch literal 15018 zcmd6OV{j$Fw`XkI&cx2d$;7s8+c!2Q_Kj`x#QP*FgQvl}sd4WB*mV!cl!Agw6(D zQGRpkFQlw3mpu8>`ElK`nika}(jz(Bj}#9oj#}hj*4O1Oi9T1UaQLX4*1%ZnRoz`3?y67lqV2vg3EfCx1CC!TBDvhN|~y4hA-vk&1K-_xC5cgY`$-1CKXU^)8!R4GKoq;b?J{F-jyH{2o{U> z;h9uIe6R88W_^=~|F7ZRkW@$*85<4s&z!=aNC;3eK@j92P~?({WN;W*8CcSyv1rnX z6w*+GP(P>1ELF)wg1|(~{dV7sMbLUrz64Om3;j`ytkNr|c?WpMqI{k00@s2z^{YG- z^`u>opsm5Ln=YnZarT)biC>6(@Yk;oU|iKJch(~~_)nmCFHJ<>nETVXgLtige-zK# zA=-5N)n_e_h^HZz_$~+P+!XD`*Hh%WvWeub25eMm9E@e_g^#9ja&}BzuP#>$K8%dcQPw!s?OTwo;)%~9CTRt3WkW7hA^z>_% zr(pz3VCz{Bx60re=+)reo&6pS4vc4#gcxoLlOTL9%1veR)&#MV)Yv%Mp-okL%sd!B z!qok$H935t*8NdEC=zujUbdvWHZ1xANZnf|`>;$eg#HNn5TT0o6(CppPp$zz#XfS(xT}eP1RTFF@pS8@K-;b{^n&;2pf-lE4X;rFc!LK^cVl&yE zZ);A+Z*z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0CMgp6{bZ~gHe&^R)X)C1D(}YTJidST`2XA isA?}leJCC^w)%>aJQYC)Y|_ceh@42Ee^k={b@LxYt$KO@ -- 2.40.1 From 34f705f562221a1ed7a4217e07af438accb0eba3 Mon Sep 17 00:00:00 2001 From: partisan Date: Thu, 15 Aug 2024 19:53:53 +0000 Subject: [PATCH 34/34] Update licence in README --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index af1d11e..a50212c 100644 --- a/README.md +++ b/README.md @@ -75,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) \ No newline at end of file -- 2.40.1