modde-sources 0.2.1

Download source implementations for modde
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Typed Nexus Mods v1 REST API client and the response types it deserializes.

use anyhow::{Result, bail};
use modde_core::manifest::collection::CollectionManifest;
use modde_core::{NexusFileId, NexusModId};
use reqwest::Client;
use serde::Deserialize;
use tracing::warn;

/// Typed Nexus API client.
pub struct NexusApi {
    client: Client,
    api_key: String,
}

/// A mod's metadata as returned by the Nexus v1 mod endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct NexusMod {
    pub mod_id: NexusModId,
    pub name: String,
    pub summary: Option<String>,
    pub version: String,
    pub author: String,
    /// Primary thumbnail URL (full-size picture shown at the top of the mod page).
    #[serde(default)]
    pub picture_url: Option<String>,
    /// Long-form HTML description. May contain BBCode-derived markup.
    #[serde(default)]
    pub description: Option<String>,
    /// Nexus game domain the mod belongs to (e.g. `"skyrimspecialedition"`).
    #[serde(default)]
    pub domain_name: Option<String>,
    /// The current user's endorsement relationship to this mod. Only
    /// populated on authenticated requests. Absent otherwise.
    #[serde(default)]
    pub endorsement: Option<NexusEndorsement>,
    /// Total endorsements the mod has received (not user-specific).
    #[serde(default)]
    pub endorsement_count: u64,
}

/// The current user's endorsement status for a mod.
///
/// `endorse_status` values returned by Nexus v1: `"Undecided"`, `"Abstained"`,
/// `"Endorsed"`. See `node-nexus-api/lib/types.d.ts` (`EndorsedStatus`) for the
/// canonical enum.
#[derive(Debug, Clone, Deserialize)]
pub struct NexusEndorsement {
    pub endorse_status: String,
    #[serde(default)]
    pub timestamp: Option<u64>,
    #[serde(default)]
    pub version: Option<String>,
}

/// A single entry in the user's tracked-mods list.
#[derive(Debug, Clone, Deserialize)]
pub struct NexusTrackedMod {
    pub mod_id: NexusModId,
    pub domain_name: String,
}

/// Metadata for a single downloadable file attached to a mod.
#[derive(Debug, Deserialize)]
pub struct NexusModFile {
    pub file_id: NexusFileId,
    pub name: String,
    pub version: Option<String>,
    pub size_kb: Option<u64>,
    pub file_name: String,
    /// File category: `"MAIN"`, `"UPDATE"`, `"OPTIONAL"`, `"OLD_VERSION"`, `"MISCELLANEOUS"`.
    #[serde(default)]
    pub category_name: Option<String>,
    /// Upload timestamp (Unix epoch seconds). Used to pick the most-recent MAIN file.
    #[serde(default)]
    pub uploaded_timestamp: Option<u64>,
}

/// Minimal collection metadata returned by the slug-based lookup endpoint.
///
/// Used in the two-step collection install flow to discover the game domain
/// before fetching the full revision manifest.
#[derive(Debug, Deserialize)]
pub struct NexusCollectionMeta {
    pub game: NexusCollectionGame,
    #[serde(default)]
    pub latest_published_revision: Option<NexusCollectionRevision>,
}

/// The game a collection belongs to.
#[derive(Debug, Deserialize)]
pub struct NexusCollectionGame {
    pub domain_name: String,
}

/// A published revision of a collection.
#[derive(Debug, Deserialize)]
pub struct NexusCollectionRevision {
    pub revision_number: u64,
}

/// The file listing for a mod.
#[derive(Debug, Deserialize)]
pub struct NexusModFiles {
    pub files: Vec<NexusModFile>,
}

/// A page of mod search results plus the total match count.
#[derive(Debug, Deserialize)]
pub struct NexusSearchResults {
    pub results: Vec<NexusMod>,
    pub total: u64,
}

/// An entry from the "recently updated mods" feed.
#[derive(Debug, Deserialize)]
pub struct NexusUpdatedMod {
    pub mod_id: NexusModId,
    pub latest_file_update: u64,
    pub latest_mod_activity: u64,
}

impl NexusApi {
    /// Create a client authenticated with the given `api_key`.
    #[must_use]
    pub fn new(client: Client, api_key: String) -> Self {
        Self { client, api_key }
    }

    async fn get<T: serde::de::DeserializeOwned>(&self, url: &str) -> Result<T> {
        let resp = self
            .client
            .get(url)
            .header("apikey", &self.api_key)
            .send()
            .await?;

        // Check rate limit headers
        if let Some(remaining) = resp.headers().get("x-rl-hourly-remaining")
            && let Ok(val) = remaining.to_str().unwrap_or("").parse::<u32>()
            && val < 10
        {
            warn!(remaining = val, "Nexus API hourly rate limit running low");
        }

        if resp.status() == 429 {
            bail!("Nexus API rate limit exceeded. Please wait before retrying.");
        }

        let body = resp.error_for_status()?.json().await?;
        Ok(body)
    }

    async fn delete_req(&self, url: &str, form: &[(&str, &str)]) -> Result<()> {
        self.client
            .delete(url)
            .header("apikey", &self.api_key)
            .form(form)
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Get mod details.
    pub async fn get_mod(&self, game_domain: &str, mod_id: NexusModId) -> Result<NexusMod> {
        let url = format!(
            "{}/games/{game_domain}/mods/{mod_id}.json",
            super::base_url()
        );
        self.get(&url).await
    }

    // ── GraphQL v2 browse helpers ─────────────────────────────

    /// Fetch a trending or monthly-top browse feed via the v2 GraphQL
    /// endpoint. Falls back to the REST `trending_mods` path when the
    /// GraphQL response is malformed, so the UI still renders something
    /// even if the v2 schema changes shape out from under us.
    pub async fn browse_feed_gql(
        &self,
        game_domain: &str,
        kind: super::graphql::ModFeedKind,
    ) -> Result<Vec<super::graphql::GqlModTile>> {
        match super::graphql::browse_feed(&self.client, &self.api_key, game_domain, kind).await {
            Ok(tiles) => Ok(tiles),
            Err(e) => {
                warn!(error = %e, "GraphQL browse feed failed, falling back to REST");
                let mods = self.trending_mods(game_domain).await?;
                Ok(mods
                    .into_iter()
                    .map(|m| super::graphql::GqlModTile {
                        mod_id: m.mod_id,
                        name: m.name,
                        summary: m.summary,
                        version: Some(m.version),
                        author: Some(m.author),
                        picture_url: m.picture_url.clone(),
                        thumbnail_url: m.picture_url,
                        endorsements: Some(m.endorsement_count),
                        downloads: None,
                        uploaded_at: None,
                        game_domain: m.domain_name,
                    })
                    .collect())
            }
        }
    }

    /// Full-text search via the v2 GraphQL endpoint, with a REST
    /// fallback mirroring `browse_feed_gql`.
    pub async fn search_mods_gql(
        &self,
        game_domain: &str,
        term: &str,
        page: u32,
    ) -> Result<Vec<super::graphql::GqlModTile>> {
        match super::graphql::search_mods(&self.client, &self.api_key, game_domain, term, page)
            .await
        {
            Ok(tiles) => Ok(tiles),
            Err(e) => {
                warn!(error = %e, "GraphQL search failed, falling back to REST");
                let results = self.search_mods(game_domain, term, page).await?;
                Ok(results
                    .results
                    .into_iter()
                    .map(|m| super::graphql::GqlModTile {
                        mod_id: m.mod_id,
                        name: m.name,
                        summary: m.summary,
                        version: Some(m.version),
                        author: Some(m.author),
                        picture_url: m.picture_url.clone(),
                        thumbnail_url: m.picture_url,
                        endorsements: Some(m.endorsement_count),
                        downloads: None,
                        uploaded_at: None,
                        game_domain: m.domain_name,
                    })
                    .collect())
            }
        }
    }

    /// Collections browse / search via the v2 GraphQL endpoint. Falls
    /// back to the REST `search_collections` path.
    pub async fn collections_feed_gql(
        &self,
        game_domain: &str,
        term: Option<&str>,
    ) -> Result<Vec<super::graphql::GqlCollectionTile>> {
        match super::graphql::collections_feed(&self.client, &self.api_key, game_domain, term).await
        {
            Ok(tiles) => Ok(tiles),
            Err(e) => {
                warn!(error = %e, "GraphQL collections feed failed, falling back to REST");
                let results = self
                    .search_collections(game_domain, term.unwrap_or(""))
                    .await?;
                Ok(results
                    .into_iter()
                    .map(|c| super::graphql::GqlCollectionTile {
                        slug: c.slug,
                        name: c.name,
                        summary: c.summary,
                        tile_image: c.image_url,
                        game_domain: Some(c.game.domain_name),
                        endorsements: Some(c.endorsements),
                        downloads: None,
                    })
                    .collect())
            }
        }
    }

    /// Fetch raw bytes from a URL, reusing the client + apikey header.
    ///
    /// Used for downloading thumbnail / gallery images referenced by the v1 API.
    /// The apikey header is harmless on image CDN URLs (ignored by the CDN),
    /// but keeping it here means one code path with consistent auth.
    pub async fn fetch_bytes(&self, url: &str) -> Result<Vec<u8>> {
        let resp = self
            .client
            .get(url)
            .header("apikey", &self.api_key)
            .send()
            .await?
            .error_for_status()?;
        Ok(resp.bytes().await?.to_vec())
    }

    /// Fetch the full image gallery for a mod via the unofficial v2 GraphQL
    /// endpoint. Returns a list of image URLs (the main `picture_url` will
    /// typically be the first entry, but this is not guaranteed — the caller
    /// should merge with `picture_url` as a fallback).
    ///
    /// The GraphQL schema is undocumented and may change; on any error this
    /// function returns an `Err` and the caller should fall back to the
    /// single `picture_url` from the v1 `get_mod` response.
    pub async fn get_mod_media(
        &self,
        game_domain: &str,
        mod_id: NexusModId,
    ) -> Result<Vec<String>> {
        let query = r"query ModMedia($modId: Int!, $gameDomain: String!) {
  mod(modId: $modId, gameDomain: $gameDomain) {
    modImages { url }
  }
}";
        let body = serde_json::json!({
            "query": query,
            "variables": {
                "modId": mod_id.get(),
                "gameDomain": game_domain,
            },
        });

        let resp = self
            .client
            .post(super::graphql_url())
            .header("apikey", &self.api_key)
            .header("content-type", "application/json")
            .json(&body)
            .send()
            .await?
            .error_for_status()?;

        let payload: serde_json::Value = resp.json().await?;
        if let Some(errors) = payload.get("errors") {
            bail!("Nexus GraphQL errors: {errors}");
        }
        let images = payload
            .get("data")
            .and_then(|d| d.get("mod"))
            .and_then(|m| m.get("modImages"))
            .and_then(|a| a.as_array())
            .ok_or_else(|| anyhow::anyhow!("unexpected GraphQL response shape"))?;

        let urls: Vec<String> = images
            .iter()
            .filter_map(|img| {
                img.get("url")
                    .and_then(|u| u.as_str())
                    .map(std::string::ToString::to_string)
            })
            .collect();
        Ok(urls)
    }

    /// Get files for a mod.
    pub async fn get_mod_files(
        &self,
        game_domain: &str,
        mod_id: NexusModId,
    ) -> Result<NexusModFiles> {
        let url = format!(
            "{}/games/{game_domain}/mods/{mod_id}/files.json",
            super::base_url()
        );
        self.get(&url).await
    }

    /// Search mods by query string.
    pub async fn search_mods(
        &self,
        game_domain: &str,
        query: &str,
        page: u32,
    ) -> Result<NexusSearchResults> {
        let url = format!(
            "{}/games/{game_domain}/mods/search.json?search={query}&page={page}",
            super::base_url()
        );
        self.get(&url).await
    }

    /// Get trending mods for a game.
    pub async fn trending_mods(&self, game_domain: &str) -> Result<Vec<NexusMod>> {
        let url = format!(
            "{}/games/{game_domain}/mods/trending.json",
            super::base_url()
        );
        self.get(&url).await
    }

    /// Get recently updated mods. Period must be `"1d"`, `"1w"`, or `"1m"`.
    pub async fn updated_mods(
        &self,
        game_domain: &str,
        period: &str,
    ) -> Result<Vec<NexusUpdatedMod>> {
        let url = format!(
            "{}/games/{game_domain}/mods/updated.json?period={period}",
            super::base_url()
        );
        self.get(&url).await
    }

    /// Search collections for a game.
    pub async fn search_collections(
        &self,
        game_domain: &str,
        query: &str,
    ) -> Result<Vec<CollectionManifest>> {
        let url = format!(
            "{}/games/{game_domain}/collections.json?search={query}",
            super::base_url()
        );
        self.get(&url).await
    }

    /// Get a specific collection by slug.
    pub async fn get_collection(
        &self,
        game_domain: &str,
        slug: &str,
    ) -> Result<CollectionManifest> {
        let url = format!(
            "{}/games/{game_domain}/collections/{slug}.json",
            super::base_url()
        );
        self.get(&url).await
    }

    /// Get a specific revision of a collection.
    pub async fn get_collection_revision(
        &self,
        game_domain: &str,
        slug: &str,
        revision: u64,
    ) -> Result<CollectionManifest> {
        let url = format!(
            "{}/games/{game_domain}/collections/{slug}/revisions/{revision}.json",
            super::base_url()
        );
        self.get(&url).await
    }

    /// Discover a collection's game domain (and latest revision) by slug alone.
    ///
    /// Step 1 of the two-step collection install flow.
    pub async fn get_collection_meta(&self, slug: &str) -> Result<NexusCollectionMeta> {
        // The collections endpoint accepts a slug without game_domain:
        //   GET /v1/collections/{slug}.json
        let url = format!("{}/collections/{slug}.json", super::base_url());
        self.get(&url).await
    }

    /// Endorse a mod on Nexus.
    ///
    /// The v1 endpoint requires a `Version` form parameter — passing the
    /// installed mod version lets Nexus reject endorsements of obsolete
    /// installs. Callers should pass the version string from the currently
    /// loaded `NexusMod` response (not the local install, which may be
    /// stale).
    pub async fn endorse_mod(
        &self,
        game_domain: &str,
        mod_id: NexusModId,
        version: &str,
    ) -> Result<()> {
        let url = format!(
            "{}/games/{game_domain}/mods/{mod_id}/endorse.json",
            super::base_url()
        );
        self.client
            .post(&url)
            .header("apikey", &self.api_key)
            .form(&[("Version", version)])
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Abstain from endorsing (won't be asked again).
    pub async fn abstain_mod(
        &self,
        game_domain: &str,
        mod_id: NexusModId,
        version: &str,
    ) -> Result<()> {
        let url = format!(
            "{}/games/{game_domain}/mods/{mod_id}/abstain.json",
            super::base_url()
        );
        self.client
            .post(&url)
            .header("apikey", &self.api_key)
            .form(&[("Version", version)])
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Fetch the full list of mods the current user is tracking, across all
    /// games. The v1 endpoint is not filterable by domain, so callers that
    /// only care about one mod should filter the returned list themselves.
    pub async fn get_tracked_mods(&self) -> Result<Vec<NexusTrackedMod>> {
        let url = format!("{}/user/tracked_mods.json", super::base_url());
        self.get(&url).await
    }

    /// Track a mod (receive Nexus notifications).
    pub async fn track_mod(&self, game_domain: &str, mod_id: NexusModId) -> Result<()> {
        let url = format!("{}/user/tracked_mods.json", super::base_url());
        self.client
            .post(&url)
            .header("apikey", &self.api_key)
            .form(&[
                ("domain_name", game_domain),
                ("mod_id", &mod_id.to_string()),
            ])
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Stop tracking a mod.
    pub async fn untrack_mod(&self, game_domain: &str, mod_id: NexusModId) -> Result<()> {
        let url = format!("{}/user/tracked_mods.json", super::base_url());
        self.delete_req(
            &url,
            &[
                ("domain_name", game_domain),
                ("mod_id", &mod_id.to_string()),
            ],
        )
        .await
    }

    /// Fetch a collection manifest, discovering the game domain automatically.
    ///
    /// If `version` is `Some`, that revision number is used directly.
    /// Otherwise the latest published revision is queried first (two-step fetch).
    pub async fn get_collection_by_slug(
        &self,
        slug: &str,
        version: Option<u64>,
    ) -> Result<CollectionManifest> {
        let (game_domain, revision) = if let Some(rev) = version {
            // Still need the game domain; do step-1 but skip revision lookup
            let meta = self.get_collection_meta(slug).await?;
            (meta.game.domain_name, rev)
        } else {
            let meta = self.get_collection_meta(slug).await?;
            let rev = meta
                .latest_published_revision
                .map(|r| r.revision_number)
                .ok_or_else(|| anyhow::anyhow!("collection '{slug}' has no published revisions"))?;
            (meta.game.domain_name, rev)
        };

        self.get_collection_revision(&game_domain, slug, revision)
            .await
    }
}