-
-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathconfig.rs
More file actions
487 lines (427 loc) · 14.9 KB
/
config.rs
File metadata and controls
487 lines (427 loc) · 14.9 KB
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
use anyhow::{Context, anyhow, bail};
use serde::{
Deserialize, Serialize,
de::{self, MapAccess, Visitor},
};
use tracing::warn;
use url::Url;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{fmt, fs};
use crate::{command::ModeKeybindingConfig, passphrase::Passphrase};
const GURK_DB_NAME: &str = "gurk.sqlite";
const SIGNAL_DB_NAME: &str = "signal.sqlite";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
/// Directory to store messages and signal database, and attachments.
#[serde(
default = "default_data_dir",
skip_serializing_if = "is_default_data_dir"
)]
pub data_dir: PathBuf,
/// Path to the Signal database containing the linked device data.
#[serde(
rename = "signal_db_path",
default = "default_signal_db_path",
skip_serializing_if = "is_default_signal_db_path"
)]
pub deprecated_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,
/// Notification settings
#[serde(default, deserialize_with = "deserialize_notification_config")]
pub notifications: NotificationConfig,
#[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(skip_serializing_if = "Option::is_none")]
pub sqlite: Option<SqliteConfig>,
#[serde(default)]
/// If set, enables encryption of the key store and messages database
pub passphrase: Option<Passphrase>,
/// 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
#[serde(alias = "name")]
pub display_name: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NotificationConfig {
/// Whether to show system notifications on incoming messages
#[serde(default = "default_true")]
pub enabled: bool,
/// Whether to show message preview in notifications
#[serde(default = "default_true")]
pub show_message_text: bool,
/// Whether to show message origin in notifications
#[serde(default = "default_true")]
pub show_message_chat: bool,
/// Whether to show reactions in notifications
#[serde(default = "default_true")]
pub show_reactions: bool,
/// Whether to mute reactions bell
#[serde(default)]
pub mute_reactions_bell: bool,
}
impl Default for NotificationConfig {
fn default() -> Self {
Self {
enabled: true,
show_message_text: true,
show_message_chat: true,
show_reactions: true,
mute_reactions_bell: false,
}
}
}
#[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()
}
}
#[derive(Debug, Clone)]
pub struct LoadedConfig {
pub(crate) config: Config,
pub(crate) deprecated_keys: DeprecatedKeys,
}
impl LoadedConfig {
pub fn report_deprecated_keys(self) -> Config {
if !self.deprecated_keys.keys.is_empty() {
println!("In '{}':", self.deprecated_keys.file_path.display());
for DeprecatedConfigKey { key, message } in self.deprecated_keys.keys.iter() {
warn!(key, message, "deprecated config key");
println!("deprecated config key: {key}, {message}");
}
}
self.config
}
}
#[derive(Debug, Clone)]
pub(crate) struct DeprecatedKeys {
pub(crate) file_path: PathBuf,
pub(crate) keys: Vec<DeprecatedConfigKey>,
}
#[derive(Debug, Clone)]
pub(crate) struct DeprecatedConfigKey {
pub(crate) key: &'static str,
pub(crate) message: &'static str,
}
/// Accepts either `notifications = true/false` (legacy) or `[notifications]` (current struct).
fn deserialize_notification_config<'de, D>(deserializer: D) -> Result<NotificationConfig, D::Error>
where
D: serde::Deserializer<'de>,
{
struct NotificationConfigVisitor;
impl<'de> Visitor<'de> for NotificationConfigVisitor {
type Value = NotificationConfig;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a boolean or a notification config table")
}
fn visit_bool<E: de::Error>(self, enabled: bool) -> Result<NotificationConfig, E> {
Ok(NotificationConfig {
enabled,
..Default::default()
})
}
fn visit_map<M: MapAccess<'de>>(self, map: M) -> Result<NotificationConfig, M::Error> {
NotificationConfig::deserialize(de::value::MapAccessDeserializer::new(map))
}
}
deserializer.deserialize_any(NotificationConfigVisitor)
}
/// Writes `content` to `path` with owner-only permissions (0o600 on Unix).
///
/// This is important in case the passphrase is stored in the config file.
fn write_config(path: &Path, content: &str) -> anyhow::Result<()> {
let mut options = fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options.open(path)?.write_all(content.as_bytes())?;
Ok(())
}
impl Config {
/// Create new config with default paths from the given user.
pub fn with_user(user: User) -> Self {
Config {
user,
data_dir: default_data_dir(),
deprecated_signal_db_path: default_signal_db_path(),
first_name_only: false,
show_receipts: true,
notifications: NotificationConfig::default(),
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<LoadedConfig>> {
installed_config().map(Self::load).transpose()
}
pub fn load_installed_passphrase() -> anyhow::Result<Option<Passphrase>> {
let loaded = Self::load_installed()?;
Ok(loaded.and_then(|c| c.config.passphrase))
}
/// 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<PathBuf> {
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)
.with_context(|| format!("failed to save config at {}", config_file.display()))?;
Ok(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 = default_data_dir();
fs::create_dir_all(data_path).context("could not create data dir")?;
self.save(path)
}
fn load(path: impl AsRef<Path>) -> anyhow::Result<LoadedConfig> {
let path = path.as_ref();
let content = std::fs::read_to_string(path)?;
let config = toml::de::from_str(&content)?;
// check for deprecated keys
let config_value: toml::Value = toml::de::from_str(&content)?;
let mut keys = Vec::new();
if config_value
.get("sqlite")
.map(|v| v.get("enabled").is_some())
.unwrap_or(false)
{
keys.push(DeprecatedConfigKey {
key: "sqlite.enabled",
message: "sqlite is now enabled by default",
});
}
if config_value.get("signal_db_path").is_some() {
keys.push(DeprecatedConfigKey {
key: "signal_db_path",
message: "is not used anymore; use `data_dir` instead",
});
}
if config_value.get("sqlite").is_some() {
keys.push(DeprecatedConfigKey {
key: "sqlite",
message: "will be removed in a future version; use `<data_dir>/gurk.sqlite` instead",
});
}
if config_value
.get("notifications")
.and_then(|v| v.as_bool())
.is_some()
{
keys.push(DeprecatedConfigKey {
key: "notifications",
message: "boolean format is deprecated; use [notifications] section with enabled, show_message_text, show_message_chat, show_reactions and mute_reactions_bell fields",
});
}
let deprecated_keys = DeprecatedKeys {
file_path: path.to_path_buf(),
keys,
};
Ok(LoadedConfig {
config,
deprecated_keys,
})
}
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();
write_config(path, &content)?;
Ok(())
}
pub fn gurk_db_path(&self) -> PathBuf {
self.data_dir.join(GURK_DB_NAME)
}
pub(crate) fn signal_db_path(&self) -> PathBuf {
self.data_dir.join(SIGNAL_DB_NAME)
}
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct SqliteConfig {
#[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_unencrypted")]
pub preserve_unencrypted: bool,
}
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.
fn default_signal_db_path() -> PathBuf {
default_data_dir().join("signal-db")
}
fn is_default_signal_db_path(path: &Path) -> bool {
path == default_signal_db_path()
}
/// 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 {
let data_dir =
dirs::data_dir().expect("data directory not found, $XDG_DATA_HOME and $HOME are unset?");
data_dir.join("gurk")
}
fn is_default_data_dir(path: &Path) -> bool {
path == default_data_dir()
}
fn default_true() -> bool {
true
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::{NamedTempFile, TempDir, tempdir};
fn example_config_with_random_paths(dir: &TempDir) -> Config {
let data_dir = dir.path().join("some-data-dir/some-other-dir/data.json");
assert!(!data_dir.parent().unwrap().exists());
Config {
data_dir,
..Config::with_user(User {
display_name: "Tyler Durden".to_string(),
})
}
}
#[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 LoadedConfig {
config: loaded_config,
deprecated_keys: _,
} = Config::load(&config_path)?;
assert_eq!(config, loaded_config);
assert!(config_path.parent().unwrap().exists()); // data path parent is created
Ok(())
}
#[test]
fn test_notifications_bool_compat() {
// Old configs with `notifications = true/false` should parse successfully
let toml_true = r#"
notifications = true
[user]
display_name = "Test"
"#;
let config: Config = toml::de::from_str(toml_true).unwrap();
assert!(config.notifications.enabled);
let toml_false = r#"
notifications = false
[user]
display_name = "Test"
"#;
let config: Config = toml::de::from_str(toml_false).unwrap();
assert!(!config.notifications.enabled);
// New struct format should still work
let toml_struct = r#"
[user]
display_name = "Test"
[notifications]
enabled = false
show_message_text = true
"#;
let config: Config = toml::de::from_str(toml_struct).unwrap();
assert!(!config.notifications.enabled);
assert!(config.notifications.show_message_text);
}
#[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());
Ok(())
}
}