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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
#[cfg(test)]
mod tests;
mod error;
pub mod models;

use self::error::{
    ApiError,
    ApiErrorKind,
};
use failure::ResultExt;
use std::str::FromStr;
use log::info;
use percent_encoding::define_encode_set;
use url::Url;
use url::percent_encoding::{
    utf8_percent_encode,
    USERINFO_ENCODE_SET,
};
use serde_json::{
    json,
};
use reqwest::{Client, StatusCode};
use reqwest::header::{
    AUTHORIZATION,
    CONTENT_TYPE,
};
use chrono::{
    NaiveDateTime,
    Local,
    Duration
};
use self::models::{
    Profile,
    ProfileUpdate,
    AccessTokenResponse,
    RefreshTokenResponse,
    Category,
    Subscription,
    SubscriptionInput,
    Tag,
    Entry,
    Stream,
    Counts,
    FeedlyError,
};

pub type AuthCode = String;
pub type AccessToken = String;
pub type RefreshToken = String;

define_encode_set! {
    pub FEEDLY_ENCODE_SET = [USERINFO_ENCODE_SET] | {'+'}
}

pub struct FeedlyApi {
    base_uri: Url,
    client_id: String,
    client_secret: String,
    redirect_uri: Url,
    auth_scope: Url,
    client: Client,
    user_id: Option<String>,
    access_token: Option<AccessToken>,
    refresh_token: Option<RefreshToken>,
    token_expires: Option<NaiveDateTime>,
}

impl FeedlyApi {
    pub fn new(
        id: String,
        secret: String,
        access_token: Option<AccessToken>,
        refresh_token: Option<RefreshToken>,
        token_expires: Option<NaiveDateTime>,
    ) -> Result<FeedlyApi, ApiError> {
        let api = FeedlyApi {
            base_uri: Url::parse("http://cloud.feedly.com").context(ApiErrorKind::Url)?,
            client_id: id,
            client_secret: secret,
            redirect_uri: Url::parse("http://localhost").context(ApiErrorKind::Url)?,
            auth_scope: Url::parse("https://cloud.feedly.com/subscriptions").context(ApiErrorKind::Url)?,
            client: Client::new(),
            user_id: None,
            access_token: access_token,
            refresh_token: refresh_token,
            token_expires: token_expires,
        };

        Ok(api)
    }

    pub fn has_access_token(&self) -> bool {
        self.access_token.is_some()
    }

    pub fn login_url(&self) -> Result<Url, ApiError> {
        let mut url = self.base_uri.as_str().to_owned();
        url.push_str("v3/auth/auth");
        url.push_str(&format!("?client_secret={}", self.client_secret));
        url.push_str(&format!("&client_id={}", self.client_id));
        url.push_str(&format!("&redirect_uri={}", self.redirect_uri.as_str()));
        url.push_str(&format!("&scope={}", self.auth_scope.as_str()));
        url.push_str("&response_type=code");
        url.push_str("&state=getting_code");
        let url = Url::parse(&url).context(ApiErrorKind::Url)?;
        Ok(url)
    }

    pub fn parse_redirected_url(url: Url) -> Result<AuthCode, ApiError> {
        if let Some(code) = url.query_pairs().find(|ref x| x.0 == "code") {
            return Ok(code.1.to_string());
        }

        if let Some(error) = url.query_pairs().find(|ref x| x.0 == "error") {
            if error.1 == "access_denied" {
                Err(ApiErrorKind::AccessDenied)?
            }
        }

        Err(ApiErrorKind::Unknown)?
    }

    pub fn redirect_url(&self) -> Url {
        self.redirect_uri.clone()
    }

    pub fn initialize_user_id(&mut self) -> Result<(), ApiError> {
        if self.user_id.is_none() {
            let profile = self.get_profile()?;
            self.user_id = Some(profile.id.clone());
        }
        Ok(())
    }

    pub fn parse_expiration_date(expires_in: Option<String>) -> Result<Option<NaiveDateTime>, ApiError> {
        match expires_in {
            Some(expires_at) => {
                let expires_datetime = NaiveDateTime::from_str(&expires_at).context(ApiErrorKind::Input)?;
                Ok(Some(expires_datetime))
            },
            None => Ok(None),
        }
    }

    pub fn gernerate_feed_id(url: Url) -> String {
        format!("feed/{}", url.as_str())
    }

    pub fn generate_category_id(&mut self, title: &str) -> Result<String, ApiError> {
        self.initialize_user_id()?;
        if let Some(ref user_id) = self.user_id {
            return Ok(format!("user/{}/category/{}", user_id, title))
        }
        // should never happen
        Err(ApiErrorKind::Unknown)?
    }

    pub fn generate_tag_id(&mut self, title: &str) -> Result<String, ApiError> {
        self.initialize_user_id()?;
        if let Some(ref user_id) = self.user_id {
            return Ok(format!("user/{}/tag/{}", user_id, title))
        }
        // should never happen
        Err(ApiErrorKind::Unknown)?
    }

    pub fn category_all(&mut self) -> Result<String, ApiError> {
        self.generate_category_id("global.all")
    }

    pub fn tag_marked(&mut self) -> Result<String, ApiError> {
        self.generate_tag_id("global.saved")
    }

    pub fn tag_read(&mut self) -> Result<String, ApiError> {
        self.generate_tag_id("global.read")
    }

    pub fn request_auth_token(&mut self, auth_code: AuthCode) -> Result<AccessTokenResponse, ApiError> {

        let input = json!(
            {
                "code" : auth_code,
                "client_id" : self.client_id,
                "client_secret" : self.client_secret,
                "redirect_uri" : self.redirect_uri.as_str(),
                "state" : "news flash feedly",
                "grant_type" : "authorization_code"
            }
        );

        let api_endpoint = self.base_uri.clone().join("/v3/auth/token").context(ApiErrorKind::Url)?;
        let response = self.client.post(api_endpoint).json(&input)
                            .send().context(ApiErrorKind::Http)?
                            .text().context(ApiErrorKind::Http)?;
        let response : AccessTokenResponse = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        self.access_token = Some(response.access_token.clone());
        self.refresh_token = Some(response.refresh_token.clone());
        self.token_expires = Some(Local::now().naive_local() + Duration::seconds(response.expires_in as i64));

        Ok(response)
    }

    fn refresh_auth_token(&self, refresh_token: RefreshToken) -> Result<RefreshTokenResponse, ApiError> {
        let input = json!(
            {
                "refresh_token" : refresh_token,
                "client_id" : self.client_id,
                "client_secret" : self.client_secret,
                "grant_type" : "refresh_token"
            }
        );
        let api_endpoint = self.base_uri.clone().join("/v3/auth/token").context(ApiErrorKind::Url)?;
        let response = self.client.post(api_endpoint).json(&input)
                            .send().context(ApiErrorKind::Http)?
                            .text().context(ApiErrorKind::Http)?;
        let response : RefreshTokenResponse = serde_json::from_str(&response).context(ApiErrorKind::Json)?;

        info!("Feedly refresh token: {:?}", response);

        Ok(response)
    }

    fn get_access_token(&mut self) -> Result<AccessToken, ApiError> {
        
        if let Some(access_token) = self.access_token.clone() {
            
            // check if access_token is still valid
            if let Some(token_expires) = self.token_expires.clone() {
                let duration = token_expires.signed_duration_since(Local::now().naive_local());
                let expired = duration.num_seconds() <= 60;

                if !expired {
                    return Ok(access_token)
                }

                // if acces_token expired try to refresh it
                if let Some(refresh_token) = self.refresh_token.clone() {
                    let refreshed_token_response = self.refresh_auth_token(refresh_token).context(ApiErrorKind::Token)?;
                    self.access_token = Some(refreshed_token_response.access_token.clone());
                    self.refresh_token = Some(refreshed_token_response.refresh_token.clone());
                    let token_expires = Local::now().naive_local() + Duration::seconds(refreshed_token_response.expires_in as i64);
                    self.token_expires = Some(token_expires);

                    return Ok(refreshed_token_response.access_token.clone())
                }
            }
        }

        Err(ApiErrorKind::Token)?
    }

    fn post_request(&mut self, json: serde_json::Value, api_endpoint: &str) -> Result<String, ApiError> {
        let token = self.get_access_token()?;
        let api_endpoint = self.base_uri.clone().join(api_endpoint).context(ApiErrorKind::Url)?;
        let mut response = self.client.post(api_endpoint)
                        .header(AUTHORIZATION, token)
                        .json(&json)
                        .send().context(ApiErrorKind::Http)?;

        let status = response.status();
        let response = response.text().context(ApiErrorKind::Http)?;
        if status != StatusCode::OK {
            let error : FeedlyError = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
            return Err(ApiErrorKind::Feedly(error))?
        }
        Ok(response)
    }

    fn get_request(&mut self, api_endpoint: &str) -> Result<String, ApiError> {
        let token = self.get_access_token()?;
        let api_endpoint = self.base_uri.clone().join(api_endpoint).context(ApiErrorKind::Url)?;
        let mut response = self.client.get(api_endpoint)
                        .header(AUTHORIZATION, token)
                        .send().context(ApiErrorKind::Http)?;
        
        let status = response.status();
        let response = response.text().context(ApiErrorKind::Http)?;
        if status != StatusCode::OK {
            let error : FeedlyError = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
            return Err(ApiErrorKind::Feedly(error))?
        }
        Ok(response)
    }

    fn put_request(&mut self, json: serde_json::Value, api_endpoint: &str) -> Result<String, ApiError> {
        let token = self.get_access_token()?;
        let api_endpoint = self.base_uri.clone().join(api_endpoint).context(ApiErrorKind::Url)?;
        let mut response = self.client.put(api_endpoint)
                        .header(AUTHORIZATION, token)
                        .json(&json)
                        .send().context(ApiErrorKind::Http)?;
        
        let status = response.status();
        let response = response.text().context(ApiErrorKind::Http)?;
        if status != StatusCode::OK {
            let error : FeedlyError = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
            return Err(ApiErrorKind::Feedly(error))?
        }
        Ok(response)
    }

    fn delete_request(&mut self, api_endpoint: &str) -> Result<(), ApiError> {
        let token = self.get_access_token()?;
        let api_endpoint = self.base_uri.clone().join(api_endpoint).context(ApiErrorKind::Url)?;
        let mut response = self.client.delete(api_endpoint)
                        .header(AUTHORIZATION, token)
                        .send().context(ApiErrorKind::Http)?;
        if response.status() != StatusCode::OK {
            let response = response.text().context(ApiErrorKind::Http)?;
            let error : FeedlyError = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
            return Err(ApiErrorKind::Feedly(error))?
        }
        Ok(())
    }

    pub fn get_profile(&mut self) -> Result<Profile, ApiError> {
        let response = self.get_request("/v3/profile")?;
        let profile : Profile = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(profile)
    }

    #[allow(dead_code)]
    pub fn update_profile(
        &mut self,
        email: Option<String>,
        given_name: Option<String>,
        family_name: Option<String>,
        picture: Option<String>,
        gender: Option<bool>,
        locale: Option<String>,
        twitter: Option<String>,
        facebook: Option<String>)
    -> Result<Profile, ApiError> {

        let update = ProfileUpdate {
            email: email,
            given_name: given_name,
            family_name: family_name,
            picture: picture,
            gender: gender,
            locale: locale,
            twitter: twitter,
            facebook: facebook,
        };

        let update = serde_json::to_value(update).context(ApiErrorKind::Json)?;
        let response = self.post_request(update, "/v3/profile")?;
        let profile : Profile = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(profile)
    }

    pub fn get_categories(&mut self) -> Result<Vec<Category> ,ApiError> {
        let response = self.get_request("/v3/categories?sort=feedly")?;
        let category_vec : Vec<Category> = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(category_vec)
    }

    pub fn update_category(&mut self, id: &str, label: &str) -> Result<(), ApiError> {
        let input = json!(
            {
                "label" : label,
            }
        );
        let id = utf8_percent_encode(&id, FEEDLY_ENCODE_SET).to_string();
        let _ = self.post_request(input, &format!("/v3/categories/{}", id))?;
        Ok(())
    }

    pub fn delete_category(&mut self, id: &str) -> Result<(), ApiError> {
        let id = utf8_percent_encode(&id, FEEDLY_ENCODE_SET).to_string();
        let _ = self.delete_request(&format!("/v3/categories/{}", id))?;
        Ok(())
    }

    pub fn get_subsriptions(&mut self) -> Result<Vec<Subscription>, ApiError> {
        let response = self.get_request("/v3/subscriptions")?;
        let subscription_vec : Vec<Subscription> = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(subscription_vec)
    }

    // also updates existing subscriptions
    pub fn add_subscription(&mut self, subscription: SubscriptionInput) -> Result<(), ApiError> {
        let json = serde_json::to_value(subscription).context(ApiErrorKind::Json)?;
        let _ = self.post_request(json, "/v3/subscriptions")?;
        Ok(())
    }

    pub fn update_subscriptions(&mut self, subscriptions: Vec<SubscriptionInput>) -> Result<(), ApiError> {
        let json = serde_json::to_value(subscriptions).context(ApiErrorKind::Json)?;
        let _ = self.post_request(json, "/v3/subscriptions/.mput")?;
        Ok(())
    }

    pub fn delete_subscription(&mut self, id: &str) -> Result<(), ApiError> {
        let id = utf8_percent_encode(&id, FEEDLY_ENCODE_SET).to_string();
        self.delete_request(&format!("/v3/subscriptions/{}", id))?;
        Ok(())
    }

    pub fn get_tags(&mut self) -> Result<Vec<Tag> ,ApiError> {
        let response = self.get_request("/v3/tags")?;
        let tag_vec : Vec<Tag> = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(tag_vec)
    }

    fn tag_api_endpoint(tag_ids: Vec<&str>, entry_ids: Option<Vec<&str>>) -> Result<String, ApiError> {
        if tag_ids.len() == 0 {
            return Err(ApiErrorKind::Input)?
        }

        let mut api_endpoint = String::from("/v3/tags/");
        for tag_id in tag_ids {
            let tag_id = utf8_percent_encode(tag_id, FEEDLY_ENCODE_SET).to_string();
            api_endpoint.push_str(&tag_id);
            api_endpoint.push_str(",");
        }
        api_endpoint = api_endpoint[..api_endpoint.len()-1].to_owned();
        if let Some(entry_ids) = entry_ids {
            if entry_ids.len() == 0 {
                return Err(ApiErrorKind::Input)?
            }
            api_endpoint.push_str("/");
            for entry_id in entry_ids {
                let entry_id = utf8_percent_encode(&entry_id, FEEDLY_ENCODE_SET).to_string();
                api_endpoint.push_str(&entry_id);
                api_endpoint.push_str(",");
            }
            api_endpoint = api_endpoint[..api_endpoint.len()-1].to_owned();
        }

        Ok(api_endpoint)
    }

    pub fn tag_entry(&mut self, entry_id: &str, tag_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "entryId" : entry_id,
            }
        );
        let api_endpoint = FeedlyApi::tag_api_endpoint(tag_ids, None)?;
        let _ = self.put_request(json, &api_endpoint)?;
        Ok(())
    }

    #[allow(dead_code)]
    pub fn tag_entries(&mut self, entry_ids: Vec<&str>, tag_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "entryIds" : entry_ids,
            }
        );
        let api_endpoint = FeedlyApi::tag_api_endpoint(tag_ids, None)?;
        let _ = self.put_request(json, &api_endpoint)?;
        Ok(())
    }

    pub fn update_tag(&mut self, tag_id: &str, label: &str) -> Result<(), ApiError> {
        let json = json!(
            {
                "label" : label,
            }
        );
        let api_endpoint = FeedlyApi::tag_api_endpoint(vec!(tag_id), None)?;
        let _ = self.post_request(json, &api_endpoint)?;
        Ok(())
    }

    pub fn untag_entries(&mut self, entry_ids: Vec<&str>, tag_ids: Vec<&str>) -> Result<(), ApiError> {
        let api_endpoint = FeedlyApi::tag_api_endpoint(tag_ids, Some(entry_ids))?;
        let _ = self.delete_request(&api_endpoint)?;
        Ok(())
    }

    pub fn delete_tags(&mut self, tag_ids: Vec<&str>) -> Result<(), ApiError> {
        let api_endpoint = FeedlyApi::tag_api_endpoint(tag_ids, None)?;
        let _ = self.delete_request(&api_endpoint)?;
        Ok(())
    }

    #[allow(dead_code)]
    pub fn get_entries(&mut self, entry_ids: Vec<&str>) -> Result<Vec<Entry>, ApiError> {
        let json = serde_json::to_value(entry_ids).context(ApiErrorKind::Json)?;
        let response = self.post_request(json, "/v3/entries/.mget")?;
        let entry_vec : Vec<Entry> = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(entry_vec)
    }

    #[allow(dead_code)]
    pub fn create_entry(&mut self, entry: Entry) -> Result<Vec<String>, ApiError> {
        let json = serde_json::to_value(entry).context(ApiErrorKind::Json)?;
        let response = self.post_request(json, "/v3/entries/")?;
        let entry_ids : Vec<String> = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(entry_ids)
    }

    fn stream_api_endpoint(
        stream_id: &str,
        continuation: Option<String>,
        count: Option<u32>,
        ranked: Option<&str>,
        unread_only: Option<bool>,
        newer_than: Option<u64>,
    ) -> String {
        let mut api_endpoint = String::from("/v3/streams/contents?streamId=");
        let stream_id = utf8_percent_encode(&stream_id, FEEDLY_ENCODE_SET).to_string();
        api_endpoint.push_str(&stream_id);

        if let Some(continuation) = continuation {
            api_endpoint.push_str(&format!("&continuation={}", continuation));
        }

        if let Some(count) = count {
            api_endpoint.push_str(&format!("&count={}", count));
        }

        if let Some(ranked) = ranked {
            api_endpoint.push_str(&format!("&ranked={}", ranked));
        }

        if let Some(unread_only) = unread_only {
            api_endpoint.push_str(&format!("&unreadOnly={}", unread_only));
        }

        if let Some(newer_than) = newer_than {
            api_endpoint.push_str(&format!("&newerThan={}", newer_than));
        }

        api_endpoint
    }

    pub fn get_stream(
        &mut self,
        stream_id: &str,
        continuation: Option<String>,
        count: Option<u32>,
        ranked: Option<&str>,
        unread_only: Option<bool>,
        newer_than: Option<u64>,
    ) -> Result<Stream, ApiError> {
        let api_endpoint = FeedlyApi::stream_api_endpoint(
            stream_id,
            continuation,
            count,
            ranked,
            unread_only,
            newer_than
        );
        let response = self.get_request(&api_endpoint)?;
        let stream : Stream = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(stream)
    }

    pub fn get_unread_counts(&mut self) -> Result<Counts, ApiError> {
        let response = self.get_request("/v3/markers/counts")?;
        let counts : Counts = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
        Ok(counts)
    }

    pub fn mark_entries_read(&mut self, entry_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "action" : "markAsRead",
                "type" : "entries",
                "entryIds" : entry_ids
            }
        );
        let _ = self.post_request(json, "/v3/markers")?;
        Ok(())
    }

    pub fn mark_entries_unread(&mut self, entry_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "action" : "keepUnread",
                "type" : "entries",
                "entryIds" : entry_ids
            }
        );
        let _ = self.post_request(json, "/v3/markers")?;
        Ok(())
    }

    pub fn mark_feeds_read(&mut self, feed_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "action" : "markAsRead",
                "type" : "feeds",
                "feedIds" : feed_ids
            }
        );
        let _ = self.post_request(json, "/v3/markers")?;
        Ok(())
    }

    pub fn mark_categories_read(&mut self, category_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "action" : "markAsRead",
                "type" : "categories",
                "categoryIds" : category_ids
            }
        );
        let _ = self.post_request(json, "/v3/markers")?;
        Ok(())
    }

    pub fn mark_tags_read(&mut self, tag_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "action" : "markAsRead",
                "type" : "tags",
                "tagIds" : tag_ids
            }
        );
        let _ = self.post_request(json, "/v3/markers")?;
        Ok(())
    }

    pub fn mark_entries_saved(&mut self, entry_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "action" : "markAsSaved",
                "type" : "entries",
                "entryIds" : entry_ids
            }
        );
        let _ = self.post_request(json, "/v3/markers")?;
        Ok(())
    }

    pub fn mark_entries_unsaved(&mut self, entry_ids: Vec<&str>) -> Result<(), ApiError> {
        let json = json!(
            {
                "action" : "markAsUnsaved",
                "type" : "entries",
                "entryIds" : entry_ids
            }
        );
        let _ = self.post_request(json, "/v3/markers")?;
        Ok(())
    }

    #[allow(dead_code)]
    pub fn export_opml(&mut self) -> Result<String, ApiError> {
        self.get_request("/v3/opml")
    }

    pub fn import_opml(&mut self, opml: &str) -> Result<(), ApiError> {
        let token = self.get_access_token()?;
        let api_endpoint = self.base_uri.clone().join("/v3/opml").context(ApiErrorKind::Url)?;
        let mut response = self.client.post(api_endpoint)
                        .header(AUTHORIZATION, token)
                        .header(CONTENT_TYPE, "text/xml")
                        .body(opml.to_owned())
                        .send().context(ApiErrorKind::Http)?;

        let status = response.status();
        let response = response.text().context(ApiErrorKind::Http)?;
        if status != StatusCode::OK {
            let error : FeedlyError = serde_json::from_str(&response).context(ApiErrorKind::Json)?;
            return Err(ApiErrorKind::Feedly(error))?
        }
        Ok(())
    }
}