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
//! Games interface
use std::ffi::OsStr;
use std::path::Path;

use mime::IMAGE_STAR;
use url::Url;

use crate::mods::{ModRef, Mods};
use crate::multipart::FileSource;
use crate::prelude::*;

pub use crate::types::game::{
    ApiAccessOptions, CommunityOptions, CurationOption, Downloads, Game, HeaderImage, Icon,
    MaturityOptions, PresentationOption, RevenueOptions, Statistics, SubmissionOption, TagOption,
    TagType,
};
pub use crate::types::Logo;
pub use crate::types::Status;

/// Interface for games.
pub struct Games {
    modio: Modio,
}

impl Games {
    pub(crate) fn new(modio: Modio) -> Self {
        Self { modio }
    }

    /// Returns a `Query` interface to retrieve games.
    ///
    /// See [Filters and sorting](filters).
    pub fn search(&self, filter: Filter) -> Query<Game> {
        Query::new(self.modio.clone(), Route::GetGames, filter)
    }

    /// Return a reference to a game.
    pub fn get(&self, id: u32) -> GameRef {
        GameRef::new(self.modio.clone(), id)
    }
}

/// Reference interface of a game.
pub struct GameRef {
    modio: Modio,
    id: u32,
}

impl GameRef {
    pub(crate) fn new(modio: Modio, id: u32) -> Self {
        Self { modio, id }
    }

    /// Get a reference to the Modio game object that this `GameRef` refers to.
    pub async fn get(self) -> Result<Game> {
        let route = Route::GetGame { game_id: self.id };
        self.modio.request(route).send().await
    }

    /// Return a reference to a mod of a game.
    pub fn mod_(&self, mod_id: u32) -> ModRef {
        ModRef::new(self.modio.clone(), self.id, mod_id)
    }

    /// Return a reference to an interface that provides access to the mods of a game.
    pub fn mods(&self) -> Mods {
        Mods::new(self.modio.clone(), self.id)
    }

    /// Return the statistics for a game.
    pub async fn statistics(self) -> Result<Statistics> {
        let route = Route::GetGameStats { game_id: self.id };
        self.modio.request(route).send().await
    }

    /// Return a reference to an interface that provides access to the tags of a game.
    pub fn tags(&self) -> Tags {
        Tags::new(self.modio.clone(), self.id)
    }

    /// Edit details for a game. [required: token]
    pub async fn edit(self, options: EditGameOptions) -> Result<Editing<Game>> {
        let route = Route::EditGame { game_id: self.id };
        self.modio.request(route).form(&options).send().await
    }

    /// Add new media to a game. [required: token]
    pub async fn edit_media(self, media: EditMediaOptions) -> Result<()> {
        let route = Route::AddGameMedia { game_id: self.id };
        self.modio
            .request(route)
            .multipart(Form::from(media))
            .send::<Message>()
            .await?;
        Ok(())
    }
}

/// Interface for tag options.
pub struct Tags {
    modio: Modio,
    game_id: u32,
}

impl Tags {
    fn new(modio: Modio, game_id: u32) -> Self {
        Self { modio, game_id }
    }

    /// List tag options.
    pub async fn list(self) -> Result<Vec<TagOption>> {
        let route = Route::GetGameTags {
            game_id: self.game_id,
        };
        Query::new(self.modio, route, Default::default())
            .collect()
            .await
    }

    /// Provides a stream over all tag options.
    pub async fn iter(self) -> Result<impl Stream<Item = Result<TagOption>>> {
        let route = Route::GetGameTags {
            game_id: self.game_id,
        };
        let filter = Default::default();
        Query::new(self.modio, route, filter).iter().await
    }

    /// Add tag options. [required: token]
    #[allow(clippy::should_implement_trait)]
    pub async fn add(self, options: AddTagsOptions) -> Result<()> {
        let route = Route::AddGameTags {
            game_id: self.game_id,
        };
        self.modio
            .request(route)
            .form(&options)
            .send::<Message>()
            .await?;
        Ok(())
    }

    /// Delete tag options. [required: token]
    pub async fn delete(self, options: DeleteTagsOptions) -> Result<Deletion> {
        let route = Route::DeleteGameTags {
            game_id: self.game_id,
        };
        self.modio.request(route).form(&options).send().await
    }
}

/// Game filters and sorting.
///
/// # Filters
/// - Fulltext
/// - Id
/// - Status
/// - SubmittedBy
/// - DateAdded
/// - DateUpdated
/// - DateLive
/// - Name
/// - NameId
/// - Summary
/// - InstructionsUrl
/// - UgcName
/// - PresentationOption
/// - SubmissionOption
/// - CurationOption
/// - CommunityOptions
/// - RevenueOptions
/// - ApiAccessOptions
/// - MaturityOptions
///
/// # Sorting
/// - Id
/// - Status
/// - Name
/// - NameId
/// - DateUpdated
///
/// See [modio docs](https://docs.mod.io/#get-all-games) for more information.
///
/// By default this returns up to `100` items. You can limit the result by using `limit` and
/// `offset`.
///
/// # Example
/// ```
/// use modio::filter::prelude::*;
/// use modio::games::filters::Id;
///
/// let filter = Id::_in(vec![1, 2]).order_by(Id::desc());
/// ```
#[rustfmt::skip]
pub mod filters {
    #[doc(inline)]
    pub use crate::filter::prelude::Fulltext;
    #[doc(inline)]
    pub use crate::filter::prelude::Id;
    #[doc(inline)]
    pub use crate::filter::prelude::Name;
    #[doc(inline)]
    pub use crate::filter::prelude::NameId;
    #[doc(inline)]
    pub use crate::filter::prelude::Status;
    #[doc(inline)]
    pub use crate::filter::prelude::DateAdded;
    #[doc(inline)]
    pub use crate::filter::prelude::DateUpdated;
    #[doc(inline)]
    pub use crate::filter::prelude::DateLive;
    #[doc(inline)]
    pub use crate::filter::prelude::SubmittedBy;

    filter!(Summary, SUMMARY, "summary", Eq, NotEq, Like);
    filter!(InstructionsUrl, INSTRUCTIONS_URL, "instructions_url", Eq, NotEq, In, Like);
    filter!(UgcName, UGC_NAME, "ugc_name", Eq, NotEq, In, Like);
    filter!(PresentationOption, PRESENTATION_OPTION, "presentation_option", Eq, NotEq, In, Cmp, Bit);
    filter!(SubmissionOption, SUBMISSION_OPTION, "submission_option", Eq, NotEq, In, Cmp, Bit);
    filter!(CurationOption, CURATION_OPTION, "curation_option", Eq, NotEq, In, Cmp, Bit);
    filter!(CommunityOptions, COMMUNITY_OPTIONS, "community_options", Eq, NotEq, In, Cmp, Bit);
    filter!(RevenueOptions, REVENUE_OPTIONS, "revenue_options", Eq, NotEq, In, Cmp, Bit);
    filter!(ApiAccessOptions, API_ACCESS_OPTIONS, "api_access_options", Eq, NotEq, In, Cmp, Bit);
    filter!(MaturityOptions, MATURITY_OPTIONS, "maturity_options", Eq, NotEq, In, Cmp, Bit);
}

#[derive(Default)]
pub struct EditGameOptions {
    params: std::collections::BTreeMap<&'static str, String>,
}

impl EditGameOptions {
    option!(status: Status >> "status");
    option!(name >> "name");
    option!(name_id >> "name_id");
    option!(summary >> "summary");
    option!(instructions >> "instructions");
    option!(instructions_url: Url >> "instructions_url");
    option!(ugc_name >> "ugc_name");
    option!(presentation_option: PresentationOption >> "presentation_option");
    option!(submission_option: SubmissionOption >> "submission_option");
    option!(curation_option: CurationOption >> "curation_option");
    option!(community_options: CommunityOptions >> "community_options");
    option!(revenue_options: RevenueOptions >> "revenue_options");
    option!(api_access_options: ApiAccessOptions >> "api_access_options");
    option!(maturity_options: MaturityOptions >> "maturity_options");
}

impl_serialize_params!(EditGameOptions >> params);

pub struct AddTagsOptions {
    name: String,
    kind: TagType,
    hidden: bool,
    tags: Vec<String>,
}

impl AddTagsOptions {
    pub fn public<S: Into<String>>(name: S, kind: TagType, tags: &[String]) -> Self {
        Self {
            name: name.into(),
            kind,
            hidden: false,
            tags: tags.to_vec(),
        }
    }

    pub fn hidden<S: Into<String>>(name: S, kind: TagType, tags: &[String]) -> Self {
        Self {
            name: name.into(),
            kind,
            hidden: true,
            tags: tags.to_vec(),
        }
    }
}

#[doc(hidden)]
impl serde::ser::Serialize for AddTagsOptions {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        use serde::ser::SerializeMap;

        let mut map = serializer.serialize_map(Some(self.tags.len() + 3))?;
        map.serialize_entry("name", &self.name)?;
        map.serialize_entry("type", &self.kind.to_string())?;
        map.serialize_entry("hidden", &self.hidden.to_string())?;
        for t in &self.tags {
            map.serialize_entry("tags[]", t)?;
        }
        map.end()
    }
}

pub struct DeleteTagsOptions {
    name: String,
    tags: Option<Vec<String>>,
}

impl DeleteTagsOptions {
    pub fn all<S: Into<String>>(name: S) -> Self {
        Self {
            name: name.into(),
            tags: None,
        }
    }

    pub fn some<S: Into<String>>(name: S, tags: &[String]) -> Self {
        Self {
            name: name.into(),
            tags: if tags.is_empty() {
                None
            } else {
                Some(tags.to_vec())
            },
        }
    }
}

#[doc(hidden)]
impl serde::ser::Serialize for DeleteTagsOptions {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        use serde::ser::SerializeMap;

        let len = self.tags.as_ref().map(|t| t.len()).unwrap_or(1);
        let mut map = serializer.serialize_map(Some(len + 1))?;
        map.serialize_entry("name", &self.name)?;
        if let Some(ref tags) = self.tags {
            for t in tags {
                map.serialize_entry("tags[]", t)?;
            }
        } else {
            map.serialize_entry("tags[]", "")?;
        }
        map.end()
    }
}

#[derive(Default)]
pub struct EditMediaOptions {
    logo: Option<FileSource>,
    icon: Option<FileSource>,
    header: Option<FileSource>,
}

impl EditMediaOptions {
    pub fn logo<P: AsRef<Path>>(self, logo: P) -> Self {
        let logo = logo.as_ref();
        let filename = logo
            .file_name()
            .and_then(OsStr::to_str)
            .map_or_else(String::new, ToString::to_string);

        Self {
            logo: Some(FileSource::new_from_file(logo, filename, IMAGE_STAR)),
            ..self
        }
    }

    pub fn icon<P: AsRef<Path>>(self, icon: P) -> Self {
        let icon = icon.as_ref();
        let filename = icon
            .file_name()
            .and_then(OsStr::to_str)
            .map_or_else(String::new, ToString::to_string);

        Self {
            icon: Some(FileSource::new_from_file(icon, filename, IMAGE_STAR)),
            ..self
        }
    }

    pub fn header<P: AsRef<Path>>(self, header: P) -> Self {
        let header = header.as_ref();
        let filename = header
            .file_name()
            .and_then(OsStr::to_str)
            .map_or_else(String::new, ToString::to_string);

        Self {
            header: Some(FileSource::new_from_file(header, filename, IMAGE_STAR)),
            ..self
        }
    }
}

#[doc(hidden)]
impl From<EditMediaOptions> for Form {
    fn from(opts: EditMediaOptions) -> Form {
        let mut form = Form::new();
        if let Some(logo) = opts.logo {
            form = form.part("logo", logo.into());
        }
        if let Some(icon) = opts.icon {
            form = form.part("icon", icon.into());
        }
        if let Some(header) = opts.header {
            form = form.part("header", header.into());
        }
        form
    }
}