Skip to content

Commit 97eaa21

Browse files
committed
Update
1 parent d811cb9 commit 97eaa21

2 files changed

Lines changed: 93 additions & 34 deletions

File tree

_hosts/media.codonaft/etc/nginx/http.d/userscripts.conf

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,14 @@ server {
2828
ssl_certificate_key /etc/nginx/ssl/codonaft.com/privkey.pem;
2929
ssl_trusted_certificate /etc/nginx/ssl/codonaft.com/chain.pem;
3030

31+
location = / {
32+
return 301 https://github.com/codonaft/userscripts;
33+
}
34+
3135
location / {
3236
add_header Cache-Control "public, max-age=7200";
3337
expires 2h;
3438
default_type "text/plain";
35-
return 301 https://raw.githubusercontent.com/codonaft/userscripts/refs/heads/main/$request_uri;
39+
return 301 https://raw.githubusercontent.com/codonaft/userscripts/refs/heads/main$request_uri;
3640
}
3741
}

searxng.html

Lines changed: 88 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -10,56 +10,83 @@
1010
<link rel="icon" href="https://searx.space/favicon.svg" type="image/svg+xml">
1111
<link rel="apple-touch-icon" href="https://searx.space/favicon.png">
1212
<title>SearXNG Random Instance Redirector</title>
13-
<style>code { background-color: rgba(128, 128, 128, 0.4); padding: 0.1rem 0.25rem 0.1rem 0.25rem }</style>
13+
<style>
14+
code { background-color: rgba(128, 128, 128, 0.4); padding: 0.1rem 0.25rem 0.1rem 0.25rem }
15+
.pale { color: #808080 }
16+
</style>
1417
</head>
1518
<body>
1619
<script type="module">
1720
import { detectAll } from '{{ site.url }}/assets/js/vendor/tinyld.min.js';
1821

19-
const MIN_MONTH_UPTIME = 95;
20-
const FALLBACKS = ['paulgo.io', 'search.im-in.space', 'search.ononoki.org', 'search.undertale.uk', 'searx.bndkt.io', 'searx.oloke.xyz'];
22+
const INSTANCES = ['search.charliewhiskey.net', 'search.im-in.space', 'search.ipsys.bf', 'search.mycotrip.tech', 'search.ononoki.org', 'search.pollorebozado.com', 'search.rowie.at', 'search.system51.co.uk', 'search.undertale.uk', 'search.url4irl.com', 'searx.bndkt.io', 'searx.dresden.network', 'searx.foss.family', 'searx.oloke.xyz', 'searx.ox2.fr', 'searx.party', 'searx.perennialte.ch', 'searx.tiekoetter.com', 'searx.zhenyapav.com', 'searxng.shreven.org']
23+
const LANGUAGES = ['en'];
24+
const TIMEOUT = 5000;
25+
const ATTEMPTS = 20;
2126

22-
const params = new URLSearchParams(window.location.search);
27+
const params = new URLSearchParams(window.location.href.split('#')[1] || '');
28+
const timeout = Number(params.get('timeout')) || TIMEOUT;
29+
const attempts = Number(params.get('attempts')) || ATTEMPTS;
2330

24-
const loadInstances = async () => {
25-
const fallbacks = FALLBACKS.map(i => `https://${i}/`);
26-
if (params.get('fast') === '1') return fallbacks;
31+
const loadAndShuffleInstances = async () => {
32+
const instancesFromParams = params.get('instances')?.split(',') || [];
33+
const instances = shuffle((instancesFromParams.length > 0 ? instancesFromParams : INSTANCES))
34+
.slice(0, attempts).map(i => {
35+
const protocol = i.endsWith('.onion') ? 'http' : 'https';
36+
return `${protocol}://${i}/`;
37+
});
38+
if (params.get('fast') === '1') return instances;
2739

2840
const response = await fetch('https://searx.space/data/instances.json');
2941
if (!response.ok) {
30-
console.log('fallback');
31-
return fallbacks;
42+
console.log('failed to load instances');
43+
return instances;
3244
}
3345

34-
const instances = (await response.json()).instances;
35-
console.log('instances', instances);
46+
const loadedInstances = (await response.json()).instances;
47+
console.log('instances', loadedInstances);
3648

3749
const onion = window.location.host.endsWith('.onion');
3850
const best = Object
39-
.entries(instances)
51+
.entries(loadedInstances)
4052
.filter(([u, i]) => {
4153
try {
4254
const url = new URL(u);
4355
if (onion) {
44-
if (i.network_type !== 'tor') return false;
56+
if (i?.network_type !== 'tor') return false;
4557
} else {
46-
if (i.network_type !== 'normal' || url.protocol !== 'https:' || i.tls.grade !== 'A+') return false;
58+
if (i?.network_type !== 'normal' || url.protocol !== 'https:' || i?.tls?.grade !== 'A+' || i?.html?.grade !== 'V') return false;
4759
}
48-
return i.uptime.uptimeMonth >= MIN_MONTH_UPTIME && i.uptime.uptimeDay === 100 && !i.analytics && i.engines.duckduckgo?.error_rate < 2 && i.engines.google?.error_rate < 2;
60+
return !i?.analytics;
4961
} catch(e) {
62+
console.error(e);
5063
return false;
5164
}
5265
})
53-
.map(([u, _]) => u);
66+
.map(([u, i]) => {
67+
const key = [i?.uptime?.uptimeDay, i?.uptime?.uptimeMonth, 1 / i?.engines?.google?.error_rate, 1 / i?.engines?.duckduckgo?.error_rate];
68+
return [u, key];
69+
})
70+
.sort(([_a, a], [_b, b]) => {
71+
const index = a.findIndex((_, i) => (a[i] || 0) !== (b[i] || 0));
72+
if (index === -1) return 0;
73+
return b[index] - a[index];
74+
})
75+
.map(([u, _]) => u)
76+
.slice(0, attempts);
5477

5578
console.log('best', best);
56-
return best;
79+
if (best.length === 0) {
80+
console.log('instances not found');
81+
return instances;
82+
}
83+
return shuffle(best);
5784
};
5885

5986
const detectLanguage = query => {
6087
const en = 'en';
61-
const allowedLanguages = params.get('allowed_languages');
62-
const only = allowedLanguages ? allowedLanguages.split(',') : [en];
88+
const allowedLanguages = params.get('languages');
89+
const only = allowedLanguages ? allowedLanguages.split(',') : LANGUAGES;
6390
console.log('allowed languages', only);
6491
if (only.length <= 1) return en;
6592

@@ -74,30 +101,58 @@
74101
return detected[0].lang;
75102
};
76103

77-
const redirect = (url, queryFromForm) => {
78-
params
79-
.entries()
80-
.filter(([k, _]) => k !== 'fast' && k !== 'allowed_languages')
81-
.forEach(([k, v]) => url.searchParams.set(k, v));
82-
url.searchParams.set('language', detectLanguage(params.get('q') || queryFromForm));
83-
if (queryFromForm) {
84-
url.searchParams.set('q', queryFromForm)
85-
window.location.href = url.toString();
86-
} else {
87-
window.location.replace(url.toString());
104+
const shuffle = xs => {
105+
for (let i = xs.length - 1; i > 0; i--) {
106+
let j = Math.floor(Math.random() * (i + 1));
107+
[xs[i], xs[j]] = [xs[j], xs[i]];
88108
}
109+
return xs;
89110
};
90111

91-
const pick = xs => xs[Math.floor(Math.random() * xs.length)];
92-
const targetUrl = new URL(pick(await loadInstances()));
112+
const shuffledInstances = await loadAndShuffleInstances();
113+
const targetUrl = new URL(shuffledInstances[0]);
114+
console.log('will be trying instances', shuffledInstances);
115+
93116
targetUrl.pathname = '/search';
94117
targetUrl.searchParams.set('safesearch', params.get('safesearch') || '0');
95118

119+
const redirect = (targetUrl, queryFromForm) => {
120+
document.body.innerHTML = '<div id="message" class="pale"></div>';
121+
const messageElement = document.querySelector('#message');
122+
123+
params
124+
.entries()
125+
.filter(([k, _]) => !['languages', 'fast', 'instances'].includes(k))
126+
.forEach(([k, v]) => targetUrl.searchParams.set(k, v));
127+
128+
const query = params.get('q') || queryFromForm;
129+
targetUrl.searchParams.set('language', detectLanguage(query));
130+
targetUrl.searchParams.set('q', query);
131+
132+
for (let i = 0; i < attempts; i++) setTimeout(_ => {
133+
window.stop();
134+
const retryTargetUrl = new URL(targetUrl.toString());
135+
retryTargetUrl.host = new URL(shuffledInstances[i]).host;
136+
if (i > 0) {
137+
messageElement.innerHTML = `Retrying(${i}) with ${retryTargetUrl.host}`;
138+
}
139+
const href = retryTargetUrl.toString();
140+
console.log('trying', href);
141+
if (queryFromForm) {
142+
window.location.href = href;
143+
} else {
144+
window.location.replace(href);
145+
}
146+
}, i * timeout);
147+
148+
setTimeout(_ => messageElement.innerHTML = 'Failed', attempts * timeout);
149+
};
150+
96151
if (params.has('q')) {
97152
redirect(targetUrl);
98153
} else {
99154
const pageUrl = window.location.origin + window.location.pathname;
100-
document.body.innerHTML = `<p>Redirect to <a rel="noopener noreferrer nofollow" href="${pageUrl}?q=">random SearXNG</a> instance</p><p>This page accepts SearXNG <a target="_blank" href="https://docs.searxng.org/dev/search_api.html">GET parameters</a> and optional parameters:<p><p><ul><li><code>fast=1</code> for hardcoded instances</li><li><code>allowed_languages=en,fr,ru</code> for automatic language filter derived from the query</li></ul></p><p>Example for browser search engine settings (<code>about:preferences#search</code> or <code>chrome://settings/search</code>): <code>${pageUrl}?q=%s&fast=1&image_proxy=True&categories=images</code></p><p>Use this page locally for the best performance: <code>wget ${pageUrl} -O searxng.html</code></p><p>Additionally can be combined with the Violentmonkey <a target="_blank" href="https://userscripts.codonaft.com/searxng-redirect-on-failure.js">userscript</a> to handle search errors</p>`;
155+
document.body.innerHTML = `<p>This page redirects to a <a rel="noopener noreferrer nofollow" href="${pageUrl}#q=" onclick="window.location.replace('${targetUrl}')">random SearXNG</a> instance.</p><p>It also supports the <a rel="noopener noreferrer nofollow" target="_blank" href="https://docs.searxng.org/dev/search_api.html">GET parameters</a> (provided as an anchor for privacy) and the optional parameters:<p><p><ul><li><code>languages=en,fr,ru</code> to use automatic language filter derived from the query; default is <code>${LANGUAGES.join(',')}</code></li><li><code>fast=1</code> to force use of predefined instances (instead of fetching them using the <a rel="noopener noreferrer nofollow" target="_blank" href="https://searx.space/data/instances.json">API</a>); default is <code>0</code></li><li><code>instances=search.ononoki.org,searx.bndkt.io</code> to predefine the instances; default is <code>${INSTANCES.join(',')}</code></li><li><code>timeout</code> in milliseconds until attempting the next instance; default is <code>${TIMEOUT}</code></li><li><code>attempts</code> how many instances to try; default is <code>${ATTEMPTS}</code></li></ul></p><p>Example for <strong>browser search engine settings</strong> (<code>about:preferences#search</code> or <code>chrome://settings/search</code>): <code>${pageUrl}#q=%s&fast=1&image_proxy=True&categories=images&languages=en,fr,ru</code>.</p><p>For local use: <code>wget ${pageUrl} -O searxng.html</code>.</p><p>Additionally can be combined with the Violentmonkey <a rel="noopener noreferrer nofollow" target="_blank" href="https://userscripts.codonaft.com/searxng-redirect-on-failure.js">userscript</a> to turn search failures into redirects as well.</p>`;
101156

102157
const input = document.createElement('input');
103158
input.name = 'q';

0 commit comments

Comments
 (0)