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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
mod error;
pub mod models;
#[cfg(test)]
mod tests;

pub use crate::error::{ApiError, ApiErrorKind};
use crate::models::{
    cache::Cache,
    cache::CacheRequestResponse,
    cache::CacheResult,
    entry::Entry,
    entry::UpdateEntryStarredInput,
    entry::UpdateEntryUnreadInput,
    icon::Icon,
    subscription::Subscription,
    subscription::SubscriptionMode,
    subscription::UpdateSubscriptionInput,
    subscription::{CreateSubscriptionInput, CreateSubscriptionResult},
    tagging::CreateTaggingInput,
    tagging::DeleteTagInput,
    tagging::RenameTagInput,
    tagging::Tagging,
};
use chrono::{DateTime, Utc};
use failure::ResultExt;
use reqwest::header::{CONTENT_TYPE, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED};
use reqwest::{Client, Method, RequestBuilder, Response, StatusCode};
use url::Url;

pub type FeedID = u64;
pub type EntryID = u64;
pub type SubscriptionID = u64;
pub type TaggingID = u64;

pub struct FeedbinApi {
    base_url: Url,
    username: String,
    password: String,
}

impl FeedbinApi {
    pub fn new<S: Into<String>>(base_url: Url, username: S, password: S) -> Self {
        FeedbinApi {
            base_url: base_url,
            username: username.into(),
            password: password.into(),
        }
    }

    pub fn with_base_url(&self, base_url: Url) -> Self {
        FeedbinApi {
            base_url: base_url,
            username: self.username.clone(),
            password: self.password.clone(),
        }
    }

    pub fn with_password<S: Into<String>>(&self, password: S) -> Self {
        FeedbinApi {
            base_url: self.base_url.clone(),
            username: self.username.clone(),
            password: password.into(),
        }
    }

    fn build_url(&self, path: &str) -> Url {
        self.base_url.clone().join(path).unwrap() // We control all path inputs so failure is impossible
    }

    async fn request<F: FnOnce(RequestBuilder) -> RequestBuilder>(
        &self,
        client: &Client,
        method: Method,
        path: &str,
        f: F,
    ) -> Result<Response, ApiError> {
        let url = self.build_url(path);
        let request = client
            .request(method, url)
            .basic_auth(&self.username, Some(&self.password));

        let request = f(request);
        let response = request.send().await.context(ApiErrorKind::Network)?;
        match response.status().as_u16() {
            401 => Err(ApiError::from(ApiErrorKind::InvalidLogin)),
            403 => Err(ApiError::from(ApiErrorKind::AccessDenied)),
            200 | 201 | 204 | 302 | 404 => Ok(response),
            _ => Err(ApiError::from(ApiErrorKind::ServerIsBroken)),
        }
    }

    async fn get(
        &self,
        client: &Client,
        path: &str,
        cache: Option<Cache>,
    ) -> Result<CacheRequestResponse<Response>, ApiError> {
        // HEAD request to check for NOT MODIFIED
        if let Some(cache) = cache {
            let response = client
                .request(Method::GET, self.build_url(path))
                .basic_auth(&self.username, Some(&self.password))
                .header(IF_MODIFIED_SINCE, cache.last_modified)
                .header(IF_NONE_MATCH, cache.etag)
                .send()
                .await
                .context(ApiErrorKind::Network)?;

            if response.status() == StatusCode::NOT_MODIFIED {
                return Ok(CacheRequestResponse::NotModified);
            }
        }

        let response = self.request(client, Method::GET, path, |req| req).await?;

        // extract http cache (etag, last_modified)
        if let Some(etag) = response.headers().get(ETAG) {
            if let Some(last_modified) = response.headers().get(LAST_MODIFIED) {
                if let Ok(etag) = etag.to_str() {
                    if let Ok(last_modified) = last_modified.to_str() {
                        let cache = Cache {
                            etag: etag.into(),
                            last_modified: last_modified.into(),
                        };
                        return Ok(CacheRequestResponse::Modified(CacheResult {
                            value: response,
                            cache: Some(cache),
                        }));
                    }
                }
            }
        }

        Ok(CacheRequestResponse::Modified(CacheResult {
            value: response,
            cache: None,
        }))
    }

    async fn delete_with_body<F: FnOnce(RequestBuilder) -> RequestBuilder>(
        &self,
        client: &Client,
        path: &str,
        f: F,
    ) -> Result<Response, ApiError> {
        self.request(client, Method::DELETE, path, f).await
    }

    async fn delete(&self, client: &Client, path: &str) -> Result<Response, ApiError> {
        self.request(client, Method::DELETE, path, |req| req).await
    }

    async fn post<F: FnOnce(RequestBuilder) -> RequestBuilder>(
        &self,
        client: &Client,
        path: &str,
        f: F,
    ) -> Result<Response, ApiError> {
        self.request(client, Method::POST, path, f).await
    }

    pub async fn is_authenticated(&self, client: &Client) -> Result<bool, ApiError> {
        match self.get(client, "/v2/authentication.json", None).await {
            Err(err) => match err.kind() {
                ApiErrorKind::InvalidLogin => Ok(false),
                _ => Err(err),
            },
            Ok(CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _,
            })) => match response.status().as_u16() {
                200 => Ok(true),
                _ => Err(ApiErrorKind::ServerIsBroken)?,
            },
            Ok(CacheRequestResponse::NotModified) => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    pub async fn is_reachable(&self, client: &Client) -> Result<bool, ApiError> {
        match self.is_authenticated(client).await {
            Ok(_) => Ok(true),
            Err(err) => match err.kind() {
                ApiErrorKind::ServerIsBroken => Ok(true),
                ApiErrorKind::Network => Ok(false),
                _ => Err(err),
            },
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/entries.md#entries
    pub async fn get_entries(
        &self,
        client: &Client,
        page: Option<u32>,
        since: Option<DateTime<Utc>>,
        ids: Option<&[EntryID]>,
        starred: Option<bool>,
        enclosure: Option<bool>,
    ) -> Result<Vec<Entry>, ApiError> {
        let mut api_endpoint = String::from("/v2/entries.json");
        if page.is_some()
            || since.is_some()
            || ids.is_some()
            || starred.is_some()
            || enclosure.is_some()
        {
            api_endpoint.push_str("?");
        }
        if let Some(page) = page {
            api_endpoint.push_str(&format!("page={}", page));
        }
        if let Some(since) = since {
            if page.is_some() {
                api_endpoint.push_str("&");
            }
            api_endpoint.push_str(&format!(
                "since={}",
                since.format("%Y-%m-%dT%H:%M:%S%.f").to_string()
            ));
        }
        if let Some(ids) = ids {
            if page.is_some() || since.is_some() {
                api_endpoint.push_str("&");
            }
            let id_strings = ids.iter().map(|id| id.to_string()).collect::<Vec<String>>();
            api_endpoint.push_str(&format!("ids={}", id_strings.join(",")));
        }
        if let Some(starred) = starred {
            if page.is_some() || since.is_some() || ids.is_some() {
                api_endpoint.push_str("&");
            }
            api_endpoint.push_str(&format!("starred={}", starred));
        }
        if let Some(enclosure) = enclosure {
            if page.is_some() || since.is_some() || ids.is_some() || starred.is_some() {
                api_endpoint.push_str("&");
            }
            api_endpoint.push_str(&format!("include_enclosure={}", enclosure));
        }

        match self.get(client, &api_endpoint, None).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _cache,
            }) => response
                .json()
                .await
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/entries.md#get-v2feeds203entriesjson
    pub async fn get_entries_for_feed(
        &self,
        client: &Client,
        feed_id: FeedID,
        cache: Option<Cache>,
    ) -> Result<CacheRequestResponse<Vec<Entry>>, ApiError> {
        let path = format!("/v2/feeds/{}/entries.json", feed_id);
        match self.get(client, &path, cache).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache,
            }) => response
                .json()
                .await
                .map(|res| {
                    CacheRequestResponse::Modified(CacheResult {
                        value: res,
                        cache: cache,
                    })
                })
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Ok(CacheRequestResponse::NotModified),
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/unread-entries.md#unread-entries
    pub async fn get_unread_entry_ids(&self, client: &Client) -> Result<Vec<EntryID>, ApiError> {
        match self.get(client, "/v2/unread_entries.json", None).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _cache,
            }) => response
                .json()
                .await
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/unread-entries.md#create-unread-entries-mark-as-unread
    pub async fn set_entries_unread(
        &self,
        client: &Client,
        entry_ids: &[EntryID],
    ) -> Result<(), ApiError> {
        if entry_ids.len() > 1000 {
            return Err(ApiErrorKind::InputSize.into());
        }
        let input = UpdateEntryUnreadInput {
            unread_entries: entry_ids.into(),
        };
        self.post(client, "/v2/unread_entries.json", |r| r.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/unread-entries.md#delete-unread-entries-mark-as-read
    pub async fn set_entries_read(
        &self,
        client: &Client,
        entry_ids: &[EntryID],
    ) -> Result<(), ApiError> {
        if entry_ids.len() > 1000 {
            return Err(ApiErrorKind::InputSize.into());
        }
        let input = UpdateEntryUnreadInput {
            unread_entries: entry_ids.into(),
        };
        self.delete_with_body(client, "/v2/unread_entries.json", |r| r.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/starred-entries.md#get-starred-entries
    pub async fn get_starred_entry_ids(&self, client: &Client) -> Result<Vec<EntryID>, ApiError> {
        match self.get(client, "/v2/starred_entries.json", None).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _cache,
            }) => response
                .json()
                .await
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/starred-entries.md#create-starred-entries
    pub async fn set_entries_starred(
        &self,
        client: &Client,
        entry_ids: &[EntryID],
    ) -> Result<(), ApiError> {
        if entry_ids.len() > 1000 {
            return Err(ApiErrorKind::InputSize.into());
        }
        let input = UpdateEntryStarredInput {
            starred_entries: entry_ids.into(),
        };
        self.post(client, "/v2/starred_entries.json", |r| r.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/starred-entries.md#delete-starred-entries-unstar
    pub async fn set_entries_unstarred(
        &self,
        client: &Client,
        entry_ids: &[EntryID],
    ) -> Result<(), ApiError> {
        if entry_ids.len() > 1000 {
            return Err(ApiErrorKind::InputSize.into());
        }
        let input = UpdateEntryStarredInput {
            starred_entries: entry_ids.into(),
        };
        self.delete_with_body(client, "/v2/starred_entries.json", |r| r.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/entries.md#get-v2entries3648json
    pub async fn get_entry(&self, client: &Client, entry_id: EntryID) -> Result<Entry, ApiError> {
        let path = format!("/v2/entries/{}.json", entry_id);
        match self.get(client, &path, None).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _cache,
            }) => response
                .json()
                .await
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/subscriptions.md#get-subscriptions
    pub async fn get_subscriptions(
        &self,
        client: &Client,
        since: Option<DateTime<Utc>>,
        mode: Option<SubscriptionMode>,
        cache: Option<Cache>,
    ) -> Result<CacheRequestResponse<Vec<Subscription>>, ApiError> {
        let mut api_endpoint = String::from("/v2/subscriptions.json");
        if since.is_some() || mode.is_some() {
            api_endpoint.push_str("?");
        }
        if let Some(since) = since {
            api_endpoint.push_str(&format!(
                "since={}",
                since.format("%Y-%m-%dT%H:%M:%S%.f").to_string()
            ));
        }
        if let Some(mode) = mode {
            if since.is_some() {
                api_endpoint.push_str("&");
            }
            api_endpoint.push_str(&mode.to_string());
        }

        match self.get(client, &api_endpoint, cache).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache,
            }) => response
                .json()
                .await
                .map(|res| CacheRequestResponse::Modified(CacheResult { value: res, cache }))
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Ok(CacheRequestResponse::NotModified),
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/subscriptions.md#get-subscription
    pub async fn get_subscription(
        &self,
        client: &Client,
        subscription_id: SubscriptionID,
    ) -> Result<Subscription, ApiError> {
        let path = format!("/v2/subscriptions/{}.json", subscription_id);
        match self.get(client, &path, None).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _cache,
            }) => response
                .json()
                .await
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/subscriptions.md#create-subscription
    pub async fn create_subscription<S: Into<String>>(
        &self,
        client: &Client,
        url: S,
    ) -> Result<CreateSubscriptionResult, ApiError> {
        let input = CreateSubscriptionInput {
            feed_url: url.into(),
        };
        let res = self
            .post(client, "/v2/subscriptions.json", |request| {
                request.json(&input)
            })
            .await?;
        match res.status().as_u16() {
            201 => {
                let subscription = res.json().await.context(ApiErrorKind::ServerIsBroken)?;
                Ok(CreateSubscriptionResult::Created(subscription))
            }
            300 => {
                let options = res.json().await.context(ApiErrorKind::ServerIsBroken)?;
                Ok(CreateSubscriptionResult::MultipleOptions(options))
            }
            303 => {
                let location = res
                    .headers()
                    .get("Location")
                    .ok_or(ApiErrorKind::ServerIsBroken)?
                    .to_str()
                    .context(ApiErrorKind::ServerIsBroken)?;
                let location = Url::parse(location).context(ApiErrorKind::ServerIsBroken)?;
                Ok(CreateSubscriptionResult::Found(location))
            }
            404 => Ok(CreateSubscriptionResult::NotFound),
            _ => Err(ApiError::from(ApiErrorKind::ServerIsBroken)),
        }
    }

    pub async fn delete_subscription(
        &self,
        client: &Client,
        subscription_id: SubscriptionID,
    ) -> Result<(), ApiError> {
        let path = format!("/v2/subscriptions/{}.json", subscription_id);
        self.delete(client, &path).await.map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/subscriptions.md#update-subscription
    pub async fn update_subscription<S: Into<String>>(
        &self,
        client: &Client,
        subscription_id: SubscriptionID,
        title: S,
    ) -> Result<(), ApiError> {
        let input = UpdateSubscriptionInput {
            title: title.into(),
        };
        let path = format!("/v2/subscriptions/{}/update.json", subscription_id);
        self.post(client, &path, |request| request.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/taggings.md#get-taggings
    pub async fn get_taggings(
        &self,
        client: &Client,
        cache: Option<Cache>,
    ) -> Result<CacheRequestResponse<Vec<Tagging>>, ApiError> {
        match self.get(client, "/v2/taggings.json", cache).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache,
            }) => response
                .json()
                .await
                .map(|res| CacheRequestResponse::Modified(CacheResult { value: res, cache }))
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Ok(CacheRequestResponse::NotModified),
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/taggings.md#get-tagging
    pub async fn get_tagging(
        &self,
        client: &Client,
        tagging_id: TaggingID,
    ) -> Result<Tagging, ApiError> {
        let path = format!("/v2/taggings/{}.json", tagging_id);
        match self.get(client, &path, None).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _cache,
            }) => response
                .json()
                .await
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/taggings.md#create-tagging
    pub async fn create_tagging(
        &self,
        client: &Client,
        feed_id: FeedID,
        name: &str,
    ) -> Result<(), ApiError> {
        let input = CreateTaggingInput {
            feed_id,
            name: name.into(),
        };
        self.post(client, "/v2/taggings.json", |r| r.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/taggings.md#delete-tagging
    pub async fn delete_tagging(
        &self,
        client: &Client,
        tagging_id: TaggingID,
    ) -> Result<(), ApiError> {
        let path = format!("/v2/taggings/{}.json", tagging_id);
        self.delete(client, &path).await.map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/tags.md
    pub async fn rename_tag(
        &self,
        client: &Client,
        old_name: &str,
        new_name: &str,
    ) -> Result<(), ApiError> {
        let input = RenameTagInput {
            old_name: old_name.into(),
            new_name: new_name.into(),
        };
        self.post(client, "/v2/tags.json", |r| r.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/tags.md#delete-v2tagsjson
    pub async fn delete_tag(&self, client: &Client, name: &str) -> Result<(), ApiError> {
        let input = DeleteTagInput { name: name.into() };
        self.delete_with_body(client, "/v2/tags.json", |r| r.json(&input))
            .await
            .map(|_| ())
    }

    // https://github.com/feedbin/feedbin-api/blob/master/content/icons.md#get-v2iconsjson
    pub async fn get_icons(&self, client: &Client) -> Result<Vec<Icon>, ApiError> {
        match self.get(client, "/v2/icons.json", None).await? {
            CacheRequestResponse::Modified(CacheResult {
                value: response,
                cache: _cache,
            }) => response
                .json()
                .await
                .context(ApiErrorKind::ServerIsBroken)
                .map_err(ApiError::from),
            CacheRequestResponse::NotModified => Err(ApiErrorKind::InvalidCaching)?,
        }
    }

    pub async fn import_opml(&self, client: &Client, opml: &str) -> Result<(), ApiError> {
        self.post(client, "/v2/imports.json", |req_builder| {
            req_builder
                .header(CONTENT_TYPE, "text/xml")
                .body(opml.to_owned())
        })
        .await
        .map(|_| ())
    }
}