diff --git a/config.php.example b/config.php.example index d53280e..7e1b0ed 100644 --- a/config.php.example +++ b/config.php.example @@ -20,6 +20,9 @@ "disable_hidden_service_search" => false, + // Fallback to another librex instance if google search fails + "instance_fallback" => true, + /* Preset privacy friendly frontends for users, these can be overwritten by users in the settings e.g.: Preset the invidious instance URL: "instance_url" => "https://yewtu.be", diff --git a/engines/google/text.php b/engines/google/text.php index c598cc1..336d2f4 100644 --- a/engines/google/text.php +++ b/engines/google/text.php @@ -70,11 +70,11 @@ do { curl_multi_exec($mh, $running); } while ($running); - if (curl_getinfo($google_ch)['http_code'] == '302') { - $instances_json = json_decode(file_get_contents("instances.json"), true); - $instances = array_map(fn($n) => $n['clearnet'], array_filter($instances_json['instances'], fn($n) => !is_null($n['clearnet']))); - header("Location: " . $instances[array_rand($instances)] . "search.php?q=$query"); - die(); + + if (curl_getinfo($google_ch)['http_code'] != '200') + { + require "engines/librex/text.php"; + return get_librex_results($query, $page); } diff --git a/engines/librex/text.php b/engines/librex/text.php new file mode 100644 index 0000000..fe89a65 --- /dev/null +++ b/engines/librex/text.php @@ -0,0 +1,51 @@ +instance_fallback) + return array(); + + $instances_json = json_decode(file_get_contents("instances.json"), true); + + if (empty($instances_json["instances"])) + return array(); + + + $instances = array_map(fn($n) => $n['clearnet'], array_filter($instances_json['instances'], fn($n) => !is_null($n['clearnet']))); + shuffle($instances); + + $query_encoded = urlencode($query); + + $results = array(); + $tries = 0; + + do { + $tries++; + + // after "too many" requests, give up + if ($tries > 5) + return array(); + + $instance = array_pop($instances); + + if (parse_url($instance)["host"] == parse_url($_SERVER['HTTP_HOST'])["host"]) + continue; + + $url = $instance . "api.php?q=$query_encoded&p=$page&t=0"; + + $librex_ch = curl_init($url); + curl_setopt_array($librex_ch, $config->curl_settings); + copy_cookies($librex_ch); + $response = curl_exec($librex_ch); + curl_close($librex_ch); + + $code = curl_getinfo($librex_ch)["http_code"]; + $results = json_decode($response, true); + + } while ( $results == null || count($results) <= 1); + + return array_values($results); + } +?> diff --git a/misc/tools.php b/misc/tools.php index 6735220..80bc370 100644 --- a/misc/tools.php +++ b/misc/tools.php @@ -230,4 +230,11 @@ echo ""; echo ""; } + + function copy_cookies($curl) + { + if (array_key_exists("HTTP_COOKIE", $_SERVER)) + curl_setopt( $curl, CURLOPT_COOKIE, $_SERVER['HTTP_COOKIE'] ); + } + ?> diff --git a/settings.php b/settings.php index 5ec6a10..e24d43d 100644 --- a/settings.php +++ b/settings.php @@ -1,7 +1,7 @@