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
305
306
307
308
309
310
311
312
313
314
315
316
use crate::Language;
#[cfg(feature = "chrono")]
use chrono::{serde::ts_seconds, DateTime, Utc};
use serde::Deserialize;
use serde_repr::Deserialize_repr;

/// Whether long-strip mode is default
#[derive(
	Debug, Deserialize_repr, Clone, Copy, PartialEq, PartialOrd, Eq, Ord,
)]
#[repr(u8)]
pub enum LongStrip {
	/// Not long-strip (boolean false)
	No = 0,
	/// Long strip (boolean true)
	Yes = 1,
}
impl From<bool> for LongStrip {
	fn from(b: bool) -> Self {
		if b { LongStrip::Yes } else { LongStrip::No }
	}
}
impl From<LongStrip> for bool {
	fn from(b: LongStrip) -> Self {
		match b {
			LongStrip::No => false,
			LongStrip::Yes => true,
		}
	}
}

/// Information on chapters that are currently available
#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct Data {
	/// Server on which it's hosted (/data/ => https://mangadex.org/data/)
	pub server: String,
	/// Hash of the data
	pub hash: String,
	/// Array of pages
	pub page_array: Vec<String>,
}

/// Information on a manga chapter
#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct ChapterBase {
	pub id: u32,
	#[cfg(feature = "chrono")]
	#[serde(with = "ts_seconds", default = "Utc::now")]
	pub timestamp: DateTime<Utc>,
	#[cfg(not(feature = "chrono"))]
	pub timestamp: u64,
	/// Parent manga (prefix: https://mangadex.org/api/manga)
	pub manga_id: u32,

	pub volume: String,
	pub chapter: String,
	pub title: String,

	#[serde(rename(deserialize = "lang_code"))]
	pub lang: Language,
	pub comments: Option<u32>,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct GroupIDs {
	pub group_id: u32,
	pub group_id_2: u32,
	pub group_id_3: u32,
}
impl From<GroupIDs> for [Option<std::num::NonZeroU32>; 3] {
	fn from(v: GroupIDs) -> Self {
		use std::num::NonZeroU32;
		let GroupIDs {
			group_id,
			group_id_2,
			group_id_3,
		} = v;
		[
			NonZeroU32::new(group_id),
			NonZeroU32::new(group_id_2),
			NonZeroU32::new(group_id_3),
		]
	}
}

/// Chapter API data when delayed
#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct Delayed {
	/// Group website, if available.
	#[serde(default)]
	pub group_website: String,
	/// Information
	#[serde(flatten)]
	pub info: ChapterBase,
	/// Groups contributing
	#[serde(flatten)]
	pub groups: GroupIDs,
}
/// Chapter API data when unavailable
/// Note that it does not include the group id.
#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct Unavailable(ChapterBase);

/// Chapter API data when external
/// Note that it includes more data than is represented here
#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct External {
	/// Information
	#[serde(flatten)]
	pub info: ChapterBase,
	/// Contributed external data
	#[serde(flatten)]
	pub groups: GroupIDs,
	/// External site link
	pub external: String,
}

/// Chapter API data when OK
#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct OK {
	/// Pages
	#[serde(flatten)]
	pub pages: Data,
	/// Information
	#[serde(flatten)]
	pub info: ChapterBase,
	/// Contributing groups
	#[serde(flatten)]
	pub groups: GroupIDs,
	pub long_strip: LongStrip,
}

/// Information from the mangadex chapter api (/api/chapter/2; .)
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(tag = "status")]
pub enum Chapter {
	/// When the chapter is deleted by the user or a moderator
	#[serde(rename(deserialize = "deleted"))]
	Deleted { id: u32 },
	/// When the chapter has a group delay
	#[serde(rename(deserialize = "delayed"))]
	Delayed(Box<Delayed>),
	/// When the chapter is unavailable
	#[serde(rename(deserialize = "unavailable"))]
	Unavailable(Box<Unavailable>),
	/// When the chapter is available
	#[serde(rename(deserialize = "OK"))]
	Ok(Box<OK>),
	/// When the chapter is an external chapter
	#[serde(rename(deserialize = "external"))]
	External(Box<External>),
	/// When some other error happens (eg not created yet)
	#[serde(rename(deserialize = "error"))]
	Error(Error),
}
impl Chapter {
	pub fn is_ok(&self) -> bool {
		match self {
			Chapter::Ok(_) => true,
			_ => false,
		}
	}
	pub fn is_deleted(&self) -> bool {
		match self {
			Chapter::Deleted { .. } => true,
			_ => false,
		}
	}
	pub fn is_delayed(&self) -> bool {
		match self {
			Chapter::Delayed(_) => true,
			_ => false,
		}
	}
	pub fn is_error(&self) -> bool {
		match self {
			Chapter::Error { .. } => true,
			_ => false,
		}
	}
	pub fn is_unavailable(&self) -> bool {
		match self {
			Chapter::Unavailable(_) => true,
			_ => false,
		}
	}
	pub fn is_external(&self) -> bool {
		match self {
			Chapter::External(_) => true,
			_ => false,
		}
	}
	/// Converts a mangadexchapterapi into an Option for information.
	pub fn ok(self) -> Option<OK> {
		match self {
			Chapter::Ok(ok) => Some(*ok),
			_ => None,
		}
	}
	pub fn delayed(self) -> Option<Delayed> {
		match self {
			Chapter::Delayed(delayed) => Some(*delayed),
			_ => None,
		}
	}
	pub fn err(self) -> Option<Error> {
		match self {
			Chapter::Error(err) => Some(err),
			_ => None,
		}
	}
	pub fn external(self) -> Option<External> {
		match self {
			Chapter::External(ext) => Some(*ext),
			_ => None,
		}
	}
}

/// Generic error type
#[derive(Deserialize, Clone, Debug, PartialEq)]
pub struct Error {
	pub id: u32,
	pub message: String,
}
use std::fmt;
impl fmt::Display for Error {
	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		write!(fmt, "{} on id {}", self.message, self.id)
	}
}
impl std::error::Error for Error {}

#[cfg(test)]
pub mod tests {
	use super::Chapter as API;
	use crate::test_data::*;
	use serde_json::from_str;

	/// Decoding of a deleted chapter
	#[test]
	fn it_decodes_a_deleted_chapter() -> R {
		let test_deleted: API = from_str(TEST_CHAPTER_DELETED)?;
		assert!(test_deleted.is_deleted());
		eprintln!("{:?}", test_deleted);
		Ok(())
	}
	/// Decoding of an available chapter
	#[test]
	fn it_decodes_an_available_chapter() -> R {
		let test_avilable: API = from_str(TEST_CHAPTER_OK)?;
		assert!(test_avilable.is_ok());
		eprintln!("{:?}", test_avilable);
		let _ = test_avilable.ok().unwrap();
		Ok(())
	}
	/// Decoding of another available chapter
	#[test]
	fn it_decodes_another_available_chapter() -> R {
		let test_avilable: API = from_str(TEST_CHAPTER_OK_2)?;
		assert!(test_avilable.is_ok());
		eprintln!("{:?}", test_avilable);
		let _ = test_avilable.ok().unwrap();
		Ok(())
	}
	/// Decoding of an unavailable chapter
	#[test]
	fn it_decodes_an_unavailable_chapter() -> R {
		let test_unavilable: API = from_str(TEST_CHAPTER_UNAVAILABLE)?;
		assert!(test_unavilable.is_unavailable());
		eprintln!("{:?}", test_unavilable);
		Ok(())
	}
	/// Decoding of a delayed chapter
	#[test]
	fn it_decodes_a_delayed_chapter() -> R {
		let test_delayed: API = from_str(TEST_CHAPTER_DELAYED)?;
		assert!(test_delayed.is_delayed());
		eprintln!("{:?}", test_delayed);
		let _ = test_delayed.delayed().unwrap();
		Ok(())
	}
	/// Decoding of an external chapter
	#[test]
	fn it_decodes_an_external_chapter() -> R {
		let test_extern: API = from_str(TEST_CHAPTER_EXTERNAL)?;
		assert!(test_extern.is_external());
		eprintln!("{:?}", test_extern);
		let _ = test_extern.external().unwrap();
		Ok(())
	}
	/// Decoding of a chapter that does not yet exist
	#[test]
	fn it_decodes_a_non_existing_chapter() -> R {
		let test_non_existing: API = from_str(TEST_CHAPTER_ERROR)?;
		assert!(test_non_existing.is_error());
		eprintln!("{:?}", test_non_existing);
		let _ = test_non_existing.err().unwrap();
		Ok(())
	}
	/// Decoding of a non-chapter is an error
	#[test]
	fn it_does_not_decode_a_non_chapter() -> Result<(), API> {
		let test_non_chapter: Result<API, serde_json::Error> =
			from_str("{\"status\":\"None\"}");
		if test_non_chapter.is_err() {
			let err = test_non_chapter.expect_err("Error not found");
			assert!(err.is_data());
			eprintln!("{:?}", err);
			eprintln!("{}", err);
			Ok(())
		} else {
			Err(test_non_chapter.unwrap())
		}
	}
}