1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Copyright 2023-2024 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

use std::io::Read;

use anyhow::{bail, Context};
use http::Uri;
use hyper::client::HttpConnector;
use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder};
use libdav::{carddav_service_for_url, dav::WebDavClient, sd::find_context_url, CardDavClient};
use log::info;

use crate::{cli::ServerCommand, common::auth_from_env};

type Client = CardDavClient<HttpsConnector<HttpConnector>>;

/// Create a new client. Note that bootstrap is not performed implicitly.
fn carddav_client() -> anyhow::Result<Client> {
    let base_url = std::env::var("DAVCLI_BASE_URL")
        .context("failed to determine base_url")?
        .try_into()
        .context("parsing DAVCLI_BASE_URL")?;
    let auth = auth_from_env()?;

    let https = HttpsConnectorBuilder::new()
        .with_native_roots()?
        .https_or_http()
        .enable_http1()
        .build();
    let webdav = WebDavClient::new(base_url, auth, https);
    let client = CardDavClient::new(webdav);

    Ok(client)
}

#[tokio::main(flavor = "current_thread")]
pub(crate) async fn execute(command: ServerCommand) -> anyhow::Result<()> {
    let client = carddav_client()?;

    match command {
        ServerCommand::Discover => discover(client).await?,
        ServerCommand::FindCollections => list_collections(client).await?,
        ServerCommand::ListItems { collection_href } => {
            list_resources(&client, collection_href).await?;
        }
        ServerCommand::Get { resource_href } => get(client, resource_href).await?,
        ServerCommand::Delete { force, href } => {
            if !force {
                bail!("Must force deletion (no etag support in davcli)");
            }
            delete(&client, href).await?;
        }
        ServerCommand::Tree => tree(client).await?,
        ServerCommand::Create { resource_href } => create(client, resource_href).await?,
    };

    Ok(())
}

async fn discover(mut client: Client) -> anyhow::Result<()> {
    let service = carddav_service_for_url(client.base_url())?;
    println!("- Base url: {}", client.base_url());
    match find_context_url(&client, service).await? {
        Some(context_path) => {
            println!("- Resolved context path: {context_path}");
            client.webdav_client.base_url = context_path;
        }
        None => {
            println!("- Context path not found; using given URL");
        }
    };
    match client.find_current_user_principal().await? {
        Some(principal) => {
            println!("- Current user principal: {principal}");
            let home_set = client.find_address_book_home_set(&principal).await?;
            if home_set.is_empty() {
                println!("- Address book home set not found.");
            } else {
                for collection in home_set {
                    println!("- Address book home set: {collection}");
                }
            }
        }
        None => println!("- Curent user principal not found."),
    };
    Ok(())
}

async fn urls_for_finding_address_books(client: &Client) -> anyhow::Result<Vec<Uri>> {
    let urls = match client.find_current_user_principal().await? {
        Some(principal) => {
            let home_set = client.find_address_book_home_set(&principal).await?;
            if home_set.is_empty() {
                vec![client.base_url().clone()]
            } else {
                home_set
            }
        }
        None => vec![client.base_url().clone()],
    };
    Ok(urls)
}

async fn list_collections(client: Client) -> anyhow::Result<()> {
    let urls = urls_for_finding_address_books(&client).await?;
    for url in urls {
        let response = client.find_addressbooks(&url).await?;
        for collection in response {
            println!("{}", collection.href);
        }
    }

    Ok(())
}

async fn get(client: Client, href: String) -> anyhow::Result<()> {
    let collection = match href.rfind('/') {
        Some(i) => &href[0..i],
        None => "/",
    }
    .to_string();

    let response = client
        .get_address_book_resources(collection, &[href])
        .await?
        .into_iter()
        .next()
        .context("Server returned a response with no resources")?;

    let raw = &response
        .content
        .as_ref()
        .map_err(|code| anyhow::anyhow!("Server returned error code: {0}", code))?
        .data;

    println!("{raw}");

    Ok(())
}

async fn list_resources(client: &Client, href: String) -> anyhow::Result<()> {
    let resources = client.list_resources(&href).await?;
    if resources.is_empty() {
        info!("No items in collection");
    } else {
        for resource in resources {
            println!("{}", resource.href);
        }
    }

    Ok(())
}

async fn delete(client: &Client, href: String) -> anyhow::Result<()> {
    client
        .force_delete(&href)
        .await
        .map_err(anyhow::Error::from)
}

async fn tree(client: Client) -> anyhow::Result<()> {
    let urls = urls_for_finding_address_books(&client).await?;
    for url in urls {
        let response = client.find_addressbooks(&url).await?;
        for collection in response {
            println!("{}", collection.href);
            list_resources(&client, collection.href).await?;
        }
    }

    Ok(())
}

async fn create(client: Client, href: String) -> anyhow::Result<()> {
    let mut data = Vec::new();
    let mut stdin = std::io::stdin().lock();
    stdin.read_to_end(&mut data).context("reading from stdin")?;

    let response = client
        .create_resource(&href, data, b"text/vcard")
        .await
        .context("sending request to create resource")?;

    if let Some(etag) = response {
        println!("Etag: {etag}");
    } else {
        println!("No etag");
    }

    Ok(())
}