Compare commits
No commits in common. "master" and "acf00d8afa9e6a0e9753d44b132b0011248060f0" have entirely different histories.
master
...
acf00d8afa
23
Cargo.toml
23
Cargo.toml
|
@ -1,19 +1,20 @@
|
|||
[package]
|
||||
name = "libjens"
|
||||
version = "1.1.0"
|
||||
version = "0.1.6"
|
||||
authors = ["LordMZTE <lord@mzte.de>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
env_logger = "^0.9"
|
||||
lazy_static = "^1.4"
|
||||
log = "^0.4"
|
||||
once_cell = "^1"
|
||||
reqwest = "^0.11"
|
||||
serde = { version = "^1.0", features = ["derive"] }
|
||||
serde_json = "^1.0"
|
||||
thiserror = "^1.0"
|
||||
tokio = { version = "^1.15", features = ["macros", "fs", "rt-multi-thread"] }
|
||||
url = "^2.2"
|
||||
anyhow = "1.0.34"
|
||||
env_logger = "0.8.2"
|
||||
lazy_static = "1.4.0"
|
||||
log = "0.4.11"
|
||||
once_cell = "1.5.2"
|
||||
reqwest = "0.11.3"
|
||||
serde = { version = "1.0.117", features = ["derive"] }
|
||||
serde_json = "1.0.60"
|
||||
thiserror = "1.0.23"
|
||||
tokio = { version = "1.7.0", features = ["macros", "fs", "rt-multi-thread"] }
|
||||
url = "2.2.0"
|
||||
|
|
12
rustfmt.toml
12
rustfmt.toml
|
@ -1,12 +0,0 @@
|
|||
unstable_features = true
|
||||
binop_separator = "Back"
|
||||
format_code_in_doc_comments = true
|
||||
format_macro_matchers = true
|
||||
format_strings = true
|
||||
imports_layout = "HorizontalVertical"
|
||||
match_block_trailing_comma = true
|
||||
merge_imports = true
|
||||
normalize_comments = true
|
||||
use_field_init_shorthand = true
|
||||
use_try_shorthand = true
|
||||
wrap_comments = true
|
59
src/api.rs
59
src/api.rs
|
@ -1,9 +1,9 @@
|
|||
use anyhow::{anyhow, Result};
|
||||
use serde::{
|
||||
de::{self, Visitor},
|
||||
Deserialize,
|
||||
Deserializer,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
|
||||
pub struct UpResp {
|
||||
|
@ -35,45 +35,37 @@ pub struct Category {
|
|||
pub struct Meme {
|
||||
pub id: String,
|
||||
pub link: String,
|
||||
pub path: String,
|
||||
pub category: String,
|
||||
pub user: String,
|
||||
#[serde(deserialize_with = "deserialize_timestamp")]
|
||||
pub timestamp: i64,
|
||||
pub ipfs: Option<String>,
|
||||
}
|
||||
|
||||
impl Meme {
|
||||
pub fn file_name(&self) -> Result<&str, MemeFileNameError> {
|
||||
let fname = self.link.split('/').last().ok_or(MemeFileNameError)?;
|
||||
|
||||
// in a valid URL with a filename, there'll always be at least 4 slashes first.
|
||||
if fname.is_empty() || self.link.split('/').count() < 4 {
|
||||
return Err(MemeFileNameError);
|
||||
}
|
||||
|
||||
Ok(fname)
|
||||
pub fn file_name(&self) -> Result<&str> {
|
||||
self.path
|
||||
.split('/')
|
||||
.last()
|
||||
.ok_or_else(|| anyhow!("failed to get file name. server response invalid"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
#[error("Failed to get file name. Server response invalid!")]
|
||||
pub struct MemeFileNameError;
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
|
||||
pub struct User {
|
||||
pub name: String,
|
||||
pub id: Option<String>,
|
||||
pub tokenhash: Option<String>,
|
||||
pub userdir: Option<String>,
|
||||
pub dayuploads: u16,
|
||||
pub dayuploads: String,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn get_id(&self) -> Option<&String> {
|
||||
self.id
|
||||
.as_ref()
|
||||
.or(self.tokenhash.as_ref())
|
||||
.or(self.userdir.as_ref())
|
||||
.or_else(|| self.tokenhash.as_ref())
|
||||
.or_else(|| self.userdir.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -111,34 +103,3 @@ where
|
|||
|
||||
deserializer.deserialize_any(Vis)
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
|
||||
pub struct RandomResp {
|
||||
pub meme: Meme,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn meme_with_link(link: &str) -> Meme {
|
||||
Meme {
|
||||
id: "0".to_string(),
|
||||
link: link.to_string(),
|
||||
category: "test".to_string(),
|
||||
user: "test".to_string(),
|
||||
timestamp: 123,
|
||||
ipfs: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_meme_file_name() {
|
||||
assert!(meme_with_link("https://").file_name().is_err());
|
||||
assert!(meme_with_link("https://test").file_name().is_err());
|
||||
assert_eq!(
|
||||
meme_with_link("https://test/some_meme").file_name(),
|
||||
Ok("some_meme"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use crate::api::{Category, CatsResp, Meme, MemesResp, RandomResp, User, UsersResp};
|
||||
use crate::api::{Category, CatsResp, Meme, MemesResp, User, UsersResp};
|
||||
use log::info;
|
||||
use once_cell::sync::OnceCell;
|
||||
use reqwest::Url;
|
||||
|
@ -36,8 +36,7 @@ impl JMClient {
|
|||
JMClientBuilder::default()
|
||||
}
|
||||
|
||||
/// clears the cache. all requests will be made again after this has been
|
||||
/// called.
|
||||
/// clears the cache. all requests will be made again after this has been called.
|
||||
pub async fn clear_cache(&mut self) {
|
||||
self.cache.lock().await.clear();
|
||||
}
|
||||
|
@ -62,7 +61,6 @@ impl JMClient {
|
|||
}))
|
||||
}
|
||||
|
||||
/// Request the categories from the server. Result will be cached.
|
||||
pub async fn get_cats(&self) -> Result<Arc<Vec<Category>>, JMClientError> {
|
||||
self.get_api_json(
|
||||
&self.cache.lock().await.cats,
|
||||
|
@ -72,7 +70,6 @@ impl JMClient {
|
|||
.await
|
||||
}
|
||||
|
||||
/// Request the memes from the server. Result will be cached.
|
||||
pub async fn get_memes(&self) -> Result<Arc<Vec<Meme>>, JMClientError> {
|
||||
self.get_api_json(&self.cache.lock().await.memes, "memes", |r: MemesResp| {
|
||||
r.memes
|
||||
|
@ -80,22 +77,12 @@ impl JMClient {
|
|||
.await
|
||||
}
|
||||
|
||||
/// Request the users from the server. Result will be cached.
|
||||
pub async fn get_users(&self) -> Result<Arc<Vec<User>>, JMClientError> {
|
||||
self.get_api_json(&self.cache.lock().await.users, "users", |r: UsersResp| {
|
||||
r.users
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Requests a random meme from the server. Result is not cached!
|
||||
pub async fn get_random(&self) -> Result<Meme, JMClientError> {
|
||||
info!("Requesting random meme from server");
|
||||
|
||||
let res = self.http.get(self.endpoint.join("random")?).send().await?;
|
||||
|
||||
Ok(serde_json::from_slice::<RandomResp>(&res.bytes().await?)?.meme)
|
||||
}
|
||||
}
|
||||
impl Default for JMClient {
|
||||
fn default() -> Self {
|
||||
|
@ -137,7 +124,6 @@ pub struct JMClientBuilder {
|
|||
}
|
||||
|
||||
impl JMClientBuilder {
|
||||
#[must_use]
|
||||
pub fn build(self) -> JMClient {
|
||||
JMClient {
|
||||
http: self.client.unwrap_or_else(reqwest::Client::new),
|
||||
|
@ -149,13 +135,11 @@ impl JMClientBuilder {
|
|||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn client(mut self, client: reqwest::Client) -> Self {
|
||||
self.client = Some(client);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn endpoint(mut self, endpoint: impl Into<Url>) -> Self {
|
||||
self.endpoint = Some(endpoint.into());
|
||||
self
|
||||
|
|
13
src/util.rs
13
src/util.rs
|
@ -1,6 +1,5 @@
|
|||
use thiserror::Error;
|
||||
|
||||
use crate::api::Meme;
|
||||
use anyhow::bail;
|
||||
use std::str::FromStr;
|
||||
|
||||
pub mod consts {
|
||||
|
@ -23,7 +22,7 @@ impl MemeSorting {
|
|||
a.$field
|
||||
.to_ascii_lowercase()
|
||||
.cmp(&b.$field.to_ascii_lowercase())
|
||||
})
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -37,12 +36,8 @@ impl MemeSorting {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
#[error("Invalid Meme sorting! Options are id, link, category and user!")]
|
||||
pub struct InvalidMemeSortingError;
|
||||
|
||||
impl FromStr for MemeSorting {
|
||||
type Err = InvalidMemeSortingError;
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.to_lowercase().as_ref() {
|
||||
|
@ -51,7 +46,7 @@ impl FromStr for MemeSorting {
|
|||
"category" => Ok(Self::Category),
|
||||
"user" => Ok(Self::User),
|
||||
"timestamp" => Ok(Self::Timestamp),
|
||||
_ => Err(InvalidMemeSortingError),
|
||||
_ => bail!("Invalid Meme sorting! options are id, link, category and user!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue