wf-market 0.3.2

A Rust client library for the warframe.market API
Documentation
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! HTTP client for the warframe.market API.
//!
//! This module provides the [`Client`] type which is the main entry point
//! for interacting with the warframe.market API.
//!
//! # Type States
//!
//! The client uses a type-state pattern to provide compile-time safety:
//!
//! - [`Client<Unauthenticated>`]: Can only access public endpoints
//! - [`Client<Authenticated>`]: Can access all endpoints including user-specific ones
//!
//! # Example
//!
//! ```no_run
//! use wf_market::{Client, Credentials};
//!
//! async fn example() -> wf_market::Result<()> {
//!     // Create an unauthenticated client
//!     let client = Client::builder().build().await?;
//!
//!     // Fetch public data
//!     let items = client.fetch_items().await?;
//!
//!     // Login to access authenticated endpoints
//!     let creds = Credentials::new("email", "password", Credentials::generate_device_id());
//!     let client = client.login(creds).await?;
//!
//!     // Now we can access user-specific endpoints
//!     let my_orders = client.my_orders().await?;
//!
//!     Ok(())
//! }
//! ```

mod auth;
mod builder;

pub use builder::*;

use std::marker::PhantomData;
use std::sync::Arc;

use crate::error::{Error, Result};
use crate::internal::ApiRateLimiter;
use crate::models::{Credentials, Item, ItemIndex, Language, Platform};

// Sealed trait pattern for auth states
mod private {
    pub trait Sealed {}
    impl Sealed for super::Unauthenticated {}
    impl Sealed for super::Authenticated {}
}

/// Marker trait for authentication states.
pub trait AuthState: private::Sealed {}

/// Unauthenticated state - can only access public endpoints.
#[derive(Debug, Clone, Copy)]
pub struct Unauthenticated;
impl AuthState for Unauthenticated {}

/// Authenticated state - can access all endpoints.
#[derive(Debug, Clone, Copy)]
pub struct Authenticated;
impl AuthState for Authenticated {}

/// Client configuration.
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// Gaming platform (default: PC)
    pub platform: Platform,
    /// Language for responses (default: English)
    pub language: Language,
    /// Enable cross-play orders (default: true)
    pub crossplay: bool,
    /// Rate limit (requests per second, default: 3)
    pub rate_limit: u32,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            platform: Platform::Pc,
            language: Language::English,
            crossplay: true,
            rate_limit: 3,
        }
    }
}

/// HTTP client for the warframe.market API.
///
/// The client is parameterized by an authentication state:
///
/// - `Client<Unauthenticated>`: Can only access public endpoints
/// - `Client<Authenticated>`: Can access all endpoints
///
/// Use [`Client::builder()`] to create a new client.
pub struct Client<S: AuthState = Unauthenticated> {
    pub(crate) http: reqwest::Client,
    pub(crate) config: ClientConfig,
    pub(crate) limiter: Arc<ApiRateLimiter>,
    pub(crate) credentials: Option<Credentials>,
    pub(crate) items: Arc<ItemIndex>,
    pub(crate) _state: PhantomData<S>,
}

impl Client<Unauthenticated> {
    /// Create a new client builder.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::{Client, Platform, Language};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::builder()
    ///         .platform(Platform::Pc)
    ///         .language(Language::English)
    ///         .build()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Create a client and login in one step.
    ///
    /// This is a convenience method equivalent to:
    /// ```no_run
    /// # use wf_market::{Client, Credentials};
    /// # async fn example() -> wf_market::Result<()> {
    /// # let credentials = Credentials::new("", "", "");
    /// let client = Client::builder().build().await?.login(credentials).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Example
    ///
    /// ```no_run
    /// use wf_market::{Client, Credentials};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let creds = Credentials::new("email", "password", Credentials::generate_device_id());
    ///     let client = Client::from_credentials(creds).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn from_credentials(credentials: Credentials) -> Result<Client<Authenticated>> {
        Self::builder().build().await?.login(credentials).await
    }

    /// Create a client with custom config and login in one step.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use wf_market::{Client, ClientConfig, Credentials, Platform};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let config = ClientConfig {
    ///         platform: Platform::Ps4,
    ///         ..Default::default()
    ///     };
    ///     let creds = Credentials::new("email", "password", Credentials::generate_device_id());
    ///     let client = Client::from_credentials_with_config(creds, config).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn from_credentials_with_config(
        credentials: Credentials,
        config: ClientConfig,
    ) -> Result<Client<Authenticated>> {
        Self::builder()
            .config(config)
            .build()
            .await?
            .login(credentials)
            .await
    }

    /// Validate credentials without fully logging in.
    ///
    /// This is useful for checking if a saved token is still valid
    /// before creating a full authenticated client.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use wf_market::{Client, Credentials};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let saved = Credentials::from_token("email", "device-id", "saved-token");
    ///
    ///     if Client::validate_credentials(&saved).await? {
    ///         let client = Client::from_credentials(saved).await?;
    ///         println!("Session restored!");
    ///     } else {
    ///         println!("Token expired, please login again");
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn validate_credentials(credentials: &Credentials) -> Result<bool> {
        use crate::internal::{BASE_URL, build_authenticated_client};

        if let Some(token) = credentials.token() {
            let http = build_authenticated_client(Platform::Pc, Language::English, true, token)
                .map_err(Error::Network)?;

            match http.get(format!("{}/me", BASE_URL)).send().await {
                Ok(resp) if resp.status().is_success() => Ok(true),
                Ok(resp) if resp.status() == reqwest::StatusCode::UNAUTHORIZED => Ok(false),
                Ok(resp) => Err(Error::api(
                    resp.status(),
                    format!("Unexpected response: {}", resp.status()),
                )),
                Err(e) => Err(Error::Network(e)),
            }
        } else {
            // Password-based credentials can't be validated without logging in
            // Return true since we'll find out during login if they're invalid
            Ok(true)
        }
    }

    /// Create an unauthenticated client (internal use).
    pub(crate) fn new_unauthenticated(
        http: reqwest::Client,
        config: ClientConfig,
        limiter: Arc<ApiRateLimiter>,
        items: Arc<ItemIndex>,
    ) -> Self {
        Self {
            http,
            config,
            limiter,
            credentials: None,
            items,
            _state: PhantomData,
        }
    }
}

impl<S: AuthState> Client<S> {
    /// Get the client configuration.
    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    /// Get the platform this client is configured for.
    pub fn platform(&self) -> Platform {
        self.config.platform
    }

    /// Get the language this client is configured for.
    pub fn language(&self) -> Language {
        self.config.language
    }

    /// Get the item index.
    ///
    /// The item index provides O(1) lookups for items by ID or slug.
    /// It is automatically populated when the client is constructed.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let client = Client::builder().build().await?;
    ///
    /// // Iterate over all items
    /// for item in client.items().iter() {
    ///     println!("{}: {}", item.slug, item.name());
    /// }
    ///
    /// // Lookup by slug
    /// if let Some(item) = client.items().get_by_slug("serration") {
    ///     println!("Found: {}", item.name());
    /// }
    /// ```
    pub fn items(&self) -> &ItemIndex {
        &self.items
    }

    /// Get an item by its unique ID.
    ///
    /// This is a convenience method equivalent to `client.items().get_by_id(id)`.
    pub fn get_item_by_id(&self, id: &str) -> Option<&Item> {
        self.items.get_by_id(id)
    }

    /// Get an item by its URL-friendly slug.
    ///
    /// This is a convenience method equivalent to `client.items().get_by_slug(slug)`.
    pub fn get_item_by_slug(&self, slug: &str) -> Option<&Item> {
        self.items.get_by_slug(slug)
    }

    /// Get a shared reference to the item index.
    ///
    /// This is useful for passing to functions that need the index.
    pub(crate) fn items_arc(&self) -> Arc<ItemIndex> {
        Arc::clone(&self.items)
    }

    /// Wait for rate limiter before making a request.
    pub(crate) async fn wait_for_rate_limit(&self) {
        self.limiter.until_ready().await;
    }
}

impl Client<Authenticated> {
    /// Get the current credentials (with token) for persistence.
    ///
    /// The returned credentials can be serialized and stored, then
    /// used with [`Credentials::from_token()`] to restore the session.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use wf_market::{Client, Credentials};
    ///
    /// async fn save_session(client: &Client<wf_market::client::Authenticated>) -> std::io::Result<()> {
    ///     let creds = client.credentials();
    ///     let json = serde_json::to_string(creds)?;
    ///     std::fs::write("session.json", json)?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// This method uses `expect()` internally but should never panic because
    /// `Client<Authenticated>` can only be constructed with valid credentials.
    /// If this panics, it indicates an internal invariant violation.
    pub fn credentials(&self) -> &Credentials {
        self.credentials
            .as_ref()
            .expect("Authenticated client must have credentials")
    }

    /// Export credentials for saving (convenience method).
    ///
    /// This clones the credentials so they can be serialized and stored.
    pub fn export_session(&self) -> Credentials {
        self.credentials().clone()
    }

    /// Get the authentication token.
    ///
    /// # Panics
    ///
    /// This method uses `expect()` internally but should never panic because
    /// `Client<Authenticated>` can only be constructed with valid credentials
    /// that include a token. If this panics, it indicates an internal invariant violation.
    pub fn token(&self) -> &str {
        self.credentials()
            .token()
            .expect("Authenticated client must have token")
    }

    /// Get the device ID.
    pub fn device_id(&self) -> &str {
        &self.credentials().device_id
    }

    /// Create an authenticated client (internal use).
    pub(crate) fn new_authenticated(
        http: reqwest::Client,
        config: ClientConfig,
        limiter: Arc<ApiRateLimiter>,
        credentials: Credentials,
        items: Arc<ItemIndex>,
    ) -> Self {
        Self {
            http,
            config,
            limiter,
            credentials: Some(credentials),
            items,
            _state: PhantomData,
        }
    }
}

// Clone implementations
impl Clone for Client<Unauthenticated> {
    fn clone(&self) -> Self {
        Self {
            http: self.http.clone(),
            config: self.config.clone(),
            limiter: self.limiter.clone(),
            credentials: None,
            items: self.items.clone(),
            _state: PhantomData,
        }
    }
}

impl Clone for Client<Authenticated> {
    fn clone(&self) -> Self {
        Self {
            http: self.http.clone(),
            config: self.config.clone(),
            limiter: self.limiter.clone(),
            credentials: self.credentials.clone(),
            items: self.items.clone(),
            _state: PhantomData,
        }
    }
}