anki_direct 0.1.0

A Simple Rust library for 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::{borrow::Cow, collections::HashMap};

use derive_builder::Builder;
use futures::future::try_join_all;
use indexmap::IndexMap;
use num_traits::PrimInt;
use serde::{Deserialize, Serialize};

use crate::{
    error::AnkiError,
    generic::{GenericRequest, GenericRequestBuilder},
    notes::NoteBuilder,
    ModelsProxy, Number,
};

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum NoteType {
    Regular(RegNoteType),
    Cloze(ClozeNoteType),
}

#[derive(Clone, Debug, Serialize, Deserialize, Builder)]
pub struct RegNoteType {
    #[builder(setter(custom))]
    pub id: Number,
    pub name: String,
    pub fields: Vec<String>,
    pub card_templates: Vec<CardTemplate>,
}
impl RegNoteTypeBuilder {
    /// Custom setter for the `id` field.
    /// This method is NOT generated by derive_builder. We wrote it.
    /// It can be generic to accept any primitive integer.
    pub fn id(&mut self, val: impl PrimInt) -> &mut Self {
        self.id = Some(Number::new(val));
        self
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Builder)]
pub struct ClozeNoteType {
    #[builder(setter(custom))]
    pub id: Number,
    pub name: String,
    pub fields: Vec<String>,
    pub card_template: CardTemplate,
}
impl ClozeNoteTypeBuilder {
    /// Custom setter for the `id` field.
    /// This method is NOT generated by derive_builder. We wrote it.
    /// It can be generic to accept any primitive integer.
    pub fn id(&mut self, val: impl PrimInt) -> &mut Self {
        self.id = Some(Number::new(val));
        self
    }
}

// In anki::models::card_template
#[derive(Clone, Debug, Serialize, Deserialize, Builder, Default)]
pub struct CardTemplate {
    pub name: String,
    // HTML template
    pub front: String,
    // HTML template
    pub back: String,
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct ModelTemplates {
    // The API returns a dictionary where the key is the card template name.
    #[serde(flatten)]
    pub inner: IndexMap<String, TemplateInfo>,
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct TemplateInfo {
    #[serde(rename = "Front")]
    pub front: String,
    #[serde(rename = "Back")]
    pub back: String,
}
// Result for "modelStyling"
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ModelStyling {
    pub css: String,
    #[serde(default)]
    pub is_cloze: bool,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ModelDetails {
    Less(LessModelDetails),
    Full(FullModelDetails),
}

trait IntoNoteBuilder {
    fn note_builder(&self) -> NoteBuilder;
}

/// Version of [FullModelDetails] that excludes the `templates` & `styling` fields
/// It's recommended to use this as `<T>` if you only need the name and fields as it doesn't need to make extra requests
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LessModelDetails {
    pub name: String,
    pub fields: Vec<String>,
}
impl From<FullModelDetails> for LessModelDetails {
    fn from(details: FullModelDetails) -> Self {
        let FullModelDetails { name, fields, .. } = details;
        LessModelDetails { name, fields }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FullModelDetails {
    pub name: String,
    pub fields: Vec<String>,
    pub templates: ModelTemplates,
    pub styling: ModelStyling,
}
impl FullModelDetails {
    /// A convenient helper to know if this model is a Cloze type.
    pub fn is_cloze(&self) -> bool {
        self.styling.is_cloze
    }

    /// Creates a mock [FullModelDetails] object for testing.
    ///
    /// This data is a simplified but structurally accurate representation
    /// of a real Japanese vocabulary model
    /// It's useful for testing functions that process or interact with Anki models
    /// without making requests or needing async.
    pub fn mock() -> Self {
        FullModelDetails {
            name: "JapaneseVocab".to_string(),
            fields: vec![
                "Sentence".to_string(),
                "Reading".to_string(),
                "Definition".to_string(),
                "WordAudio".to_string(),
                "Picture".to_string(),
            ],
            templates: ModelTemplates {
                inner: IndexMap::from([(
                    // A single card template named "Recognition"
                    "Recognition".to_string(),
                    TemplateInfo {
                        // The front of the card just shows the sentence
                        front: "<div class='sentence'>{{Sentence}}</div>".to_string(),
                        // The back shows the answer
                        back: r#"
                            {{FrontSide}}
                            <hr id="answer">
                            <div class="picture">{{Picture}}</div>
                            <div class="reading">{{Reading}}</div>
                            <div class="definition">{{Definition}}</div>
                            <div class="audio">{{WordAudio}}</div>
                        "#
                        .to_string(),
                    },
                )]),
            },
            styling: ModelStyling {
                // CSS is simplified but styles the classes used in the template
                css: r#"
                    .card {
                        font-family: "Noto Sans JP", sans-serif;
                        background-color: #121511;
                        color: white;
                        text-align: center;
                        border-radius: 10px;
                        padding: 1em;
                    }

                    .sentence {
                        font-size: 2rem;
                        margin-bottom: 1rem;
                    }

                    .reading {
                        font-size: 1.5rem;
                        color: #89daff; /* a color from your real css */
                    }

                    .definition {
                        margin-top: 1rem;
                        font-size: 1.2rem;
                    }

                    img {
                        max-width: 200px;
                        border-radius: 5px;
                    }
                "#
                .to_string(),
                // This model type is not a cloze deletion
                is_cloze: false,
            },
        }
    }

    /// Finds templates by their names and returns an iterator
    pub fn find_templates_by_names<'a>(
        &'a self,
        template_names: &'a [&str],
    ) -> impl Iterator<Item = (&'a str, &'a TemplateInfo)> {
        template_names.iter().filter_map(move |name| {
            self.templates
                .inner
                .get_key_value(*name)
                .map(|(k, v)| (k.as_str(), v))
        })
    }
}

#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct ModelNameParams {
    model_name: String,
}

impl ModelsProxy {
    /// Returns: `Map<(name, id)>`
    /// `See:` [ankiconnect/modelNamesAndIds](https://git.sr.ht/~foosoft/anki-connect#codemodelnamesandidscode)
    async fn get_all_model_names_and_ids(&self) -> Result<IndexMap<String, Number>, AnkiError> {
        type ModelsResult = IndexMap<String, Number>;
        let payload: GenericRequest<()> = GenericRequestBuilder::default()
            .action("modelNamesAndIds".into())
            .version(self.version)
            .build()
            .unwrap();
        self.post_generic_request::<ModelsResult>(payload).await
    }

    /// Get all models found in current anki session.
    /// Returns: `Map<(name, details)>`
    ///
    /// # Example
    ///
    /// This function can be used to update a cache:
    /// ```no_run
    /// #[derive(Default)]
    /// struct ModelCache(IndexMap<String, LessModelDetails);
    ///
    /// static CACHE: LazyLock<RwLock<ModelCache>> = LazyLock::new(|| {
    ///     ModelCache::default().into()
    /// })
    ///
    /// impl ModelCache {
    ///     async fn update() {
    ///         let ac = AnkiClient::default_latest();
    ///         let latest = ac.get_all_models_less().await.expect("u have no models");
    ///         let mut cache = CACHE.write().unwrap();
    ///         cache = latest;
    ///     }
    /// }
    /// ```
    pub async fn get_all_models_less(
        &self,
    ) -> Result<IndexMap<String, LessModelDetails>, AnkiError> {
        let indexmap = self.get_all_model_names_and_ids().await?;
        let futures = indexmap
            .into_iter()
            .map(move |(name, _id)| self.get_less_model_details_by_name(name.into()));
        let details = try_join_all(futures.into_iter()).await?;
        let res: IndexMap<String, LessModelDetails> =
            details.into_iter().map(|d| (d.name.clone(), d)).collect();
        Ok(res)
    }

    // Get all models found in current anki session.
    /// Returns: `Map<(name, details)>`
    ///
    /// # Example
    ///
    /// This function can be used to update a cache:
    /// ```no_run
    /// #[derive(Default)]
    /// struct ModelCache(IndexMap<String, LessModelDetails);
    ///
    /// static CACHE: LazyLock<RwLock<ModelCache>> = LazyLock::new(|| {
    ///     ModelCache::default().into()
    /// })
    ///
    /// impl ModelCache {
    ///     async fn update() {
    ///         let ac = AnkiClient::default_latest();
    ///         let latest = ac.get_all_models_full().await.expect("u have no models");
    ///         let mut cache = CACHE.write().unwrap();
    ///         cache = latest;
    ///     }
    /// }
    /// ```
    pub async fn get_all_models_full(
        &self,
    ) -> Result<IndexMap<String, FullModelDetails>, AnkiError> {
        let indexmap = self.get_all_model_names_and_ids().await?;
        let futures = indexmap
            .into_iter()
            .map(move |(name, _id)| self.get_full_model_details_by_name(name.into()));
        let details = try_join_all(futures.into_iter()).await?;
        let res: IndexMap<String, FullModelDetails> =
            details.into_iter().map(|d| (d.name.clone(), d)).collect();
        Ok(res)
    }

    /// Fetches the complete list of field names for the provided model name.
    /// https://git.sr.ht/~foosoft/anki-connect#codemodelfieldnamescode
    pub async fn get_model_field_names(&self, model_name: &str) -> Result<Vec<String>, AnkiError> {
        let params = ModelNameParams {
            model_name: model_name.to_string(),
        };
        let payload: GenericRequest<_> = GenericRequestBuilder::default()
            .action("modelFieldNames".into())
            .version(self.version)
            .params(Some(params))
            .build()
            .unwrap();
        self.post_generic_request(payload).await
    }

    /// Fetches the card templates for the provided model name.
    /// Corresponds to the "modelTemplates" action.
    pub async fn get_model_templates(&self, model_name: &str) -> Result<ModelTemplates, AnkiError> {
        let params = ModelNameParams {
            model_name: model_name.to_string(),
        };
        let payload: GenericRequest<_> = GenericRequestBuilder::default()
            .action("modelTemplates".into())
            .version(self.version)
            .params(Some(params))
            .build()
            .unwrap();
        self.post_generic_request(payload).await
    }

    /// Fetches the CSS styling and cloze status for the provided model name.
    /// Corresponds to the "modelStyling" action.
    pub async fn get_model_styling(&self, model_name: &str) -> Result<ModelStyling, AnkiError> {
        let params = ModelNameParams {
            model_name: model_name.to_string(),
        };
        let payload: GenericRequest<_> = GenericRequestBuilder::default()
            .action("modelStyling".into())
            .version(self.version)
            .params(Some(params))
            .build()
            .unwrap();
        self.post_generic_request(payload).await
    }

    /// Fetches all the details for a model by concurrently calling:
    /// [Self::get_model_field_names]
    /// [Self::get_model_templates]
    /// [Self::get_model_styling]
    pub async fn get_full_model_details_by_name(
        &self,
        model_name: Cow<'_, str>,
    ) -> Result<FullModelDetails, AnkiError> {
        let model_name = model_name.into_owned();
        let (fields, templates, styling) = tokio::try_join!(
            self.get_model_field_names(&model_name),
            self.get_model_templates(&model_name),
            self.get_model_styling(&model_name)
        )?;

        Ok(FullModelDetails {
            name: model_name.to_string(),
            fields,
            templates,
            styling,
        })
    }

    pub async fn get_less_model_details_by_name(
        &self,
        model_name: Cow<'_, str>,
    ) -> Result<LessModelDetails, AnkiError> {
        let fields = self.get_model_field_names(&model_name).await?;
        Ok(LessModelDetails {
            name: model_name.into_owned(),
            fields,
        })
    }
}

#[cfg(test)]
mod modeltests {
    use crate::{error::AnkiResult, test_utils::ANKICLIENT};

    #[tokio::test]
    async fn get_all_model_names_and_ids() {
        let res = ANKICLIENT
            .models()
            .get_all_model_names_and_ids()
            .await
            .unwrap();
        assert!(!res.is_empty());
        dbg!(res);
    }

    #[tokio::test]
    async fn get_full_model_details() {
        let res = ANKICLIENT
            .models()
            .get_all_model_names_and_ids()
            .await
            .unwrap();
        assert!(!res.is_empty());
        let first = res.first().unwrap();
        let res = ANKICLIENT
            .models()
            .get_full_model_details_by_name(first.0.into())
            .await
            .map_err(|e| e.pretty_panic())
            .unwrap();
        dbg!(res);
    }

    #[tokio::test]
    async fn get_less_model_details() -> AnkiResult<()> {
        let res = ANKICLIENT.models().get_all_model_names_and_ids().await?;
        assert!(!res.is_empty());
        let first = res.first().unwrap();
        let res = ANKICLIENT
            .models()
            .get_less_model_details_by_name(first.0.into())
            .await?;
        dbg!(res);
        Ok(())
    }

    #[tokio::test]
    async fn get_all_models_less() {
        let res = ANKICLIENT.models().get_all_models_less().await.unwrap();
        assert!(!res.is_empty());
        dbg!(res);
    }
}