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
#![doc = include_str!("../README.md")]

use reqwest::{blocking::RequestBuilder, header};
use serde::de::DeserializeOwned;
use url::Url;

use self::{
    detail::{ModDetailsRequest, ModDetailsResponse},
    error::{ApiError, ApiErrorKind},
    image::{
        ImageAddRequest, ImageAddResponse, ImageEditRequest, ImageEditResponse, ImageUploadRequest,
        ImageUploadResponse,
    },
    portal::{SearchQuery, SearchResponse, SearchResult},
    publish::{InitPublishRequest, InitPublishResponse, PublishRequest, PublishResponse},
    upload::{InitUploadRequest, InitUploadResponse, UploadRequest, UploadResponse},
};

pub mod detail;
pub mod error;
pub mod image;
pub mod portal;
pub mod publish;
pub mod upload;

pub const DEFAULT_BASE_URL: &str = "https://mods.factorio.com/api/";

pub struct ApiClient {
    client: reqwest::blocking::Client,
    base_url: Url,
    api_key: Option<String>,
}

type Result<T> = core::result::Result<T, ApiError>;

impl ApiClient {
    pub fn new<T: Into<String>>(api_key: Option<T>) -> Self {
        Self::builder().api_key(api_key).build()
    }

    pub fn builder() -> ApiClientBuilder {
        ApiClientBuilder::new()
    }

    pub fn search(&self, query: &SearchQuery) -> Result<SearchResponse> {
        self.get("mods", false, |r| r.query(query))
    }

    pub fn info_short(&self, name: &str) -> Result<SearchResult> {
        self.get(&format!("mods/{}", name), false, |r| r)
    }

    pub fn info_full(&self, name: &str) -> Result<SearchResult> {
        self.get(&format!("mods/{}/full", name), false, |r| r)
    }

    pub fn init_upload(&self, data: InitUploadRequest) -> Result<InitUploadResponse> {
        self.post("v2/mods/upload", true, |r| r.multipart(data.into()))
    }

    pub fn upload(&self, url: Url, data: UploadRequest) -> Result<UploadResponse> {
        let form_data = data.try_into().map_err(|e| {
            ApiError::new(
                ApiErrorKind::ImageIo,
                format!("Could not read mod file {:?}", e),
                None,
            )
        })?;

        self.send(self.client.post(url).multipart(form_data), false)
    }

    pub fn edit_details(&self, data: ModDetailsRequest) -> Result<ModDetailsResponse> {
        self.post("v2/mods/edit_details", true, |r| r.multipart(data.into()))
    }

    pub fn add_image(&self, data: ImageAddRequest) -> Result<ImageAddResponse> {
        self.post("v2/mods/images/add", true, |r| r.multipart(data.into()))
    }

    pub fn upload_image(&self, url: Url, data: ImageUploadRequest) -> Result<ImageUploadResponse> {
        let form_data = data.try_into().map_err(|e| {
            ApiError::new(
                ApiErrorKind::ImageIo,
                format!("Could not read image file: {:?}", e),
                None,
            )
        })?;

        self.send(self.client.post(url).multipart(form_data), false)
    }

    pub fn edit_images(&self, data: ImageEditRequest) -> Result<ImageEditResponse> {
        self.post("v2/mods/images/edit", true, |r| r.multipart(data.into()))
    }

    pub fn init_publish(&self, data: InitPublishRequest) -> Result<InitPublishResponse> {
        self.post("v2/mods/init_publish", true, |r| r.multipart(data.into()))
    }

    pub fn publish(&self, url: Url, data: PublishRequest) -> Result<PublishResponse> {
        let form_data = data.try_into().map_err(|e| {
            ApiError::new(
                ApiErrorKind::ImageIo,
                format!("Could not read mod file: {:?}", e),
                None,
            )
        })?;

        self.send(self.client.post(url).multipart(form_data), false)
    }

    fn url(&self, path: &str) -> Result<Url> {
        self.base_url.join(path).map_err(|_| {
            ApiError::new(
                ApiErrorKind::UrlParseFailed,
                format!("Failed to join base URL with path {}", path),
                None,
            )
        })
    }

    fn send<T>(&self, request: reqwest::blocking::RequestBuilder, auth: bool) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let mut request = request.header(header::USER_AGENT, "facti");
        if auth {
            if let Some(api_key) = &self.api_key {
                request = request.bearer_auth(api_key)
            } else {
                return Err(ApiError::new(
                    ApiErrorKind::MissingApiKey,
                    "Missing API key",
                    None,
                ));
            }
        }

        let response = request.send()?;

        if response.status().is_success() {
            Ok(response.json::<T>()?)
        } else {
            Err(response.into())
        }
    }

    fn get<T, F>(&self, path: &str, auth: bool, f: F) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
        F: FnOnce(RequestBuilder) -> RequestBuilder,
    {
        let url = self.url(path)?;
        let request = f(self.client.get(url));

        self.send::<T>(request, auth)
    }

    fn post<T, F>(&self, path: &str, auth: bool, f: F) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
        F: FnOnce(RequestBuilder) -> RequestBuilder,
    {
        let url = self.url(path)?;
        let request = f(self.client.post(url));

        self.send::<T>(request, auth)
    }
}

impl Default for ApiClient {
    fn default() -> Self {
        Self::new::<String>(None)
    }
}

#[derive(Default)]
pub struct ApiClientBuilder {
    client: Option<reqwest::blocking::Client>,
    base_url: Option<Url>,
    api_key: Option<String>,
}

impl ApiClientBuilder {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn client(mut self, client: Option<reqwest::blocking::Client>) -> Self {
        self.client = client;
        self
    }

    pub fn base_url(mut self, base_url: Option<Url>) -> Self {
        self.base_url = base_url;
        self
    }

    pub fn api_key<T: Into<String>>(mut self, api_key: Option<T>) -> Self {
        self.api_key = api_key.map(Into::into);
        self
    }

    pub fn build(self) -> ApiClient {
        let client = self.client.unwrap_or_default();
        let base_url = self
            .base_url
            .unwrap_or(Url::parse(DEFAULT_BASE_URL).unwrap());

        ApiClient {
            client,
            base_url,
            api_key: self.api_key,
        }
    }
}