cyclone-mod 0.1.0

A NexusMods API wrapper
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::collections::HashMap;

use reqwest::{
    Client, ClientBuilder, Method, RequestBuilder, StatusCode,
    header::{HeaderMap, HeaderValue},
};

use crate::{
    VERSION,
    err::{self, delete, get, post, validate},
    nexus_joiner,
    request::{
        CategoryName, Changelog, Endorsements, GameId, GameMod, ModFile, ModFiles, ModId,
        ModUpdated, RateLimiting, TimePeriod, TrackedModsRaw, Validate,
    },
};

/// Top level API handler.
///
/// All network calls are handled through here.
pub struct Api {
    key: String,
    client: Client,
}

impl Api {
    /// Create a new wrapper with a [personal API key](https://next.nexusmods.com/settings/api-keys).
    ///
    /// Ideally should be checked with [`Api::validate`] right after:
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use cyclone::Api;
    /// # tokio_test::block_on(async {
    /// let api = Api::new("here is my custom key");
    /// assert!(api.validate().await.is_ok());
    /// # })
    /// ```
    pub fn new<S: Into<String>>(key: S) -> Self {
        let key = key.into();
        let client = ClientBuilder::new().default_headers({
            let mut h = HeaderMap::new();
            h.insert("apikey", key.parse().unwrap());
            h.insert("accept", HeaderValue::from_static("application/json"));
            h
        });
        Self {
            key,
            client: client.build().expect("oops"),
        }
    }

    pub(crate) fn key(&self) -> &str {
        &self.key
    }

    fn build(
        &self,
        method: Method,
        ver: &str,
        slugs: &[&str],
        params: &[(&'static str, &str)],
    ) -> RequestBuilder {
        self.client
            .request(method, nexus_joiner!(ver, slugs))
            .query(params)
    }

    // TODO: Add rate limiting checking.
}

/// User related methods.
///
/// # Status
///
/// - [x] `GET`    [`v1/users/validate`](`Api::validate`)
/// - [x] `GET`    [`v1/user/tracked_mods`](`Api::tracked_mods`)
/// - [x] `POST`   [`v1/user/tracked_mods`](`Api::track_mod`)
/// - [x] `DELETE` [`v1/user/tracked_mods`](`Api::untrack_mod`)
/// - [x] `GET`    [`v1/user/endorsements`](`Api::endorsements`)
impl Api {
    /// Validate API key and retrieve user details.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use cyclone::{Api, err::validate::ValidateError};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), ValidateError> {
    /// let api = Api::new("...");
    /// // I am a premium user!
    /// assert!(api.validate().await?.is_premium());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn validate(&self) -> Result<Validate, validate::ValidateError> {
        let response = self
            .build(Method::GET, VERSION, &["users", "validate"], &[])
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response
                .json()
                .await
                .map_err(validate::ValidateError::Reqwest),
            StatusCode::UNAUTHORIZED => Err(validate::ValidateError::InvalidAPIKey(
                response.json().await?,
            )),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404 (401), and 422"),
        }
    }

    /// Get a list of the user's tracked mods.
    ///
    /// # Notes
    /// Consider converting to [`TrackedMods`](`crate::request::TrackedMods`).
    pub async fn tracked_mods(&self) -> Result<TrackedModsRaw, validate::ValidateError> {
        let response = self
            .build(Method::GET, VERSION, &["user", "tracked_mods"], &[])
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response
                .json()
                .await
                .map_err(validate::ValidateError::Reqwest),
            StatusCode::UNAUTHORIZED => Err(validate::ValidateError::InvalidAPIKey(
                response.json().await?,
            )),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404 (401), and 422"),
        }
    }

    /// Track a mod based on a `u64` mod ID.
    pub async fn track_mod<T: Into<u64>>(
        &self,
        game: &str,
        id: T,
    ) -> Result<post::PostModStatus, post::TrackModError> {
        let id = id.into();
        let response = self
            .build(Method::POST, VERSION, &["user", "tracked_mods"], &[])
            .query(&[("domain_name", game)])
            .form(&HashMap::from([("mod_id", id)]))
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => Ok(post::PostModStatus::AlreadyTracking(ModId::from_u64(id))),
            StatusCode::CREATED => Ok(post::PostModStatus::SuccessfullyTracked(ModId::from_u64(
                id,
            ))),
            StatusCode::UNAUTHORIZED => {
                Err(response.json::<err::InvalidAPIKeyError>().await?.into())
            }
            StatusCode::NOT_FOUND => Err(response.json::<err::ModNotFoundError>().await?.into()),
            _ => unreachable!("The only four documented return codes are 200, 201, 404, and 401"),
        }
    }

    /// Untrack a mod.
    ///
    /// # Notes
    /// This function takes in a [`ModId`], not a `u64` because it is assumed that (unlike
    /// [`Api::track_mod`]) the caller knows of a valid mod ID.
    pub async fn untrack_mod<T: Into<ModId>>(
        &self,
        game: &str,
        id: T,
    ) -> Result<(), delete::DeleteModError> {
        let id = id.into();
        let response = self
            .build(Method::DELETE, VERSION, &["user", "tracked_mods"], &[])
            .query(&[("domain_name", game)])
            .form(&HashMap::from([("mod_id", id)]))
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => Ok(()),
            StatusCode::NOT_FOUND => {
                Err(response.json::<err::UntrackedOrInvalidMod>().await?.into())
            }
            _ => unreachable!("The only two documented return codes are 200 and 404"),
        }
    }

    /// Get a list of mods the user has endorsed.
    pub async fn endorsements(&self) -> Result<Endorsements, validate::ValidateError> {
        let response = self
            .build(Method::GET, VERSION, &["user", "endorsements"], &[])
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response
                .json()
                .await
                .map_err(validate::ValidateError::Reqwest),
            StatusCode::UNAUTHORIZED => Err(validate::ValidateError::InvalidAPIKey(
                response.json().await?,
            )),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404 (401), and 422"),
        }
    }
}

/// Mod related methods.
///
/// - [x] `GET`  [`v1/games/{game_domain_name}/mods/updated`](`Api::updated_during`)
/// - [x] `GET`  `v1/games/{game_domain_name}/mods/{mod_id}/changelogs`
/// - [ ] `GET`  `v1/games/{game_domain_name}/mods/latest_added`
/// - [ ] `GET`  `v1/games/{game_domain_name}/mods/latest_updated`
/// - [ ] `GET`  `v1/games/{game_domain_name}/mods/trending`
/// - [x] `GET`  `v1/games/{game_domain_name}/mods/{id}`
/// - [ ] `GET`  `v1/games/{game_domain_name}/mods/md5_search/{md5_hash}`
/// - [ ] `POST` `v1/games/{game_domain_name}/mods/{id}/endorse`
/// - [ ] `POST` `v1/games/{game_domain_name}/mods/{id}/abstain`
impl Api {
    /// Get a list of mods updated within a timeframe.
    pub async fn updated_during(
        &self,
        game: &str,
        time: TimePeriod,
    ) -> Result<Vec<ModUpdated>, get::GameModError> {
        let response = self
            .build(
                Method::GET,
                VERSION,
                &["games", game, "mods", "updated"],
                &[("period", time.as_str())],
            )
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response.json().await.map_err(get::GameModError::Reqwest),
            StatusCode::NOT_FOUND => Err(response.json::<err::InvalidAPIKeyError>().await?.into()),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404, and 422"),
        }
    }

    /// Get changelogs for a mod.
    pub async fn changelogs<T: Into<ModId>>(
        &self,
        game: &str,
        id: T,
    ) -> Result<Changelog, get::GameModError> {
        let id = id.into();
        let response = self
            .build(
                Method::GET,
                VERSION,
                &["games", game, "mods", id.to_string().as_str(), "changelogs"],
                &[],
            )
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response.json().await.map_err(get::GameModError::Reqwest),
            StatusCode::NOT_FOUND => Err(response.json::<err::InvalidAPIKeyError>().await?.into()),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404, and 422"),
        }
    }

    /// Get specific mod information.
    pub async fn mod_info<T: Into<ModId>>(
        &self,
        game: &str,
        id: T,
    ) -> Result<GameMod, get::GameModError> {
        let id = id.into();
        let response = self
            .build(
                Method::GET,
                VERSION,
                &["games", game, "mods", id.to_string().as_str()],
                &[],
            )
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response.json().await.map_err(get::GameModError::Reqwest),
            StatusCode::NOT_FOUND => Err(response.json::<err::InvalidAPIKeyError>().await?.into()),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404, and 422"),
        }
    }
}

/// Game related methods.
///
/// - [x] `GET` [`v1/games`](`Api::games`)
/// - [x] `GET` [`v1/games/{game_domain_name}`](`Api::game`)
impl Api {
    /// Get a list of all games tracked by NexusMods.
    pub async fn games(&self) -> Result<Vec<GameId>, get::GameModError> {
        let response = self
            .build(Method::GET, VERSION, &["games"], &[])
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response.json().await.map_err(get::GameModError::Reqwest),
            StatusCode::NOT_FOUND => Err(response.json::<err::InvalidAPIKeyError>().await?.into()),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404, and 422"),
        }
    }

    /// Get information about a single game.
    pub async fn game(&self, game: &str) -> Result<GameId, get::GameModError> {
        let response = self
            .build(Method::GET, VERSION, &["games", game], &[])
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response.json().await.map_err(get::GameModError::Reqwest),
            StatusCode::NOT_FOUND => Err(response.json::<err::InvalidAPIKeyError>().await?.into()),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404, and 422"),
        }
    }
}

/// Mod file related methods.
///
/// - [x] `GET` [`v1/games/{game_domain_name}/mods/{mod_id}/files`](`Api::mod_files`)
/// - [x] `GET` [`v1/games/{game_domain_name}/mods/{mod_id}/files/{file_id}`](`Api::mod_file`)
/// - [ ] `GET` `v1/games/{game_domain_name}/mods/{mod_id}/files/{id}/download_link`
impl Api {
    /// Based on a game and a [`ModId`], get data about the download files the mod provides.
    pub async fn mod_files<S: Into<ModId>>(
        &self,
        game: &str,
        mod_id: S,
        category: Option<CategoryName>,
    ) -> Result<ModFiles, get::GameModError> {
        let mod_id = mod_id.into();
        let response = self
            .build(
                Method::GET,
                VERSION,
                &["games", game, "mods", mod_id.to_string().as_str(), "files"],
                &category
                    .iter()
                    .map(|c| ("category", c.to_header_str()))
                    .collect::<Vec<_>>(),
            )
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response.json().await.map_err(get::GameModError::Reqwest),
            StatusCode::NOT_FOUND => Err(response.json::<err::InvalidAPIKeyError>().await?.into()),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404, and 422"),
        }
    }

    pub async fn mod_file<S: Into<ModId>>(
        &self,
        game: &str,
        mod_id: S,
        file_id: u64,
    ) -> Result<ModFile, get::GameModError> {
        let mod_id = mod_id.into();
        let response = self
            .build(
                Method::GET,
                VERSION,
                &[
                    "games",
                    game,
                    "mods",
                    mod_id.to_string().as_str(),
                    "files",
                    file_id.to_string().as_str(),
                ],
                &[],
            )
            .send()
            .await?;

        match response.status() {
            StatusCode::OK => response.json().await.map_err(get::GameModError::Reqwest),
            StatusCode::NOT_FOUND => Err(response.json::<err::InvalidAPIKeyError>().await?.into()),
            StatusCode::UNPROCESSABLE_ENTITY => {
                unimplemented!(
                    "I have not yet encountered this return code but it is listed as a valid return code"
                );
            }
            _ => unreachable!("The only three documented return codes are 200, 404, and 422"),
        }
    }
}