junobuild_storage/
utils.rs

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
use crate::constants::{
    ASSET_ENCODING_NO_COMPRESSION, WELL_KNOWN_CUSTOM_DOMAINS, WELL_KNOWN_II_ALTERNATIVE_ORIGINS,
};
use crate::http::types::HeaderField;
use crate::types::interface::AssetNoContent;
use crate::types::state::FullPath;
use crate::types::store::{Asset, AssetEncoding, AssetKey};
use candid::Principal;
use ic_cdk::api::time;
use junobuild_collections::assert_stores::assert_permission;
use junobuild_collections::types::core::CollectionKey;
use junobuild_collections::types::rules::Permission;
use junobuild_shared::constants::INITIAL_VERSION;
use junobuild_shared::list::{filter_timestamps, matcher_regex};
use junobuild_shared::types::core::Blob;
use junobuild_shared::types::list::ListParams;
use junobuild_shared::types::state::{Controllers, Timestamp, UserId, Version};
use regex::Regex;
use std::collections::HashMap;

pub fn map_asset_no_content(asset: &Asset) -> (FullPath, AssetNoContent) {
    (asset.key.full_path.clone(), AssetNoContent::from(asset))
}

pub fn filter_values<'a>(
    caller: Principal,
    controllers: &'a Controllers,
    rule: &'a Permission,
    collection: CollectionKey,
    ListParams {
        matcher,
        order: _,
        paginate: _,
        owner,
    }: &'a ListParams,
    assets: &'a [(&'a FullPath, &'a Asset)],
) -> Vec<(&'a FullPath, &'a Asset)> {
    let (regex_key, regex_description) = matcher_regex(matcher);

    assets
        .iter()
        .filter_map(|(key, asset)| {
            if filter_collection(collection.clone(), asset)
                && filter_full_path(&regex_key, asset)
                && filter_description(&regex_description, asset)
                && filter_owner(*owner, asset)
                && filter_timestamps(matcher, *asset)
                && assert_permission(rule, asset.key.owner, caller, controllers)
            {
                Some((*key, *asset))
            } else {
                None
            }
        })
        .collect()
}

fn filter_full_path(regex: &Option<Regex>, asset: &Asset) -> bool {
    match regex {
        None => true,
        Some(re) => re.is_match(&asset.key.full_path),
    }
}

fn filter_description(regex: &Option<Regex>, asset: &Asset) -> bool {
    match regex {
        None => true,
        Some(re) => match &asset.key.description {
            None => false,
            Some(description) => re.is_match(description),
        },
    }
}

fn filter_collection(collection: CollectionKey, asset: &Asset) -> bool {
    asset.key.collection == collection
}

fn filter_owner(filter_owner: Option<UserId>, asset: &Asset) -> bool {
    match filter_owner {
        None => true,
        Some(filter_owner) => filter_owner == asset.key.owner,
    }
}

pub fn filter_collection_values<'a>(
    collection: CollectionKey,
    assets: &'a [(&'a FullPath, &'a Asset)],
) -> Vec<(&'a FullPath, &'a Asset)> {
    assets
        .iter()
        .filter_map(|(key, asset)| {
            if filter_collection(collection.clone(), asset) {
                Some((*key, *asset))
            } else {
                None
            }
        })
        .collect()
}

pub fn get_token_protected_asset(
    asset: &Asset,
    asset_token: &String,
    token: Option<String>,
) -> Option<Asset> {
    match token {
        None => None,
        Some(token) => {
            if &token == asset_token {
                return Some(asset.clone());
            }

            None
        }
    }
}

pub fn should_include_asset_for_deletion(collection: &CollectionKey, asset_path: &String) -> bool {
    let excluded_paths = [
        WELL_KNOWN_CUSTOM_DOMAINS.to_string(),
        WELL_KNOWN_II_ALTERNATIVE_ORIGINS.to_string(),
    ];

    collection != "#dapp" || !excluded_paths.contains(asset_path)
}

pub fn map_content_type_headers(content_type: &str) -> Vec<HeaderField> {
    vec![HeaderField(
        "content-type".to_string(),
        content_type.to_string(),
    )]
}

pub fn map_content_encoding(content: &Blob) -> AssetEncoding {
    let max_chunk_size = 1_900_000; // Max 1.9 MB per chunk
    let chunks = content
        .chunks(max_chunk_size)
        .map(|chunk| chunk.to_vec())
        .collect();

    AssetEncoding::from(&chunks)
}

pub fn create_asset_with_content(
    content: &str,
    headers: &[HeaderField],
    existing_asset: Option<Asset>,
    key: AssetKey,
) -> Asset {
    let mut asset: Asset = create_empty_asset(headers, existing_asset, key);

    let encoding = map_content_encoding(&content.as_bytes().to_vec());

    asset
        .encodings
        .insert(ASSET_ENCODING_NO_COMPRESSION.to_string(), encoding);

    asset
}

pub fn create_empty_asset(
    headers: &[HeaderField],
    existing_asset: Option<Asset>,
    key: AssetKey,
) -> Asset {
    let now = time();

    let created_at: Timestamp = match existing_asset.clone() {
        None => now,
        Some(existing_asset) => existing_asset.created_at,
    };

    let version: Version = match existing_asset {
        None => INITIAL_VERSION,
        Some(existing_asset) => existing_asset.version.unwrap_or_default() + 1,
    };

    Asset {
        key,
        headers: headers.to_owned(),
        encodings: HashMap::new(),
        created_at,
        updated_at: now,
        version: Some(version),
    }
}