litchee 0.1.4

Async, builder-pattern Rust client for the Lichess API: full endpoint coverage, NDJSON streaming, and OAuth2 PKCE ('Log in with Lichess').
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
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
//! The Users API: look up players, their status, and head-to-head records.
//!
//! Reached through [`LichessClient::users`].

use std::collections::HashMap;

use reqwest::Method;
use reqwest::header::{ACCEPT, CONTENT_TYPE};
use serde::{Deserialize, Serialize};

use crate::client::LichessClient;
use crate::config::Host;
use crate::error::Result;
use crate::http;
use crate::model::{LichessLightUser, LichessTitle, LichessUser, LichessUserExtended};

/// Accessor for the Users API.
#[derive(Debug)]
pub struct UsersApi<'a> {
    client: &'a LichessClient,
}

impl<'a> UsersApi<'a> {
    /// Binds the accessor to a client.
    pub(crate) fn new(client: &'a LichessClient) -> Self {
        Self { client }
    }

    /// Gets the extended profile of a single user.
    ///
    /// `GET /api/user/{username}`
    ///
    /// `query` toggles the optional extra sections (trophies, full profile,
    /// leaderboard rank, FIDE id); [`UserQuery::default`] requests none.
    pub async fn get(&self, username: &str, query: &UserQuery) -> Result<LichessUserExtended> {
        let path = format!("/api/user/{}", http::segment(username));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(query);
        http::json(request, "LichessUserExtended").await
    }

    /// Gets several users by id (up to 300), returned in the requested order.
    ///
    /// `profile`/`rank` include each user's full profile / leaderboard rank.
    /// `POST /api/users`
    pub async fn get_many(
        &self,
        ids: &[&str],
        profile: Option<bool>,
        rank: Option<bool>,
    ) -> Result<Vec<LichessUser>> {
        let request = self
            .client
            .request(Method::POST, Host::Default, "/api/users")
            .query(&[("profile", profile), ("rank", rank)])
            .header(CONTENT_TYPE, "text/plain")
            .body(ids.join(","));
        http::json(request, "Vec<LichessUser>").await
    }

    /// Gets the real-time online/playing/streaming status of several users.
    ///
    /// The `with_*` flags add signal strength, current game ids, and game
    /// metadata. `GET /api/users/status`
    pub async fn statuses(
        &self,
        ids: &[&str],
        with_signal: Option<bool>,
        with_game_ids: Option<bool>,
        with_game_metas: Option<bool>,
    ) -> Result<Vec<LichessUserStatus>> {
        let request = self
            .client
            .request(Method::GET, Host::Default, "/api/users/status")
            .query(&[("ids", ids.join(","))])
            .query(&[
                ("withSignal", with_signal),
                ("withGameIds", with_game_ids),
                ("withGameMetas", with_game_metas),
            ]);
        http::json(request, "Vec<LichessUserStatus>").await
    }

    /// Gets the head-to-head record of two users.
    ///
    /// When `matchup` is `true` and the players are currently facing off, the
    /// current-match score is also returned. `GET /api/crosstable/{u1}/{u2}`
    pub async fn crosstable(
        &self,
        user1: &str,
        user2: &str,
        matchup: bool,
    ) -> Result<LichessCrosstable> {
        let path = format!(
            "/api/crosstable/{}/{}",
            http::segment(user1),
            http::segment(user2)
        );
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(&[("matchup", matchup)]);
        http::json(request, "LichessCrosstable").await
    }

    /// Autocompletes usernames from a prefix (at least 3 characters).
    ///
    /// Returns a builder; refine it with the optional filters and finish with
    /// [`AutocompleteRequest::send`]. `GET /api/player/autocomplete`
    #[must_use]
    pub fn autocomplete(&self, term: &'a str) -> AutocompleteRequest<'a> {
        AutocompleteRequest::new(self.client, term)
    }

    /// Gets a user's rating history across all perfs.
    ///
    /// `GET /api/user/{username}/rating-history`
    pub async fn rating_history(&self, username: &str) -> Result<Vec<LichessRatingHistoryEntry>> {
        let path = format!("/api/user/{}/rating-history", http::segment(username));
        let request = self.client.request(Method::GET, Host::Default, &path);
        http::json(request, "Vec<LichessRatingHistoryEntry>").await
    }

    /// Gets a user's statistics in a single perf.
    ///
    /// `GET /api/user/{username}/perf/{perf}`
    pub async fn perf_stats(&self, username: &str, perf: &str) -> Result<LichessPerfStat> {
        let path = format!(
            "/api/user/{}/perf/{}",
            http::segment(username),
            http::segment(perf)
        );
        let request = self.client.request(Method::GET, Host::Default, &path);
        http::json(request, "LichessPerfStat").await
    }

    /// Gets a user's recent activity feed.
    ///
    /// `GET /api/user/{username}/activity`
    pub async fn activity(&self, username: &str) -> Result<Vec<LichessActivity>> {
        let path = format!("/api/user/{}/activity", http::segment(username));
        let request = self.client.request(Method::GET, Host::Default, &path);
        http::json(request, "Vec<LichessActivity>").await
    }

    /// Gets the top-10 players for every standard perf. `GET /api/player`
    pub async fn leaderboards(&self) -> Result<HashMap<String, Vec<LichessTopUser>>> {
        let request = self
            .client
            .request(Method::GET, Host::Default, "/api/player");
        http::json(request, "leaderboards").await
    }

    /// Gets the top `nb` players for a single perf.
    ///
    /// `GET /api/player/top/{nb}/{perfType}`
    pub async fn top(&self, perf: &str, nb: u32) -> Result<LichessLeaderboard> {
        let path = format!("/api/player/top/{nb}/{}", http::segment(perf));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .header(ACCEPT, "application/vnd.lichess.v3+json");
        http::json(request, "LichessLeaderboard").await
    }

    /// Lists the currently-live streamers. `GET /api/streamer/live`
    pub async fn live_streamers(&self) -> Result<Vec<LichessLiveStreamer>> {
        let request = self
            .client
            .request(Method::GET, Host::Default, "/api/streamer/live");
        http::json(request, "Vec<LichessLiveStreamer>").await
    }

    /// Reads the private notes about a user. `GET /api/user/{username}/note`
    pub async fn notes(&self, username: &str) -> Result<Vec<LichessUserNote>> {
        let path = format!("/api/user/{}/note", http::segment(username));
        let request = self.client.request(Method::GET, Host::Default, &path);
        http::json(request, "Vec<LichessUserNote>").await
    }

    /// Writes a private note about a user. `POST /api/user/{username}/note`
    pub async fn write_note(&self, username: &str, text: &str) -> Result<()> {
        let path = format!("/api/user/{}/note", http::segment(username));
        let request = self
            .client
            .request(Method::POST, Host::Default, &path)
            .form(&[("text", text)]);
        http::ok(request).await
    }
}

/// Optional extra sections to include in a [`UsersApi::get`] lookup.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UserQuery {
    #[serde(skip_serializing_if = "Option::is_none")]
    trophies: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    profile: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    rank: Option<bool>,
    #[serde(rename = "fideId", skip_serializing_if = "Option::is_none")]
    fide_id: Option<bool>,
}

impl UserQuery {
    /// Include the user's trophies.
    #[must_use]
    pub fn trophies(mut self, include: bool) -> Self {
        self.trophies = Some(include);
        self
    }

    /// Include the user's full profile.
    #[must_use]
    pub fn profile(mut self, include: bool) -> Self {
        self.profile = Some(include);
        self
    }

    /// Include the user's leaderboard rank.
    #[must_use]
    pub fn rank(mut self, include: bool) -> Self {
        self.rank = Some(include);
        self
    }

    /// Include the user's FIDE id.
    #[must_use]
    pub fn fide_id(mut self, include: bool) -> Self {
        self.fide_id = Some(include);
        self
    }
}

/// Query parameters for the username autocomplete.
#[derive(Debug, Default, Serialize)]
struct AutocompleteQuery<'a> {
    term: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    names: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    friend: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    team: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tour: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    swiss: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    teacher: Option<bool>,
}

/// Builder for the username autocomplete (`GET /api/player/autocomplete`).
///
/// Always returns the array-of-usernames form; the spec's `object=true` and
/// `exists=true` modes (which change the response shape to an object and a bare
/// boolean respectively) are not modeled.
#[derive(Debug)]
pub struct AutocompleteRequest<'a> {
    client: &'a LichessClient,
    query: AutocompleteQuery<'a>,
}

impl<'a> AutocompleteRequest<'a> {
    /// Creates the request builder for the search `term`.
    pub(crate) fn new(client: &'a LichessClient, term: &'a str) -> Self {
        Self {
            client,
            query: AutocompleteQuery {
                term,
                ..Default::default()
            },
        }
    }

    /// Return usernames with their preferred casing.
    #[must_use]
    pub fn names(mut self, value: bool) -> Self {
        self.query.names = Some(value);
        self
    }

    /// Prefer followed players (requires OAuth).
    #[must_use]
    pub fn friend(mut self, value: bool) -> Self {
        self.query.friend = Some(value);
        self
    }

    /// Restrict the search to a team (id/slug).
    #[must_use]
    pub fn team(mut self, team_id: &'a str) -> Self {
        self.query.team = Some(team_id);
        self
    }

    /// Restrict the search to an arena tournament (id).
    #[must_use]
    pub fn tour(mut self, tour_id: &'a str) -> Self {
        self.query.tour = Some(tour_id);
        self
    }

    /// Restrict the search to a swiss tournament (id).
    #[must_use]
    pub fn swiss(mut self, swiss_id: &'a str) -> Self {
        self.query.swiss = Some(swiss_id);
        self
    }

    /// Only return players who also have a teacher role.
    #[must_use]
    pub fn teacher(mut self, value: bool) -> Self {
        self.query.teacher = Some(value);
        self
    }

    /// Executes the autocomplete, returning matching usernames.
    pub async fn send(self) -> Result<Vec<String>> {
        let request = self
            .client
            .request(Method::GET, Host::Default, "/api/player/autocomplete")
            .query(&self.query);
        http::json(request, "Vec<String>").await
    }
}

impl LichessClient {
    /// Users API: look up players, their status, and head-to-head records.
    #[must_use]
    pub fn users(&self) -> UsersApi<'_> {
        UsersApi::new(self)
    }
}

/// The real-time status of a user: online / playing / streaming flags.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessUserStatus {
    /// The canonical (lowercased) user id.
    pub id: String,
    /// The display name.
    pub name: String,
    /// The player's title, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<LichessTitle>,
    /// The player's flair, if set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flair: Option<String>,
    /// Whether the user is currently online.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub online: Option<bool>,
    /// Whether the user is currently playing a game.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playing: Option<bool>,
    /// Whether the user is currently streaming.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub streaming: Option<bool>,
    /// Deprecated patron flag; prefer [`patron_color`](Self::patron_color).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub patron: Option<bool>,
    /// The chosen Patron wing color; its presence marks an active patron.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub patron_color: Option<u8>,
    /// Network signal strength 1–4, only when requested with `withSignal`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal: Option<u8>,
    /// Id of the game being played, only when requested with `withGameIds`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub playing_id: Option<String>,
}

/// Head-to-head totals between two players.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessCrosstable {
    /// Each user's cumulative score (half-points), keyed by user id.
    pub users: HashMap<String, f64>,
    /// Total number of games played between the two users.
    pub nb_games: u32,
    /// Current-match data, present only when `matchup` was requested and the
    /// two users are playing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub matchup: Option<LichessMatchup>,
}

/// The ongoing match score between two players.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LichessMatchup {
    /// Each user's score in the current match, keyed by user id.
    pub users: HashMap<String, f64>,
    /// Number of games in the current match.
    pub nb_games: u32,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn user_query_serializes_toggles() {
        assert_eq!(
            serde_urlencoded::to_string(UserQuery::default().trophies(true).fide_id(false))
                .unwrap(),
            "trophies=true&fideId=false"
        );
        assert_eq!(
            serde_urlencoded::to_string(UserQuery::default()).unwrap(),
            ""
        );
    }

    #[test]
    fn autocomplete_query_serializes_filters() {
        let query = AutocompleteQuery {
            term: "bob",
            names: Some(true),
            team: Some("coders"),
            ..Default::default()
        };
        let encoded = serde_urlencoded::to_string(&query).unwrap();
        assert_eq!(encoded, "term=bob&names=true&team=coders");
    }

    #[test]
    fn parses_user_status_flags() {
        let json = r#"{"id":"bobby","name":"Bobby","online":true,"playing":false}"#;
        let status: LichessUserStatus = serde_json::from_str(json).unwrap();
        assert_eq!(status.id, "bobby");
        assert_eq!(status.online, Some(true));
        assert_eq!(status.playing, Some(false));
        assert_eq!(status.streaming, None);
    }

    #[test]
    fn parses_crosstable_scores() {
        let json = r#"{"users":{"neio":201.5,"thibault":144.5},"nbGames":346}"#;
        let crosstable: LichessCrosstable = serde_json::from_str(json).unwrap();
        assert_eq!(crosstable.nb_games, 346);
        assert_eq!(crosstable.users.get("neio"), Some(&201.5));
        assert!(crosstable.matchup.is_none());
    }
}

/// An entry in a user's rating history for one perf.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessRatingHistoryEntry {
    /// The perf name (e.g. `"Blitz"`).
    pub name: String,
    /// Data points, each `[year, month, day, rating]` (month is 0-indexed).
    #[serde(default)]
    pub points: Vec<[i32; 4]>,
}

/// A private note about another player.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessUserNote {
    /// The author of the note.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<LichessLightUser>,
    /// The user the note is about.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub to: Option<LichessLightUser>,
    /// The note text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// When the note was written (Unix milliseconds).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub date: Option<i64>,
}

/// A perf rating/progress pair within a [`LichessTopUser`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessTopUserPerf {
    /// The rating.
    pub rating: i32,
    /// The recent progress.
    pub progress: i32,
}

/// A leaderboard player.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessTopUser {
    /// The user id.
    pub id: String,
    /// The display name.
    pub username: String,
    /// Per-perf rating and progress.
    #[serde(default)]
    pub perfs: HashMap<String, LichessTopUserPerf>,
    /// The player's title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<LichessTitle>,
    /// The chosen Patron wing color.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub patron_color: Option<u8>,
    /// Whether the user is online.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub online: Option<bool>,
}

/// A single-perf leaderboard. `GET /api/player/top/{nb}/{perfType}`
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessLeaderboard {
    /// The top players.
    #[serde(default)]
    pub users: Vec<LichessTopUser>,
}

/// Glicko-2 rating details.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessGlicko {
    /// The rating.
    pub rating: f64,
    /// The rating deviation.
    pub deviation: f64,
    /// Whether the rating is provisional.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provisional: Option<bool>,
}

/// The rating part of a [`LichessPerfStat`].
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessPerfStatPerf {
    /// The Glicko-2 rating.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub glicko: Option<LichessGlicko>,
    /// Number of games played.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nb: Option<u32>,
    /// Recent progress.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub progress: Option<i32>,
}

/// Statistics for one of a user's perfs. `GET /api/user/{username}/perf/{perf}`
///
/// Models the headline fields; the detailed `stat` aggregate is not decoded.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessPerfStat {
    /// The user's percentile within this perf.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub percentile: Option<f64>,
    /// The user's rank within this perf.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rank: Option<u32>,
    /// The user.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<LichessLightUser>,
    /// The rating details.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perf: Option<LichessPerfStatPerf>,
}

/// The time range of a [`LichessActivity`] entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessActivityInterval {
    /// Start time (Unix milliseconds).
    pub start: i64,
    /// End time (Unix milliseconds).
    pub end: i64,
}

/// One day of a user's activity. `GET /api/user/{username}/activity`
///
/// Models the time interval; the per-category activity payloads vary widely and
/// are not all decoded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessActivity {
    /// The time range this entry covers.
    pub interval: LichessActivityInterval,
}

/// The stream details of a [`LichessLiveStreamer`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessStreamDetails {
    /// The streaming service (`twitch` or `youtube`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<String>,
    /// The stream title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// The stream language.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lang: Option<String>,
}

/// A currently-live streamer. `GET /api/streamer/live`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessLiveStreamer {
    /// The streamer's light user info.
    #[serde(flatten)]
    pub user: LichessLightUser,
    /// The current stream details.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<LichessStreamDetails>,
}

#[cfg(test)]
mod added_tests {
    use super::*;

    #[test]
    fn parses_rating_history() {
        let json = r#"[{"name":"Bullet","points":[[2011,0,8,1472],[2011,8,12,1314]]}]"#;
        let history: Vec<LichessRatingHistoryEntry> = serde_json::from_str(json).unwrap();
        assert_eq!(history[0].name, "Bullet");
        assert_eq!(history[0].points[1], [2011, 8, 12, 1314]);
    }

    #[test]
    fn parses_leaderboard_top_user() {
        let json = r#"{"users":[{"id":"a","username":"A",
            "perfs":{"bullet":{"rating":2900,"progress":5}},"title":"GM"}]}"#;
        let board: LichessLeaderboard = serde_json::from_str(json).unwrap();
        assert_eq!(board.users[0].perfs["bullet"].rating, 2900);
        assert_eq!(board.users[0].title, Some(LichessTitle::Gm));
    }

    #[test]
    fn parses_live_streamer_with_flattened_user() {
        let json = r#"{"id":"a","name":"A","stream":{"service":"twitch","status":"Live!"}}"#;
        let streamer: LichessLiveStreamer = serde_json::from_str(json).unwrap();
        assert_eq!(streamer.user.id, "a");
        assert_eq!(streamer.stream.unwrap().service.as_deref(), Some("twitch"));
    }
}