litchee 0.1.8

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
//! The Teams API: discover teams and manage membership.
//!
//! Reached through [`LichessClient::teams`].

use futures_util::stream::BoxStream;
use reqwest::Method;
use serde::{Deserialize, Serialize};

use crate::api::tournaments::arena::LichessArena;
use crate::api::tournaments::swiss::LichessSwiss;
use crate::client::LichessClient;
use crate::config::Host;
use crate::error::Result;
use crate::http;
use crate::model::{LichessLightUser, LichessUser};
use crate::secret::Secret;

/// Form body for joining a team.
///
/// The entry `password` is a [`Secret`], so it is redacted from [`Debug`].
#[derive(Debug, Serialize)]
struct JoinForm<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    message: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    password: Option<Secret<&'a str>>,
}

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

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

    /// Gets a team by id. `GET /api/team/{teamId}`
    pub async fn get(&self, team_id: &str) -> Result<LichessTeam> {
        let path = format!("/api/team/{}", http::segment(team_id));
        let request = self.client.request(Method::GET, Host::Default, &path);
        http::json(request, "LichessTeam").await
    }

    /// Lists the most popular teams, paginated. `GET /api/team/all`
    pub async fn all(&self, page: u32) -> Result<LichessTeamPaginator> {
        let request = self
            .client
            .request(Method::GET, Host::Default, "/api/team/all")
            .query(&[("page", page)]);
        http::json(request, "LichessTeamPaginator").await
    }

    /// Lists the teams a user belongs to. `GET /api/team/of/{username}`
    pub async fn of_user(&self, username: &str) -> Result<Vec<LichessTeam>> {
        let path = format!("/api/team/of/{}", http::segment(username));
        let request = self.client.request(Method::GET, Host::Default, &path);
        http::json(request, "Vec<LichessTeam>").await
    }

    /// Searches teams by text, paginated. `GET /api/team/search`
    pub async fn search(&self, text: &str, page: u32) -> Result<LichessTeamPaginator> {
        let request = self
            .client
            .request(Method::GET, Host::Default, "/api/team/search")
            .query(&[("text", text), ("page", &page.to_string())]);
        http::json(request, "LichessTeamPaginator").await
    }

    /// Streams the members of a team. `GET /api/team/{teamId}/users`
    ///
    /// `full` includes each member's full profile.
    pub async fn members(
        &self,
        team_id: &str,
        full: Option<bool>,
    ) -> Result<BoxStream<'static, Result<LichessUser>>> {
        let path = format!("/api/team/{}/users", http::segment(team_id));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(&[("full", full)]);
        http::stream(request, self.client.max_line_bytes()).await
    }

    /// Joins a team, optionally with a message and entry password.
    /// `POST /team/{teamId}/join`
    pub async fn join(
        &self,
        team_id: &str,
        message: Option<&str>,
        password: Option<&str>,
    ) -> Result<()> {
        let path = format!("/team/{}/join", http::segment(team_id));
        let request = self
            .client
            .request(Method::POST, Host::Default, &path)
            .form(&JoinForm {
                message,
                password: password.map(Secret::new),
            });
        http::ok(request).await
    }

    /// Leaves a team. `POST /team/{teamId}/quit`
    pub async fn quit(&self, team_id: &str) -> Result<()> {
        let path = format!("/team/{}/quit", http::segment(team_id));
        http::ok(self.client.request(Method::POST, Host::Default, &path)).await
    }

    /// Kicks a member from a team. `POST /api/team/{teamId}/kick/{userId}`
    pub async fn kick(&self, team_id: &str, user_id: &str) -> Result<()> {
        let path = format!(
            "/api/team/{}/kick/{}",
            http::segment(team_id),
            http::segment(user_id)
        );
        http::ok(self.client.request(Method::POST, Host::Default, &path)).await
    }

    /// Posts a team update to all members. `POST /team/{teamId}/pm-all`
    ///
    /// Requires a team leader with the "Updates" permission.
    pub async fn message_all(&self, team_id: &str, message: &str) -> Result<()> {
        let path = format!("/team/{}/pm-all", http::segment(team_id));
        let request = self
            .client
            .request(Method::POST, Host::Default, &path)
            .form(&[("message", message)]);
        http::ok(request).await
    }

    /// Gets recent updates from all teams you have joined, paginated.
    /// `GET /team/updates`
    pub async fn updates(&self, page: u32) -> Result<LichessTeamUpdates> {
        let request = self
            .client
            .request(Method::GET, Host::Default, "/team/updates")
            .query(&[("page", page)]);
        http::json(request, "LichessTeamUpdates").await
    }

    /// Gets recent updates from one team you have joined, paginated.
    /// `GET /team/updates/{teamId}`
    pub async fn team_updates(&self, team_id: &str, page: u32) -> Result<LichessTeamUpdatesOfTeam> {
        let path = format!("/team/updates/{}", http::segment(team_id));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(&[("page", page)]);
        http::json(request, "LichessTeamUpdatesOfTeam").await
    }

    /// Lists pending join requests. `GET /api/team/{teamId}/requests`
    ///
    /// `declined` lists the declined requests instead of the pending ones.
    pub async fn join_requests(
        &self,
        team_id: &str,
        declined: Option<bool>,
    ) -> Result<Vec<LichessTeamRequestWithUser>> {
        let path = format!("/api/team/{}/requests", http::segment(team_id));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(&[("declined", declined)]);
        http::json(request, "Vec<LichessTeamRequestWithUser>").await
    }

    /// Accepts a join request.
    /// `POST /api/team/{teamId}/request/{userId}/accept`
    pub async fn accept_request(&self, team_id: &str, user_id: &str) -> Result<()> {
        let path = format!(
            "/api/team/{}/request/{}/accept",
            http::segment(team_id),
            http::segment(user_id)
        );
        http::ok(self.client.request(Method::POST, Host::Default, &path)).await
    }

    /// Declines a join request.
    /// `POST /api/team/{teamId}/request/{userId}/decline`
    pub async fn decline_request(&self, team_id: &str, user_id: &str) -> Result<()> {
        let path = format!(
            "/api/team/{}/request/{}/decline",
            http::segment(team_id),
            http::segment(user_id)
        );
        http::ok(self.client.request(Method::POST, Host::Default, &path)).await
    }

    /// Streams the arena tournaments of a team (NDJSON).
    /// `GET /api/team/{teamId}/arena`
    pub async fn arena_tournaments(
        &self,
        team_id: &str,
        query: &TeamTournamentQuery<'_>,
    ) -> Result<BoxStream<'static, Result<LichessArena>>> {
        let path = format!("/api/team/{}/arena", http::segment(team_id));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(query);
        http::stream(request, self.client.max_line_bytes()).await
    }

    /// Streams the swiss tournaments of a team (NDJSON).
    /// `GET /api/team/{teamId}/swiss`
    pub async fn swiss_tournaments(
        &self,
        team_id: &str,
        query: &TeamTournamentQuery<'_>,
    ) -> Result<BoxStream<'static, Result<LichessSwiss>>> {
        let path = format!("/api/team/{}/swiss", http::segment(team_id));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(query);
        http::stream(request, self.client.max_line_bytes()).await
    }
}

/// Filter parameters for a team's arena/swiss tournament listings.
#[derive(Debug, Clone, Default, Serialize)]
pub struct TeamTournamentQuery<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    max: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    status: Option<&'a str>,
    #[serde(rename = "createdBy", skip_serializing_if = "Option::is_none")]
    created_by: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<&'a str>,
}

impl<'a> TeamTournamentQuery<'a> {
    /// Maximum number of tournaments to return.
    #[must_use]
    pub fn max(mut self, max: u32) -> Self {
        self.max = Some(max);
        self
    }

    /// Filter by tournament status (`created`, `started`, or `finished`).
    #[must_use]
    pub fn status(mut self, status: &'a str) -> Self {
        self.status = Some(status);
        self
    }

    /// Only tournaments created by this user.
    #[must_use]
    pub fn created_by(mut self, username: &'a str) -> Self {
        self.created_by = Some(username);
        self
    }

    /// Only tournaments whose name contains this text.
    #[must_use]
    pub fn name(mut self, name: &'a str) -> Self {
        self.name = Some(name);
        self
    }
}

impl LichessClient {
    /// Teams API: discover teams and manage membership.
    #[must_use]
    pub fn teams(&self) -> TeamsApi<'_> {
        TeamsApi::new(self)
    }
}

/// A team.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessTeam {
    /// The team id.
    pub id: String,
    /// The team name.
    pub name: String,
    /// The team description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The team flair.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flair: Option<String>,
    /// The primary leader.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub leader: Option<LichessLightUser>,
    /// All team leaders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub leaders: Option<Vec<LichessLightUser>>,
    /// The number of members.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nb_members: Option<u32>,
    /// Whether the team is open to join.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub open: Option<bool>,
    /// Whether the authenticated user has joined.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub joined: Option<bool>,
    /// Whether the authenticated user has a pending join request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested: Option<bool>,
}

/// A paginated list of teams.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessTeamPaginator {
    /// The current page number.
    pub current_page: u32,
    /// The maximum results per page.
    pub max_per_page: u32,
    /// The teams on this page.
    pub current_page_results: Vec<LichessTeam>,
    /// The previous page number, if any.
    #[serde(default)]
    pub previous_page: Option<u32>,
    /// The next page number, if any.
    #[serde(default)]
    pub next_page: Option<u32>,
    /// The total number of results.
    pub nb_results: u32,
    /// The total number of pages.
    pub nb_pages: u32,
}

/// A pending join request on a team.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessTeamRequest {
    /// The team id.
    pub team_id: String,
    /// The requesting user id.
    pub user_id: String,
    /// When the request was made (Unix milliseconds).
    pub date: i64,
    /// The request message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// A join request together with the requesting user's profile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessTeamRequestWithUser {
    /// The request.
    pub request: LichessTeamRequest,
    /// The requesting user.
    pub user: LichessUser,
}

/// A minimal team reference: just enough to identify and display a team.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessLightTeam {
    /// The team id.
    pub id: String,
    /// The team name.
    pub name: String,
    /// The team flair, if set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flair: Option<String>,
}

/// The message carried by a single team update.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessTeamUpdateMessage {
    /// The update id.
    pub id: String,
    /// When the update was posted (Unix milliseconds).
    pub date: i64,
    /// The team leader who posted the update.
    pub sender: LichessLightUser,
    /// The team the update belongs to, when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub team: Option<LichessLightTeam>,
    /// The update text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

/// A single team update together with its read state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessTeamUpdate {
    /// The update message.
    pub msg: LichessTeamUpdateMessage,
    /// Whether the authenticated user has seen the update.
    pub seen: bool,
}

/// A paginated list of team updates.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessTeamUpdatesPager {
    /// The current page number.
    pub current_page: u32,
    /// The maximum results per page.
    pub max_per_page: u32,
    /// The updates on this page.
    pub current_page_results: Vec<LichessTeamUpdate>,
    /// The previous page number, if any.
    #[serde(default)]
    pub previous_page: Option<u32>,
    /// The next page number, if any.
    #[serde(default)]
    pub next_page: Option<u32>,
    /// The total number of results.
    pub nb_results: u32,
    /// The total number of pages.
    pub nb_pages: u32,
}

/// A per-team summary of a member's team-update state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessTeamUpdatesByTeamEntry {
    /// The team the summary is about.
    pub team: LichessLightTeam,
    /// The last update's timestamp (Unix milliseconds).
    ///
    /// Modelled as `i64` for consistency with the other Unix-ms fields, but
    /// note that `schemas/TeamUpdatesByTeam.yaml` declares this one as
    /// `type: number` rather than `type: integer` (unlike
    /// [`LichessTeamUpdateMessage::date`]). Lichess only ever emits whole
    /// milliseconds here, so this holds in practice — but a fractional value
    /// would fail deserialization of the entire response. Switch to `f64` if
    /// that ever shows up.
    pub last: i64,
    /// The number of unread updates in this team.
    pub unread: u32,
}

/// Updates aggregated across every team the user has joined.
/// `GET /team/updates`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessTeamUpdates {
    /// The paginated updates across all joined teams.
    pub updates: LichessTeamUpdatesPager,
    /// Per-team unread summaries.
    pub by_team: Vec<LichessTeamUpdatesByTeamEntry>,
}

/// Updates scoped to a single team the user has joined.
/// `GET /team/updates/{teamId}`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessTeamUpdatesOfTeam {
    /// The team the updates belong to.
    pub team: LichessLightTeam,
    /// Whether the user is subscribed to this team's updates.
    pub subscribed: bool,
    /// The paginated updates for this team.
    pub updates: LichessTeamUpdatesPager,
    /// Per-team unread summaries.
    pub by_team: Vec<LichessTeamUpdatesByTeamEntry>,
}

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

    #[test]
    fn team_tournament_query_serializes_filters() {
        let query = TeamTournamentQuery::default()
            .max(10)
            .status("started")
            .created_by("thibault");
        let encoded = serde_urlencoded::to_string(&query).unwrap();
        assert_eq!(encoded, "max=10&status=started&createdBy=thibault");
        assert_eq!(
            serde_urlencoded::to_string(TeamTournamentQuery::default()).unwrap(),
            ""
        );
    }

    #[test]
    fn join_form_debug_redacts_password() {
        let form = JoinForm {
            message: Some("hi"),
            password: Some(Secret::new("supersecret")),
        };
        let debug = format!("{form:?}");
        assert!(!debug.contains("supersecret"));
        assert!(debug.contains("<redacted>"));
        assert!(debug.contains("hi"));
    }

    #[test]
    fn parses_team() {
        let json = r#"{"id":"coders","name":"Coders","nbMembers":42,"open":true,
            "leader":{"id":"t","name":"T"}}"#;
        let team: LichessTeam = serde_json::from_str(json).unwrap();
        assert_eq!(team.id, "coders");
        assert_eq!(team.nb_members, Some(42));
        assert_eq!(team.leader.unwrap().name, "T");
    }

    #[test]
    fn parses_paginator_with_null_pages() {
        let json = r#"{"currentPage":1,"maxPerPage":15,"currentPageResults":[],
            "previousPage":null,"nextPage":2,"nbResults":30,"nbPages":2}"#;
        let page: LichessTeamPaginator = serde_json::from_str(json).unwrap();
        assert_eq!(page.previous_page, None);
        assert_eq!(page.next_page, Some(2));
    }

    #[test]
    fn parses_request_with_user() {
        let json = r#"{"request":{"userId":"mary","teamId":"t","date":1,"message":"hi"},
            "user":{"id":"mary","username":"Mary"}}"#;
        let req: LichessTeamRequestWithUser = serde_json::from_str(json).unwrap();
        assert_eq!(req.request.user_id, "mary");
        assert_eq!(req.user.username, "Mary");
    }

    #[test]
    fn parses_team_updates() {
        let json = r#"{"updates":{"currentPage":1,"maxPerPage":15,
            "currentPageResults":[{"msg":{"id":"u1","date":1700000000000,
            "sender":{"id":"t","name":"T"},"team":{"id":"coders","name":"Coders"},
            "text":"hello"},"seen":false}],"previousPage":null,"nextPage":null,
            "nbResults":1,"nbPages":1},
            "byTeam":[{"team":{"id":"coders","name":"Coders"},"last":1700000000000,"unread":3}]}"#;
        let updates: LichessTeamUpdates = serde_json::from_str(json).unwrap();
        let first = &updates.updates.current_page_results[0];
        assert_eq!(first.msg.id, "u1");
        assert_eq!(first.msg.sender.name, "T");
        assert!(!first.seen);
        assert_eq!(updates.by_team[0].unread, 3);
    }

    #[test]
    fn parses_team_updates_of_team() {
        let json = r#"{"team":{"id":"coders","name":"Coders"},"subscribed":true,
            "updates":{"currentPage":1,"maxPerPage":15,"currentPageResults":[],
            "previousPage":null,"nextPage":null,"nbResults":0,"nbPages":1},
            "byTeam":[]}"#;
        let of_team: LichessTeamUpdatesOfTeam = serde_json::from_str(json).unwrap();
        assert_eq!(of_team.team.id, "coders");
        assert!(of_team.subscribed);
        assert!(of_team.updates.current_page_results.is_empty());
    }
}