-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.rs
221 lines (178 loc) · 7.94 KB
/
api.rs
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
/// Entry-point to the local Factorio API
#[derive(Debug)]
pub struct Api {
game_version: factorio_mods_common::ReleaseVersion,
mods_directory: std::path::PathBuf,
mod_list_file_path: std::path::PathBuf,
player_data_json_file_path: std::path::PathBuf,
}
impl Api {
/// Constructs an API client.
pub fn new(install_directory: &std::path::Path, user_directory: &std::path::Path) -> Result<Self, crate::Error> {
let game_version = {
let mut base_info_file_path = install_directory.join("data");
base_info_file_path.push("base");
base_info_file_path.push("info.json");
if !base_info_file_path.is_file() {
return Err(crate::Error::InstallDirectoryNotFound);
}
let base_info_file = match std::fs::File::open(&base_info_file_path) {
Ok(base_info_file) => base_info_file,
Err(err) => return Err(crate::Error::Io(base_info_file_path, err)),
};
let base_info: BaseInfo =
serde_json::from_reader(base_info_file)
.map_err(|err| crate::Error::ReadJsonFile(base_info_file_path, err))?;
base_info.version
};
let (mods_directory, mod_list_file_path, player_data_json_file_path) = {
let mods_directory = user_directory.join("mods");
let mod_list_file_path = mods_directory.join("mod-list.json");
let player_data_json_file_path = user_directory.join("player-data.json");
if mod_list_file_path.is_file() && player_data_json_file_path.is_file() {
(mods_directory, mod_list_file_path, player_data_json_file_path)
}
else {
return Err(crate::Error::UserDirectoryNotFound);
}
};
Ok(Api {
game_version,
mods_directory,
mod_list_file_path,
player_data_json_file_path,
})
}
/// Returns the game version.
pub fn game_version(&self) -> &factorio_mods_common::ReleaseVersion {
&self.game_version
}
/// Returns the directory where mods should be installed.
pub fn mods_directory(&self) -> &std::path::Path {
&self.mods_directory
}
/// Returns an iterator over all the locally installed mods, matching the given name pattern if any.
pub fn installed_mods(&self) -> Result<impl Iterator<Item = Result<crate::InstalledMod, crate::Error>> + 'static, crate::Error> {
crate::installed_mod::find(&self.mods_directory, None, None)
}
/// Fetches the locally saved user credentials, if any.
pub fn user_credentials(&self) -> Result<factorio_mods_common::UserCredentials, crate::Error> {
let player_data_json_file_path = &self.player_data_json_file_path;
let player_data_json_file =
std::fs::File::open(player_data_json_file_path)
.map_err(|err| crate::Error::Io(player_data_json_file_path.clone(), err))?;
let PlayerData { service_username, service_token } =
serde_json::from_reader(player_data_json_file)
.map_err(|err| crate::Error::ReadJsonFile(player_data_json_file_path.clone(), err))?;
if service_username.0.is_empty() {
return Err(crate::Error::IncompleteUserCredentials(None));
}
if service_token.0.is_empty() {
return Err(crate::Error::IncompleteUserCredentials(Some(service_username)));
}
Ok(factorio_mods_common::UserCredentials { username: service_username, token: service_token })
}
/// Saves the given user credentials to `player-data.json`
pub fn save_user_credentials(&self, user_credentials: factorio_mods_common::UserCredentials) -> Result<(), crate::Error> {
let player_data_json_file_path = &self.player_data_json_file_path;
let mut player_data: serde_json::Map<_, _> = {
let player_data_json_file =
std::fs::File::open(player_data_json_file_path)
.map_err(|err| crate::Error::Io(player_data_json_file_path.clone(), err))?;
serde_json::from_reader(player_data_json_file)
.map_err(|err| crate::Error::ReadJsonFile(player_data_json_file_path.clone(), err))?
};
player_data.insert("service-username".to_owned(), serde_json::Value::String(user_credentials.username.0));
player_data.insert("service-token".to_owned(), serde_json::Value::String(user_credentials.token.0));
let player_data = player_data;
let mut player_data_json_file =
std::fs::File::create(player_data_json_file_path)
.map_err(|err| crate::Error::Io(player_data_json_file_path.clone(), err))?;
let () =
serde_json::to_writer_pretty(&mut player_data_json_file, &player_data)
.map_err(|err| crate::Error::WriteJsonFile(player_data_json_file_path.clone(), err))?;
Ok(())
}
/// Returns a map of installed mod name to its enabled / disabled status in `mod-list.json`
pub fn mods_status(&self) -> Result<std::collections::BTreeMap<factorio_mods_common::ModName, bool>, crate::Error> {
let mod_list = self.load_mod_list()?;
Ok(mod_list.mods.into_iter().map(|m| (m.name.into_owned(), m.enabled)).collect())
}
/// Marks the given locally installed mods as enabled or disabled in `mod-list.json`
pub fn set_enabled<'a, I>(&self, installed_mods: I, enabled: bool) -> Result<(), crate::Error> where I: IntoIterator<Item = &'a crate::InstalledMod> {
let mod_list = self.load_mod_list()?;
let mut mods_status: std::collections::BTreeMap<_, _> = mod_list.mods.into_iter().map(|m| (m.name, m.enabled)).collect();
for installed_mod in installed_mods {
mods_status.insert(std::borrow::Cow::Borrowed(&installed_mod.info.name), enabled);
}
let mod_list_file_path = &self.mod_list_file_path;
let mut mod_list_file =
std::fs::File::create(mod_list_file_path)
.map_err(|err| crate::Error::Io(mod_list_file_path.clone(), err))?;
let mut mods: Vec<_> =
mods_status.into_iter()
.map(|(name, enabled)| ModListMod { name, enabled })
.collect();
mods.sort_by(|mod1, mod2| mod1.name.cmp(&mod2.name));
let mod_list = ModList { mods };
let () =
serde_json::to_writer_pretty(&mut mod_list_file, &mod_list)
.map_err(|err| crate::Error::WriteJsonFile(mod_list_file_path.clone(), err))?;
Ok(())
}
fn load_mod_list(&self) -> Result<ModList<'static>, crate::Error> {
let mod_list_file_path = &self.mod_list_file_path;
let mod_list_file =
std::fs::File::open(mod_list_file_path)
.map_err(|err| crate::Error::Io(mod_list_file_path.clone(), err))?;
let mod_list =
serde_json::from_reader(mod_list_file)
.map_err(|err| crate::Error::ReadJsonFile(mod_list_file_path.clone(), err))?;
Ok(mod_list)
}
}
/// Represents the contents of `mod-list.json`
#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct ModList<'a> {
mods: Vec<ModListMod<'a>>,
}
/// A mod entry in the mod list
#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct ModListMod<'a> {
name: std::borrow::Cow<'a, factorio_mods_common::ModName>,
#[serde(deserialize_with = "deserialize_mod_list_mod_enabled")]
enabled: bool,
}
/// Represents the contents of `base/info.json`
#[derive(Debug, serde::Deserialize)]
struct BaseInfo {
version: factorio_mods_common::ReleaseVersion,
}
/// Represents the contents of `player-data.json`
#[derive(Debug, serde::Deserialize)]
struct PlayerData {
// A clean install of Factorio defaults these fields to the empty string if the user has not logged in,
// so coerce them to the empty string even if they don't exist and treat empty string as if they don't exist.
#[serde(rename(deserialize = "service-username"), default)]
service_username: factorio_mods_common::ServiceUsername,
#[serde(rename(deserialize = "service-token"), default)]
service_token: factorio_mods_common::ServiceToken,
}
/// Deserializes the `enabled` field of a mod in `mod-list.json`, which can be a JSON string or a JSON boolean.
fn deserialize_mod_list_mod_enabled<'de, D>(deserializer: D) -> Result<bool, D::Error>
where D: serde::Deserializer<'de> {
struct Visitor;
impl serde::de::Visitor<'_> for Visitor {
type Value = bool;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(r#""true" or "false" or true or false"#)
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(v)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
v.parse().map_err(|_| serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &self))
}
}
deserializer.deserialize_any(Visitor)
}