impl TryFrom instead of having conversion functions

This commit is contained in:
2025-06-25 00:35:35 +02:00
parent 2f381d540b
commit b685c3a831
5 changed files with 396 additions and 374 deletions

View File

@@ -5,13 +5,13 @@ edition = "2021"
[dependencies] [dependencies]
chrono = "0.4.38" chrono = "0.4.38"
crossterm = "0.28.1" crossterm = "0.29"
futures = "0.3.30" futures = "0.3.30"
icy_sixel = "0.1.2" icy_sixel = "0.1.2"
image = { version = "0.25.2", default-features = false, features = ["jpeg", "png"] } image = { version = "0.25.2", default-features = false, features = ["jpeg", "png"] }
reqwest = "0.12.5" reqwest = "0.12.5"
reqwest-middleware = "0.3.2" reqwest-middleware = "0.4"
reqwest-retry = "0.6.0" reqwest-retry = "0.7"
serde = { version = "1.0.204", features = ["derive"] } serde = { version = "1.0.204", features = ["derive"] }
serde_json = "1.0.121" serde_json = "1.0.121"
tokio = { version = "1.39.2", default-features = false, features = ["macros", "rt-multi-thread"] } tokio = { version = "1.39.2", default-features = false, features = ["macros", "rt-multi-thread"] }

View File

@@ -149,7 +149,7 @@ async fn main() {
let mut chapters = match get_chapters(client, &manga.id).await { let mut chapters = match get_chapters(client, &manga.id).await {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("ERROR: {:#?}", e); eprintln!("ERROR: {e:#?}");
std::process::exit(1); std::process::exit(1);
} }
}; };
@@ -458,7 +458,7 @@ async fn select_manga_from_search(
let choice = match select::select(&entries) { let choice = match select::select(&entries) {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("ERROR: Failed to select: {:?}", e); eprintln!("ERROR: Failed to select: {e:?}");
std::process::exit(1); std::process::exit(1);
} }
}; };

View File

@@ -625,21 +625,21 @@ enum ChapterImageError {
Result(String), Result(String),
} }
impl TryInto<State> for &str { impl TryFrom<&str> for State {
type Error = (); type Error = ();
fn try_into(self) -> Result<State, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
Ok(match self { Ok(match s {
"published" => State::Published, "published" => State::Published,
_ => return Err(()), _ => return Err(()),
}) })
} }
} }
impl TryInto<ContentRating> for &str { impl TryFrom<&str> for ContentRating {
type Error = (); type Error = ();
fn try_into(self) -> Result<ContentRating, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
Ok(match self { Ok(match s {
"safe" => ContentRating::Safe, "safe" => ContentRating::Safe,
"suggestive" => ContentRating::Suggestive, "suggestive" => ContentRating::Suggestive,
"erotica" => ContentRating::Erotica, "erotica" => ContentRating::Erotica,
@@ -648,11 +648,11 @@ impl TryInto<ContentRating> for &str {
}) })
} }
} }
impl TryInto<Language> for &str { impl TryFrom<&str> for Language {
type Error = (); type Error = ();
fn try_into(self) -> Result<Language, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
Ok(match self { Ok(match s {
"ab" => Language::Abkhazian, "ab" => Language::Abkhazian,
"aa" => Language::Afar, "aa" => Language::Afar,
"af" => Language::Afrikaans, "af" => Language::Afrikaans,
@@ -883,11 +883,11 @@ impl TryInto<Language> for &str {
}) })
} }
} }
impl TryInto<PublicationDemographic> for &str { impl TryFrom<&str> for PublicationDemographic {
type Error = (); type Error = ();
fn try_into(self) -> Result<PublicationDemographic, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
Ok(match self { Ok(match s {
"shounen" => PublicationDemographic::Shounen, "shounen" => PublicationDemographic::Shounen,
"josei" => PublicationDemographic::Josei, "josei" => PublicationDemographic::Josei,
"shoujo" => PublicationDemographic::Shoujo, "shoujo" => PublicationDemographic::Shoujo,
@@ -896,11 +896,11 @@ impl TryInto<PublicationDemographic> for &str {
}) })
} }
} }
impl TryInto<DataType> for &str { impl TryFrom<&str> for DataType {
type Error = (); type Error = ();
fn try_into(self) -> Result<DataType, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
Ok(match self { Ok(match s {
"manga" => DataType::Manga, "manga" => DataType::Manga,
"chapter" => DataType::Chapter, "chapter" => DataType::Chapter,
"cover_art" => DataType::CoverArt, "cover_art" => DataType::CoverArt,
@@ -915,11 +915,11 @@ impl TryInto<DataType> for &str {
}) })
} }
} }
impl TryInto<Status> for &str { impl TryFrom<&str> for Status {
type Error = (); type Error = ();
fn try_into(self) -> Result<Status, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
Ok(match self { Ok(match s {
"ongoing" => Status::Ongoing, "ongoing" => Status::Ongoing,
"completed" => Status::Completed, "completed" => Status::Completed,
"hiatus" => Status::Hiatus, "hiatus" => Status::Hiatus,
@@ -928,21 +928,21 @@ impl TryInto<Status> for &str {
}) })
} }
} }
impl TryInto<ResponseResult> for &str { impl TryFrom<&str> for ResponseResult {
type Error = (); type Error = ();
fn try_into(self) -> Result<ResponseResult, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
match self { match s {
"ok" => Ok(ResponseResult::Ok), "ok" => Ok(ResponseResult::Ok),
_ => Err(()), _ => Err(()),
} }
} }
} }
impl TryInto<Response> for &str { impl TryFrom<&str> for Response {
type Error = (); type Error = ();
fn try_into(self) -> Result<Response, ()> { fn try_from(s: &str) -> Result<Self, Self::Error> {
match self { match s {
"collection" => Ok(Response::Collection), "collection" => Ok(Response::Collection),
"entity" => Ok(Response::Entity), "entity" => Ok(Response::Entity),
_ => Err(()), _ => Err(()),
@@ -950,9 +950,9 @@ impl TryInto<Response> for &str {
} }
} }
fn convert_response_to_result( impl TryFrom<SearchResponse> for SearchResult {
search_response: SearchResponse, type Error = ResponseConversionError;
) -> Result<SearchResult, ResponseConversionError> { fn try_from(search_response: SearchResponse) -> Result<Self, Self::Error> {
let response = (search_response.response.as_str()) let response = (search_response.response.as_str())
.try_into() .try_into()
.map_err(|_| ResponseConversionError::Result(search_response.response))?; .map_err(|_| ResponseConversionError::Result(search_response.response))?;
@@ -964,7 +964,7 @@ fn convert_response_to_result(
Ok(Vec::with_capacity(search_response.data.len())); Ok(Vec::with_capacity(search_response.data.len()));
for m in search_response.data { for m in search_response.data {
if let Ok(ref mut d) = data { if let Ok(ref mut d) = data {
match convert_data_to_manga(m) { match m.try_into() {
Ok(v) => d.push(v), Ok(v) => d.push(v),
Err(e) => { Err(e) => {
data = Err(e); data = Err(e);
@@ -979,6 +979,7 @@ fn convert_response_to_result(
data: data?, data: data?,
}) })
} }
}
#[derive(Debug)] #[derive(Debug)]
enum AttributeConversionError { enum AttributeConversionError {
@@ -1023,9 +1024,9 @@ impl Display for ContentRating {
} }
} }
fn convert_attributes( impl TryFrom<ContentAttributes> for MangaAttributes {
attributes: ContentAttributes, type Error = AttributeConversionError;
) -> Result<MangaAttributes, AttributeConversionError> { fn try_from(attributes: ContentAttributes) -> Result<Self, Self::Error> {
Ok(MangaAttributes { Ok(MangaAttributes {
title: attributes.title, title: attributes.title,
alt_titles: attributes.alt_titles, alt_titles: attributes.alt_titles,
@@ -1089,7 +1090,8 @@ fn convert_attributes(
.map_err(|_| AttributeConversionError::DataType(m.type_name))?, .map_err(|_| AttributeConversionError::DataType(m.type_name))?,
id: Id(m.id), id: Id(m.id),
relationships: { relationships: {
let mut relationships = Vec::with_capacity(m.relationships.len()); let mut relationships =
Vec::with_capacity(m.relationships.len());
for m in m.relationships { for m in m.relationships {
relationships.push(({ relationships.push(({
|| { || {
@@ -1109,7 +1111,8 @@ fn convert_attributes(
}, },
) )
} }
})()?); })(
)?);
} }
relationships relationships
}, },
@@ -1162,53 +1165,57 @@ fn convert_attributes(
.map(|m| Id(m.clone())), .map(|m| Id(m.clone())),
}) })
} }
}
pub fn deserialize_id_query(json: &str) -> IdQueryResult { pub fn deserialize_id_query(json: &str) -> IdQueryResult {
let id_query_response: IdQueryResponse = match serde_json::from_str(json) { let id_query_response: IdQueryResponse = match serde_json::from_str(json) {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("ERROR: {:#?}", e); eprintln!("ERROR: {e:#?}");
std::fs::write("out.json", json).unwrap(); std::fs::write("out.json", json).unwrap();
std::process::exit(1); std::process::exit(1);
} }
}; };
convert_id_query(id_query_response).unwrap() id_query_response.try_into().unwrap()
} }
fn convert_id_query(response: IdQueryResponse) -> Result<IdQueryResult, AttributeConversionError> { impl TryFrom<IdQueryResponse> for IdQueryResult {
type Error = AttributeConversionError;
fn try_from(response: IdQueryResponse) -> Result<Self, Self::Error> {
Ok(IdQueryResult { Ok(IdQueryResult {
result: response.result.as_str().try_into().unwrap(), result: response.result.as_str().try_into().unwrap(),
response: response.response.as_str().try_into().unwrap(), response: response.response.as_str().try_into().unwrap(),
data: convert_data_to_manga(response.data).unwrap(), data: response.data.try_into().unwrap(),
}) })
} }
}
pub fn deserialize_chapter_feed(json: &str) -> ChapterFeed { pub fn deserialize_chapter_feed(json: &str) -> ChapterFeed {
let chapter_feed_response: ChapterFeedResponse = match serde_json::from_str(json) { let chapter_feed_response: ChapterFeedResponse = match serde_json::from_str(json) {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("ERROR: {:#?}", e); eprintln!("ERROR: {e:#?}");
std::fs::write("chapter_feed.json", json).unwrap(); std::fs::write("chapter_feed.json", json).unwrap();
std::process::exit(1); std::process::exit(1);
} }
}; };
convert_chapter_feed(chapter_feed_response).unwrap() chapter_feed_response.try_into().unwrap()
} }
pub fn deserializer(json: &str) -> SearchResult { pub fn deserializer(json: &str) -> SearchResult {
let search_response: SearchResponse = match serde_json::from_str(json) { let search_response: SearchResponse = match serde_json::from_str(json) {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("ERROR: {:#?}", e); eprintln!("ERROR: {e:#?}");
std::fs::write("search_result.json", json).unwrap(); std::fs::write("search_result.json", json).unwrap();
std::process::exit(1); std::process::exit(1);
} }
}; };
let search_result = convert_response_to_result(search_response); let search_result = search_response.try_into();
match search_result { match search_result {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("ERROR: Failed to convert search response: {:#?}", e); eprintln!("ERROR: Failed to convert search response: {e:#?}");
std::process::exit(1); std::process::exit(1);
} }
} }
@@ -1235,9 +1242,10 @@ enum ChapterRelationshipError {
Id(String), Id(String),
} }
fn convert_chapter_feed( impl TryFrom<ChapterFeedResponse> for ChapterFeed {
feed: ChapterFeedResponse, type Error = ChapterFeedConversionError;
) -> Result<ChapterFeed, ChapterFeedConversionError> {
fn try_from(feed: ChapterFeedResponse) -> Result<Self, Self::Error> {
// Now this is a bit of an abomination. It uses closures such that you can use the ? syntax // Now this is a bit of an abomination. It uses closures such that you can use the ? syntax
// sugar to return an error. Also uses for loops instead of iterators since they do not take // sugar to return an error. Also uses for loops instead of iterators since they do not take
// ownership. I think I should have just kept the iterators. // ownership. I think I should have just kept the iterators.
@@ -1250,7 +1258,9 @@ fn convert_chapter_feed(
.try_into() .try_into()
.map_err(|_| ChapterConversionError::DataType(m.type_name))?, .map_err(|_| ChapterConversionError::DataType(m.type_name))?,
id: Id(m.id), id: Id(m.id),
attributes: convert_chapter_attributes(m.attributes) attributes: m
.attributes
.try_into()
.map_err(ChapterConversionError::Attributes)?, .map_err(ChapterConversionError::Attributes)?,
relationships: { relationships: {
let mut relationships = Vec::with_capacity(m.relationships.len()); let mut relationships = Vec::with_capacity(m.relationships.len());
@@ -1296,6 +1306,7 @@ fn convert_chapter_feed(
total: feed.total, total: feed.total,
}) })
} }
}
#[derive(Debug)] #[derive(Debug)]
enum ChapterAttributeConversionError { enum ChapterAttributeConversionError {
@@ -1307,9 +1318,9 @@ enum ChapterAttributeConversionError {
TranslatedLanguage(String), TranslatedLanguage(String),
} }
fn convert_chapter_attributes( impl TryFrom<ChapterAttributesContent> for ChapterAttributes {
attributes: ChapterAttributesContent, type Error = ChapterAttributeConversionError;
) -> Result<ChapterAttributes, ChapterAttributeConversionError> { fn try_from(attributes: ChapterAttributesContent) -> Result<Self, Self::Error> {
Ok(ChapterAttributes { Ok(ChapterAttributes {
volume: match &attributes.volume { volume: match &attributes.volume {
Some(v) => match v.parse() { Some(v) => match v.parse() {
@@ -1337,13 +1348,18 @@ fn convert_chapter_attributes(
translated_language: (attributes.translated_language.as_str()) translated_language: (attributes.translated_language.as_str())
.try_into() .try_into()
.map_err(|_| { .map_err(|_| {
ChapterAttributeConversionError::TranslatedLanguage(attributes.translated_language) ChapterAttributeConversionError::TranslatedLanguage(
attributes.translated_language,
)
})?, })?,
version: attributes.version, version: attributes.version,
}) })
} }
}
fn convert_chapter_images(data: ChapterImagesContent) -> Result<ChapterImages, ChapterImageError> { impl TryFrom<ChapterImagesContent> for ChapterImages {
type Error = ChapterImageError;
fn try_from(data: ChapterImagesContent) -> Result<Self, Self::Error> {
Ok(ChapterImages { Ok(ChapterImages {
result: (data.result.as_str()) result: (data.result.as_str())
.try_into() .try_into()
@@ -1355,6 +1371,7 @@ fn convert_chapter_images(data: ChapterImagesContent) -> Result<ChapterImages, C
}, },
}) })
} }
}
pub fn deserialize_chapter_images(json: &str) -> Result<ChapterImages, ChapterImagesContentError> { pub fn deserialize_chapter_images(json: &str) -> Result<ChapterImages, ChapterImagesContentError> {
let chapter_images: ChapterImagesContent = match serde_json::from_str(json) { let chapter_images: ChapterImagesContent = match serde_json::from_str(json) {
@@ -1364,22 +1381,28 @@ pub fn deserialize_chapter_images(json: &str) -> Result<ChapterImages, ChapterIm
Ok(v) => return Err(v), Ok(v) => return Err(v),
Err(e) => { Err(e) => {
// If you can't parse the error then there is no point in continuing. // If you can't parse the error then there is no point in continuing.
eprintln!("ERROR: {:#?}", e); eprintln!("ERROR: {e:#?}");
std::process::exit(1); std::process::exit(1);
} }
} }
} }
}; };
Ok(convert_chapter_images(chapter_images).unwrap()) Ok(chapter_images.try_into().unwrap())
} }
fn convert_data_to_manga(m: ContentData) -> Result<Manga, ResponseConversionError> { impl TryFrom<ContentData> for Manga {
type Error = ResponseConversionError;
fn try_from(m: ContentData) -> Result<Self, Self::Error> {
Ok(Manga { Ok(Manga {
id: Id(m.id), id: Id(m.id),
data_type: (m.type_name.as_str()).try_into().map_err(|_| { data_type: (m.type_name.as_str()).try_into().map_err(|_| {
ResponseConversionError::AttributeError(AttributeConversionError::DataType(m.type_name)) ResponseConversionError::AttributeError(AttributeConversionError::DataType(
m.type_name,
))
})?, })?,
attributes: convert_attributes(m.attributes) attributes: m
.attributes
.try_into()
.map_err(ResponseConversionError::AttributeError)?, .map_err(ResponseConversionError::AttributeError)?,
relationships: { relationships: {
let mut relationships = Vec::with_capacity(m.relationships.len()); let mut relationships = Vec::with_capacity(m.relationships.len());
@@ -1389,11 +1412,9 @@ fn convert_data_to_manga(m: ContentData) -> Result<Manga, ResponseConversionErro
|| { || {
Ok::<Relationship, AttributeConversionError>(Relationship { Ok::<Relationship, AttributeConversionError>(Relationship {
id: Id(m.id), id: Id(m.id),
data_type: m data_type: m.type_name.as_str().try_into().map_err(|_| {
.type_name AttributeConversionError::DataType(m.type_name)
.as_str() })?,
.try_into()
.map_err(|_| AttributeConversionError::DataType(m.type_name))?,
attributes: { attributes: {
if let Some(attributes) = m.attributes { if let Some(attributes) = m.attributes {
Some(CoverAttributes { Some(CoverAttributes {
@@ -1444,3 +1465,4 @@ fn convert_data_to_manga(m: ContentData) -> Result<Manga, ResponseConversionErro
}, },
}) })
} }
}

View File

@@ -64,7 +64,7 @@ fn get_input() -> Option<Action> {
_ => return None, _ => return None,
}), }),
Err(e) => { Err(e) => {
eprintln!("ERROR: {:#?}", e); eprintln!("ERROR: {e:#?}");
exit(); exit();
} }
_ => None, _ => None,
@@ -72,7 +72,7 @@ fn get_input() -> Option<Action> {
} }
Ok(false) => None, Ok(false) => None,
Err(e) => { Err(e) => {
eprintln!("ERROR: {:#?}", e); eprintln!("ERROR: {e:#?}");
exit(); exit();
} }
} }

View File

@@ -185,7 +185,7 @@ pub fn choose_volumes(input: &str) -> Option<VolumeSelection> {
{ {
Ok(v) => Some(VolumeSelection::List(v)), Ok(v) => Some(VolumeSelection::List(v)),
Err(e) => { Err(e) => {
eprintln!("Invalid number in list: {:#?}", e); eprintln!("Invalid number in list: {e:#?}");
None None
} }
} }
@@ -224,7 +224,7 @@ pub fn choose_chapters(input: &str) -> Option<ChapterSelection> {
.map(|m| match m.parse() { .map(|m| match m.parse() {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("Invalid input: {:#?}", e); eprintln!("Invalid input: {e:#?}");
invalid = true; invalid = true;
0. 0.
} }
@@ -247,7 +247,7 @@ pub fn choose_chapters(input: &str) -> Option<ChapterSelection> {
} }
pub fn get_input(msg: &str) -> String { pub fn get_input(msg: &str) -> String {
print!("{}", msg); print!("{msg}");
io::stdout().flush().expect("failed to flush stdout"); io::stdout().flush().expect("failed to flush stdout");
let mut input = String::new(); let mut input = String::new();
@@ -404,7 +404,7 @@ pub fn args() -> Config {
Some(a) => match a.parse() { Some(a) => match a.parse() {
Ok(v) => v, Ok(v) => v,
Err(e) => { Err(e) => {
eprintln!("Failed to parse value for result-limit: {:?}, type: u32", e); eprintln!("Failed to parse value for result-limit: {e:?}, type: u32");
std::process::exit(1); std::process::exit(1);
} }
}, },