-
Notifications
You must be signed in to change notification settings - Fork 37
/
config.rs
294 lines (256 loc) · 8.97 KB
/
config.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
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
use anyhow::{anyhow, bail, Context};
use serde::{Deserialize, Serialize};
use url::Url;
use std::fs;
use std::path::{Path, PathBuf};
use crate::command::ModeKeybindingConfig;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
/// Path to the JSON file (incl. filename) storing channels and messages.
#[serde(default = "default_data_path")]
pub data_path: PathBuf,
/// Path to the Signal database containing the linked device data.
#[serde(default = "default_signal_db_path")]
pub signal_db_path: PathBuf,
/// Whether only to show the first name of a contact
#[serde(default)]
pub first_name_only: bool,
/// Whether to show receipts (sent, delivered, read) information next to your user name in UI
#[serde(default = "default_true")]
pub show_receipts: bool,
/// Whether to show system notifications on incoming messages
#[serde(default = "default_true")]
pub notifications: bool,
#[serde(default = "default_true")]
pub bell: bool,
/// User configuration
pub user: User,
#[cfg(feature = "dev")]
#[serde(default, skip_serializing_if = "DeveloperConfig::is_default")]
pub developer: DeveloperConfig,
#[serde(default)]
pub sqlite: SqliteConfig,
#[serde(default)]
/// If set, enables encryption of the key store and messages database
pub passphrase: Option<String>,
/// If set, the full message text will be colored, not only the author name
#[serde(default)]
pub colored_messages: bool,
#[serde(default)]
/// Keymaps
pub keybindings: ModeKeybindingConfig,
/// Whether to enable the default keybindings
#[serde(default = "default_true")]
pub default_keybindings: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct User {
/// Name to be shown in the application
pub name: String,
/// Phone number used in Signal
pub phone_number: String,
}
#[cfg(feature = "dev")]
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeveloperConfig {
/// Dump raw messages to `messages.json` for collecting debug/benchmark data
pub dump_raw_messages: bool,
}
#[cfg(feature = "dev")]
impl DeveloperConfig {
fn is_default(&self) -> bool {
self == &Self::default()
}
}
impl Config {
/// Create new config with default paths from the given user.
pub fn with_user(user: User) -> Self {
Config {
user,
data_path: default_data_path(),
signal_db_path: default_signal_db_path(),
first_name_only: false,
show_receipts: true,
notifications: true,
bell: true,
#[cfg(feature = "dev")]
developer: Default::default(),
sqlite: Default::default(),
passphrase: None,
colored_messages: false,
default_keybindings: true,
keybindings: ModeKeybindingConfig::default(),
}
}
/// Tries to load configuration from one of the default locations:
///
/// 1. $XDG_CONFIG_HOME/gurk/gurk.toml
/// 2. $XDG_CONFIG_HOME/gurk.toml
/// 3. $HOME/.config/gurk/gurk.toml
/// 4. $HOME/.gurk.toml
///
/// If no config is found returns `None`.
pub fn load_installed() -> anyhow::Result<Option<Self>> {
installed_config().map(Self::load).transpose()
}
/// Saves a new config file in case it does not exist.
///
/// Also makes sure that the `config.data_path` exists.
pub fn save_new(&self) -> anyhow::Result<()> {
let config_dir =
dirs::config_dir().ok_or_else(|| anyhow!("could not find default config directory"))?;
let config_file = config_dir.join("gurk/gurk.toml");
self.save_new_at(config_file)
}
fn save_new_at(&self, path: impl AsRef<Path>) -> anyhow::Result<()> {
// check that config won't be overridden
if path.as_ref().exists() {
bail!(
"will not override config file at: {}",
path.as_ref().display()
);
}
// make sure data_path exists
let data_path = self
.data_path
.parent()
.ok_or_else(|| anyhow!("invalid data path: no parent dir"))?;
fs::create_dir_all(data_path).context("could not create data dir")?;
self.save(path)
}
fn load(path: impl AsRef<Path>) -> anyhow::Result<Config> {
let content = std::fs::read_to_string(path)?;
let config = toml::de::from_str(&content)?;
Ok(config)
}
fn save(&self, path: impl AsRef<Path>) -> anyhow::Result<()> {
let path = path.as_ref();
let content = toml::ser::to_string(self)?;
let parent_dir = path
.parent()
.ok_or_else(|| anyhow!("invalid config path {}: no parent dir", path.display()))?;
fs::create_dir_all(parent_dir).unwrap();
fs::write(path, content)?;
Ok(())
}
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct SqliteConfig {
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(default = "SqliteConfig::default_db_url")]
pub url: Url,
/// Don't delete the unencrypted db, after applying encryption to it
///
/// Useful for testing.
#[serde(default, rename = "_preserve_unencryped")]
pub preserve_unencrypted: bool,
}
impl Default for SqliteConfig {
fn default() -> Self {
Self {
enabled: false,
url: Self::default_db_url(),
preserve_unencrypted: false,
}
}
}
impl SqliteConfig {
fn default_db_url() -> Url {
let path = default_data_dir().join("gurk.sqlite");
format!("sqlite://{}", path.display())
.parse()
.expect("invalid default sqlite path")
}
}
/// Get the location of the first found default config file paths
/// according to the following order:
///
/// 1. $XDG_CONFIG_HOME/gurk/gurk.toml
/// 2. $XDG_CONFIG_HOME/gurk.yml
/// 3. $HOME/.config/gurk/gurk.toml
/// 4. $HOME/.gurk.toml
fn installed_config() -> Option<PathBuf> {
// case 1, and 3 as fallback (note: case 2 is not possible if 1 is not possible)
let config_dir = dirs::config_dir()?;
let config_file = config_dir.join("gurk/gurk.toml");
if config_file.exists() {
return Some(config_file);
}
// case 2
let config_file = config_dir.join("gurk.toml");
if config_file.exists() {
return Some(config_file);
}
// case 4
let home_dir = dirs::home_dir()?;
let config_file = home_dir.join(".gurk.toml");
if config_file.exists() {
return Some(config_file);
}
None
}
/// Path to store the signal database containing the data for the linked device.
pub fn default_signal_db_path() -> PathBuf {
default_data_dir().join("signal-db")
}
/// Fallback to legacy data path location
pub fn fallback_data_path() -> Option<PathBuf> {
dirs::home_dir().map(|p| p.join(".gurk.data.json"))
}
fn default_data_dir() -> PathBuf {
match dirs::data_dir() {
Some(dir) => dir.join("gurk"),
None => panic!("default data directory not found, $XDG_DATA_HOME and $HOME are unset"),
}
}
fn default_data_path() -> PathBuf {
default_data_dir().join("gurk.data.json")
}
fn default_true() -> bool {
true
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::{tempdir, NamedTempFile, TempDir};
fn example_user() -> User {
User {
name: "Tyler Durden".to_string(),
phone_number: "+0000000000".to_string(),
}
}
fn example_config_with_random_paths(dir: &TempDir) -> Config {
let data_path = dir.path().join("some-data-dir/some-other-dir/data.json");
assert!(!data_path.parent().unwrap().exists());
let signal_db_path = dir.path().join("some-signal-db-dir/some-other-dir");
assert!(!signal_db_path.exists());
Config {
data_path,
signal_db_path,
..Config::with_user(example_user())
}
}
#[test]
fn test_save_new_at_non_existent() -> anyhow::Result<()> {
let dir = tempdir()?;
let config = example_config_with_random_paths(&dir);
let config_path = dir.path().join("some-dir/some-other-dir/gurk.toml");
config.save_new_at(&config_path)?;
let loaded_config = Config::load(config_path)?;
assert_eq!(config, loaded_config);
assert!(config.data_path.parent().unwrap().exists()); // data path parent is created
assert!(!config.signal_db_path.exists()); // signal path is not touched
Ok(())
}
#[test]
fn test_save_new_fails_or_existent() -> anyhow::Result<()> {
let dir = tempdir()?;
let config = example_config_with_random_paths(&dir);
let file = NamedTempFile::new()?;
assert!(config.save_new_at(file.path()).is_err());
assert!(!config.data_path.parent().unwrap().exists()); // data path parent is not touched
assert!(!config.signal_db_path.exists()); // signal path is not touched
Ok(())
}
}