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
use crate::error_from;
use crate::vars::PIN_UA;
use boolinator::Boolinator;
use json::JsonValue;
use log::debug;
use reqwest::header::USER_AGENT;
use serde_urlencoded::to_string as encode;
use snafu::{Backtrace, GenerateBacktrace, OptionExt, Snafu};
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("{}", cause))]
Other {
#[snafu(source(true))]
cause: Box<dyn std::error::Error>,
#[snafu(backtrace(true))]
back: Backtrace,
},
#[snafu(display("While calling `{}' got {}", ep, status))]
Http {
ep: String,
status: reqwest::StatusCode,
#[snafu(backtrace(true))]
back: Backtrace,
},
#[snafu(display(
"Successfully added the URL to Instapaper, but the response contained no bookmark ID."
))]
NoBookmarkId,
#[snafu(display("Unexpected JSON response type {:#?}", item))]
BadJsonResponseType {
item: JsonValue,
#[snafu(backtrace(true))]
back: Backtrace,
},
#[snafu(display("Unexpected JSON response type {:#?}", item))]
BadJsonValueType {
item: JsonValue,
#[snafu(backtrace(true))]
back: Backtrace,
},
}
error_from!(json::Error);
error_from!(reqwest::Error);
error_from!(serde_urlencoded::ser::Error);
pub type Result<T> = std::result::Result<T, Error>;
pub trait Instapaper {
fn send(&mut self, url: &str, title: Option<&str>) -> Result<String>;
}
pub struct Client {
user: String,
pass: String,
}
impl Client {
pub fn new(username: &str, password: &str) -> Client {
Client {
user: username.to_string(),
pass: password.to_string(),
}
}
}
impl Instapaper for Client {
fn send(&mut self, url: &str, title: Option<&str>) -> Result<String> {
let ep = "/api/add";
let mut args = vec![("url", url)];
if let Some(title) = title {
args.push(("title", title));
}
let req = format!("https://www.instapaper.com{}?{}", ep, encode(&args)?);
let client = reqwest::blocking::Client::new();
let rsp = client
.get(&req)
.header(USER_AGENT, PIN_UA)
.basic_auth(&self.user, Some(&self.pass))
.send()?;
(rsp.status().is_success()).as_option().context(Http {
ep: String::from(ep),
status: rsp.status(),
})?;
let rsp = rsp.text()?;
debug!("requesting {}...done: {}", req, rsp);
let val = json::parse(&rsp)?;
match val {
JsonValue::Object(doc) => {
let id = doc.get("bookmark_id").context(NoBookmarkId)?;
debug!("Got an id of {:#?}", id);
match id {
JsonValue::Short(n) => Ok(format!("new bookmark {}", n)),
JsonValue::Number(n) => Ok(format!("new bookmark {}", n)),
_ => Err(Error::BadJsonValueType {
item: id.clone(),
back: Backtrace::generate(),
}),
}
}
_ => Err(Error::BadJsonResponseType {
item: val.clone(),
back: Backtrace::generate(),
}),
}
}
}