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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use base64::decode;
use eyre::{eyre, Result};
use futures::{
    stream::{StreamExt, TryStreamExt},
    Stream
};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::to_value;
use std::{fs::{self}, io::Cursor, path::PathBuf};
use std::{
    fs::File,
    io::{self, ErrorKind, Read, Write},
};
use tokio::sync::mpsc;
use tokio_util::bytes::Bytes;

const DEBUG: bool = false;
pub async fn handle_download(node: NftNode, dir: &PathBuf, client: &Client) -> Result<()> {
    /* Pin<Box<dyn Stream<Item = Result<DownloadResult>>>> */
    let image = &node.token.image;
    let name = match &node.token.name {
        Some(name) => name,
        None => return Err(eyre!("Image data not found for {:#?}", node)),
    };

    let (url, mime) = match image {
        NftImage::Object {
            url,
            mime_type,
            size: _,
        } => (url, mime_type),
        NftImage::Url(url) => (url, &None), //meant here
        _ => return Err(eyre!("No image URL found for {name}")),
    };

    let extension = if url.starts_with("data:image/svg") {
        "svg".to_string()
    } else if let Some(mime) = mime {
        mime.rsplit("/").next().unwrap_or_default().to_string()
    } else {
        url.rsplit('.').next().unwrap_or_default().to_lowercase()
    };

    let file_path = dir.join(format!("{name}.{extension}"));
		
    if file_path.is_file() {
        if DEBUG {
            println!("Skipping {name}");
        }
        // progress.inc(1);
        return Ok(());
    }

    if DEBUG {
        println!("Downloading {name} to {:?}", file_path);
    }

    let (progress_tx, mut _progress_rx) = mpsc::channel(10); // Adjust the buffer size as needed
    match url {
        // Decode and save svg
        url if url.starts_with("data:image/svg") => save_base64_image(
            &url.strip_prefix("data:image/svg+xml;base64,")
                .unwrap_or(&url),
            file_path,
        )?,
        // append IPFS gateway
        url if url.starts_with("ipfs") => {
            let parts: Vec<&str> = url.split('/').collect();
            if let Some(hash) = parts.iter().find(|&&part| part.starts_with("Qm")) {
                let ipfs_url = format!("https://ipfs.io/ipfs/{hash}");
                if let Err(error) = download_image(&client, &ipfs_url, file_path, progress_tx).await {
                    return Err(eyre::eyre!("Error downloading image {}: {}", name, error));
                }
            }
        }
        url => {
            if let Err(error) = download_image(&client, &url, file_path, progress_tx).await {
                return Err(eyre::eyre!("Error downloading image {}: {}", name, error));
            };
        }
    }

    if DEBUG {
        println!("{name} saved successfully");
    }

    Ok(())
}
// async fn get_address()

pub struct DownloadProgress {
    pub name: String,
    pub progress: u64,
    pub total: u64,
}

#[derive(Debug)]
struct DownloadResult {
    file_path: std::path::PathBuf,
    progress: u64,
    total: u64,
}

struct ProgressTracker {
    progress: u64,
}
impl ProgressTracker {
    fn new() -> Self {
        ProgressTracker { progress: 0 }
    }

    // async fn track_progress<R: Read + Unpin>(
    async fn track_progress<R: Stream<Item = Result<Bytes>> + Unpin>(
        &mut self,
        index: usize,
        mut reader_stream: R,
        mut file: File,
        progress_tx: &mpsc::Sender<(usize, u64)>,
    ) -> Result<()> {
        let mut buffer = [0; 8192];
        while let Some(chunk_result) = reader_stream.next().await {
            let chunk = match chunk_result {
                Ok(chunk) => chunk,
                Err(e) => return Err(e.into()),
            };

            let mut cursor = Cursor::new(chunk);
            let bytes_read = cursor.read(&mut buffer)?;
            file.write_all(&buffer[..bytes_read])?;
            self.progress += bytes_read as u64;

            match progress_tx.try_send((index, self.progress)) {
                Ok(_) => {
                    // The progress update was sent successfully.
                }
                Err(mpsc::error::TrySendError::Full(_)) => {
                    // The receiver's buffer is full, you can either:
                    // 1. Drop the progress update and continue downloading
                    // 2. Wait for the receiver to process some messages before sending more updates
                }
                Err(mpsc::error::TrySendError::Closed(_)) => {
                    // The receiver was dropped, so we stop sending progress updates.
                    break;
                }
            }
        }
        Ok(())
    }
}

async fn download_image(
    client: &Client,
    image_url: &str,
    file_path: PathBuf,
    progress_tx: mpsc::Sender<(u64, u64)>,
) -> Result<()> {
    let response = client.get(image_url).send().await?;
    let content_length = response.content_length().unwrap_or(0);
    let mut byte_stream = response.bytes_stream();

    let mut progress: u64 = 0; 
    let mut file = File::create(file_path)?;

    while let Some(chunk) = byte_stream.next().await {
			let chunk = chunk?;
			let chunk_len = chunk.len();

			progress += chunk_len as u64;
			file.write_all(&chunk)
					.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;

			// Send progress update through the channel
			let _ = progress_tx.send((progress, content_length)).await;
	}

    if content_length != progress {
        return Err(eyre::eyre!(
            "Downloaded file size does not match the expected size"
        ));
    }

    Ok(())
}

pub async fn create_directory(dir_path: &PathBuf) -> Result<PathBuf>
 {
    let res  = match fs::metadata(dir_path) {
        Ok(metadata) => {
            if !metadata.is_dir() {
                return Err(io::Error::new(
                    ErrorKind::InvalidInput,
                    format!("{:?} is not a directory", dir_path),
                )
                .into());
            }
						dir_path.to_path_buf()
        }
        Err(e) if e.kind() == ErrorKind::NotFound => {
            fs::create_dir_all(dir_path)?;
            if DEBUG { println!("created directory: {:?}", dir_path);}
						dir_path.to_path_buf()
        }
        Err(e) => {
            return Err(e.into());
        }
    };
    Ok(res)
}

fn save_base64_image(base64_data: &str, file_path: PathBuf) -> Result<()> {
    let decoded_data = decode(base64_data)?;
    let mut file = File::create(file_path)?;
    file.write_all(&decoded_data)?;
    Ok(())
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
#[serde(rename_all = "camelCase")]
pub enum NftImage {
    Null,
    Url(String),
    Object {
        url: String,
        size: Option<serde_json::Value>,
        mime_type: Option<String>,
    },
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NftToken {
    pub image: NftImage,
    pub name: Option<String>,
    pub collection_name: Option<String>,
    pub token_url: Option<String>,
    pub token_id: Option<String>,
    pub metadata: Option<serde_json::Value>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NftNode {
    token: NftToken,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NftTokens {
    pub nodes: Vec<NftNode>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NftData {
    pub tokens: NftTokens,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NftResponse {
    pub data: NftData,
}

impl NftResponse {
    pub async fn request(address: &str) -> Result<NftResponse> {
        let query = format!(
            r#"
		query NFTsForAddress {{
			tokens(networks: [{{network: ETHEREUM, chain: MAINNET}}],
						pagination: {{limit: 32}},
						where: {{ownerAddresses: "{}"}}) {{
				nodes {{
					token {{
						tokenId
						tokenUrl
						collectionName
						name
						image {{
							url
							size
							mimeType
						}}
						metadata
					}}
				}}
			}}
		}}
		"#,
            address
        );

        let request_body = to_value(serde_json::json!({
                        "query": query,
                        "variables": null,
        }))?;

        let response = Client::new()
            .post("https://api.zora.co/graphql")
            .json(&request_body)
            .send()
            .await
            .map_err(|err| eyre!("Failed to send request: {}", err))?;
        let mut response_body = response.bytes_stream();

        let mut response_data = Vec::new();
        while let Some(item) = response_body.next().await {
            let chunk = item.map_err(|err| eyre!("Failed to read response: {}", err))?;
            response_data.extend_from_slice(&chunk);
        }

        let response_str = String::from_utf8(response_data)
            .map_err(|err| eyre!("Failed to convert response to string: {}", err))?;
        if DEBUG {
            println!("{}", &response_str);
        }
        let response: NftResponse = serde_json::from_str(&response_str)
            .map_err(|err| eyre!("Failed to parse JSON response: {}", err))?;
        if DEBUG {
            println!("{:#?}", &response.data.tokens.nodes);
        }

        Ok(response)
    }
}

#[cfg(test)]
mod tests {
	/*
	use super::*;

    #[test]
    async fn resolve() {
        let provider: Provider<Http> = Provider::<Http>::try_from("https://eth.llamarpc.com");

        let address = &provider.resolve_name("tygra.eth").await;
        let result = format!("0x{}", encode(address));
        // let result = resolve_ens_name("tygra.eth", &provider);

        assert_eq!(result, "0x");
    }
		*/
	}