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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use async_trait::async_trait;
use console::style;
use std::{
    collections::HashSet,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

use crate::cache::{load_cache, Cache};
use crate::common::*;
use crate::config::{data::SugarConfig, get_config_data, UploadMethod};
use crate::upload::bundlr::BundlrHandler;
use crate::upload::*;
use crate::utils::*;
use crate::validate::format::Metadata;

/// A trait for storage upload handlers.
#[async_trait]
pub trait UploadHandler {
    /// Prepares the upload of the specified media/metadata files.
    async fn prepare(
        &self,
        sugar_config: &SugarConfig,
        assets: &HashMap<usize, AssetPair>,
        media_indices: &[usize],
        metadata_indices: &[usize],
    ) -> Result<()>;

    /// Upload the data to a (permanent) storage.
    async fn upload_data(
        &self,
        sugar_config: &SugarConfig,
        assets: &HashMap<usize, AssetPair>,
        cache: &mut Cache,
        indices: &[usize],
        data_type: DataType,
        interrupted: Arc<AtomicBool>,
    ) -> Result<Vec<UploadError>>;
}

pub struct UploadArgs {
    pub assets_dir: String,
    pub config: String,
    pub keypair: Option<String>,
    pub rpc_url: Option<String>,
    pub cache: String,
    pub interrupted: Arc<AtomicBool>,
}

pub async fn process_upload(args: UploadArgs) -> Result<()> {
    let sugar_config = sugar_setup(args.keypair, args.rpc_url)?;
    let config_data = get_config_data(&args.config)?;

    // loading assets
    println!(
        "{} {}Loading assets",
        style("[1/4]").bold().dim(),
        ASSETS_EMOJI
    );

    let pb = spinner_with_style();
    pb.enable_steady_tick(120);
    pb.set_message("Reading files...");

    let asset_pairs = get_asset_pairs(&args.assets_dir)?;
    // creates/loads the cache
    let mut cache = load_cache(&args.cache, true)?;

    // list of indices to upload
    // 0: media
    // 1: metadata
    let mut indices = (Vec::new(), Vec::new());

    for (index, pair) in &asset_pairs {
        match cache.items.0.get_mut(&index.to_string()) {
            Some(item) => {
                // has the media file changed?
                if !item.media_hash.eq(&pair.media_hash) || item.media_link.is_empty() {
                    // we replace the entire item to trigger the media and metadata upload
                    cache
                        .items
                        .0
                        .insert(index.to_string(), pair.clone().into_cache_item());
                    // we need to upload both media/metadata
                    indices.0.push(*index);
                    indices.1.push(*index);
                } else if !item.metadata_hash.eq(&pair.metadata_hash)
                    || item.metadata_link.is_empty()
                {
                    // triggers the metadata upload
                    item.metadata_hash = pair.metadata_hash.clone();
                    item.metadata_link = String::new();
                    item.on_chain = false;
                    // we need to upload metadata only
                    indices.1.push(*index);
                }
            }
            None => {
                cache
                    .items
                    .0
                    .insert(index.to_string(), pair.clone().into_cache_item());
                // we need to upload both media/metadata
                indices.0.push(*index);
                indices.1.push(*index);
            }
        }
        // sanity check: verifies that both symbol and seller-fee-basis-points are the
        // same as the ones in the config file
        let f = File::open(Path::new(&pair.metadata))?;
        match serde_json::from_reader(f) {
            Ok(metadata) => {
                let metadata: Metadata = metadata;
                // symbol check
                if config_data.symbol.ne(&metadata.symbol) {
                    return Err(UploadError::MismatchValue(
                        "symbol".to_string(),
                        pair.metadata.clone(),
                        config_data.symbol,
                        metadata.symbol,
                    )
                    .into());
                }
                // seller-fee-basis-points check
                if config_data.seller_fee_basis_points != metadata.seller_fee_basis_points {
                    return Err(UploadError::MismatchValue(
                        "seller_fee_basis_points".to_string(),
                        pair.metadata.clone(),
                        config_data.seller_fee_basis_points.to_string(),
                        metadata.seller_fee_basis_points.to_string(),
                    )
                    .into());
                }
            }
            Err(err) => {
                let error = anyhow!("Error parsing metadata ({}): {}", pair.metadata, err);
                error!("{:?}", error);
                return Err(error);
            }
        }
    }

    pb.finish_and_clear();

    println!(
        "Found {} media/metadata pair(s), uploading files:",
        asset_pairs.len()
    );
    println!("+--------------------+");
    println!("| media     | {:>6} |", indices.0.len());
    println!("| metadata  | {:>6} |", indices.1.len());
    println!("+--------------------+");

    // this should never happen, since every time we update the media file we
    // need to update the metadata
    if indices.0.len() > indices.1.len() {
        return Err(anyhow!(format!(
            "There are more media files ({}) to upload than metadata ({})",
            indices.0.len(),
            indices.1.len(),
        )));
    }

    let need_upload = !indices.0.is_empty() || !indices.1.is_empty();

    // ready to upload data

    let mut errors = Vec::new();

    if need_upload {
        println!(
            "\n{} {}Initializing upload",
            style("[2/4]").bold().dim(),
            COMPUTER_EMOJI
        );

        let pb = spinner_with_style();
        pb.set_message("Connecting...");

        let handler = match config_data.upload_method {
            UploadMethod::Bundlr => Box::new(
                BundlrHandler::initialize(&get_config_data(&args.config)?, &sugar_config).await?,
            ) as Box<dyn UploadHandler>,
            UploadMethod::AWS => {
                Box::new(AWSHandler::initialize(&get_config_data(&args.config)?).await?)
                    as Box<dyn UploadHandler>
            }
        };

        pb.finish_with_message("Connected");

        handler
            .prepare(&sugar_config, &asset_pairs, &indices.0, &indices.1)
            .await?;

        // clear the interruption handler value ahead of the upload
        args.interrupted.store(false, Ordering::SeqCst);

        println!(
            "\n{} {}Uploading media files {}",
            style("[3/4]").bold().dim(),
            UPLOAD_EMOJI,
            if indices.0.is_empty() {
                "(skipping)"
            } else {
                ""
            }
        );

        if !indices.0.is_empty() {
            errors.extend(
                handler
                    .upload_data(
                        &sugar_config,
                        &asset_pairs,
                        &mut cache,
                        &indices.0,
                        DataType::Media,
                        args.interrupted.clone(),
                    )
                    .await?,
            );

            // updates the list of metadata indices since the media upload
            // might fail - removes any index that the media upload failed
            if !indices.1.is_empty() {
                for index in indices.0 {
                    let item = cache.items.0.get(&index.to_string()).unwrap();

                    if item.media_link.is_empty() {
                        // no media link, not ready for metadata upload
                        indices.1.retain(|&x| x != index);
                    }
                }
            }
        }

        println!(
            "\n{} {}Uploading metadata files {}",
            style("[4/4]").bold().dim(),
            UPLOAD_EMOJI,
            if indices.1.is_empty() {
                "(skipping)"
            } else {
                ""
            }
        );

        if !indices.1.is_empty() {
            errors.extend(
                handler
                    .upload_data(
                        &sugar_config,
                        &asset_pairs,
                        &mut cache,
                        &indices.1,
                        DataType::Metadata,
                        args.interrupted.clone(),
                    )
                    .await?,
            );
        }
    } else {
        println!("\n....no files need uploading, skipping remaining steps.");
    }

    // sanity check

    cache.items.0.sort_keys();
    cache.sync_file()?;

    let mut count = 0;

    for (_index, item) in cache.items.0 {
        if !(item.media_link.is_empty() || item.metadata_link.is_empty()) {
            count += 1;
        }
    }

    println!(
        "\n{}",
        style(format!(
            "{}/{} media/metadata pair(s) uploaded.",
            count,
            asset_pairs.len()
        ))
        .bold()
    );

    if count != asset_pairs.len() {
        let message = if !errors.is_empty() {
            let mut message = String::new();
            message.push_str(&format!(
                "Failed to upload all files, {0} error(s) occurred:",
                errors.len()
            ));

            let mut unique = HashSet::new();

            for err in errors {
                unique.insert(err.to_string());
            }

            for u in unique {
                message.push_str(&style("\n=> ").dim().to_string());
                message.push_str(&u);
            }

            message
        } else {
            "Incorrect number of media/metadata pairs".to_string()
        };

        return Err(UploadError::Incomplete(message).into());
    }

    Ok(())
}