Skip to content

Commit a9013ce

Browse files
committed
Update
1 parent d811cb9 commit a9013ce

2 files changed

Lines changed: 101 additions & 40 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: 96 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -10,56 +10,85 @@
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'];
21-
22-
const params = new URLSearchParams(window.location.search);
23-
24-
const loadInstances = async () => {
25-
const fallbacks = FALLBACKS.map(i => `https://${i}/`);
26-
if (params.get('fast') === '1') return fallbacks;
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 = 10;
26+
const CUSTOM_PARAMS = ['attempts', 'languages', 'fast', 'instances', 'timeout'];
27+
28+
const params = new URLSearchParams(window.location.href.split('#')[1] || '');
29+
const timeout = Number(params.get('timeout')) || TIMEOUT;
30+
const attempts = Number(params.get('attempts')) || ATTEMPTS;
31+
32+
const loadAndShuffleInstances = async () => {
33+
const instancesFromParams = params.get('instances')?.split(',') || [];
34+
const instances = shuffle((instancesFromParams.length > 0 ? instancesFromParams : INSTANCES))
35+
.slice(0, attempts)
36+
.map(i => {
37+
const protocol = i.endsWith('.onion') ? 'http' : 'https';
38+
return `${protocol}://${i}/`;
39+
});
40+
if (params.get('fast') === '1') return instances;
2741

2842
const response = await fetch('https://searx.space/data/instances.json');
2943
if (!response.ok) {
30-
console.log('fallback');
31-
return fallbacks;
44+
console.log('failed to load instances');
45+
return instances;
3246
}
3347

34-
const instances = (await response.json()).instances;
35-
console.log('instances', instances);
48+
const loadedInstances = (await response.json()).instances;
49+
console.log('instances', loadedInstances);
3650

3751
const onion = window.location.host.endsWith('.onion');
3852
const best = Object
39-
.entries(instances)
53+
.entries(loadedInstances)
4054
.filter(([u, i]) => {
4155
try {
4256
const url = new URL(u);
4357
if (onion) {
44-
if (i.network_type !== 'tor') return false;
58+
if (i?.network_type !== 'tor') return false;
4559
} else {
46-
if (i.network_type !== 'normal' || url.protocol !== 'https:' || i.tls.grade !== 'A+') return false;
60+
if (i?.network_type !== 'normal' || url.protocol !== 'https:' || i?.tls?.grade !== 'A+' || i?.html?.grade !== 'V') return false;
4761
}
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;
62+
return !i?.analytics;
4963
} catch(e) {
64+
console.error(e);
5065
return false;
5166
}
5267
})
53-
.map(([u, _]) => u);
68+
.map(([u, i]) => {
69+
const key = [i?.uptime?.uptimeDay, i?.uptime?.uptimeMonth, 1 / i?.engines?.google?.error_rate, 1 / i?.engines?.duckduckgo?.error_rate];
70+
return [u, key];
71+
})
72+
.sort(([_a, a], [_b, b]) => {
73+
const index = a.findIndex((_, i) => (a[i] || 0) !== (b[i] || 0));
74+
if (index === -1) return 0;
75+
return b[index] - a[index];
76+
})
77+
.map(([u, _]) => u)
78+
.slice(0, attempts);
5479

5580
console.log('best', best);
56-
return best;
81+
if (best.length === 0) {
82+
console.log('instances not found');
83+
return instances;
84+
}
85+
return shuffle(best);
5786
};
5887

5988
const detectLanguage = query => {
6089
const en = 'en';
61-
const allowedLanguages = params.get('allowed_languages');
62-
const only = allowedLanguages ? allowedLanguages.split(',') : [en];
90+
const allowedLanguages = params.get('languages');
91+
const only = allowedLanguages ? allowedLanguages.split(',') : LANGUAGES;
6392
console.log('allowed languages', only);
6493
if (only.length <= 1) return en;
6594

@@ -74,30 +103,58 @@
74103
return detected[0].lang;
75104
};
76105

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());
106+
const shuffle = xs => {
107+
for (let i = xs.length - 1; i > 0; i--) {
108+
let j = Math.floor(Math.random() * (i + 1));
109+
[xs[i], xs[j]] = [xs[j], xs[i]];
88110
}
111+
return xs;
89112
};
90113

91-
const pick = xs => xs[Math.floor(Math.random() * xs.length)];
92-
const targetUrl = new URL(pick(await loadInstances()));
93-
targetUrl.pathname = '/search';
94-
targetUrl.searchParams.set('safesearch', params.get('safesearch') || '0');
114+
const redirect = async (queryFromForm) => {
115+
document.body.innerHTML = '<div id="message" class="pale"></div>';
116+
const messageElement = document.querySelector('#message');
117+
118+
const shuffledInstances = await loadAndShuffleInstances();
119+
console.log('will be trying instances', shuffledInstances);
120+
121+
const targetUrl = new URL(shuffledInstances[0]);
122+
targetUrl.pathname = '/search';
123+
targetUrl.searchParams.set('safesearch', params.get('safesearch') || '0');
124+
125+
params
126+
.entries()
127+
.filter(([k, _]) => !CUSTOM_PARAMS.includes(k))
128+
.forEach(([k, v]) => targetUrl.searchParams.set(k, v));
129+
130+
const query = params.get('q') || queryFromForm;
131+
targetUrl.searchParams.set('language', detectLanguage(query));
132+
targetUrl.searchParams.set('q', query);
133+
134+
for (let i = 0; i < shuffledInstances.length; i++) setTimeout(_ => {
135+
window.stop();
136+
const retryTargetUrl = new URL(targetUrl.toString());
137+
retryTargetUrl.host = new URL(shuffledInstances[i]).host;
138+
if (i > 0) {
139+
messageElement.innerHTML = `Attempt ${i + 1}/${shuffledInstances.length}: ${retryTargetUrl.host}`;
140+
}
141+
const href = retryTargetUrl.toString();
142+
console.log('trying', href);
143+
if (queryFromForm) {
144+
window.location.href = href;
145+
} else {
146+
window.location.replace(href);
147+
}
148+
}, i * timeout);
149+
150+
setTimeout(_ => messageElement.innerHTML = 'Failed', shuffledInstances.length * timeout);
151+
};
95152

96153
if (params.has('q')) {
97-
redirect(targetUrl);
154+
redirect();
98155
} else {
99156
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>`;
157+
document.body.innerHTML = `<p>This page redirects to a <a rel="noopener noreferrer nofollow" href="${pageUrl}#q=" onclick="window.location.replace('${pageUrl}#q=')">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>`;
101158

102159
const input = document.createElement('input');
103160
input.name = 'q';
@@ -112,7 +169,7 @@
112169
const form = document.createElement('form');
113170
form.addEventListener('submit', event => {
114171
event.preventDefault();
115-
redirect(targetUrl, input.value);
172+
redirect(input.value);
116173
});
117174

118175
form.appendChild(input);

0 commit comments

Comments
 (0)