use std::collections::HashMap;
use ankit::AnkiClient;
use serde::Serialize;
use crate::diff::{DeckDiff, DeckDiffer, FieldChange, TagChanges};
use crate::error::Result;
use crate::schema::{DeckDefinition, NoteDef};
#[derive(Debug, Clone)]
pub struct SyncStrategy {
pub conflict_resolution: ConflictResolution,
pub pull_new_notes: bool,
pub push_new_notes: bool,
pub update_tags: bool,
}
impl Default for SyncStrategy {
fn default() -> Self {
Self {
conflict_resolution: ConflictResolution::Skip,
pull_new_notes: false,
push_new_notes: true,
update_tags: true,
}
}
}
impl SyncStrategy {
pub fn push_only() -> Self {
Self {
conflict_resolution: ConflictResolution::PreferToml,
pull_new_notes: false,
push_new_notes: true,
update_tags: true,
}
}
pub fn pull_only() -> Self {
Self {
conflict_resolution: ConflictResolution::PreferAnki,
pull_new_notes: true,
push_new_notes: false,
update_tags: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConflictResolution {
PreferToml,
PreferAnki,
Fail,
#[default]
Skip,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SyncPlan {
pub to_push: Vec<SyncNote>,
pub to_pull: Vec<SyncNote>,
pub conflicts: Vec<SyncConflict>,
pub unchanged: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct SyncNote {
pub note_id: Option<i64>,
pub model: String,
pub deck: String,
pub first_field: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct SyncConflict {
pub note_id: i64,
pub first_field: String,
pub model: String,
pub field_changes: Vec<FieldChange>,
pub tag_changes: TagChanges,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SyncResult {
pub pushed: Vec<SyncedNote>,
pub pulled: Vec<SyncedNote>,
pub resolved_conflicts: Vec<ResolvedConflict>,
pub skipped_conflicts: Vec<SyncConflict>,
pub errors: Vec<SyncError>,
pub updated_definition: Option<DeckDefinition>,
}
#[derive(Debug, Clone, Serialize)]
pub struct SyncedNote {
pub note_id: i64,
pub first_field: String,
pub was_new: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct ResolvedConflict {
pub note_id: i64,
pub first_field: String,
pub resolution: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct SyncError {
pub description: String,
pub first_field: Option<String>,
pub error: String,
}
pub struct DeckSyncer<'a> {
client: &'a AnkiClient,
definition: DeckDefinition,
}
impl<'a> DeckSyncer<'a> {
pub fn new(client: &'a AnkiClient, definition: DeckDefinition) -> Self {
Self { client, definition }
}
pub async fn plan(&self) -> Result<SyncPlan> {
let differ = DeckDiffer::new(self.client, &self.definition);
let diff = differ.diff().await?;
Ok(self.diff_to_plan(diff))
}
fn diff_to_plan(&self, diff: DeckDiff) -> SyncPlan {
let mut plan = SyncPlan {
unchanged: diff.unchanged,
..Default::default()
};
for note in diff.toml_only {
plan.to_push.push(SyncNote {
note_id: None,
model: note.model,
deck: note.deck,
first_field: note.first_field,
});
}
for note in diff.anki_only {
plan.to_pull.push(SyncNote {
note_id: note.note_id,
model: note.model,
deck: note.deck,
first_field: note.first_field,
});
}
for modified in diff.modified {
plan.conflicts.push(SyncConflict {
note_id: modified.note_id,
first_field: modified.first_field,
model: modified.model,
field_changes: modified.field_changes,
tag_changes: modified.tag_changes,
});
}
plan
}
pub async fn sync(mut self, strategy: SyncStrategy) -> Result<SyncResult> {
let differ = DeckDiffer::new(self.client, &self.definition);
let diff = differ.diff().await?;
let mut result = SyncResult::default();
let mut definition_modified = false;
if strategy.push_new_notes {
for note_diff in &diff.toml_only {
match self.push_new_note(note_diff).await {
Ok(note_id) => {
self.update_note_id(¬e_diff.first_field, ¬e_diff.model, note_id);
definition_modified = true;
result.pushed.push(SyncedNote {
note_id,
first_field: note_diff.first_field.clone(),
was_new: true,
});
}
Err(e) => {
result.errors.push(SyncError {
description: "Failed to push new note".to_string(),
first_field: Some(note_diff.first_field.clone()),
error: e.to_string(),
});
}
}
}
}
if strategy.pull_new_notes {
for note_diff in &diff.anki_only {
if let Some(note_id) = note_diff.note_id {
match self.pull_note(note_id, ¬e_diff.deck).await {
Ok(note_def) => {
self.definition.notes.push(note_def);
definition_modified = true;
result.pulled.push(SyncedNote {
note_id,
first_field: note_diff.first_field.clone(),
was_new: true,
});
}
Err(e) => {
result.errors.push(SyncError {
description: "Failed to pull note".to_string(),
first_field: Some(note_diff.first_field.clone()),
error: e.to_string(),
});
}
}
}
}
}
for modified in diff.modified {
let conflict = SyncConflict {
note_id: modified.note_id,
first_field: modified.first_field.clone(),
model: modified.model.clone(),
field_changes: modified.field_changes.clone(),
tag_changes: modified.tag_changes.clone(),
};
match strategy.conflict_resolution {
ConflictResolution::Fail => {
return Err(crate::error::Error::SyncConflict(format!(
"Conflict on note '{}' - use a different conflict resolution strategy",
modified.first_field
)));
}
ConflictResolution::Skip => {
result.skipped_conflicts.push(conflict);
}
ConflictResolution::PreferToml => {
match self
.push_updates(
modified.note_id,
&modified.model,
&modified.field_changes,
&strategy,
)
.await
{
Ok(_) => {
result.resolved_conflicts.push(ResolvedConflict {
note_id: modified.note_id,
first_field: modified.first_field,
resolution: "Pushed TOML values to Anki".to_string(),
});
}
Err(e) => {
result.errors.push(SyncError {
description: "Failed to push conflict resolution".to_string(),
first_field: Some(conflict.first_field.clone()),
error: e.to_string(),
});
result.skipped_conflicts.push(conflict);
}
}
}
ConflictResolution::PreferAnki => {
self.update_definition_from_anki(
&modified.first_field,
&modified.model,
&modified.field_changes,
&modified.tag_changes,
);
definition_modified = true;
result.resolved_conflicts.push(ResolvedConflict {
note_id: modified.note_id,
first_field: modified.first_field,
resolution: "Updated TOML with Anki values".to_string(),
});
}
}
}
if definition_modified {
result.updated_definition = Some(self.definition);
}
Ok(result)
}
async fn push_new_note(&self, note_diff: &crate::diff::NoteDiff) -> Result<i64> {
let note_def = self
.definition
.notes
.iter()
.find(|n| {
let model = self.definition.get_model(&n.model);
if let Some(model) = model {
if let Some(first_field_name) = model.fields.first() {
let first_field =
n.fields.get(first_field_name).cloned().unwrap_or_default();
return first_field == note_diff.first_field && n.model == note_diff.model;
}
}
false
})
.ok_or_else(|| {
crate::error::Error::InvalidDefinition(format!(
"Note '{}' not found in definition",
note_diff.first_field
))
})?;
let markdown_fields = self
.definition
.get_model(¬e_def.model)
.map(|m| m.markdown_fields.clone())
.unwrap_or_default();
let fields = note_def.fields_as_html(&markdown_fields);
let note =
ankit::NoteBuilder::new(¬e_def.deck, ¬e_def.model).tags(note_def.tags.clone());
let mut note = note;
for (field, value) in &fields {
note = note.field(field, value);
}
let note_id = self.client.notes().add(note.build()).await?;
Ok(note_id)
}
async fn pull_note(&self, note_id: i64, deck: &str) -> Result<NoteDef> {
let note_infos = self.client.notes().info(&[note_id]).await?;
let note_info = note_infos.into_iter().next().ok_or_else(|| {
crate::error::Error::InvalidDefinition(format!("Note {} not found in Anki", note_id))
})?;
let fields: HashMap<String, String> = note_info
.fields
.into_iter()
.map(|(name, field)| (name, field.value))
.collect();
let mut note_def = NoteDef {
deck: deck.to_string(),
model: note_info.model_name.clone(),
fields,
tags: note_info.tags,
guid: None,
note_id: Some(note_id),
};
let markdown_fields = self
.definition
.get_model(¬e_info.model_name)
.map(|m| m.markdown_fields.clone())
.unwrap_or_default();
note_def.convert_html_to_markdown(&markdown_fields);
Ok(note_def)
}
async fn push_updates(
&self,
note_id: i64,
model_name: &str,
field_changes: &[FieldChange],
strategy: &SyncStrategy,
) -> Result<()> {
let markdown_fields = self
.definition
.get_model(model_name)
.map(|m| m.markdown_fields.clone())
.unwrap_or_default();
let fields: HashMap<String, String> = field_changes
.iter()
.map(|fc| {
let value = if markdown_fields.contains(&fc.field) {
crate::markdown::markdown_to_html(&fc.toml_value)
} else {
fc.toml_value.clone()
};
(fc.field.clone(), value)
})
.collect();
if !fields.is_empty() {
self.client.notes().update_fields(note_id, &fields).await?;
}
if strategy.update_tags {
}
Ok(())
}
fn update_note_id(&mut self, first_field: &str, model_name: &str, note_id: i64) {
for note in &mut self.definition.notes {
let model = self.definition.models.iter().find(|m| m.name == note.model);
if let Some(model) = model {
if let Some(first_field_name) = model.fields.first() {
let note_first_field = note
.fields
.get(first_field_name)
.cloned()
.unwrap_or_default();
if note_first_field == first_field && note.model == model_name {
note.note_id = Some(note_id);
return;
}
}
}
}
}
fn update_definition_from_anki(
&mut self,
first_field: &str,
model_name: &str,
field_changes: &[FieldChange],
tag_changes: &TagChanges,
) {
for note in &mut self.definition.notes {
let model = self.definition.models.iter().find(|m| m.name == note.model);
if let Some(model) = model {
if let Some(first_field_name) = model.fields.first() {
let note_first_field = note
.fields
.get(first_field_name)
.cloned()
.unwrap_or_default();
if note_first_field == first_field && note.model == model_name {
for fc in field_changes {
note.fields.insert(fc.field.clone(), fc.anki_value.clone());
}
for tag in &tag_changes.removed {
if !note.tags.contains(tag) {
note.tags.push(tag.clone());
}
}
for tag in &tag_changes.added {
note.tags.retain(|t| t != tag);
}
return;
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sync_strategy_default() {
let strategy = SyncStrategy::default();
assert_eq!(strategy.conflict_resolution, ConflictResolution::Skip);
assert!(!strategy.pull_new_notes);
assert!(strategy.push_new_notes);
assert!(strategy.update_tags);
}
#[test]
fn test_sync_strategy_push_only() {
let strategy = SyncStrategy::push_only();
assert_eq!(strategy.conflict_resolution, ConflictResolution::PreferToml);
assert!(!strategy.pull_new_notes);
assert!(strategy.push_new_notes);
}
#[test]
fn test_sync_strategy_pull_only() {
let strategy = SyncStrategy::pull_only();
assert_eq!(strategy.conflict_resolution, ConflictResolution::PreferAnki);
assert!(strategy.pull_new_notes);
assert!(!strategy.push_new_notes);
}
}