ankit_builder/connect.rs
1//! AnkiConnect import functionality.
2//!
3//! This module provides [`ConnectImporter`] for importing deck definitions directly
4//! into a running Anki instance via AnkiConnect.
5//!
6//! # Requirements
7//!
8//! - Anki must be running
9//! - The [AnkiConnect](https://foosoft.net/projects/anki-connect/) add-on must be installed
10//! - Note types (models) referenced in the definition must already exist in Anki
11//!
12//! # Example
13//!
14//! ```no_run
15//! use ankit_builder::{ConnectImporter, DeckDefinition};
16//!
17//! # async fn example() -> ankit_builder::Result<()> {
18//! let definition = DeckDefinition::from_file("vocabulary.toml")?;
19//! let importer = ConnectImporter::new(definition);
20//!
21//! // Optionally validate before importing
22//! let missing_models = importer.validate_models().await?;
23//! if !missing_models.is_empty() {
24//! eprintln!("Missing models: {:?}", missing_models);
25//! return Ok(());
26//! }
27//!
28//! let result = importer.import().await?;
29//! println!("Created {} notes", result.notes_created);
30//! # Ok(())
31//! # }
32//! ```
33
34use std::collections::HashMap;
35
36use ankit::{AnkiClient, NoteBuilder};
37
38use crate::error::{Error, Result};
39use crate::schema::DeckDefinition;
40
41/// Imports deck definitions into Anki via AnkiConnect.
42///
43/// `ConnectImporter` handles the live import of notes into a running Anki
44/// instance. It automatically creates missing decks but requires that all
45/// referenced note types (models) already exist.
46///
47/// # Import Methods
48///
49/// - [`import()`](Self::import): Adds notes one at a time (safer, better error tracking)
50/// - [`import_batch()`](Self::import_batch): Adds all notes in a single call (faster)
51///
52/// # Validation
53///
54/// Use [`validate_models()`](Self::validate_models) and [`validate_decks()`](Self::validate_decks)
55/// to check prerequisites before importing.
56pub struct ConnectImporter {
57 definition: DeckDefinition,
58 client: AnkiClient,
59}
60
61/// Result of an import operation.
62#[derive(Debug, Clone)]
63pub struct ImportResult {
64 /// Number of decks created.
65 pub decks_created: usize,
66 /// Number of notes created.
67 pub notes_created: usize,
68 /// Number of notes skipped (duplicates or errors).
69 pub notes_skipped: usize,
70 /// Errors encountered (note index -> error message).
71 pub errors: HashMap<usize, String>,
72}
73
74impl ConnectImporter {
75 /// Create a new importer from a deck definition.
76 pub fn new(definition: DeckDefinition) -> Self {
77 Self {
78 definition,
79 client: AnkiClient::new(),
80 }
81 }
82
83 /// Create a new importer with a custom AnkiConnect client.
84 pub fn with_client(definition: DeckDefinition, client: AnkiClient) -> Self {
85 Self { definition, client }
86 }
87
88 /// Import the deck definition into Anki.
89 ///
90 /// This will:
91 /// 1. Create any missing decks
92 /// 2. Add all notes (using existing models)
93 ///
94 /// Note: Models must already exist in Anki. This method does not create models.
95 pub async fn import(&self) -> Result<ImportResult> {
96 let mut result = ImportResult {
97 decks_created: 0,
98 notes_created: 0,
99 notes_skipped: 0,
100 errors: HashMap::new(),
101 };
102
103 // Create decks if they don't exist
104 let existing_decks = self.client.decks().names().await?;
105 for deck in &self.definition.decks {
106 if !existing_decks.contains(&deck.name) {
107 self.client.decks().create(&deck.name).await?;
108 result.decks_created += 1;
109 }
110 }
111
112 // Verify models exist
113 let existing_models = self.client.models().names().await?;
114 for model in &self.definition.models {
115 if !existing_models.contains(&model.name) {
116 return Err(Error::ModelNotFound(format!(
117 "Model '{}' does not exist in Anki. Create it manually first.",
118 model.name
119 )));
120 }
121 }
122
123 // Add notes
124 for (i, note_def) in self.definition.notes.iter().enumerate() {
125 let mut builder = NoteBuilder::new(¬e_def.deck, ¬e_def.model);
126
127 // Get markdown fields for this model
128 let markdown_fields = self
129 .definition
130 .get_model(¬e_def.model)
131 .map(|m| m.markdown_fields.clone())
132 .unwrap_or_default();
133
134 // Convert markdown to HTML for markdown fields
135 let fields = note_def.fields_as_html(&markdown_fields);
136
137 for (field, value) in &fields {
138 builder = builder.field(field, value);
139 }
140
141 for tag in ¬e_def.tags {
142 builder = builder.tag(tag);
143 }
144
145 let note = builder.build();
146
147 match self.client.notes().add(note).await {
148 Ok(_) => {
149 result.notes_created += 1;
150 }
151 Err(e) => {
152 result.notes_skipped += 1;
153 result.errors.insert(i, e.to_string());
154 }
155 }
156 }
157
158 Ok(result)
159 }
160
161 /// Import notes in batches for better performance.
162 ///
163 /// Note: Models must already exist in Anki. This method does not create models.
164 pub async fn import_batch(&self) -> Result<ImportResult> {
165 let mut result = ImportResult {
166 decks_created: 0,
167 notes_created: 0,
168 notes_skipped: 0,
169 errors: HashMap::new(),
170 };
171
172 // Create decks if they don't exist
173 let existing_decks = self.client.decks().names().await?;
174 for deck in &self.definition.decks {
175 if !existing_decks.contains(&deck.name) {
176 self.client.decks().create(&deck.name).await?;
177 result.decks_created += 1;
178 }
179 }
180
181 // Verify models exist
182 let existing_models = self.client.models().names().await?;
183 for model in &self.definition.models {
184 if !existing_models.contains(&model.name) {
185 return Err(Error::ModelNotFound(format!(
186 "Model '{}' does not exist in Anki. Create it manually first.",
187 model.name
188 )));
189 }
190 }
191
192 // Build notes for batch add
193 let notes: Vec<_> = self
194 .definition
195 .notes
196 .iter()
197 .map(|note_def| {
198 let mut builder = NoteBuilder::new(¬e_def.deck, ¬e_def.model);
199
200 // Get markdown fields for this model
201 let markdown_fields = self
202 .definition
203 .get_model(¬e_def.model)
204 .map(|m| m.markdown_fields.clone())
205 .unwrap_or_default();
206
207 // Convert markdown to HTML for markdown fields
208 let fields = note_def.fields_as_html(&markdown_fields);
209
210 for (field, value) in &fields {
211 builder = builder.field(field, value);
212 }
213 for tag in ¬e_def.tags {
214 builder = builder.tag(tag);
215 }
216 builder.build()
217 })
218 .collect();
219
220 // Add notes in batch
221 let results = self.client.notes().add_many(¬es).await?;
222
223 for (i, note_result) in results.iter().enumerate() {
224 match note_result {
225 Some(_) => result.notes_created += 1,
226 None => {
227 result.notes_skipped += 1;
228 result.errors.insert(i, "Failed to add note".to_string());
229 }
230 }
231 }
232
233 Ok(result)
234 }
235
236 /// Check if all required models exist in Anki.
237 ///
238 /// Returns a list of model names that are defined in the TOML but do not
239 /// exist in Anki. An empty list means all models are available.
240 ///
241 /// Unlike decks, models cannot be created automatically and must exist
242 /// before import. Use this to warn users or fail early.
243 ///
244 /// # Example
245 ///
246 /// ```no_run
247 /// use ankit_builder::{ConnectImporter, DeckDefinition};
248 ///
249 /// # async fn example() -> ankit_builder::Result<()> {
250 /// let definition = DeckDefinition::from_file("deck.toml")?;
251 /// let importer = ConnectImporter::new(definition);
252 ///
253 /// let missing = importer.validate_models().await?;
254 /// if !missing.is_empty() {
255 /// eprintln!("Please create these note types in Anki first:");
256 /// for model in &missing {
257 /// eprintln!(" - {}", model);
258 /// }
259 /// }
260 /// # Ok(())
261 /// # }
262 /// ```
263 pub async fn validate_models(&self) -> Result<Vec<String>> {
264 let existing_models = self.client.models().names().await?;
265 let missing: Vec<String> = self
266 .definition
267 .models
268 .iter()
269 .filter(|m| !existing_models.contains(&m.name))
270 .map(|m| m.name.clone())
271 .collect();
272 Ok(missing)
273 }
274
275 /// Check if all required decks exist in Anki.
276 ///
277 /// Returns a list of deck names that are defined in the TOML but do not
278 /// exist in Anki. An empty list means all decks are available.
279 ///
280 /// Note that [`import()`](Self::import) automatically creates missing decks,
281 /// so this is mainly useful for informational purposes.
282 ///
283 /// # Example
284 ///
285 /// ```no_run
286 /// use ankit_builder::{ConnectImporter, DeckDefinition};
287 ///
288 /// # async fn example() -> ankit_builder::Result<()> {
289 /// let definition = DeckDefinition::from_file("deck.toml")?;
290 /// let importer = ConnectImporter::new(definition);
291 ///
292 /// let missing = importer.validate_decks().await?;
293 /// if !missing.is_empty() {
294 /// println!("Will create {} new decks", missing.len());
295 /// }
296 /// # Ok(())
297 /// # }
298 /// ```
299 pub async fn validate_decks(&self) -> Result<Vec<String>> {
300 let existing_decks = self.client.decks().names().await?;
301 let missing: Vec<String> = self
302 .definition
303 .decks
304 .iter()
305 .filter(|d| !existing_decks.contains(&d.name))
306 .map(|d| d.name.clone())
307 .collect();
308 Ok(missing)
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn test_import_result_default() {
318 let result = ImportResult {
319 decks_created: 0,
320 notes_created: 0,
321 notes_skipped: 0,
322 errors: HashMap::new(),
323 };
324 assert_eq!(result.decks_created, 0);
325 }
326}