pinata_sdk/api/data.rs
1use std::collections::HashMap;
2use serde::{Deserialize, Serialize};
3use derive_builder::Builder;
4use crate::api::metadata::{PinMetadata, PinListMetadata, MetadataKeyValues, MetadataValue};
5
6#[derive(Clone, Debug, Deserialize, Serialize)]
7/// All the currently supported regions on Pinata
8pub enum Region {
9 /// Frankfurt, Germany (max 2 replications)
10 FRA1,
11 /// New York City, USA (max 2 replications)
12 NYC1,
13}
14
15#[derive(Clone, Debug, Deserialize, Serialize)]
16#[serde(rename_all = "camelCase")]
17/// Region and desired replication for that region
18pub struct RegionPolicy {
19 /// Region Id
20 pub id: Region,
21 /// Replication count for the region. Maximum of 2 in most regions
22 pub desired_replication_count: u8,
23}
24
25#[derive(Debug, Deserialize, Serialize)]
26/// Pinata Pin Policy Regions
27pub struct PinPolicy {
28 /// List of regions and their Policy
29 pub regions: Vec<RegionPolicy>,
30}
31
32#[derive(Serialize)]
33#[serde(rename_all = "camelCase")]
34/// Represents a PinPolicy linked to a particular ipfs pinned hash
35pub struct HashPinPolicy {
36 ipfs_pin_hash: String,
37 new_pin_policy: PinPolicy,
38}
39
40impl HashPinPolicy {
41 /// Create a new HashPinPolicy.
42 ///
43 /// See the [pinata docs](https://pinata.cloud/documentation#HashPinPolicy) for more information.
44 pub fn new<S>(ipfs_pin_hash: S, regions: Vec<RegionPolicy>) -> HashPinPolicy
45 where S: Into<String>
46 {
47 HashPinPolicy {
48 ipfs_pin_hash: ipfs_pin_hash.into(),
49 new_pin_policy: PinPolicy { regions },
50 }
51 }
52}
53
54#[derive(Clone, Debug, Deserialize, Serialize)]
55/// Status of Jobs
56#[serde(rename_all = "snake_case")]
57pub enum JobStatus {
58 /// Pinata is running preliminary validations on your pin request.
59 Prechecking,
60 /// Pinata is actively searching for your content on the IPFS network.
61 Searching,
62 /// Pinata has located your content and is now in the process of retrieving it.
63 Retrieving,
64 /// Pinata wasn't able to find your content after a day of searching the IPFS network.
65 Expired,
66 /// Pinning this object would put you over the free tier limit. Please add a credit card
67 /// to continue.
68 OverFreeLimit,
69 /// This object is too large of an item to pin. If you're seeing this, please contact pinata
70 /// for a more custom solution.
71 OverMaxSize,
72 /// The object you're attempting to pin isn't readable by IPFS nodes.
73 InvalidObject,
74 /// You provided a host node that was either invalid or unreachable.
75 BadHostNode,
76}
77
78#[derive(Deserialize, Debug)]
79#[serde(rename_all = "camelCase")]
80/// Represents response of a pinByHash request.
81pub struct PinByHashResult {
82 /// This is Pinata's ID for the pin job.
83 pub id: String,
84 /// This is the IPFS multi-hash provided to Pinata to pin.
85 pub ipfs_hash: String,
86 /// Current status of the pin job.
87 pub status: JobStatus,
88 /// The name of the pin (if provided initially)
89 pub name: Option<String>,
90}
91
92#[derive(Serialize)]
93#[serde(rename_all = "camelCase")]
94/// Used to add additional options when pinning by hash
95pub struct PinOptions {
96 /// multiaddresses of nodes your content is already stored on
97 pub host_nodes: Option<Vec<String>>,
98 /// Custom pin policy for the piece of content being pinned
99 pub custom_pin_policy: Option<PinPolicy>,
100 /// CID Version IPFS will use when creating a hash for your content
101 pub cid_version: Option<u8>,
102}
103
104#[derive(Serialize)]
105#[serde(rename_all = "camelCase")]
106/// Request object to pin hash of an already existing IPFS hash to pinata.
107///
108/// ## Example
109/// ```
110/// # use pinata_sdk::{ApiError, PinataApi, PinByHash};
111/// # async fn run() -> Result<(), ApiError> {
112/// let api = PinataApi::new("api_key", "secret_api_key").unwrap();
113///
114/// let result = api.pin_by_hash(PinByHash::new("hash")).await;
115///
116/// if let Ok(pinning_job) = result {
117/// // track result job here
118/// }
119/// # Ok(())
120/// # }
121/// ```
122pub struct PinByHash {
123 hash_to_pin: String,
124 pinata_metadata: Option<PinMetadata>,
125 pinata_option: Option<PinOptions>,
126}
127
128impl PinByHash {
129 /// Create a new default PinByHash object with only the hash to pin set.
130 ///
131 /// To set the pinata metadata and pinata options use the `set_metadata()` and
132 /// `set_options()` chainable function to set those values.
133 pub fn new<S>(hash: S) -> PinByHash
134 where S: Into<String>
135 {
136 PinByHash {
137 hash_to_pin: hash.into(),
138 pinata_metadata: None,
139 pinata_option: None,
140 }
141 }
142
143 /// Consumes the current PinByHash and returns a new PinByHash with keyvalues metadata set
144 pub fn set_metadata(self, keyvalues: MetadataKeyValues) -> PinByHash {
145 PinByHash {
146 hash_to_pin: self.hash_to_pin,
147 pinata_metadata: Some(PinMetadata {
148 keyvalues,
149 name: None,
150 }),
151 pinata_option: self.pinata_option,
152 }
153 }
154
155 /// Consumes the current PinByHash and returns a new PinByHash with metadata name and keyvalues set
156 pub fn set_metadata_with_name<S>(self, name: S, keyvalues: HashMap<String, MetadataValue>) -> PinByHash
157 where S: Into<String>
158 {
159 PinByHash {
160 hash_to_pin: self.hash_to_pin,
161 pinata_metadata: Some(PinMetadata {
162 keyvalues,
163 name: Some(name.into()),
164 }),
165 pinata_option: self.pinata_option,
166 }
167 }
168
169 /// Consumes the PinByHash and returns a new PinByHash with pinata options set.
170 pub fn set_options(self, options: PinOptions) -> PinByHash {
171 PinByHash {
172 hash_to_pin: self.hash_to_pin,
173 pinata_metadata: self.pinata_metadata,
174 pinata_option: Some(options),
175 }
176 }
177}
178
179#[derive(Serialize)]
180#[serde(rename_all = "camelCase")]
181/// Request object to pin json
182///
183/// ## Example
184/// ```
185/// # use pinata_sdk::{ApiError, PinataApi, PinByJson};
186/// # use std::collections::HashMap;
187/// # async fn run() -> Result<(), ApiError> {
188/// let api = PinataApi::new("api_key", "secret_api_key").unwrap();
189///
190/// let mut json_data = HashMap::new();
191/// json_data.insert("name", "user");
192///
193/// let result = api.pin_json(PinByJson::new(json_data)).await;
194///
195/// if let Ok(pinned_object) = result {
196/// let hash = pinned_object.ipfs_hash;
197/// }
198/// # Ok(())
199/// # }
200/// ```
201pub struct PinByJson<S: Serialize> {
202 pinata_content: S,
203 pinata_metadata: Option<PinMetadata>,
204 pinata_option: Option<PinOptions>,
205}
206
207impl <S> PinByJson<S>
208 where S: Serialize
209{
210 /// Create a new default PinByHash object with only the hash to pin set.
211 ///
212 /// To set the pinata metadata and pinata options use the `set_metadata()` and
213 /// `set_options()` chainable function to set those values.
214 pub fn new(json_data: S) -> PinByJson<S> {
215 PinByJson {
216 pinata_content: json_data,
217 pinata_metadata: None,
218 pinata_option: None,
219 }
220 }
221
222 /// Consumes the current PinByJson<S> and returns a new PinByJson<S> with keyvalues metadata set
223 pub fn set_metadata(mut self, keyvalues: MetadataKeyValues) -> PinByJson<S> {
224 self.pinata_metadata = Some(PinMetadata {
225 name: None,
226 keyvalues,
227 });
228 self
229 }
230
231 /// Consumes the current PinByJson<S> and returns a new PinByJson<S> with keyvalues metadata set
232 pub fn set_metadata_with_name<IntoStr>(
233 mut self, name: IntoStr,
234 keyvalues: MetadataKeyValues
235 ) -> PinByJson<S>
236 where IntoStr: Into<String>
237 {
238 self.pinata_metadata = Some(PinMetadata {
239 name: Some(name.into()),
240 keyvalues,
241 });
242 self
243 }
244
245 /// Consumes the PinByHash and returns a new PinByHash with pinata options set.
246 pub fn set_options(mut self, options: PinOptions) -> PinByJson<S> {
247 self.pinata_option = Some(options);
248 self
249 }
250}
251
252#[derive(Clone)]
253/// Internal structure use to know how to read a file or structure
254pub(crate) struct FileData {
255 pub(crate) file_path: String,
256}
257
258/// Request object to pin a file
259///
260/// ## Example
261/// ```
262/// # use pinata_sdk::{ApiError, PinataApi, PinByFile};
263/// # async fn run() -> Result<(), ApiError> {
264/// let api = PinataApi::new("api_key", "secret_api_key").unwrap();
265///
266/// let result = api.pin_file(PinByFile::new("file_or_dir_path")).await;
267///
268/// if let Ok(pinned_object) = result {
269/// let hash = pinned_object.ipfs_hash;
270/// }
271/// # Ok(())
272/// # }
273/// ```
274pub struct PinByFile {
275 pub(crate) files: Vec<FileData>,
276 pub(crate) pinata_metadata: Option<PinMetadata>,
277 pub(crate) pinata_option: Option<PinOptions>,
278}
279
280impl PinByFile {
281 /// Create a PinByFile object.
282 ///
283 /// `file_or_dir_path` can be path to a file or to a directory.
284 /// If a directory is provided
285 pub fn new<S: Into<String>>(file_or_dir_path: S) -> PinByFile {
286 let owned_file_path = file_or_dir_path.into();
287 PinByFile {
288 files: [
289 FileData { file_path: owned_file_path }
290 ].to_vec(),
291 pinata_metadata: None,
292 pinata_option: None,
293 }
294 }
295
296 /// Consumes the current PinByFile and returns a new PinByFile with keyvalues metadata set
297 pub fn set_metadata(mut self, keyvalues: MetadataKeyValues) -> PinByFile {
298 self.pinata_metadata = Some(PinMetadata {
299 name: None,
300 keyvalues,
301 });
302 self
303 }
304
305 /// Consumes the current PinByFile and returns a new PinByFile with keyvalues metadata set
306 pub fn set_metadata_with_name<IntoStr>(
307 mut self, name: IntoStr,
308 keyvalues: MetadataKeyValues
309 ) -> PinByFile
310 where IntoStr: Into<String>
311 {
312 self.pinata_metadata = Some(PinMetadata {
313 name: Some(name.into()),
314 keyvalues,
315 });
316 self
317 }
318
319 /// Consumes the PinByHash and returns a new PinByHash with pinata options set.
320 pub fn set_options(mut self, options: PinOptions) -> PinByFile {
321 self.pinata_option = Some(options);
322 self
323 }
324}
325
326#[derive(Clone, Serialize)]
327/// Sort Direction
328pub enum SortDirection {
329 /// Sort by ascending dates
330 ASC,
331 /// Sort by descending dates
332 DESC,
333}
334
335#[derive(Builder, Clone, Default, Serialize)]
336#[builder(setter(into, strip_option, prefix = "set"), default)]
337/// Filter parameters for fetching PinJobs
338///
339/// Example of how to use this:
340/// ```
341/// use pinata_sdk::{PinJobsFilterBuilder, PinJobsFilter, SortDirection, JobStatus};
342///
343/// let filters: PinJobsFilter = PinJobsFilterBuilder::default()
344/// .set_sort(SortDirection::ASC)
345/// .set_status(JobStatus::Prechecking)
346/// .set_limit(1 as u16)
347/// // ...other possible filter set methods
348/// .build().unwrap();
349/// ```
350pub struct PinJobsFilter {
351 /// Sort the results by the date added to the pinning queue
352 sort: Option<SortDirection>,
353 /// Set a status on the PinJobsFilter
354 status: Option<JobStatus>,
355 /// Set a IPFS pin hash on the PinJobsFilter
356 ipfs_pin_hash: Option<String>,
357 /// Set limit on the amount of results per page
358 limit: Option<u16>,
359 /// Set the record offset for records returned. This is how to retrieve additional pages
360 offset: Option<u64>,
361}
362
363#[derive(Debug, Deserialize)]
364/// Pin Job Record
365pub struct PinJob {
366 /// The id for the pin job record
367 pub id: String,
368 /// The IPFS mult-hash for the content pinned.
369 pub ipfs_pin_hash: String,
370 /// The date hash was initially queued. Represented in ISO8601 format
371 pub date_queued: String,
372 /// The current status for the pin job
373 pub status: JobStatus,
374 /// Optional name passed for hash
375 pub name: Option<String>,
376 /// Optional keyvalues metadata passsed for hash
377 pub keyvalues: Option<HashMap<String, String>>,
378 /// Optional list of host nodes passed for the hash
379 pub host_nodes: Option<Vec<String>>,
380 /// PinPolicy applied to content once it is found
381 pub pin_policy: Option<PinPolicy>,
382}
383
384#[derive(Debug, Deserialize)]
385/// Represents a list of pin job records for a set of filters.
386pub struct PinJobs {
387 /// Total number of pin job records that exist for the PinJobsFilter used
388 pub count: u64,
389 /// Each item in the rows represents a pin job record
390 pub rows: Vec<PinJob>,
391}
392
393#[derive(Debug, Deserialize)]
394#[serde(rename_all = "PascalCase")]
395/// Represents a PinnedObject
396pub struct PinnedObject {
397 /// IPFS multi-hash provided back for your content
398 pub ipfs_hash: String,
399 /// This is how large (in bytes) the content you just pinned is
400 pub pin_size: u64,
401 /// Timestamp for your content pinning in ISO8601 format
402 pub timestamp: String
403}
404
405#[derive(Debug, Deserialize)]
406/// Results of a call to get total users pinned data
407pub struct TotalPinnedData {
408 /// The number of pins you currently have pinned with Pinata
409 pub pin_count: u128,
410 /// The total size of all unique content you have pinned with Pinata (expressed in bytes)
411 pub pin_size_total: String,
412 /// The total size of all content you have pinned with Pinata. This value is derived by multiplying the size of each piece of unique content by the number of times that content is replicated.
413 pub pin_size_with_replications_total: String,
414}
415
416#[derive(Clone, Debug, Serialize)]
417#[serde(rename_all = "lowercase")]
418/// Status used with [PinListFilterBuilder](struct.PinListFilterBuilder.html)
419/// to filter on pin list results.
420pub enum PinListFilterStatus {
421 /// For both pinned and unpinned records
422 All,
423 /// For just pinned records (hashes that are currently pinned)
424 Pinned,
425 /// For just unpinned records (previous hashes that are no longer being pinned on pinata)
426 Unpinned,
427}
428
429#[derive(Builder, Default, Debug, Serialize)]
430#[serde(rename_all = "camelCase")]
431#[builder(setter(strip_option, prefix = "set"), default)]
432/// Options to filter your pin list based on a number of different options
433///
434/// Create and set values using [PinListFilterBuilder](struct.PinListFilterBuilder.html).
435///
436/// ```
437/// use pinata_sdk::PinListFilterBuilder;
438///
439/// let filter = PinListFilterBuilder::default()
440/// .set_hash_contains("QmWsZfQw98k9dfG1sDZB3z8YqMtxG9gYCyddgZGWq4w6Z3".to_string())
441/// .build()
442/// .unwrap();
443/// ```
444pub struct PinListFilter {
445 #[serde(skip_serializing_if = "Option::is_none")]
446 /// Filter on alphanumeric characters inside of pin hashes. Hashes which do not include the characters passed in will not be returned
447 hash_contains: Option<String>,
448 #[serde(skip_serializing_if = "Option::is_none")]
449 /// Exclude pin records that were pinned before the passed in "pinStart" datetime
450 /// (must be in ISO_8601 format)
451 pin_start: Option<String>,
452 #[serde(skip_serializing_if = "Option::is_none")]
453 /// (must be in ISO_8601 format) - Exclude pin records that were pinned after the passed in "pinEnd" datetime
454 pin_end: Option<String>,
455 #[serde(skip_serializing_if = "Option::is_none")]
456 /// (must be in ISO_8601 format) - Exclude pin records that were unpinned before the passed in "unpinStart" datetime
457 unpin_start: Option<String>,
458 #[serde(skip_serializing_if = "Option::is_none")]
459 /// (must be in ISO_8601 format) - Exclude pin records that were unpinned after the passed in "unpinEnd" datetime
460 unpin_end: Option<String>,
461 #[serde(skip_serializing_if = "Option::is_none")]
462 /// The minimum byte size that pin record you're looking for can have
463 pin_size_min: Option<usize>,
464 #[serde(skip_serializing_if = "Option::is_none")]
465 /// The maximum byte size that pin record you're looking for can have
466 pin_size_max: Option<usize>,
467 #[serde(skip_serializing_if = "Option::is_none")]
468 /// The status of pin lists results
469 status: Option<PinListFilterStatus>,
470 #[serde(skip_serializing_if = "Option::is_none")]
471 /// Filter on metadata name or metadata keyvalues.
472 /// If specifying a `metadata[keyvalues]` filter, you need to ensure that you encode the values as the recommended
473 /// JSON accordingly. See the pinata docs [here](https://pinata.cloud/documentation#PinList) under the 'Metadata Querying'
474 /// section for more details.
475 metadata: Option<HashMap<String, String>>,
476 #[serde(skip_serializing_if = "Option::is_none")]
477 /// This sets the amount of records that will be returned per API response. (Max 1000)
478 page_limit: Option<String>,
479 #[serde(skip_serializing_if = "Option::is_none")]
480 /// This tells the API how far to offset the record responses. For example, if there's 30 records that match your query, and you passed in a pageLimit of 10, providing a pageOffset of 10 would return records 11-20
481 page_offset: Option<String>,
482}
483
484#[derive(Debug, Deserialize)]
485#[serde(rename_all = "camelCase")]
486/// RegionPolicy active on the PinListItem
487pub struct PinListItemRegionPolicy {
488 /// Region this content is expected to be pinned in
489 pub region_id: Region,
490 /// The number of replications desired in this region
491 pub desired_replication_count: u8,
492 /// The number of times this content has been replicated so far
493 pub current_replication_count: u8,
494}
495
496#[derive(Debug, Deserialize)]
497/// A pinned item gotten from get PinList request
498///
499/// This is usually as part of the PinList struct which is gotten as response
500pub struct PinListItem {
501 /// The id of this pin item record
502 pub id: String,
503 /// The IPFS multihash for this items content
504 pub ipfs_pin_hash: String,
505 /// Size in bytes of the content pinned
506 pub size: usize,
507 /// Users Pinata id
508 pub user_id: String,
509 /// ISO 8601 timestamp for when this content was pinned.
510 pub date_pinned: String,
511 /// ISO 8601 timestamp for when this content was unpinned.
512 ///
513 /// Is None for content that is not yet unpinned
514 pub data_unpinned: Option<String>,
515 /// Metadata of the original uploaded files
516 pub metadata: PinListMetadata,
517 /// Region Policy set on the item
518 pub regions: Vec<PinListItemRegionPolicy>,
519}
520
521#[derive(Debug, Deserialize)]
522/// Result of request to get pinList
523pub struct PinList {
524 /// Total number of pin records that exist for the query filters passed
525 pub count: u128,
526 /// List of pinned item in the result set
527 pub rows: Vec<PinListItem>,
528}