ankit 0.1.0

Complete async Rust client for the AnkiConnect API
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
//! Card-related AnkiConnect actions.
//!
//! This module provides operations for finding and inspecting cards.
//! Note that cards are generated from notes - one note can produce multiple cards.
//!
//! # Example
//!
//! ```no_run
//! use ankit::AnkiClient;
//!
//! # async fn example() -> ankit::Result<()> {
//! let client = AnkiClient::new();
//!
//! // Find cards due today
//! let due_cards = client.cards().find("is:due").await?;
//! println!("Cards due: {}", due_cards.len());
//!
//! // Get card details
//! if !due_cards.is_empty() {
//!     let info = client.cards().info(&due_cards[..5.min(due_cards.len())]).await?;
//!     for card in info {
//!         println!("Card {} in deck {}", card.card_id, card.deck_name);
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use serde::Serialize;

use crate::client::AnkiClient;
use crate::error::Result;
use crate::types::{CardAnswer, CardInfo, CardModTime};

/// Provides access to card-related AnkiConnect operations.
///
/// Obtained via [`AnkiClient::cards()`].
#[derive(Debug)]
pub struct CardActions<'a> {
    pub(crate) client: &'a AnkiClient,
}

// Parameter structs
#[derive(Serialize)]
struct FindCardsParams<'a> {
    query: &'a str,
}

#[derive(Serialize)]
struct CardsInfoParams<'a> {
    cards: &'a [i64],
}

#[derive(Serialize)]
struct SuspendParams<'a> {
    cards: &'a [i64],
}

#[derive(Serialize)]
struct SuspendedParams {
    card: i64,
}

#[derive(Serialize)]
struct GetIntervalsParams<'a> {
    cards: &'a [i64],
    complete: bool,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SetEaseFactorsParams<'a> {
    cards: &'a [i64],
    ease_factors: &'a [i64],
}

#[derive(Serialize)]
struct AnswerCardsParams<'a> {
    answers: &'a [CardAnswer],
}

#[derive(Serialize)]
struct SetDueDateParams<'a> {
    cards: &'a [i64],
    days: &'a str,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SetSpecificValueParams<'a> {
    card: i64,
    keys: &'a [&'a str],
    new_values: &'a [&'a str],
    warning_check: bool,
}

impl<'a> CardActions<'a> {
    /// Find cards matching a query.
    ///
    /// Returns a list of card IDs. Use [`info()`](Self::info) to get full card details.
    ///
    /// # Query Syntax
    ///
    /// Uses Anki's search syntax:
    /// - `deck:DeckName` - cards in a specific deck
    /// - `is:due` - cards that are due
    /// - `is:new` - new cards
    /// - `is:review` - review cards
    /// - `is:suspended` - suspended cards
    /// - `rated:1` - cards rated today
    /// - `-is:suspended` - exclude suspended cards
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ankit::AnkiClient;
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    ///
    /// // Find all due cards in the Japanese deck
    /// let cards = client.cards().find("deck:Japanese is:due").await?;
    /// println!("Found {} due cards", cards.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn find(&self, query: &str) -> Result<Vec<i64>> {
        self.client
            .invoke("findCards", FindCardsParams { query })
            .await
    }

    /// Get detailed information about cards.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ankit::AnkiClient;
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    ///
    /// let card_ids = client.cards().find("is:due").await?;
    /// let cards = client.cards().info(&card_ids).await?;
    ///
    /// for card in cards {
    ///     println!("Card {} (note {}): {} reps, {} lapses",
    ///         card.card_id, card.note_id, card.reps, card.lapses);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn info(&self, card_ids: &[i64]) -> Result<Vec<CardInfo>> {
        self.client
            .invoke("cardsInfo", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Convert card IDs to their corresponding note IDs.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ankit::AnkiClient;
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    /// let card_ids = client.cards().find("is:due").await?;
    /// let note_ids = client.cards().to_notes(&card_ids).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn to_notes(&self, card_ids: &[i64]) -> Result<Vec<i64>> {
        self.client
            .invoke("cardsToNotes", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Get modification times for cards.
    pub async fn mod_time(&self, card_ids: &[i64]) -> Result<Vec<CardModTime>> {
        self.client
            .invoke("cardsModTime", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Suspend cards.
    ///
    /// Suspended cards will not appear in reviews.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ankit::AnkiClient;
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    /// client.cards().suspend(&[1234567890]).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn suspend(&self, card_ids: &[i64]) -> Result<bool> {
        self.client
            .invoke("suspend", SuspendParams { cards: card_ids })
            .await
    }

    /// Unsuspend cards.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ankit::AnkiClient;
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    /// client.cards().unsuspend(&[1234567890]).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn unsuspend(&self, card_ids: &[i64]) -> Result<bool> {
        self.client
            .invoke("unsuspend", SuspendParams { cards: card_ids })
            .await
    }

    /// Check if a single card is suspended.
    ///
    /// Returns `true` if the card is suspended.
    pub async fn is_suspended(&self, card_id: i64) -> Result<bool> {
        self.client
            .invoke("suspended", SuspendedParams { card: card_id })
            .await
    }

    /// Check if multiple cards are suspended.
    ///
    /// Returns `Some(true)` if suspended, `Some(false)` if not, `None` if card doesn't exist.
    pub async fn are_suspended(&self, card_ids: &[i64]) -> Result<Vec<Option<bool>>> {
        self.client
            .invoke("areSuspended", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Check if cards are due for review.
    pub async fn are_due(&self, card_ids: &[i64]) -> Result<Vec<bool>> {
        self.client
            .invoke("areDue", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Get intervals for cards.
    ///
    /// If `complete` is false, returns only the current interval.
    /// If `complete` is true, returns the full interval history.
    pub async fn intervals(
        &self,
        card_ids: &[i64],
        complete: bool,
    ) -> Result<Vec<serde_json::Value>> {
        self.client
            .invoke(
                "getIntervals",
                GetIntervalsParams {
                    cards: card_ids,
                    complete,
                },
            )
            .await
    }

    /// Get ease factors for cards.
    ///
    /// Ease factors are returned as integers (e.g., 2500 = 250%).
    pub async fn get_ease(&self, card_ids: &[i64]) -> Result<Vec<i64>> {
        self.client
            .invoke("getEaseFactors", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Set ease factors for cards.
    ///
    /// Ease factors should be integers (e.g., 2500 = 250%).
    /// Returns success status for each card.
    pub async fn set_ease(&self, card_ids: &[i64], ease_factors: &[i64]) -> Result<Vec<bool>> {
        self.client
            .invoke(
                "setEaseFactors",
                SetEaseFactorsParams {
                    cards: card_ids,
                    ease_factors,
                },
            )
            .await
    }

    /// Forget cards, making them new again.
    ///
    /// This resets the card's learning progress.
    pub async fn forget(&self, card_ids: &[i64]) -> Result<()> {
        self.client
            .invoke_void("forgetCards", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Put cards back into the learning queue.
    pub async fn relearn(&self, card_ids: &[i64]) -> Result<()> {
        self.client
            .invoke_void("relearnCards", CardsInfoParams { cards: card_ids })
            .await
    }

    /// Answer cards programmatically.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit::{AnkiClient, CardAnswer, Ease};
    ///
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    ///
    /// let answers = vec![
    ///     CardAnswer::new(1234567890, Ease::Good),
    ///     CardAnswer::new(1234567891, Ease::Easy),
    /// ];
    ///
    /// let results = client.cards().answer(&answers).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn answer(&self, answers: &[CardAnswer]) -> Result<Vec<bool>> {
        self.client
            .invoke("answerCards", AnswerCardsParams { answers })
            .await
    }

    /// Set the due date for cards.
    ///
    /// The `days` parameter can be:
    /// - A number like `"0"` (due today), `"1"` (due tomorrow), `"-1"` (due yesterday)
    /// - A range like `"0-3"` (randomly between today and 3 days from now)
    /// - An exclamation mark suffix like `"1!"` to set as review cards instead of new
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ankit::AnkiClient;
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    ///
    /// // Make cards due today
    /// client.cards().set_due_date(&[1234567890], "0").await?;
    ///
    /// // Make cards due in 7 days
    /// client.cards().set_due_date(&[1234567890], "7").await?;
    ///
    /// // Make cards due randomly between 1-7 days
    /// client.cards().set_due_date(&[1234567890], "1-7").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_due_date(&self, card_ids: &[i64], days: &str) -> Result<bool> {
        self.client
            .invoke(
                "setDueDate",
                SetDueDateParams {
                    cards: card_ids,
                    days,
                },
            )
            .await
    }

    /// Set specific internal values on a card.
    ///
    /// This is an advanced function for directly manipulating card database fields.
    /// Use with caution as it can corrupt card data if used incorrectly.
    ///
    /// # Arguments
    ///
    /// * `card_id` - The card to modify
    /// * `keys` - Field names to modify (e.g., `["ivl", "due"]`)
    /// * `values` - New values for each field
    /// * `warning_check` - If true, warns about potentially dangerous operations
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ankit::AnkiClient;
    /// # async fn example() -> ankit::Result<()> {
    /// let client = AnkiClient::new();
    ///
    /// // Set the interval to 30 days
    /// client.cards().set_specific_value(
    ///     1234567890,
    ///     &["ivl"],
    ///     &["30"],
    ///     true
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_specific_value(
        &self,
        card_id: i64,
        keys: &[&str],
        values: &[&str],
        warning_check: bool,
    ) -> Result<Vec<bool>> {
        self.client
            .invoke(
                "setSpecificValueOfCard",
                SetSpecificValueParams {
                    card: card_id,
                    keys,
                    new_values: values,
                    warning_check,
                },
            )
            .await
    }
}