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
mod error;
pub mod models;
#[cfg(test)]
mod tests;

pub use crate::error::{ApiError, ApiErrorKind};
use crate::models::{FeverError, Groups, Feeds, FavIcons, Items, Links, UnreadItems, SavedItems, ItemStatus
};

use failure::ResultExt;
use log::error;
use reqwest::{Client, StatusCode, multipart::Form};
use url::Url;

type FeedID = u64;
type GroupID = u64;
type FeedGroupID = u64;
type ItemID = u64;
type IconID = u64;
type LinkID = u64;

pub struct FeverApi {
	base_uri: Url,
	api_key: String,
}

impl FeverApi {
	/// Create a new instance of the TTrssApi
	pub fn new(url: &Url, username: String, password: String) -> Self {
		let base_uri = url.clone();


		let auth = format!("{}:{}", username, password);
		let api_key = md5::compute(auth);

		FeverApi {
			base_uri: base_uri,
			api_key: format!("{:?}", api_key),
		}
	}

	async fn post_request(
		&self,
		client: &Client,
		query: String,
	) -> Result<String, ApiError> {
		let full_query = format!("{}{}", "?api&", query);
		let api_url: Url = self.base_uri.join(&full_query).context(ApiErrorKind::Url)?;

		let form = Form::new().text("api_key", self.api_key.clone());

		let response = client
			.post(api_url.clone())
			.multipart(form)
			.header("api_key", self.api_key.clone())
			.send()
			.await
			.context(ApiErrorKind::Http)?;

		let status = response.status();
		let response = response.text().await.context(ApiErrorKind::Http)?;
		if status != StatusCode::OK {
			let error: FeverError = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
			error!("Fever API: {}", error.error_message);
			return Err(ApiErrorKind::Fever(error))?;
		}
		Ok(response)
	}

	async fn check_auth(response: &String) -> Result<(),ApiError>  {
		let tmp: serde_json::Value = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		if tmp["auth"].as_i64().unwrap() == 0 {
			return Err(ApiErrorKind::AccessDenied)?;
		}
		Ok(())
	}

	pub async fn valid_credentials(&self,
		client: &Client,
	) -> Result<bool, ApiError>  {
		let response = self.post_request(&client, "".to_string()).await?;
		let tmp: serde_json::Value = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		if tmp["auth"].as_i64().unwrap() == 0 {
			return Ok(false);
		}
		Ok(true)
	}
	pub async fn get_api_version(&self,
		client: &Client,
	) -> Result<i64, ApiError>  {
		let response = self.post_request(&client, "".to_string()).await?;
		let result: serde_json::Value = serde_json::from_str(&response).context(ApiErrorKind::Json)?;

		Ok(result["api_version"].as_i64().unwrap())
	}


	pub async fn get_groups(&self,
		client: &Client,
	) -> Result<Groups, ApiError>  {
		let response = self.post_request(&client, "groups".to_string()).await?;
		Self::check_auth(&response).await?;

		let groups: Groups = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(groups)
	}

	pub async fn get_feeds(&self,
		client: &Client,
	) -> Result<Feeds, ApiError>  {
		let response = self.post_request(&client, "feeds".to_string()).await?;
		Self::check_auth(&response).await?;

		let feeds: Feeds = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(feeds)
	}

	pub async fn get_favicons(&self,
		client: &Client,
	) -> Result<FavIcons, ApiError>  {
		let response = self.post_request(&client, "favicons".to_string()).await?;
		Self::check_auth(&response).await?;

		let favicons: FavIcons = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(favicons)
	}

	pub async fn get_items(&self,
		client: &Client,
	) -> Result<Items, ApiError>  {
		let response = self.post_request(&client, "items".to_string()).await?;
		Self::check_auth(&response).await?;

		let items: Items = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(items)
	}
	pub async fn get_items_since(&self,
		id: ItemID,
		client: &Client,
	) -> Result<Items, ApiError>  {
		let query = format!("items&since_id={}", id);
		let response = self.post_request(&client, query).await?;
		Self::check_auth(&response).await?;

		let items: Items = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(items)
	}
	pub async fn get_items_max(&self,
		id: ItemID,
		client: &Client,
	) -> Result<Items, ApiError>  {
		let query = format!("items&max_id={}", id);
		let response = self.post_request(&client, query).await?;
		Self::check_auth(&response).await?;

		let items: Items = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(items)
	}
	pub async fn get_items_with(&self,
		ids: Vec<ItemID>,
		client: &Client,
	) -> Result<Items, ApiError>  {
		let list = ids.iter().map(ToString::to_string).collect::<Vec<String>>().join(",");
		let query = format!("items&with_ids={}", list);
		let response = self.post_request(&client, query).await?;
		Self::check_auth(&response).await?;

		let items: Items = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(items)
	}

	pub async fn get_links(&self,
		client: &Client,
	) -> Result<Links, ApiError>  {
		let response = self.post_request(&client, "links".to_string()).await?;
		Self::check_auth(&response).await?;

		let links: Links = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(links)
	}

	pub async fn get_links_with(&self,
		offset: usize,
		days: usize,
		page: usize,
		client: &Client,
	) -> Result<Links, ApiError>  {
		let query = format!("links&offset={}&range={}&page={}", offset, days, page);
		let response = self.post_request(&client, query).await?;
		Self::check_auth(&response).await?;

		let links: Links = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		Ok(links)
	}

	pub async fn get_unread_items(&self,
		client: &Client,
	) -> Result<UnreadItems, ApiError>  {
		let response = self.post_request(&client, "unread_item_ids".to_string()).await?;
		Self::check_auth(&response).await?;

		let json: serde_json::Value = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		let list : Vec<ItemID>;
		let tmp = json["unread_item_ids"].as_str().unwrap();
		if tmp != "" {
			list = tmp.split(",").map(|x| x.parse::<ItemID>().unwrap()).collect::<Vec<ItemID>>();
		} else {
			list = Vec::new();
		}
		let refresh = json["last_refreshed_on_time"].as_str().unwrap();

		let items: UnreadItems = UnreadItems{ last_refreshed_on_time: refresh.to_string(), unread_item_ids: list };
		Ok(items)
	}

	pub async fn get_saved_items(&self,
		client: &Client,
	) -> Result<SavedItems, ApiError>  {
		let response = self.post_request(&client, "saved_item_ids".to_string()).await?;
		Self::check_auth(&response).await?;

		let json: serde_json::Value = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
		let list : Vec<ItemID>;
		let tmp = json["saved_item_ids"].as_str().unwrap();
		if tmp != "" {
			list = tmp.split(",").map(|x| x.parse::<ItemID>().unwrap()).collect::<Vec<ItemID>>();
		} else {
			list = Vec::new();
		}
		let refresh = json["last_refreshed_on_time"].as_str().unwrap();

		let items: SavedItems = SavedItems{ last_refreshed_on_time: refresh.to_string(), saved_item_ids: list };
		Ok(items)
	}

	pub async fn mark_item(&self,
		status: ItemStatus,
		id: ItemID,
		client: &Client,
	) -> Result<(), ApiError>  {
		let state: &str = status.into();
		let query = format!("&mark=item&as={}&id={}", state, id);
		let response = self.post_request(&client, query).await?;
		Self::check_auth(&response).await?;

		Ok(())
	}

	async fn mark_feed_or_group(&self,
		target: String,
		status: ItemStatus,
		id: isize,
		before: String,
		client: &Client,
	) -> Result<(), ApiError>  {
		let state: &str = status.into();
		let query = format!("&mark={}&as={}&id={}&before_{}", target, state, id, before);
		let response = self.post_request(&client, query).await?;
		Self::check_auth(&response).await?;

		Ok(())
	}

	pub async fn mark_group(&self,
		status: ItemStatus,
		id: isize,
		before: String,
		client: &Client,
	) -> Result<(), ApiError>  {
		self.mark_feed_or_group("group".to_string(), status, id, before, client).await
	}

	pub async fn mark_feed(&self,
		status: ItemStatus,
		id: isize,
		before: String,
		client: &Client,
	) -> Result<(), ApiError>  {
		self.mark_feed_or_group("feed".to_string(), status, id, before, client).await
	}
}