|
| 1 | +// Copyright (c) 2022-2023 Yuki Kishimoto |
| 2 | +// Copyright (c) 2023-2025 Rust Nostr Developers |
| 3 | +// Distributed under the MIT software license |
| 4 | + |
| 5 | +//! Nostr HTTP File Storage client (NIP-96) |
| 6 | +//! |
| 7 | +//! <https://github.com/nostr-protocol/nips/blob/master/96.md> |
| 8 | +
|
| 9 | +#![forbid(unsafe_code)] |
| 10 | +#![warn(missing_docs)] |
| 11 | +#![warn(rustdoc::bare_urls)] |
| 12 | +#![warn(clippy::large_futures)] |
| 13 | + |
| 14 | +use std::fmt; |
| 15 | +#[cfg(all(feature = "socks", not(target_arch = "wasm32")))] |
| 16 | +use std::net::SocketAddr; |
| 17 | +use std::time::Duration; |
| 18 | + |
| 19 | +use nostr::nips::nip96::{self, ServerConfig, UploadRequest, UploadResponse}; |
| 20 | +use nostr::signer::NostrSigner; |
| 21 | +use nostr::types::url::Url; |
| 22 | +#[cfg(all(feature = "socks", not(target_arch = "wasm32")))] |
| 23 | +use reqwest::Proxy; |
| 24 | +use reqwest::{multipart, Client, ClientBuilder, Response}; |
| 25 | + |
| 26 | +pub mod prelude; |
| 27 | + |
| 28 | +/// Nostr HTTP File Storage client error |
| 29 | +#[derive(Debug)] |
| 30 | +pub enum Error { |
| 31 | + /// Reqwest error |
| 32 | + Reqwest(reqwest::Error), |
| 33 | + /// NIP-96 error |
| 34 | + NIP96(nip96::Error), |
| 35 | + /// Multipart MIME error |
| 36 | + MultipartMime, |
| 37 | +} |
| 38 | + |
| 39 | +impl std::error::Error for Error {} |
| 40 | + |
| 41 | +impl fmt::Display for Error { |
| 42 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 43 | + match self { |
| 44 | + Self::Reqwest(e) => write!(f, "{e}"), |
| 45 | + Self::NIP96(e) => write!(f, "{e}"), |
| 46 | + Self::MultipartMime => write!(f, "Invalid MIME type for the multipart form"), |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl From<reqwest::Error> for Error { |
| 52 | + fn from(e: reqwest::Error) -> Self { |
| 53 | + Self::Reqwest(e) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl From<nip96::Error> for Error { |
| 58 | + fn from(e: nip96::Error) -> Self { |
| 59 | + Self::NIP96(e) |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +/// Nostr HTTP File Storage client |
| 64 | +#[derive(Debug, Clone)] |
| 65 | +pub struct NostrHttpFileStorageClientBuilder { |
| 66 | + /// Socks5 proxy |
| 67 | + #[cfg(all(feature = "socks", not(target_arch = "wasm32")))] |
| 68 | + pub proxy: Option<SocketAddr>, |
| 69 | + /// Timeout |
| 70 | + pub timeout: Duration, |
| 71 | +} |
| 72 | + |
| 73 | +impl Default for NostrHttpFileStorageClientBuilder { |
| 74 | + fn default() -> Self { |
| 75 | + Self { |
| 76 | + #[cfg(all(feature = "socks", not(target_arch = "wasm32")))] |
| 77 | + proxy: None, |
| 78 | + timeout: Duration::from_secs(60), |
| 79 | + } |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +impl NostrHttpFileStorageClientBuilder { |
| 84 | + /// New default builder |
| 85 | + #[inline] |
| 86 | + pub fn new() -> Self { |
| 87 | + Self::default() |
| 88 | + } |
| 89 | + |
| 90 | + /// Set proxy |
| 91 | + #[inline] |
| 92 | + #[cfg(all(feature = "socks", not(target_arch = "wasm32")))] |
| 93 | + pub fn proxy(mut self, addr: SocketAddr) -> Self { |
| 94 | + self.proxy = Some(addr); |
| 95 | + self |
| 96 | + } |
| 97 | + |
| 98 | + /// Set timeout |
| 99 | + #[inline] |
| 100 | + pub fn timeout(mut self, timeout: Duration) -> Self { |
| 101 | + self.timeout = timeout; |
| 102 | + self |
| 103 | + } |
| 104 | + |
| 105 | + /// Build the client |
| 106 | + pub fn build(self) -> Result<NostrHttpFileStorageClient, Error> { |
| 107 | + // Construct builder |
| 108 | + let mut builder: ClientBuilder = Client::builder(); |
| 109 | + |
| 110 | + // Set proxy |
| 111 | + #[cfg(all(feature = "socks", not(target_arch = "wasm32")))] |
| 112 | + if let Some(proxy) = self.proxy { |
| 113 | + let proxy: String = format!("socks5h://{proxy}"); |
| 114 | + builder = builder.proxy(Proxy::all(proxy)?); |
| 115 | + } |
| 116 | + |
| 117 | + // Set timeout |
| 118 | + builder = builder.timeout(self.timeout); |
| 119 | + |
| 120 | + // Build client |
| 121 | + let client: Client = builder.build()?; |
| 122 | + |
| 123 | + // Construct client |
| 124 | + Ok(NostrHttpFileStorageClient::from_client(client)) |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +/// Nostr HTTP File Storage client |
| 129 | +#[derive(Debug, Clone)] |
| 130 | +pub struct NostrHttpFileStorageClient { |
| 131 | + client: Client, |
| 132 | +} |
| 133 | + |
| 134 | +impl Default for NostrHttpFileStorageClient { |
| 135 | + fn default() -> Self { |
| 136 | + Self::new() |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +impl NostrHttpFileStorageClient { |
| 141 | + /// Construct a default client |
| 142 | + #[inline] |
| 143 | + pub fn new() -> Self { |
| 144 | + Self::builder().build().expect("Failed to build client") |
| 145 | + } |
| 146 | + |
| 147 | + /// Construct from reqwest [`Client`]. |
| 148 | + #[inline] |
| 149 | + pub fn from_client(client: Client) -> Self { |
| 150 | + Self { client } |
| 151 | + } |
| 152 | + |
| 153 | + /// Get a builder |
| 154 | + #[inline] |
| 155 | + pub fn builder() -> NostrHttpFileStorageClientBuilder { |
| 156 | + NostrHttpFileStorageClientBuilder::default() |
| 157 | + } |
| 158 | + |
| 159 | + /// Get the nip96.json file on the server and return the JSON as a [`ServerConfig`] |
| 160 | + pub async fn get_server_config(&self, server_url: &Url) -> Result<ServerConfig, Error> { |
| 161 | + let nip96_url: Url = nip96::get_server_config_url(server_url)?; |
| 162 | + |
| 163 | + let response = self.client.get(nip96_url).send().await?; |
| 164 | + |
| 165 | + // Deserialize response |
| 166 | + Ok(response.json().await?) |
| 167 | + } |
| 168 | + |
| 169 | + /// Uploads some data to a NIP-96 server and returns the file's download URL |
| 170 | + pub async fn upload<T>( |
| 171 | + &self, |
| 172 | + signer: &T, |
| 173 | + config: &ServerConfig, |
| 174 | + file_data: Vec<u8>, |
| 175 | + mime_type: Option<&str>, |
| 176 | + ) -> Result<Url, Error> |
| 177 | + where |
| 178 | + T: NostrSigner, |
| 179 | + { |
| 180 | + // Create new request |
| 181 | + let req: UploadRequest = UploadRequest::new(signer, config, &file_data).await?; |
| 182 | + |
| 183 | + // Make form |
| 184 | + let form: multipart::Form = make_multipart_form(file_data, mime_type)?; |
| 185 | + |
| 186 | + // Send |
| 187 | + let response: Response = self |
| 188 | + .client |
| 189 | + .post(config.api_url.clone()) |
| 190 | + .header("Authorization", req.authorization()) |
| 191 | + .multipart(form) |
| 192 | + .send() |
| 193 | + .await?; |
| 194 | + |
| 195 | + // Decode response |
| 196 | + let res: UploadResponse = response.json().await?; |
| 197 | + |
| 198 | + // Try to extract download URL |
| 199 | + Ok(res.download_url().cloned()?) |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +fn make_multipart_form( |
| 204 | + file_data: Vec<u8>, |
| 205 | + mime_type: Option<&str>, |
| 206 | +) -> Result<multipart::Form, Error> { |
| 207 | + let form_file_part = multipart::Part::bytes(file_data).file_name("filename"); |
| 208 | + |
| 209 | + // Set the part's MIME type, or leave it as is if mime_type is None |
| 210 | + let part = match mime_type { |
| 211 | + Some(mime) => form_file_part |
| 212 | + .mime_str(mime) |
| 213 | + .map_err(|_| Error::MultipartMime)?, |
| 214 | + None => form_file_part, |
| 215 | + }; |
| 216 | + |
| 217 | + Ok(multipart::Form::new().part("file", part)) |
| 218 | +} |
0 commit comments