anki_bridge 0.10.2

AnkiBridge is a Rust library that provides a bridge between your Rust code and the Anki application, enabling HTTP communication and seamless data transmission.
Documentation
/*
* The MIT License (MIT)
*
* Copyright (c) 2025 Daniél Kerkmann <daniel@kerkmann.dev>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
use serde::Serialize;
use std::collections::HashMap;

use crate::AnkiRequest;
use crate::entities::{NoteId, NoteMedia};

/// Parameters for the "addNote" action.
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AddNoteRequest {
    /// Details of the note being created.
    pub note: AddNoteEntry,
}

/// A new Anki note (also called card).
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddNoteEntry {
    /// Name of the deck where the note will be added.
    pub deck_name: String,
    /// Name of the model inside the deck where the note will be added.
    pub model_name: String,
    /// Fields available in the note.
    #[serde(serialize_with = "crate::serialize::hashmap")]
    pub fields: HashMap<String, String>,
    pub options: AddNoteOptions,
    /// The tags of the note.
    pub tags: Vec<String>,
    /// The audio samples attached to the note.
    pub audio: Vec<NoteMedia>,
    /// The videos attached to the note.
    pub video: Vec<NoteMedia>,
    /// The pictures attached to the note.
    pub picture: Vec<NoteMedia>,
}

/// Extra options for the note.
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddNoteOptions {
    /// Whether to check for duplicate notes.
    pub allow_duplicate: bool,
    /// Specify the scope for which duplicates are checked. A value of "deck" will only check for
    /// duplicates in the target deck; any other value will check the entire collection.
    pub duplicate_scope: AddNoteDuplicateScope,
    /// Additional options to customize the duplicate check.
    pub duplicate_scope_options: AddNoteDuplicateScopeOptions,
}

/// The scope for checking for duplicate files.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AddNoteDuplicateScope {
    #[default]
    Deck,
    Collection,
}

/// Additional options to customize the duplicate check.
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddNoteDuplicateScopeOptions {
    pub deck_name: Option<String>,
    pub check_children: bool,
    pub check_all_models: bool,
}

impl AnkiRequest for AddNoteRequest {
    type Response = NoteId;

    const ACTION: &'static str = "addNote";
    const VERSION: u8 = 6;
}

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

    #[test]
    fn test_serialize() {
        let request = AddNoteRequest {
            note: AddNoteEntry {
                deck_name: "Default".to_string(),
                model_name: "Basic".to_string(),
                fields: HashMap::from([
                    ("Front".to_string(), "What is the capital of France?".to_string()),
                    ("Back".to_string(), "Paris".to_string()),
                ]),
                options: AddNoteOptions {
                    allow_duplicate: false,
                    duplicate_scope: AddNoteDuplicateScope::Deck,
                    duplicate_scope_options: AddNoteDuplicateScopeOptions {
                        deck_name: Some("Default".to_string()),
                        check_children: false,
                        check_all_models: false,
                    },
                },
                tags: vec![
                    "yomichan".to_string()
                ],
                audio: vec![
                    NoteMedia {
                        filename: "yomichan_ねこ_猫.mp3".to_string(),
                        data: None,
                        path: None,
                        url: Some("https://assets.languagepod101.com/dictionary/japanese/audiomp3.php?kanji=猫&kana=ねこ".to_string()),
                        skip_hash: Some("7e2c2f954ef6051373ba916f000168dc".to_string()),
                        fields: vec![
                            "Front".to_string()
                        ],
                    }
                ],
                video: vec![
                    NoteMedia {
                        filename: "countdown.mp4".to_string(),
                        data: None,
                        path: None,
                        url: Some("https://cdn.videvo.net/videvo_files/video/free/2015-06/small_watermarked/Contador_Glam_preview.mp4".to_string()),
                        skip_hash: Some("4117e8aab0d37534d9c8eac362388bbe".to_string()),
                        fields: vec![
                            "Back".to_string()
                        ],
                    }
                ],
                picture: vec![
                    NoteMedia {
                        filename: "black_cat.jpg".to_string(),
                        data: None,
                        path: None,
                        url: Some("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/A_black_cat_named_Tilly.jpg/220px-A_black_cat_named_Tilly.jpg".to_string()),
                        skip_hash: Some("8d6e4646dfae812bf39651b59d7429ce".to_string()),
                        fields: vec![
                            "Back".to_string()
                        ],
                    }
                ],
            }
        };

        let json = serde_json::to_string_pretty(&request).unwrap();
        assert_eq!(
            json,
            r#"{
  "note": {
    "deckName": "Default",
    "modelName": "Basic",
    "fields": {
      "Back": "Paris",
      "Front": "What is the capital of France?"
    },
    "options": {
      "allowDuplicate": false,
      "duplicateScope": "deck",
      "duplicateScopeOptions": {
        "deckName": "Default",
        "checkChildren": false,
        "checkAllModels": false
      }
    },
    "tags": [
      "yomichan"
    ],
    "audio": [
      {
        "filename": "yomichan_ねこ_猫.mp3",
        "fields": [
          "Front"
        ],
        "url": "https://assets.languagepod101.com/dictionary/japanese/audiomp3.php?kanji=猫&kana=ねこ",
        "skipHash": "7e2c2f954ef6051373ba916f000168dc"
      }
    ],
    "video": [
      {
        "filename": "countdown.mp4",
        "fields": [
          "Back"
        ],
        "url": "https://cdn.videvo.net/videvo_files/video/free/2015-06/small_watermarked/Contador_Glam_preview.mp4",
        "skipHash": "4117e8aab0d37534d9c8eac362388bbe"
      }
    ],
    "picture": [
      {
        "filename": "black_cat.jpg",
        "fields": [
          "Back"
        ],
        "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/A_black_cat_named_Tilly.jpg/220px-A_black_cat_named_Tilly.jpg",
        "skipHash": "8d6e4646dfae812bf39651b59d7429ce"
      }
    ]
  }
}"#
        );
    }

    #[test]
    fn test_deserialize() {
        let json = "1496198395707";
        let response: <AddNoteRequest as AnkiRequest>::Response =
            serde_json::from_str(json).unwrap();

        assert_eq!(response, 1496198395707);
    }
}