1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
//! Dynasty reader JSON API wrapper.
#![warn(missing_docs)]
pub mod chapter;
pub mod directory;
pub mod latest;
pub mod tag;
mod traits;
mod utils;
#[cfg(test)]
mod tests;
use std::sync::Arc;
use anyhow::{Context, Result};
use latest::LatestListing;
use reqwest::{IntoUrl, Method, Request, Url};
use serde::de::DeserializeOwned;
use chapter::Chapter;
use directory::DirectoryListing;
use tag::{Tag, TagKind, TagListing};
pub use traits::{
into_dynasty_chapter_path::IntoDynastyChapterPath, into_dynasty_tag_path::IntoDynastyTagPath,
};
static USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
/// Dynasty reader's JSON API client.
#[derive(Clone, Debug)]
pub struct DynastyApi {
ptr: Arc<DynastyApiRef>,
}
#[derive(Debug)]
struct DynastyApiRef {
base: Url,
client: reqwest::Client,
}
impl Default for DynastyApi {
fn default() -> Self {
DynastyApi::with_base("https://dynasty-scans.com/")
}
}
impl DynastyApi {
/// Creates a [`DynastyApi`] client.
///
/// [`DynastyApi`] is wrapped inside an [`Arc`] internally, so you don't need to wrap it inside an [`Arc`] to reuse it.
///
/// See [`with_base`] if you want to create a [`DynastyApi`] client with a custom `base`.
///
/// [`with_base`]: #method.with_base
///
/// # Examples
///
/// ```
/// # use dynasty_api::DynastyApi;
/// #
/// let dynasty = DynastyApi::new();
/// #
/// ```
pub fn new() -> DynastyApi {
Default::default()
}
/// Creates a [`DynastyApi`] client with a custom `base` url.
///
/// `base` is assumed to be compatible with <https://dynasty-scans.com> `/` route.
///
/// # Examples
///
/// Create a client with custom `base` url.
///
/// ```
/// # use dynasty_api::DynastyApi;
/// #
/// let dynasty = DynastyApi::with_base("https://dynasty-proxy.netlify.app/");
/// #
/// ```
///
/// # Panics
///
/// Panics if it fails to parse the `base` url as [`Url`].
///
/// ```should_panic
/// # use dynasty_api::DynastyApi;
/// #
/// let _ = DynastyApi::with_base("invalid-url");
/// #
/// ```
///
/// Or if you supplied a `base` url that cannot be used as base.
///
/// ```should_panic
/// # use dynasty_api::DynastyApi;
/// #
/// let _ = DynastyApi::with_base("data:text/plain,Stuff");
/// #
/// ```
pub fn with_base<U: IntoUrl>(url: U) -> DynastyApi {
let base: Url = url.into_url().expect("you supplied an invalid base url!");
if base.cannot_be_a_base() {
panic!("can't use the url you supplied as base!")
}
let client = reqwest::ClientBuilder::new()
.user_agent(USER_AGENT)
.build()
.unwrap();
DynastyApi {
ptr: Arc::new(DynastyApiRef { base, client }),
}
}
/// List Dynasty reader's [`LatestListing`] <https://dynasty-scans.com/chapters/added>.
///
/// sample: [latest::sample]
pub async fn latest_chapters(&self, page: u16) -> Result<LatestListing> {
let url = self.join_api_url("chapters")?;
let request = self.ptr.client.get(url).query(&[("page", page)]).build()?;
self.send_request(request).await
}
/// List Dynasty reader's [`DirectoryListing`] with pagination.
///
/// sample: [directory::sample]
///
/// # Examples
///
/// List [anthologies](https://dynasty-scans.com/anthologies) at page 1.
///
/// ```
/// # use anyhow::Ok;
/// # use dynasty_api::{DynastyApi, tag::TagKind};
/// #
/// # tokio_test::block_on(async {
/// # let dynasty = DynastyApi::new();
/// #
/// let kind = TagKind::Anthology;
/// let anthology_1 = dynasty.list_directory(kind, 1).await?;
/// #
/// # Ok(())
/// # });
/// #
/// ```
///
/// You can use `total_pages` and `current_page` from [`DirectoryListing`] as limit and pointer respectively, you can use [`DirectoryListing::next_page`] method to get the next page easily.
///
/// ```
/// # use anyhow::Ok;
/// # use dynasty_api::{DynastyApi, tag::TagKind};
/// #
/// # tokio_test::block_on(async {
/// # let dynasty = DynastyApi::new();
/// #
/// let kind = TagKind::Series;
/// let series_1 = dynasty.list_directory(kind, 1).await?;
/// let next = series_1.next_page();
/// assert_eq!(next, Some(2));
/// #
/// # Ok(())
/// # });
/// #
/// ```
///
/// Keep in mind that if you exceed the _limit_ you won't get any error or whatsoever, but you will instead get an empty `tags`.
///
/// ```
/// # use anyhow::Ok;
/// # use dynasty_api::{DynastyApi, tag::TagKind};
/// #
/// # tokio_test::block_on(async {
/// # let dynasty = DynastyApi::new();
/// #
/// let kind = TagKind::Scanlator;
/// let scanlator_65535 = dynasty.list_directory(kind, 65535).await?;
/// assert!(scanlator_65535.tags.is_empty());
/// #
/// # Ok(())
/// # });
/// #
/// ```
pub async fn list_directory(&self, kind: TagKind, page: u16) -> Result<DirectoryListing> {
let raw = {
let url = self.join_api_url(kind.path())?;
let request = self.ptr.client.get(url).query(&[("page", page)]).build()?;
self.send_request(request).await?
};
Ok(DirectoryListing::from_raw(raw, kind))
}
/// List Dynasty reader's [`TagListing`].
///
/// sample: [tag::sample]
///
/// If you use [`&str`](str), it **must** follow one of the formats below:
///
/// - `{kind}/{permalink}` where `kind` **must** be parse-able into [`TagKind`] while `permalink` can be _anything_.
/// - `{permalink}` it'll be as if you wrote `tags/{permalink}`.
///
/// # Examples
///
/// ```
/// # use anyhow::Result;
/// # use dynasty_api::{DynastyApi, tag::TagKind};
/// #
/// # tokio_test::block_on(async {
/// # let dynasty = DynastyApi::new();
/// #
/// // valid
/// assert!(dynasty.list_tag("authors/manio").await.is_ok());
/// // also valid
/// assert!(dynasty.list_tag("tags/bread").await.is_ok());
/// // same as above
/// assert!(dynasty.list_tag("bread").await.is_ok());
///
/// // you could also use the `title`
/// assert!(dynasty.list_tag("404: Men Not Found").await.is_ok());
/// // above will be parsed as "tags/404_men_not_found"
/// #
/// # })
/// #
/// ```
pub async fn list_tag<P: IntoDynastyTagPath>(&self, s: P) -> Result<TagListing> {
let path = s.dynasty_path()?;
let url = self.join_api_url(&path)?;
let request = Request::new(Method::GET, url);
self.send_request(request).await
}
/// Get a Dynasty reader's [`Chapter`].
///
/// sample: [chapter::sample]
///
/// If you use [`&str`](str), it **must** follow one of the formats below:
///
/// - `chapters/{permalink}` where permalink can be _anything_.
/// - `{permalink}` it'll be as if you wrote `chapters/{permalink}`.
///
/// # Examples
///
/// ```
/// # use anyhow::Result;
/// # use dynasty_api::{DynastyApi, tag::TagKind};
/// #
/// # tokio_test::block_on(async {
/// # let dynasty = DynastyApi::new();
/// #
/// // valid
/// assert!(dynasty.chapter("chapters/kichiku_yousei").await.is_ok());
/// // same as above
/// assert!(dynasty.chapter("kichiku_yousei").await.is_ok());
///
/// // you could also use the `title`
/// assert!(dynasty.chapter("Adachi and Shimamura (Moke ver.) ch27.1").await.is_ok());
/// // above will be parsed as "chapters/adachi_and_shimamura_moke_ver_ch27_1"
///
/// // `long_title` also works
/// assert!(dynasty.chapter("Adachi and Shimamura (Moke ver.) ch27.1: Leaving Azure").await.is_ok());
/// #
/// # })
/// #
/// ```
pub async fn chapter<P: IntoDynastyChapterPath>(&self, s: P) -> Result<Chapter> {
let path = s.dynasty_path()?;
let url = self.join_api_url(&path)?;
let request = Request::new(Method::GET, url);
self.send_request(request).await
}
/// Get the `base` url used to create this `DynastyApi`.
pub fn base_url(&self) -> &Url {
&self.ptr.base
}
async fn send_request<T: DeserializeOwned>(&self, request: Request) -> Result<T> {
let url = request.url().to_string();
let response = self
.ptr
.client
.execute(request)
.await
.with_context(|| format!("failed to send request to {}", url))?
.error_for_status()?
.json()
.await
.with_context(|| format!("failed to parse {} response as {}", url, stringify!(T)));
response
}
fn join_api_url(&self, s: &str) -> Result<Url> {
Ok(self.ptr.base.join(&format!("{}.json", s))?)
}
}