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 "updateNoteFields" action.
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
pub struct UpdateNoteFieldsRequest {
    /// The note to update.
    pub note: UpdateNoteFieldsEntry,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
pub struct UpdateNoteFieldsEntry {
    /// ID of the note to update.
    ///
    /// A [CardId](crate::entities::CardId) can also be used.
    pub id: NoteId,
    /// New fields for the note. Leave empty to keep the old fields. Fields that are not already
    /// part of the note will not be added.
    #[serde(serialize_with = "crate::serialize::hashmap")]
    pub fields: HashMap<String, String>,
    /// Optional audio files to add to the note.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub audio: Vec<NoteMedia>,
    /// Optional video files to add to the note.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub video: Vec<NoteMedia>,
    /// Optional picture files to add to the note.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub picture: Vec<NoteMedia>,
}

impl AnkiRequest for UpdateNoteFieldsRequest {
    type Response = ();

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

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

    #[test]
    fn test_serialize() {
        let request = UpdateNoteFieldsRequest {
            note: UpdateNoteFieldsEntry {
                id: 1514547547030,
                fields: HashMap::from([
                    ("Front".to_string(), "new front content".to_string()),
                    ("Back".to_string(), "new back content".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": {
    "id": 1514547547030,
    "fields": {
      "Back": "new back content",
      "Front": "new front content"
    },
    "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_serialize_no_media() {
        let request = UpdateNoteFieldsRequest {
            note: UpdateNoteFieldsEntry {
                id: 1514547547030,
                ..Default::default()
            },
        };

        let json = serde_json::to_string_pretty(&request).unwrap();
        assert_eq!(
            json,
            r#"{
  "note": {
    "id": 1514547547030,
    "fields": {}
  }
}"#
        );
    }
}