use indicatrix_net::{
library::{LibraryResponse, RangeFilterWire, SortOrderWire},
messages::{ErrorMsg, error_codes},
};
use indicatrix_vault::db::sqlite::{Database, DisplayFilters, SEARCH_RESULT_CAP, SortOrder};
use super::convert::{from_range_wire, to_ranges_wire, to_summary};
pub const LIBRARY_VALIDATION_ERROR_CODE: u32 = error_codes::LIBRARY_REQUEST_INVALID;
pub const LIBRARY_ERROR_CODE: u32 = error_codes::LIBRARY_FAILED;
pub(super) fn search(
db: &Database,
query: &str,
shape_filter: &str,
gear_filter: &str,
range: &RangeFilterWire,
order: SortOrderWire,
tag_filter: Option<&str>,
) -> LibraryResponse {
let range = match from_range_wire(range) {
Ok(r) => r,
Err(resp) => return resp,
};
let tag_filter = match tag_filter.map(|name| db.tag_id_by_name(name)) {
Some(Ok(id)) => id,
Some(Err(e)) => return db_error("tag_id_by_name", &e),
None => None,
};
let filters = DisplayFilters {
order: sort_order_from_wire(order),
local_only: false,
tag_filter,
id_filter: None,
};
match db.search_diagrams_display(query, shape_filter, gear_filter, &range, filters) {
Ok(result) => LibraryResponse::SearchResults {
items: result.items.iter().map(to_summary).collect(),
excluded_for_missing_curves: result.excluded_for_missing_curves as u32,
},
Err(e) => db_error("search_diagrams_display", &e),
}
}
pub(super) const fn sort_order_from_wire(order: SortOrderWire) -> SortOrder {
match order {
SortOrderWire::CatalogueOrder => SortOrder::CatalogueOrder,
SortOrderWire::Title => SortOrder::Title,
SortOrderWire::Newest => SortOrder::Newest,
SortOrderWire::RecentlyEdited => SortOrder::RecentlyEdited,
}
}
pub(super) fn design_source(db: &Database, entry_id: i64) -> LibraryResponse {
let meta = match db.get_diagram_full_meta(entry_id) {
Ok(Some(meta)) => meta,
Ok(None) => {
tracing::debug!("FetchDesignSource: entry {entry_id} not found");
return LibraryResponse::NotFound;
}
Err(e) => return db_error("get_diagram_full_meta", &e),
};
let Some((position, kind)) = indicatrix_vault::local::design_attachment_position(
meta.attached_files.iter().map(|f| f.name.as_str()),
) else {
tracing::debug!("FetchDesignSource: entry {entry_id} has no .asc/.gem/.gcs attachment");
return LibraryResponse::DesignSourceNotAvailable;
};
let attachment = &meta.attached_files[position];
match db.get_attachment_content(attachment.id) {
Ok(Some((name, content))) => {
tracing::debug!(
"FetchDesignSource: entry {entry_id} serving attachment {} ('{name}', {} bytes)",
attachment.id,
content.len()
);
design_source_reply(entry_id, &name, kind, &content)
}
Ok(None) => {
tracing::debug!(
"FetchDesignSource: entry {entry_id}'s .asc attachment {} vanished concurrently",
attachment.id
);
LibraryResponse::DesignSourceNotAvailable
}
Err(e) => db_error("get_attachment_content", &e),
}
}
pub(super) fn design_native(db: &Database, entry_id: i64) -> LibraryResponse {
let meta = match db.get_diagram_full_meta(entry_id) {
Ok(Some(meta)) => meta,
Ok(None) => {
tracing::debug!("FetchDesignNative: entry {entry_id} not found");
return LibraryResponse::NotFound;
}
Err(e) => return db_error("get_diagram_full_meta", &e),
};
let Some(position) = indicatrix_vault::local::native_design_attachment_position(
meta.attached_files.iter().map(|f| f.name.as_str()),
) else {
tracing::debug!("FetchDesignNative: entry {entry_id} has no .indicatrix attachment");
return LibraryResponse::DesignNativeNotAvailable;
};
match db.get_attachment_content(meta.attached_files[position].id) {
Ok(Some((file_name, content))) => LibraryResponse::DesignNative {
entry_id,
file_name,
content,
},
Ok(None) => LibraryResponse::DesignNativeNotAvailable,
Err(e) => db_error("get_attachment_content", &e),
}
}
fn design_source_reply(
entry_id: i64,
name: &str,
kind: indicatrix_vault::local::DesignFileKind,
content: &[u8],
) -> LibraryResponse {
let converted = std::panic::catch_unwind(|| {
indicatrix_vault::local::design_file_to_asc_text(name, kind, content)
});
let failure = match converted {
Ok(Ok(file)) => {
return LibraryResponse::DesignSource {
entry_id,
file_name: file.asc_file_name,
asc_text: file.asc_text,
};
}
Ok(Err(e)) => format!("'{name}' could not be read: {e}"),
Err(_) => format!("'{name}' could not be read: internal error"),
};
tracing::warn!("FetchDesignSource: entry {entry_id}: {failure}");
LibraryResponse::Error(ErrorMsg {
code: LIBRARY_ERROR_CODE,
message: failure,
request_id: None,
})
}
pub(super) fn search_page(
db: &Database,
query: &str,
shape_filter: &str,
gear_filter: &str,
range: &RangeFilterWire,
cursor: Option<i64>,
) -> LibraryResponse {
let range = match from_range_wire(range) {
Ok(r) => r,
Err(resp) => return resp,
};
match db.search_diagrams_page(
query,
shape_filter,
gear_filter,
&range,
cursor,
SEARCH_RESULT_CAP,
) {
Ok(items) => {
let page_full = items.len() == usize::try_from(SEARCH_RESULT_CAP).unwrap_or(usize::MAX);
let next_cursor = if page_full {
items.last().map(|i| i.id)
} else {
None
};
LibraryResponse::SearchResultsPage {
results: items.iter().map(to_summary).collect(),
next_cursor,
excluded_for_missing_curves: 0,
}
}
Err(e) => db_error("search_diagrams_page", &e),
}
}
pub(super) fn filter_options(db: &Database) -> LibraryResponse {
let shapes = match db.get_unique_shapes() {
Ok(v) => v,
Err(e) => return db_error("get_unique_shapes", &e),
};
let gears = match db.get_unique_gears() {
Ok(v) => v,
Err(e) => return db_error("get_unique_gears", &e),
};
let ranges = match db.get_attribute_ranges() {
Ok(v) => v,
Err(e) => return db_error("get_attribute_ranges", &e),
};
LibraryResponse::FilterOptions {
shapes,
gears,
ranges: to_ranges_wire(ranges),
}
}
pub(super) fn db_error(op: &str, e: &anyhow::Error) -> LibraryResponse {
tracing::warn!("library request failed ({op}): {e:#}");
server_error()
}
pub(super) fn server_error() -> LibraryResponse {
LibraryResponse::Error(ErrorMsg {
code: LIBRARY_ERROR_CODE,
message: "internal error serving the design library".to_string(),
request_id: None,
})
}