0
0
mirror of https://github.com/neon-mmd/websurfx.git synced 2024-12-22 04:18:21 -05:00

Merge pull request #258 from neon-mmd/feat-safe-search-setting-ui

 `Safe Search` setting for the website UI
This commit is contained in:
alamin655 2023-09-23 16:54:10 +05:30 committed by GitHub
commit 5c9559b88a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 192 additions and 90 deletions

2
Cargo.lock generated
View File

@ -3932,7 +3932,7 @@ dependencies = [
[[package]]
name = "websurfx"
version = "0.21.6"
version = "0.22.0"
dependencies = [
"actix-cors",
"actix-files",

View File

@ -1,6 +1,6 @@
[package]
name = "websurfx"
version = "0.21.6"
version = "0.22.0"
edition = "2021"
description = "An open-source alternative to Searx that provides clean, ad-free, and organic results with incredible speed while keeping privacy and security in mind."
repository = "https://github.com/neon-mmd/websurfx"

View File

@ -16,8 +16,9 @@ document.addEventListener(
let cookie = decodeURIComponent(document.cookie)
// Set the value of the input field to the decoded cookie value if it is not empty
// Otherwise, display a message indicating that no cookies have been saved on the user's system
document.querySelector('.cookies input').value =
cookie !== '' ? cookie : 'No cookies have been saved on your system'
document.querySelector('.cookies input').value = cookie.length
? cookie
: 'No cookies have been saved on your system'
} catch (error) {
// If there is an error decoding the cookie, log the error to the console
// and display an error message in the input field
@ -25,5 +26,5 @@ document.addEventListener(
document.querySelector('.cookies input').value = 'Error decoding cookie'
}
},
false
false,
)

View File

@ -2,16 +2,25 @@
* Selects the input element for the search box
* @type {HTMLInputElement}
*/
const searchBox = document.querySelector('input');
const searchBox = document.querySelector('input')
/**
* Redirects the user to the search results page with the query parameter
*/
function searchWeb() {
const query = searchBox.value.trim();
if (query) {
window.location.href = `search?q=${encodeURIComponent(query)}`;
}
const query = searchBox.value.trim()
try {
let safeSearchLevel = document.querySelector('.search_options select').value
if (query) {
window.location.href = `search?q=${encodeURIComponent(
query,
)}&safesearch=${encodeURIComponent(safeSearchLevel)}`
}
} catch (error) {
if (query) {
window.location.href = `search?q=${encodeURIComponent(query)}`
}
}
}
/**
@ -19,7 +28,7 @@ function searchWeb() {
* @param {KeyboardEvent} e - The keyboard event object
*/
searchBox.addEventListener('keyup', (e) => {
if (e.key === 'Enter') {
searchWeb();
}
});
if (e.key === 'Enter') {
searchWeb()
}
})

View File

@ -3,8 +3,8 @@
* @returns {void}
*/
function navigate_forward() {
const url = new URL(window.location);
const searchParams = url.searchParams;
let url = new URL(window.location);
let searchParams = url.searchParams;
let q = searchParams.get('q');
let page = parseInt(searchParams.get('page'));
@ -23,8 +23,8 @@ function navigate_forward() {
* @returns {void}
*/
function navigate_backward() {
const url = new URL(window.location);
const searchParams = url.searchParams;
let url = new URL(window.location);
let searchParams = url.searchParams;
let q = searchParams.get('q');
let page = parseInt(searchParams.get('page'));

View File

@ -0,0 +1,18 @@
document.addEventListener(
'DOMContentLoaded',
() => {
let url = new URL(window.location)
let searchParams = url.searchParams
let safeSearchLevel = searchParams.get('safesearch')
if (
safeSearchLevel >= 0 &&
safeSearchLevel <= 2 &&
safeSearchLevel !== null
) {
document.querySelector('.search_options select').value = safeSearchLevel
}
},
false,
)

View File

@ -1,5 +1,5 @@
/**
* This function handles the toggling of selections of all upstream search engines
* This function handles the toggling of selections of all upstream search engines
* options in the settings page under the tab engines.
*/
function toggleAllSelection() {
@ -8,12 +8,12 @@ function toggleAllSelection() {
.forEach(
(engine_checkbox) =>
(engine_checkbox.checked =
document.querySelector('.select_all').checked)
document.querySelector('.select_all').checked),
)
}
/**
* This function adds the functionality to sidebar buttons to only show settings
* This function adds the functionality to sidebar buttons to only show settings
* related to that tab.
* @param {HTMLElement} current_tab - The current tab that was clicked.
*/
@ -43,20 +43,28 @@ function setClientSettings() {
// Loop through all select tags and add their values to the cookie dictionary
document.querySelectorAll('select').forEach((select_tag) => {
if (select_tag.name === 'themes') {
cookie_dictionary['theme'] = select_tag.value
} else if (select_tag.name === 'colorschemes') {
cookie_dictionary['colorscheme'] = select_tag.value
switch (select_tag.name) {
case 'themes':
cookie_dictionary['theme'] = select_tag.value
break
case 'colorschemes':
cookie_dictionary['colorscheme'] = select_tag.value
break
case 'safe_search_levels':
cookie_dictionary['safe_search_level'] = Number(select_tag.value)
break
}
})
// Loop through all engine checkboxes and add their values to the cookie dictionary
let engines = []
document.querySelectorAll('.engine').forEach((engine_checkbox) => {
if (engine_checkbox.checked === true) {
if (engine_checkbox.checked) {
engines.push(engine_checkbox.parentNode.parentNode.innerText.trim())
}
})
cookie_dictionary['engines'] = engines
// Set the expiration date for the cookie to 1 year from the current date
@ -65,7 +73,7 @@ function setClientSettings() {
// Save the cookie to the user's machine
document.cookie = `appCookie=${JSON.stringify(
cookie_dictionary
cookie_dictionary,
)}; expires=${expiration_date.toUTCString()}`
// Display a success message to the user
@ -79,9 +87,9 @@ function setClientSettings() {
}
/**
* This functions gets the saved cookies if it is present on the user's machine If it
* is available then it is parsed and converted to an object which is then used to
* retrieve the preferences that the user had selected previously and is then loaded in the
* This functions gets the saved cookies if it is present on the user's machine If it
* is available then it is parsed and converted to an object which is then used to
* retrieve the preferences that the user had selected previously and is then loaded in the
* website otherwise the function does nothing and the default server side settings are loaded.
*/
function getClientSettings() {
@ -89,21 +97,19 @@ function getClientSettings() {
let cookie = decodeURIComponent(document.cookie)
// If the cookie is not empty, parse it and use it to set the user's preferences
if (cookie !== '') {
let cookie_value = decodeURIComponent(document.cookie)
if (cookie.length) {
let cookie_value = cookie
.split(';')
.map((item) => item.split('='))
.reduce((acc, [_, v]) => (acc = JSON.parse(v)) && acc, {})
// Loop through all link tags and update their href values to match the user's preferences
let links = Array.from(document.querySelectorAll('link')).forEach(
(item) => {
if (item.href.includes('static/themes')) {
item.href = `static/themes/${cookie_value['theme']}.css`
} else if (item.href.includes('static/colorschemes')) {
item.href = `static/colorschemes/${cookie_value['colorscheme']}.css`
}
Array.from(document.querySelectorAll('link')).forEach((item) => {
if (item.href.includes('static/themes')) {
item.href = `static/themes/${cookie_value['theme']}.css`
} else if (item.href.includes('static/colorschemes')) {
item.href = `static/colorschemes/${cookie_value['colorscheme']}.css`
}
)
})
}
}

View File

@ -70,6 +70,28 @@ body {
filter: brightness(1.2);
}
.search_area .search_options {
display: flex;
justify-content: space-between;
align-items: center;
}
.search_area .search_options select {
margin: 0.7rem 0;
width: 20rem;
background-color: var(--color-one);
color: var(--foreground-color);
padding: 1rem 2rem;
border-radius: 0.5rem;
outline: none;
border: none;
text-transform: capitalize;
}
.search_area .search_options option:hover {
background-color: var(--color-one);
}
.result_not_found {
display: flex;
flex-direction: column;
@ -499,7 +521,8 @@ footer {
color: var(--foreground-color);
}
.settings_container .user_interface select {
.settings_container .user_interface select,
.settings_container .general select {
margin: 0.7rem 0;
width: 20rem;
background-color: var(--background-color);
@ -511,7 +534,8 @@ footer {
text-transform: capitalize;
}
.settings_container .user_interface option:hover {
.settings_container .user_interface option:hover,
.settings_container .general option:hover {
background-color: var(--color-one);
}

View File

@ -1,4 +1,5 @@
<div class="engines tab">
<h1>Engines</h1>
<h3>select search engines</h3>
<p class="description">
Select the search engines from the list of engines that you want results

View File

@ -1,4 +1,13 @@
<div class="general tab active">
<h1>General</h1>
<p class="description">Coming soon!!</p>
<h3>Select a safe search level</h3>
<p class="description">
Select a safe search level from the menu below to filter content based on
the level.
</p>
<select name="safe_search_levels">
<option value=0>None</option>
<option value=1>Low</option>
<option value=2>Moderate</option>
</select>
</div>

View File

@ -66,6 +66,7 @@
</div>
</main>
<script src="static/index.js"></script>
<script src="static/search_area_options.js"></script>
<script src="static/pagination.js"></script>
<script src="static/error_box.js"></script>
{{>footer}}

View File

@ -1,27 +1,36 @@
{{>bar this}}
<div class="error_box">
{{#if engineErrorsInfo}}
<button onclick="toggleErrorBox()" class="error_box_toggle_button">
<img src="./images/warning.svg" alt="Info icon for error box" />
</button>
<div class="dropdown_error_box">
{{#each engineErrorsInfo}}
<div class="error_item">
<span class="engine_name">{{{this.engine}}}</span>
<span class="engine_name">{{{this.error}}}</span>
<span class="severity_color" style="background: {{{this.severity_color}}};"></span>
<div class="search_area">
{{>bar this}}
<div class="error_box">
{{#if engineErrorsInfo}}
<button onclick="toggleErrorBox()" class="error_box_toggle_button">
<img src="./images/warning.svg" alt="Info icon for error box" />
</button>
<div class="dropdown_error_box">
{{#each engineErrorsInfo}}
<div class="error_item">
<span class="engine_name">{{{this.engine}}}</span>
<span class="engine_name">{{{this.error}}}</span>
<span class="severity_color" style="background: {{{this.severity_color}}};"></span>
</div>
{{/each}}
</div>
{{/each}}
</div>
{{else}}
<button onclick="toggleErrorBox()" class="error_box_toggle_button">
<img src="./images/info.svg" alt="Warning icon for error box" />
</button>
<div class="dropdown_error_box">
<div class="no_errors">
Everything looks good 🙂!!
{{else}}
<button onclick="toggleErrorBox()" class="error_box_toggle_button">
<img src="./images/info.svg" alt="Warning icon for error box" />
</button>
<div class="dropdown_error_box">
<div class="no_errors">
Everything looks good 🙂!!
</div>
</div>
{{/if}}
</div>
{{/if}}
</div>
<div class="search_options">
<select name="safe_search_levels" {{#if (gte safeSearchLevel 3)}} disabled {{/if}}>
<option value=0 {{#if (eq safeSearchLevel 0)}} selected {{/if}}>SafeSearch: None</option>
<option value=1 {{#if (eq safeSearchLevel 1)}} selected {{/if}}>SafeSearch: Low</option>
<option value=2 {{#if (eq safeSearchLevel 2)}} selected {{/if}}>SafeSearch: Moderate</option>
</select>
</div>
</div>

View File

@ -1,4 +1,5 @@
<div class="user_interface tab">
<h1>User Interface</h1>
<h3>select theme</h3>
<p class="description">
Select the theme from the available themes to be used in user interface

View File

@ -122,6 +122,8 @@ pub struct SearchResults {
/// search query was filtered when the safe search level set to 3 and it
/// was present in the `Blocklist` file.
pub filtered: bool,
/// Stores the safe search level `safesearch` provided in the search url.
pub safe_search_level: u8,
}
impl SearchResults {
@ -147,6 +149,7 @@ impl SearchResults {
engine_errors_info: engine_errors_info.to_owned(),
disallowed: Default::default(),
filtered: Default::default(),
safe_search_level: Default::default(),
}
}
@ -178,4 +181,9 @@ impl SearchResults {
pub fn results(&mut self) -> Vec<SearchResult> {
self.results.clone()
}
/// A setter function to set the current page safe search level.
pub fn set_safe_search_level(&mut self, safe_search_level: u8) {
self.safe_search_level = safe_search_level;
}
}

View File

@ -26,4 +26,6 @@ pub struct Cookie<'a> {
pub colorscheme: &'a str,
/// It stores the user selected upstream search engines selected from the UI.
pub engines: Vec<&'a str>,
/// It stores the user selected safe search level from the UI.
pub safe_search_level: u8,
}

View File

@ -67,61 +67,48 @@ pub async fn search(
None => 1,
};
let safe_search: u8 = match config.safe_search {
3..=4 => config.safe_search,
_ => match &params.safesearch {
Some(safesearch) => match safesearch {
0..=2 => *safesearch,
_ => 1,
},
None => config.safe_search,
},
};
let (_, results, _) = join!(
results(
format!(
"http://{}:{}/search?q={}&page={}&safesearch={}",
"http://{}:{}/search?q={}&page={}&safesearch=",
config.binding_ip,
config.port,
query,
page - 1,
safe_search
),
&config,
&cache,
query,
page - 1,
req.clone(),
safe_search
&params.safesearch
),
results(
format!(
"http://{}:{}/search?q={}&page={}&safesearch={}",
config.binding_ip, config.port, query, page, safe_search
"http://{}:{}/search?q={}&page={}&safesearch=",
config.binding_ip, config.port, query, page
),
&config,
&cache,
query,
page,
req.clone(),
safe_search
&params.safesearch
),
results(
format!(
"http://{}:{}/search?q={}&page={}&safesearch={}",
"http://{}:{}/search?q={}&page={}&safesearch=",
config.binding_ip,
config.port,
query,
page + 1,
safe_search
),
&config,
&cache,
query,
page + 1,
req.clone(),
safe_search
&params.safesearch
)
);
@ -156,7 +143,7 @@ async fn results(
query: &str,
page: u32,
req: HttpRequest,
safe_search: u8,
safe_search: &Option<u8>,
) -> Result<SearchResults, Box<dyn std::error::Error>> {
// fetch the cached results json.
let cached_results = cache.cached_json(&url).await;
@ -165,7 +152,18 @@ async fn results(
match cached_results {
Ok(results) => Ok(results),
Err(_) => {
if safe_search == 4 {
let mut safe_search_level: u8 = match config.safe_search {
3..=4 => config.safe_search,
_ => match safe_search {
Some(safesearch) => match safesearch {
0..=2 => *safesearch,
_ => config.safe_search,
},
None => config.safe_search,
},
};
if safe_search_level == 4 {
let mut results: SearchResults = SearchResults::default();
let mut _flag: bool =
is_match_from_filter_list(file_path(FileType::BlockList)?, query)?;
@ -176,6 +174,7 @@ async fn results(
results.add_style(&config.style);
results.set_page_query(query);
cache.cache_results(&results, &url).await?;
results.set_safe_search_level(safe_search_level);
return Ok(results);
}
}
@ -195,6 +194,17 @@ async fn results(
.filter_map(|name| EngineHandler::new(name))
.collect();
safe_search_level = match config.safe_search {
3..=4 => config.safe_search,
_ => match safe_search {
Some(safesearch) => match safesearch {
0..=2 => *safesearch,
_ => config.safe_search,
},
None => cookie_value.safe_search_level,
},
};
aggregate(
query,
page,
@ -202,7 +212,7 @@ async fn results(
config.debug,
&engines,
config.request_timeout,
safe_search,
safe_search_level,
)
.await?
}
@ -214,7 +224,7 @@ async fn results(
config.debug,
&config.upstream_search_engines,
config.request_timeout,
safe_search,
safe_search_level,
)
.await?
}
@ -223,7 +233,10 @@ async fn results(
results.set_filtered();
}
results.add_style(&config.style);
cache.cache_results(&results, &url).await?;
cache
.cache_results(&results, &(format!("{url}{safe_search_level}")))
.await?;
results.set_safe_search_level(safe_search_level);
Ok(results)
}
}