usaidwat 2.0.0

Answers the age-old question, "Where does a Redditor comment the most?"
Documentation
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
// usaidwat
// Copyright (C) 2025 Michael Dippery <michael@monkey-robot.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Clients for reading data from the Reddit API.

use crate::clock::{DateTime, HasAge, Utc};
use crate::http;
use crate::reddit::service::{RedditService, Service};
use crate::thing::{self, Comment, Submission, User};
pub use chrono::Weekday;
use chrono::{Datelike, Timelike};
use thiserror::Error;
use tokio::try_join;

/// Represents a Reddit user.
#[derive(Debug)]
pub struct Redditor {
    username: String,
    user: User,
}

impl Redditor {
    /// Creates a new client for retrieving information for Reddit users.
    ///
    /// `username` should be the Redditor's username.
    ///
    /// Returns an [`enum@Error`] if data cannot be parsed for the given username.
    pub async fn new(username: impl Into<String>) -> Result<Self, Error> {
        let service = RedditService::new();
        Self::new_with_service(username, service).await
    }

    /// Creates a new client for retrieving information for Reddit users.
    ///
    /// `username` should be the Redditor's username. `service` is the
    /// actual service implementation that will be used to retrieve
    /// information about the Redditor.
    ///
    /// Returns an [`enum@Error`] if data cannot be parsed for the given username.
    pub(crate) async fn new_with_service<T: Service>(
        username: impl Into<String>,
        service: T,
    ) -> Result<Self, Error> {
        let username = username.into();

        let (user_data, comment_data, post_data) = try_join!(
            service.get_resource(&username, "about"),
            service.get_resource(&username, "comments"),
            service.get_resource(&username, "submitted"),
        )?;

        let user = User::parse(&user_data, &comment_data, &post_data)?;
        Ok(Self { username, user })
    }

    /// The Redditor's username.
    pub fn username(&self) -> String {
        self.username.to_string()
    }

    /// Redditor's link karma.
    pub fn link_karma(&self) -> i64 {
        self.user.about().link_karma()
    }

    /// Redditor's comment karma.
    pub fn comment_karma(&self) -> i64 {
        self.user.about().comment_karma()
    }

    /// Redditor's comments.
    pub fn comments(&self) -> impl Iterator<Item = Comment> {
        self.user.comments()
    }

    /// Redditor's posts (articles and self posts).
    pub fn submissions(&self) -> impl Iterator<Item = Submission> {
        self.user.submissions()
    }

    /// True if the user has posted at least one comment.
    pub fn has_comments(&self) -> bool {
        self.comments().count() > 0
    }

    /// True if the user has posted as least one article or self post.
    pub fn has_submissions(&self) -> bool {
        self.submissions().count() > 0
    }

    /// A timeline of the user's comments, grouped by days of the week
    /// and hours of the day.
    pub fn timeline(&self) -> Timeline {
        Timeline::for_user(self)
    }
}

impl HasAge for Redditor {
    /// The date the account was created.
    fn created_utc(&self) -> DateTime<Utc> {
        self.user.about().created_utc()
    }
}

/// A day of comments, bucketed by hour, which each hour containing the
/// number of comments for that hour.
pub type TimelineDay = [u32; 24];

type Hour = u32;
type TimeMatrix = [TimelineDay; 7];

/// A timeline of a Redditor's comments, bucketed by day of the week and hour.
///
/// Can be useful to draw a "heatmap" of a Redditor's comments, similar to the
/// GitHub activity chart.
#[derive(Debug)]
pub struct Timeline {
    buckets: TimeMatrix,
}

impl Timeline {
    /// Calculate a new timeline for the given Redditor.
    pub fn for_user(user: &Redditor) -> Self {
        let groups = Timeline::grouped_by_weekdays_and_hours(user);
        let buckets = Timeline::group_to_matrix(groups);
        Timeline { buckets }
    }

    /// Iterate through timeline, returning a 2-tuple of `(Weekday, TimelineDay)`
    /// for each day of the week.
    pub fn days(&self) -> impl Iterator<Item = (Weekday, TimelineDay)> {
        TimelineIterator::new(&self)
    }

    fn grouped_by_weekdays_and_hours(user: &Redditor) -> impl Iterator<Item = (Weekday, Hour)> {
        user.comments()
            .map(|c| (c.created_local().weekday(), c.created_local().hour()))
    }

    fn group_to_matrix(groups: impl Iterator<Item = (Weekday, Hour)>) -> TimeMatrix {
        let mut buckets = [[0; 24]; 7];
        for (weekday, hour) in groups {
            let wday = weekday.num_days_from_monday();
            assert!(wday < 7);
            assert!(hour < 24);
            buckets[wday as usize][hour as usize] += 1;
        }
        buckets
    }
}

/// A client error.
#[derive(Debug, Error)]
pub enum Error {
    /// An error from the underlying HTTP service.
    #[error("Service error: {0}")]
    Service(#[from] http::HTTPError),

    /// An error parsing data.
    #[error("Parse error: {0}")]
    Parse(#[from] thing::Error),
}

#[derive(Debug)]
struct TimelineIterator<'a> {
    timeline: &'a Timeline,
    row: u8,
}

impl<'a> TimelineIterator<'a> {
    pub fn new(timeline: &'a Timeline) -> Self {
        Self { timeline, row: 0 }
    }
}

impl<'a> Iterator for TimelineIterator<'a> {
    type Item = (Weekday, TimelineDay);

    fn next(&mut self) -> Option<Self::Item> {
        if self.row < 7 {
            let wday = Weekday::try_from(self.row).unwrap();
            let day = self.timeline.buckets[self.row as usize];
            self.row += 1;
            Some((wday, day))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    mod user_with_data {
        use crate::clock::HasAge;
        use crate::reddit::Redditor;
        use crate::test_utils::FrozenClock;
        use chrono::DateTime;

        #[tokio::test]
        async fn it_returns_its_username() {
            let actual_username = Redditor::test().await.username();
            assert_eq!(actual_username, "mipadi");
        }

        #[tokio::test]
        async fn it_returns_its_creation_date() {
            let actual_date = Redditor::test().await.created_utc();
            let expected_date = DateTime::parse_from_rfc3339("2008-03-31T22:55:26Z").unwrap();
            assert_eq!(actual_date, expected_date);
        }

        #[tokio::test]
        async fn it_returns_its_age() {
            let actual_age = Redditor::test()
                .await
                .age(&FrozenClock::default())
                .as_seconds_f64();
            let expected_age = 541016254.0;
            assert_eq!(actual_age, expected_age, "{actual_age} != {expected_age}");
        }

        #[tokio::test]
        async fn it_returns_its_link_karma() {
            let actual_karma = Redditor::test().await.link_karma();
            let expected_karma = 11729;
            assert_eq!(actual_karma, expected_karma)
        }

        #[tokio::test]
        async fn it_returns_its_comment_karma() {
            let actual_karma = Redditor::test().await.comment_karma();
            let expected_karma = 121995;
            assert_eq!(actual_karma, expected_karma)
        }

        #[tokio::test]
        async fn it_returns_its_comments() {
            let count = Redditor::test().await.comments().count();
            assert_eq!(count, 100);
        }

        #[tokio::test]
        async fn it_returns_its_posts() {
            let count = Redditor::test().await.submissions().count();
            assert_eq!(count, 100);
        }

        #[tokio::test]
        async fn it_confirms_that_it_has_comments() {
            assert!(Redditor::test().await.has_comments())
        }

        #[tokio::test]
        async fn it_confirms_that_it_has_submissions() {
            assert!(Redditor::test().await.has_submissions())
        }

        #[tokio::test]
        async fn it_returns_a_timeline() {
            let _ = Redditor::test_empty().await.timeline();
            // Not really anything else to test: there are more comprehensive
            // tests for Timeline and TimelineIterator below.
        }
    }

    mod user_with_no_data {
        use crate::clock::HasAge;
        use crate::reddit::Redditor;
        use crate::test_utils::FrozenClock;
        use chrono::DateTime;

        #[tokio::test]
        async fn it_returns_its_username() {
            let actual_username = Redditor::test_empty().await.username();
            assert_eq!(actual_username, "testuserpleaseignore");
        }

        #[tokio::test]
        async fn it_returns_its_creation_date() {
            let actual_date = Redditor::test_empty().await.created_utc();
            let expected_date = DateTime::parse_from_rfc3339("2010-06-15T06:13:46Z").unwrap();
            assert_eq!(actual_date, expected_date);
        }

        #[tokio::test]
        async fn it_returns_its_age() {
            let actual_age = Redditor::test_empty()
                .await
                .age(&FrozenClock::default())
                .as_seconds_f64();
            let expected_age = 471437954.0;
            assert_eq!(actual_age, expected_age, "{actual_age} != {expected_age}");
        }

        #[tokio::test]
        async fn it_returns_its_link_karma() {
            let actual_karma = Redditor::test_empty().await.link_karma();
            let expected_karma = 0;
            assert_eq!(actual_karma, expected_karma)
        }

        #[tokio::test]
        async fn it_returns_its_comment_karma() {
            let actual_karma = Redditor::test_empty().await.comment_karma();
            let expected_karma = 0;
            assert_eq!(actual_karma, expected_karma)
        }

        #[tokio::test]
        async fn it_returns_its_comments() {
            let count = Redditor::test_empty().await.comments().count();
            assert_eq!(count, 0);
        }

        #[tokio::test]
        async fn it_returns_its_posts() {
            let count = Redditor::test_empty().await.submissions().count();
            assert_eq!(count, 0);
        }

        #[tokio::test]
        async fn it_confirms_that_it_has_comments() {
            assert!(!Redditor::test_empty().await.has_comments())
        }

        #[tokio::test]
        async fn it_confirms_that_it_has_submissions() {
            assert!(!Redditor::test_empty().await.has_submissions())
        }

        #[tokio::test]
        async fn it_returns_a_timeline() {
            let _ = Redditor::test_empty().await.timeline();
            // Not really anything else to test: there are more comprehensive
            // tests for Timeline and TimelineIterator below.
        }
    }

    mod invalid_user {
        use crate::reddit::Redditor;

        #[tokio::test]
        async fn it_is_none() {
            let client = Redditor::test_none().await;
            assert!(client.is_none());
        }
    }

    mod timeline {
        use crate::reddit::Redditor;
        use chrono::Weekday;
        use std::iter::zip;

        #[tokio::test]
        async fn it_processes_user_data() {
            let client = Redditor::test().await;
            let timeline = client.timeline();
            let buckets = timeline.buckets;
            #[rustfmt::skip]
            let expected_buckets = [
                [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 1, 0, 3, 0, 0, 0, 1, 3],
                [1, 0, 0, 0, 0, 0, 0, 0, 1, 4, 1, 1, 1, 1, 3, 0, 1, 0, 0, 0, 3, 1, 5, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 4, 0, 1, 4, 1, 0, 0, 0, 0, 0, 0, 0, 1],
                [3, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 2, 1, 0, 0, 0, 0, 0, 1, 0, 1, 2, 5],
            ];
            assert_eq!(buckets, expected_buckets);
        }

        #[tokio::test]
        async fn it_processes_data_for_users_with_no_comments() {
            let client = Redditor::test_empty().await;
            let timeline = client.timeline();
            let buckets = timeline.buckets;
            #[rustfmt::skip]
            let expected_buckets = [
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            ];
            assert_eq!(buckets, expected_buckets);
        }

        #[tokio::test]
        async fn it_returns_an_iterator_of_its_data() {
            #[rustfmt::skip]
            let expected_items = [
                (Weekday::Mon, [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 1, 0, 3, 0, 0, 0, 1, 3]),
                (Weekday::Tue, [1, 0, 0, 0, 0, 0, 0, 0, 1, 4, 1, 1, 1, 1, 3, 0, 1, 0, 0, 0, 3, 1, 5, 0]),
                (Weekday::Wed, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4]),
                (Weekday::Thu, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0]),
                (Weekday::Fri, [0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]),
                (Weekday::Sat, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 4, 0, 1, 4, 1, 0, 0, 0, 0, 0, 0, 0, 1]),
                (Weekday::Sun, [3, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 2, 1, 0, 0, 0, 0, 0, 1, 0, 1, 2, 5]),
            ];
            let timeline = Redditor::test().await.timeline();
            let actual_items = timeline.days();

            let zipped = zip(actual_items, expected_items);

            for ((actual_wday, actual), (expected_wday, expected)) in zipped {
                assert_eq!(actual_wday, expected_wday);
                assert_eq!(actual, expected);
            }
        }

        #[tokio::test]
        async fn it_returns_an_empty_iterator_for_users_with_no_comments() {
            #[rustfmt::skip]
            let expected_items = [
                (Weekday::Mon, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
                (Weekday::Tue, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
                (Weekday::Wed, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
                (Weekday::Thu, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
                (Weekday::Fri, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
                (Weekday::Sat, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
                (Weekday::Sun, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
            ];

            let timeline = Redditor::test_empty().await.timeline();
            let actual_items = timeline.days();

            let zipped = zip(actual_items, expected_items);

            for ((actual_wday, actual), (expected_wday, expected)) in zipped {
                assert_eq!(actual_wday, expected_wday);
                assert_eq!(actual, expected);
            }
        }
    }
}