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
use std::collections::HashMap;

use anyhow::Context;
use log::{debug, trace};
use reqwest::header::HeaderMap;
use reqwest::Client;
use serde::Deserialize;
use url::Url;

#[cfg(test)]
mod test;

#[derive(Debug)]
/// A Google Reader client
///
/// This should be instantiated with `GoogleReader::try_new()`, as a `mut` variable because login sets the authtoken.
pub struct GoogleReader {
    username: String,
    password: String,
    /// The server URL, e.g. `https://example.com/api/greader.php` for FreshRSS
    server_url: Url,
    authtoken: Option<String>,
    write_token: Option<String>,
    client: Option<Client>,
}

#[derive(Debug, Deserialize)]
/// A link to a resource
pub struct Link {
    pub href: String,
}

#[derive(Debug, Deserialize)]
/// Item Summary
pub struct Summary {
    pub content: Option<String>,
    pub author: Option<String>,
}

#[derive(Debug, Deserialize)]
/// Feed Item
pub struct Item {
    pub id: String,
    #[serde(alias = "crawlTimeMsec")]
    pub crawl_time_msec: Option<String>,
    #[serde(alias = "timestampUsec")]
    pub timestamp_usec: Option<String>,
    pub updated: Option<usize>,
    pub published: Option<usize>,
    pub title: String,
    pub canonical: Vec<Link>,
    pub alternate: Vec<Link>,
    pub categories: Vec<String>,
    pub origin: HashMap<String, String>,
    pub summary: Summary,
}

#[derive(Debug, Deserialize)]
/// Response from the API
pub struct Response {
    pub id: String,
    pub items: Vec<Item>,
    pub updated: usize,
    pub continuation: Option<String>,
}

/// Does all the things.
impl GoogleReader {
    /// The server URL is something like `https://example.com/api/greader.php` for FreshRSS
    pub fn try_new(
        username: impl ToString,
        password: impl ToString,
        server_url: impl ToString,
    ) -> anyhow::Result<Self> {
        let server_url = match server_url.to_string().ends_with('/') {
            true => server_url
                .to_string()
                .strip_suffix('/')
                .unwrap()
                .to_string(),
            false => server_url.to_string(),
        };

        let server_url = Url::parse(&server_url).with_context(|| "Failed to parse server URL")?;
        Ok(GoogleReader {
            username: username.to_string(),
            password: password.to_string(),
            server_url,
            authtoken: None,
            write_token: None,
            client: None,
        })
    }

    /// Do the login dance and cache the auth token.
    pub async fn login(&mut self) -> anyhow::Result<()> {
        let mut url = self.server_url.clone();
        url.path_segments_mut()
            .unwrap()
            .push("accounts")
            .push("ClientLogin");

        debug!("Login URL: {}", url);

        let params = [("Email", &self.username), ("Passwd", &self.password)];
        if self.client.is_none() {
            self.client = Some(reqwest::Client::new());
        }
        let res = self
            .client
            .as_ref()
            .unwrap()
            .post(url)
            .form(&params)
            .send()
            .await
            .with_context(|| "Failed to send login request")?;

        let auth_parser = regex::Regex::new(r#"Auth=(?P<authtoken>\S+)"#)
            .with_context(|| "Failed to generate auth parser regex")?;

        let body = res
            .text()
            .await
            .with_context(|| "Failed to get login response body")?;
        trace!("Login response: {}", body);

        let caps = auth_parser
            .captures(&body)
            .with_context(|| "Failed to parse login response")?;
        if let Some(authtoken) = caps.name("authtoken") {
            trace!("Got authtoken: {}", authtoken.as_str());
            self.authtoken = Some(authtoken.as_str().to_string());
        }

        Ok(())
    }

    /// Get a "write" token.
    pub async fn get_write_token(&mut self) -> anyhow::Result<String> {
        if self.authtoken.is_none() {
            self.login().await.with_context(|| "Failed to login")?;
        }
        let mut url = self.server_url.clone();
        url.path_segments_mut()
            .unwrap()
            .push("reader")
            .push("api")
            .push("0")
            .push("token");
        trace!("get_write_token url: {}", url);
        let res = self
            .client
            .as_ref()
            .unwrap()
            .get(url)
            .headers(self.get_auth_headers())
            .send()
            .await
            .with_context(|| "Failed to get write token")?;

        let mut body = res
            .text()
            .await
            .with_context(|| "Failed to get write token response body")?;

        if body.ends_with('\n') {
            body = body.strip_suffix('\n').unwrap().to_string();
        }

        self.write_token = Some(body.to_owned());

        Ok(body)
    }

    /// Returns a list of unread item IDs.
    pub async fn get_unread_items(
        &mut self,
        continuation: Option<String>,
    ) -> anyhow::Result<Response> {
        if self.authtoken.is_none() {
            self.login().await.with_context(|| "Failed to login")?;
        }

        // https://your-freshrss-instance-url/api/greader.php/reader/api/0/stream/contents/user/-/state/com.google/reading-list?ot=0&n=1000&r=n&xt=user/-/state/com.google/read

        let mut url = self.server_url.clone();
        url.path_segments_mut()
            .unwrap()
            .push("reader")
            .push("api")
            .push("0")
            .push("stream")
            .push("contents")
            .push("user")
            .push("-")
            .push("state")
            .push("com.google")
            .push("reading-list");
        /*
        ot=0: This is the "start time" for the request. Setting it to 0 means that you want to fetch all unread items since the beginning.
        n=1000: This parameter specifies the maximum number of items to fetch. You can adjust this value to the desired number of items.
        r=n: This parameter specifies the order in which items are returned. "n" stands for "newest first."
        xt=user/-/state/com.google/read: This parameter specifies that you want to exclude items that are already marked as read.
        */
        url.set_query(Some("r=n&xt=user/-/state/com.google/read"));
        if let Some(continuation) = continuation {
            url.set_query(Some(
                format!("c={}&{}", continuation, url.query().unwrap_or("")).as_str(),
            ))
        };
        trace!("url: {}", url);
        let res = self
            .client
            .as_ref()
            .unwrap()
            .get(url)
            .headers(self.get_auth_headers())
            .send()
            .await
            .with_context(|| "Failed to send unread-items request")?;

        let body = res
            .text()
            .await
            .with_context(|| "Failed to parse unread items response body")?;
        #[cfg(debug_assertions)]
        trace!("Response body:\n{}", body);
        let response: Response = serde_json::from_str(&body)
            .with_context(|| "Failed to parse unread items response body")?;
        debug!("response: {:#?}", response);

        Ok(response)
    }

    pub async fn get_item(&self, _item_id: usize) {}

    /// Returns the auth headers for use with the API.
    fn get_auth_headers(&self) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.append(
            "Authorization",
            format!("GoogleLogin auth={}", self.authtoken.clone().unwrap())
                .parse()
                .unwrap(),
        );
        #[cfg(debug_assertions)]
        trace!("Auth headers: {:?}", headers);
        headers
    }

    /// Mark an item as read
    pub async fn mark_item_read(&mut self, item_id: impl ToString) -> anyhow::Result<String> {
        if self.authtoken.is_none() {
            self.login().await.with_context(|| "Failed to login")?;
        }

        let write_token = match &self.write_token {
            Some(val) => val.to_owned(),
            None => self
                .get_write_token()
                .await
                .with_context(|| "Failed to get write token")?,
        };

        let params = [
            ("a", "user/-/state/com.google/read"),
            ("T", &write_token),
            ("i", &item_id.to_string()),
        ];

        let mut url = self.server_url.clone();
        url.path_segments_mut()
            .unwrap()
            .push("reader")
            .push("api")
            .push("0")
            .push("edit-tag");
        trace!("edit-tag url: {}", url);
        let res = self
            .client
            .as_ref()
            .unwrap()
            .post(url)
            .form(&params)
            .headers(self.get_auth_headers())
            .send()
            .await
            .with_context(|| "Failed to get write token")?;

        let body = res
            .text()
            .await
            .with_context(|| "Failed to get write token response body")?;

        Ok(body)
    }

    /// Returns the number of unread items, does'nt work for FreshRSS.
    pub async fn unread_count(&mut self) -> anyhow::Result<usize> {
        if self.authtoken.is_none() {
            self.login().await.with_context(|| "Failed to login")?;
        }

        let mut url = self.server_url.clone();
        url.path_segments_mut()
            .unwrap()
            .push("reader")
            .push("api")
            .push("0")
            .push("unread-count");
        #[cfg(debug_assertions)]
        trace!("url: {}", url);
        let res = self
            .client
            .as_ref()
            .unwrap()
            .get(url)
            .headers(self.get_auth_headers())
            .send()
            .await
            .with_context(|| "Failed to send unread-items request")?;

        let body = res
            .text()
            .await
            .with_context(|| "Failed to get unread count response body")?;

        let response_usize = body
            .parse::<usize>()
            .with_context(|| "Failed to parse unread count response")?;
        Ok(response_usize)
    }
}