aboutsummaryrefslogtreecommitdiffstats
path: root/fatcat-cli/src/lib.rs
blob: e8b112f1f6cd4fe31d65cbcbff6d4bc0a9f27f71 (plain)
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
use anyhow::{anyhow, Context, Result};
use data_encoding::BASE64;
use macaroon::{Macaroon, Verifier};
use std::path::PathBuf;
use std::str::FromStr;

mod api;
mod commands;
mod download;
mod entities;
mod search;
mod specifier;

pub use api::FatcatApiClient;
pub use commands::{
    edit_entity_locally, print_changelog_entries, print_editgroups, print_entity_histories,
    print_search_table, BatchGrouper, BatchOp, ClientStatus,
};
pub use download::{download_batch, download_file, download_release};
pub use entities::{
    entity_model_from_json_str, read_entity_file, ApiEntityModel, ApiModelIdent, ApiModelSer,
    Mutation,
};
pub use search::{crude_search, SearchResults};
pub use specifier::{EditgroupSpecifier, Specifier};

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum EntityType {
    Release,
    Work,
    Container,
    Creator,
    File,
    FileSet,
    WebCapture,
}

impl FromStr for EntityType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "release" | "releases" => Ok(EntityType::Release),
            "work" | "works" => Ok(EntityType::Work),
            "container" | "containers" => Ok(EntityType::Container),
            "creator" | "creators" => Ok(EntityType::Creator),
            "file" | "files" => Ok(EntityType::File),
            "fileset" | "filesets" => Ok(EntityType::FileSet),
            "webcapture" | "webcaptures" => Ok(EntityType::WebCapture),
            _ => Err(anyhow!("invalid entity type : {}", s)),
        }
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum SearchEntityType {
    Release,
    Container,
    File,
    Scholar,
    Reference,
}

impl FromStr for SearchEntityType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "release" | "releases" => Ok(SearchEntityType::Release),
            "container" | "containers" => Ok(SearchEntityType::Container),
            "file" | "files" => Ok(SearchEntityType::File),
            "scholar" | "fulltext" => Ok(SearchEntityType::Scholar),
            "ref" | "refs" | "references" => Ok(SearchEntityType::Reference),
            _ => Err(anyhow!("invalid entity type : {}", s)),
        }
    }
}

/// Takes a macaroon token (as base64-encoded string) and tries to parse out an editor id
pub fn parse_macaroon_editor_id(s: &str) -> Result<String> {
    let raw = BASE64
        .decode(s.as_bytes())
        .context("macaroon parsing failed")?;
    let mac = Macaroon::deserialize(&raw)
        .map_err(|err| anyhow!("macaroon deserialization failed: {:?}", err))?;
    let mac = mac
        .validate()
        .map_err(|err| anyhow!("macaroon validation failed: {:?}", err))?;
    let mut verifier = Verifier::new();
    let mut editor_id: Option<String> = None;
    for caveat in mac.first_party_caveats() {
        if caveat.predicate().starts_with("editor_id = ") {
            editor_id = Some(
                caveat
                    .predicate()
                    .get(12..)
                    .context("parsing macaroon")?
                    .to_string(),
            );
            break;
        }
    }
    let editor_id = match editor_id {
        Some(id) => id,
        None => return Err(anyhow!("expected an editor_id caveat in macaroon token")),
    };
    verifier.satisfy_exact(&format!("editor_id = {}", editor_id));
    Ok(editor_id)
}

pub fn path_or_stdin(raw: Option<PathBuf>) -> Option<PathBuf> {
    // treat "-" as "use stdin"
    match raw {
        Some(s) if s.to_string_lossy() == "-" => None,
        _ => raw,
    }
}