Provider

Struct Provider 

Source
pub struct Provider<L, T, R, U>{ /* private fields */ }
Expand description

A data source that combines two CalDavSources, which is able to sync both sources.

Usually, you will only need to use a provider between a server and a local cache, that is to say a CalDavProvider, i.e. a Provider<Cache, CachedCalendar, Client, RemoteCalendar>.
However, providers can be used for integration tests, where the remote source is mocked by a Cache.

Implementations§

Source§

impl<L, T, R, U> Provider<L, T, R, U>

Source

pub fn new(remote: R, local: L) -> Self

Create a provider.

remote is usually a Client, local is usually a Cache. However, both can be interchangeable. The only difference is that remote always wins in case of a sync conflict

Examples found in repository?
examples/shared.rs (line 34)
23pub async fn initial_sync(cache_folder: &str) -> CalDavProvider {
24    let cache_path = Path::new(cache_folder);
25
26    let client = Client::new(URL, USERNAME, PASSWORD).unwrap();
27    let cache = match Cache::from_folder(&cache_path) {
28        Ok(cache) => cache,
29        Err(err) => {
30            log::warn!("Invalid cache file: {}. Using a default cache", err);
31            Cache::new(&cache_path)
32        }
33    };
34    let mut provider = CalDavProvider::new(client, cache);
35
36
37    let cals = provider.local().get_calendars().await.unwrap();
38    println!("---- Local items, before sync -----");
39    kitchen_fridge::utils::print_calendar_list(&cals).await;
40
41    println!("Starting a sync...");
42    println!("Depending on your RUST_LOG value, you may see more or less details about the progress.");
43    // Note that we could use sync_with_feedback() to have better and formatted feedback
44    if provider.sync().await == false {
45        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync.");
46    }
47    provider.local().save_to_folder().unwrap();
48
49    println!("---- Local items, after sync -----");
50    let cals = provider.local().get_calendars().await.unwrap();
51    kitchen_fridge::utils::print_calendar_list(&cals).await;
52
53    provider
54}
Source

pub fn local(&self) -> &L

Returns the data source described as local

Examples found in repository?
examples/toggle-completions.rs (line 40)
37async fn toggle_all_tasks_and_sync_again(provider: &mut CalDavProvider) -> Result<(), Box<dyn Error>> {
38    let mut n_toggled = 0;
39
40    for (_url, cal) in provider.local().get_calendars_sync()?.iter() {
41        for (_url, item) in cal.lock().unwrap().get_items_mut_sync()?.iter_mut() {
42            match item {
43                Item::Task(task) => {
44                    match task.completed() {
45                        false => task.set_completion_status(CompletionStatus::Completed(Some(Utc::now()))),
46                        true => task.set_completion_status(CompletionStatus::Uncompleted),
47                    };
48                    n_toggled += 1;
49                }
50                Item::Event(_) => {
51                    // Not doing anything with calendar events
52                },
53            }
54        }
55    }
56
57    println!("{} items toggled.", n_toggled);
58    println!("Syncing...");
59
60    provider.sync().await;
61
62    println!("Syncing complete.");
63
64    Ok(())
65}
More examples
Hide additional examples
examples/shared.rs (line 37)
23pub async fn initial_sync(cache_folder: &str) -> CalDavProvider {
24    let cache_path = Path::new(cache_folder);
25
26    let client = Client::new(URL, USERNAME, PASSWORD).unwrap();
27    let cache = match Cache::from_folder(&cache_path) {
28        Ok(cache) => cache,
29        Err(err) => {
30            log::warn!("Invalid cache file: {}. Using a default cache", err);
31            Cache::new(&cache_path)
32        }
33    };
34    let mut provider = CalDavProvider::new(client, cache);
35
36
37    let cals = provider.local().get_calendars().await.unwrap();
38    println!("---- Local items, before sync -----");
39    kitchen_fridge::utils::print_calendar_list(&cals).await;
40
41    println!("Starting a sync...");
42    println!("Depending on your RUST_LOG value, you may see more or less details about the progress.");
43    // Note that we could use sync_with_feedback() to have better and formatted feedback
44    if provider.sync().await == false {
45        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync.");
46    }
47    provider.local().save_to_folder().unwrap();
48
49    println!("---- Local items, after sync -----");
50    let cals = provider.local().get_calendars().await.unwrap();
51    kitchen_fridge::utils::print_calendar_list(&cals).await;
52
53    provider
54}
examples/provider-sync.rs (line 59)
43async fn add_items_and_sync_again(provider: &mut CalDavProvider) {
44    println!("\nNow, we'll add a calendar and a few tasks and run the sync again.");
45    pause();
46
47    // Create a new calendar...
48    let new_calendar_url: Url = EXAMPLE_CREATED_CALENDAR_URL.parse().unwrap();
49    let new_calendar_name = "A brave new calendar".to_string();
50    if let Err(_err) = provider.local_mut()
51        .create_calendar(new_calendar_url.clone(), new_calendar_name.clone(), SupportedComponents::TODO, Some("#ff8000".parse().unwrap()))
52        .await {
53            println!("Unable to add calendar, maybe it exists already. We're not adding it after all.");
54    }
55
56    // ...and add a task in it
57    let new_name = "This is a new task in a new calendar";
58    let new_task = Task::new(String::from(new_name), true, &new_calendar_url);
59    provider.local().get_calendar(&new_calendar_url).await.unwrap()
60        .lock().unwrap().add_item(Item::Task(new_task)).await.unwrap();
61
62
63    // Also create a task in a previously existing calendar
64    let changed_calendar_url: Url = EXAMPLE_EXISTING_CALENDAR_URL.parse().unwrap();
65    let new_task_name = "This is a new task we're adding as an example, with ÜTF-8 characters";
66    let new_task = Task::new(String::from(new_task_name), false, &changed_calendar_url);
67    let new_url = new_task.url().clone();
68    provider.local().get_calendar(&changed_calendar_url).await.unwrap()
69        .lock().unwrap().add_item(Item::Task(new_task)).await.unwrap();
70
71
72    if provider.sync().await == false {
73        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync. The new task may not have been synced.");
74    } else {
75        println!("Done syncing the new task '{}' and the new calendar '{}'", new_task_name, new_calendar_name);
76    }
77    provider.local().save_to_folder().unwrap();
78
79    complete_item_and_sync_again(provider, &changed_calendar_url, &new_url).await;
80}
81
82async fn complete_item_and_sync_again(
83    provider: &mut CalDavProvider,
84    changed_calendar_url: &Url,
85    url_to_complete: &Url)
86{
87    println!("\nNow, we'll mark this last task as completed, and run the sync again.");
88    pause();
89
90    let completion_status = CompletionStatus::Completed(Some(Utc::now()));
91    provider.local().get_calendar(changed_calendar_url).await.unwrap()
92        .lock().unwrap().get_item_by_url_mut(url_to_complete).await.unwrap()
93        .unwrap_task_mut()
94        .set_completion_status(completion_status);
95
96    if provider.sync().await == false {
97        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync. The new task may not have been synced.");
98    } else {
99        println!("Done syncing the completed task");
100    }
101    provider.local().save_to_folder().unwrap();
102
103    remove_items_and_sync_again(provider, changed_calendar_url, url_to_complete).await;
104}
105
106async fn remove_items_and_sync_again(
107    provider: &mut CalDavProvider,
108    changed_calendar_url: &Url,
109    id_to_remove: &Url)
110{
111    println!("\nNow, we'll delete this last task, and run the sync again.");
112    pause();
113
114    // Remove the task we had created
115    provider.local().get_calendar(changed_calendar_url).await.unwrap()
116        .lock().unwrap()
117        .mark_for_deletion(id_to_remove).await.unwrap();
118
119    if provider.sync().await == false {
120        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync. The new task may not have been synced.");
121    } else {
122        println!("Done syncing the deleted task");
123    }
124    provider.local().save_to_folder().unwrap();
125
126    println!("Done. You can start this example again to see the cache being restored from its current saved state")
127}
Source

pub fn local_mut(&mut self) -> &mut L

Returns the data source described as local

Examples found in repository?
examples/provider-sync.rs (line 50)
43async fn add_items_and_sync_again(provider: &mut CalDavProvider) {
44    println!("\nNow, we'll add a calendar and a few tasks and run the sync again.");
45    pause();
46
47    // Create a new calendar...
48    let new_calendar_url: Url = EXAMPLE_CREATED_CALENDAR_URL.parse().unwrap();
49    let new_calendar_name = "A brave new calendar".to_string();
50    if let Err(_err) = provider.local_mut()
51        .create_calendar(new_calendar_url.clone(), new_calendar_name.clone(), SupportedComponents::TODO, Some("#ff8000".parse().unwrap()))
52        .await {
53            println!("Unable to add calendar, maybe it exists already. We're not adding it after all.");
54    }
55
56    // ...and add a task in it
57    let new_name = "This is a new task in a new calendar";
58    let new_task = Task::new(String::from(new_name), true, &new_calendar_url);
59    provider.local().get_calendar(&new_calendar_url).await.unwrap()
60        .lock().unwrap().add_item(Item::Task(new_task)).await.unwrap();
61
62
63    // Also create a task in a previously existing calendar
64    let changed_calendar_url: Url = EXAMPLE_EXISTING_CALENDAR_URL.parse().unwrap();
65    let new_task_name = "This is a new task we're adding as an example, with ÜTF-8 characters";
66    let new_task = Task::new(String::from(new_task_name), false, &changed_calendar_url);
67    let new_url = new_task.url().clone();
68    provider.local().get_calendar(&changed_calendar_url).await.unwrap()
69        .lock().unwrap().add_item(Item::Task(new_task)).await.unwrap();
70
71
72    if provider.sync().await == false {
73        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync. The new task may not have been synced.");
74    } else {
75        println!("Done syncing the new task '{}' and the new calendar '{}'", new_task_name, new_calendar_name);
76    }
77    provider.local().save_to_folder().unwrap();
78
79    complete_item_and_sync_again(provider, &changed_calendar_url, &new_url).await;
80}
Source

pub fn remote(&self) -> &R

Returns the data source described as remote.

Apart from tests, there are very few (if any) reasons to access remote directly. Usually, you should rather use the local source, which (usually) is a much faster local cache. To be sure local accurately mirrors the remote source, you can run Provider::sync

Source

pub async fn sync_with_feedback( &mut self, feedback_sender: FeedbackSender, ) -> bool

Performs a synchronisation between local and remote, and provide feeedback to the user about the progress.

This bidirectional sync applies additions/deletions made on a source to the other source. In case of conflicts (the same item has been modified on both ends since the last sync, remote always wins).

It returns whether the sync was totally successful (details about errors are logged using the log::* macros). In case errors happened, the sync might have been partially executed but your data will never be correupted (either locally nor in the server). Simply run this function again, it will re-start a sync, picking up where it failed.

Source

pub async fn sync(&mut self) -> bool

Performs a synchronisation between local and remote, without giving any feedback.

See Self::sync_with_feedback

Examples found in repository?
examples/toggle-completions.rs (line 60)
37async fn toggle_all_tasks_and_sync_again(provider: &mut CalDavProvider) -> Result<(), Box<dyn Error>> {
38    let mut n_toggled = 0;
39
40    for (_url, cal) in provider.local().get_calendars_sync()?.iter() {
41        for (_url, item) in cal.lock().unwrap().get_items_mut_sync()?.iter_mut() {
42            match item {
43                Item::Task(task) => {
44                    match task.completed() {
45                        false => task.set_completion_status(CompletionStatus::Completed(Some(Utc::now()))),
46                        true => task.set_completion_status(CompletionStatus::Uncompleted),
47                    };
48                    n_toggled += 1;
49                }
50                Item::Event(_) => {
51                    // Not doing anything with calendar events
52                },
53            }
54        }
55    }
56
57    println!("{} items toggled.", n_toggled);
58    println!("Syncing...");
59
60    provider.sync().await;
61
62    println!("Syncing complete.");
63
64    Ok(())
65}
More examples
Hide additional examples
examples/shared.rs (line 44)
23pub async fn initial_sync(cache_folder: &str) -> CalDavProvider {
24    let cache_path = Path::new(cache_folder);
25
26    let client = Client::new(URL, USERNAME, PASSWORD).unwrap();
27    let cache = match Cache::from_folder(&cache_path) {
28        Ok(cache) => cache,
29        Err(err) => {
30            log::warn!("Invalid cache file: {}. Using a default cache", err);
31            Cache::new(&cache_path)
32        }
33    };
34    let mut provider = CalDavProvider::new(client, cache);
35
36
37    let cals = provider.local().get_calendars().await.unwrap();
38    println!("---- Local items, before sync -----");
39    kitchen_fridge::utils::print_calendar_list(&cals).await;
40
41    println!("Starting a sync...");
42    println!("Depending on your RUST_LOG value, you may see more or less details about the progress.");
43    // Note that we could use sync_with_feedback() to have better and formatted feedback
44    if provider.sync().await == false {
45        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync.");
46    }
47    provider.local().save_to_folder().unwrap();
48
49    println!("---- Local items, after sync -----");
50    let cals = provider.local().get_calendars().await.unwrap();
51    kitchen_fridge::utils::print_calendar_list(&cals).await;
52
53    provider
54}
examples/provider-sync.rs (line 72)
43async fn add_items_and_sync_again(provider: &mut CalDavProvider) {
44    println!("\nNow, we'll add a calendar and a few tasks and run the sync again.");
45    pause();
46
47    // Create a new calendar...
48    let new_calendar_url: Url = EXAMPLE_CREATED_CALENDAR_URL.parse().unwrap();
49    let new_calendar_name = "A brave new calendar".to_string();
50    if let Err(_err) = provider.local_mut()
51        .create_calendar(new_calendar_url.clone(), new_calendar_name.clone(), SupportedComponents::TODO, Some("#ff8000".parse().unwrap()))
52        .await {
53            println!("Unable to add calendar, maybe it exists already. We're not adding it after all.");
54    }
55
56    // ...and add a task in it
57    let new_name = "This is a new task in a new calendar";
58    let new_task = Task::new(String::from(new_name), true, &new_calendar_url);
59    provider.local().get_calendar(&new_calendar_url).await.unwrap()
60        .lock().unwrap().add_item(Item::Task(new_task)).await.unwrap();
61
62
63    // Also create a task in a previously existing calendar
64    let changed_calendar_url: Url = EXAMPLE_EXISTING_CALENDAR_URL.parse().unwrap();
65    let new_task_name = "This is a new task we're adding as an example, with ÜTF-8 characters";
66    let new_task = Task::new(String::from(new_task_name), false, &changed_calendar_url);
67    let new_url = new_task.url().clone();
68    provider.local().get_calendar(&changed_calendar_url).await.unwrap()
69        .lock().unwrap().add_item(Item::Task(new_task)).await.unwrap();
70
71
72    if provider.sync().await == false {
73        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync. The new task may not have been synced.");
74    } else {
75        println!("Done syncing the new task '{}' and the new calendar '{}'", new_task_name, new_calendar_name);
76    }
77    provider.local().save_to_folder().unwrap();
78
79    complete_item_and_sync_again(provider, &changed_calendar_url, &new_url).await;
80}
81
82async fn complete_item_and_sync_again(
83    provider: &mut CalDavProvider,
84    changed_calendar_url: &Url,
85    url_to_complete: &Url)
86{
87    println!("\nNow, we'll mark this last task as completed, and run the sync again.");
88    pause();
89
90    let completion_status = CompletionStatus::Completed(Some(Utc::now()));
91    provider.local().get_calendar(changed_calendar_url).await.unwrap()
92        .lock().unwrap().get_item_by_url_mut(url_to_complete).await.unwrap()
93        .unwrap_task_mut()
94        .set_completion_status(completion_status);
95
96    if provider.sync().await == false {
97        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync. The new task may not have been synced.");
98    } else {
99        println!("Done syncing the completed task");
100    }
101    provider.local().save_to_folder().unwrap();
102
103    remove_items_and_sync_again(provider, changed_calendar_url, url_to_complete).await;
104}
105
106async fn remove_items_and_sync_again(
107    provider: &mut CalDavProvider,
108    changed_calendar_url: &Url,
109    id_to_remove: &Url)
110{
111    println!("\nNow, we'll delete this last task, and run the sync again.");
112    pause();
113
114    // Remove the task we had created
115    provider.local().get_calendar(changed_calendar_url).await.unwrap()
116        .lock().unwrap()
117        .mark_for_deletion(id_to_remove).await.unwrap();
118
119    if provider.sync().await == false {
120        log::warn!("Sync did not complete, see the previous log lines for more info. You can safely start a new sync. The new task may not have been synced.");
121    } else {
122        println!("Done syncing the deleted task");
123    }
124    provider.local().save_to_folder().unwrap();
125
126    println!("Done. You can start this example again to see the cache being restored from its current saved state")
127}

Trait Implementations§

Source§

impl<L, T, R, U> Debug for Provider<L, T, R, U>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<L, T, R, U> Freeze for Provider<L, T, R, U>
where R: Freeze, L: Freeze,

§

impl<L, T, R, U> RefUnwindSafe for Provider<L, T, R, U>

§

impl<L, T, R, U> Send for Provider<L, T, R, U>
where R: Send, L: Send,

§

impl<L, T, R, U> Sync for Provider<L, T, R, U>
where R: Sync, L: Sync,

§

impl<L, T, R, U> Unpin for Provider<L, T, R, U>
where R: Unpin, L: Unpin, T: Unpin, U: Unpin,

§

impl<L, T, R, U> UnwindSafe for Provider<L, T, R, U>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,