feat: rework as library

This commit is contained in:
Ladislav Hano 2024-10-02 21:33:05 +02:00
parent a313367d54
commit 4d45ac8ee5
6 changed files with 68 additions and 44 deletions

35
tenor_v2rs/Cargo.lock generated
View file

@ -26,12 +26,6 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "anyhow"
version = "1.0.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1"
[[package]] [[package]]
name = "atomic-waker" name = "atomic-waker"
version = "1.1.2" version = "1.1.2"
@ -117,12 +111,6 @@ version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "dotenv"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
[[package]] [[package]]
name = "encoding_rs" name = "encoding_rs"
version = "0.8.33" version = "0.8.33"
@ -920,12 +908,31 @@ dependencies = [
name = "tenor_v2rs" name = "tenor_v2rs"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow",
"dotenv",
"form_urlencoded", "form_urlencoded",
"json", "json",
"regex", "regex",
"reqwest", "reqwest",
"thiserror",
]
[[package]]
name = "thiserror"
version = "1.0.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3"
dependencies = [
"proc-macro2",
"quote",
"syn",
] ]
[[package]] [[package]]

View file

@ -6,12 +6,11 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
anyhow = "1.0.71"
dotenv = "0.15.0"
regex = "1.9.0" regex = "1.9.0"
json = "0.12.4" json = "0.12.4"
reqwest = "0.12.7" reqwest = "0.12.7"
form_urlencoded = "1.2.1" form_urlencoded = "1.2.1"
thiserror = "1.0.64"
[features] [features]
DEBUG = [] DEBUG = []

View file

@ -1,14 +1,3 @@
pub fn add(left: u64, right: u64) -> u64 { pub mod tenor;
left + right pub mod tenor_builder;
} pub mod tenor_types;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}

View file

@ -1,15 +1,18 @@
use crate::tenor_types::TenorError;
use super::tenor_types::MediaFilter; use super::tenor_types::MediaFilter;
use json::JsonValue; use json::JsonValue;
pub fn get_gif_url(filter: MediaFilter, tenor_response: JsonValue) -> anyhow::Result<Vec<String>> { pub fn get_gif_url(filter: MediaFilter, tenor_response: JsonValue) -> Result<Vec<String>, TenorError> {
use anyhow::Context;
let mut urls: Vec<String> = Vec::new(); let mut urls: Vec<String> = Vec::new();
let results = tenor_response["results"].members(); let results = tenor_response["results"].members();
for result in results { for result in results {
let url = result["media_formats"][filter.to_string()]["url"].as_str().context("Value not found in Json")?; let url = match result["media_formats"][filter.to_string()]["url"].as_str() {
Some(v) => v,
None => return Err(TenorError::Error("Value no found".into()))
};
urls.push(url.to_string()); urls.push(url.to_string());
} }

View file

@ -2,11 +2,9 @@ use json::JsonValue;
use std::collections::HashSet; use std::collections::HashSet;
use anyhow::Error; use crate::tenor_types::TenorError;
use crate::util::security::dotenv_var; use crate::tenor_types::{ContentFilter, ArRange, MediaFilter};
use super::tenor_types::{ContentFilter, ArRange, MediaFilter};
pub struct Tenor { pub struct Tenor {
/// Specify the country of origin for the request. To do so, provide its two-letter ISO 3166-1 country code. /// Specify the country of origin for the request. To do so, provide its two-letter ISO 3166-1 country code.
@ -34,7 +32,9 @@ pub struct Tenor {
limit: Option<u8>, limit: Option<u8>,
/// Retrieve results that start at the position /// Retrieve results that start at the position
/// Use a non-zero, non-empty value from next, returned by the API response, to get the next set of results /// Use a non-zero, non-empty value from next, returned by the API response, to get the next set of results
pos: Option<String> pos: Option<String>,
/// Tenor api key to be used in queries
key: Option<String>
} }
impl Tenor { impl Tenor {
@ -47,7 +47,8 @@ impl Tenor {
ar_range: None, ar_range: None,
random: None, random: None,
limit: None, limit: None,
pos: None pos: None,
key: None
} }
} }
@ -115,13 +116,19 @@ impl Tenor {
self self
} }
pub async fn search(self, query: &str) -> Result<JsonValue, Error> { pub fn key(mut self, key: String) -> Self {
use anyhow::Context; self.key = Some(key);
self
}
pub async fn search(self, query: &str) -> Result<JsonValue, TenorError> {
let q: String = form_urlencoded::byte_serialize(query.as_bytes()).collect(); let q: String = form_urlencoded::byte_serialize(query.as_bytes()).collect();
let base_url = "https://tenor.googleapis.com/v2/search?"; let base_url = "https://tenor.googleapis.com/v2/search?";
let api_key = dotenv_var("TENORV2").context("TENORV2 key not found in the .env")?; let api_key = match self.key {
Some(key) => key,
None => return Err(TenorError::KeyError("API key undefined".into()))
};
let mut request = format!("{base_url}q={q}&key={api_key}"); let mut request = format!("{base_url}q={q}&key={api_key}");
@ -162,7 +169,10 @@ impl Tenor {
request.push_str(&format!("&limit={}", self.limit.unwrap())); request.push_str(&format!("&limit={}", self.limit.unwrap()));
} }
let response = reqwest::get(request).await?.text().await?; let response = reqwest::get(request)
.await?
.text()
.await?;
let response_json = json::parse(&response)?; let response_json = json::parse(&response)?;

View file

@ -1,6 +1,7 @@
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
use std::fmt; use std::fmt;
use thiserror::Error;
#[derive(Debug)] #[derive(Debug)]
pub enum ContentFilter { pub enum ContentFilter {
@ -61,3 +62,18 @@ impl fmt::Display for ArRange {
write!(f, "{:?}", self) write!(f, "{:?}", self)
} }
} }
#[derive(Debug, Error)]
pub enum TenorError {
#[error("Request error")]
RequestError(#[from] reqwest::Error),
#[error("API key error: {0}")]
KeyError(String),
#[error("JSON error")]
JSONError(#[from] json::Error),
#[error("Error: {0}")]
Error(String)
}