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
use std::fs;
use std::io::Error as IoError;
use std::path::PathBuf;
use failure::Fail;
use ffsend_api::{
file::remote_file::{FileParseError, RemoteFile},
url::Url,
};
use toml::{de::Error as DeError, ser::Error as SerError};
use version_compare::Cmp;
use crate::util::{print_error, print_warning};
/// The minimum supported history file version.
const VERSION_MIN: &str = "0.0.1";
/// The maximum supported history file version.
const VERSION_MAX: &str = crate_version!();
#[derive(Serialize, Deserialize)]
pub struct History {
/// The application version the history file was built with.
/// Used for compatibility checking.
version: Option<String>,
/// The file history.
files: Vec<RemoteFile>,
/// Whether the list of files has changed.
#[serde(skip)]
changed: bool,
/// An optional path to automatically save the history to.
#[serde(skip)]
autosave: Option<PathBuf>,
}
impl History {
/// Construct a new history.
/// A path may be given to automatically save the history to once changed.
pub fn new(autosave: Option<PathBuf>) -> Self {
let mut history = History::default();
history.autosave = autosave;
history
}
/// Load the history from the given file.
pub fn load(path: PathBuf) -> Result<Self, LoadError> {
// Read the file to a string
let data = fs::read_to_string(&path)?;
// Parse the data, set the autosave path
let mut history: Self = toml::from_str(&data)?;
history.autosave = Some(path);
// Make sure the file version is supported
match history.version.as_ref() {
None => {
print_warning("History file has no version, ignoring");
history.version = Some(crate_version!().into());
}
Some(version) => {
if let Ok(true) = version_compare::compare_to(version, VERSION_MIN, Cmp::Lt) {
print_warning("history file version is too old, ignoring");
} else if let Ok(true) = version_compare::compare_to(version, VERSION_MAX, Cmp::Gt) {
print_warning("history file has an unknown version, ignoring");
}
}
}
// Garbage collect
history.gc();
Ok(history)
}
/// Load the history from the given file.
/// If the file doesn't exist, create a new empty history instance.
///
/// Autosaving will be enabled, and will save to the given file path.
pub fn load_or_new(file: PathBuf) -> Result<Self, LoadError> {
if file.is_file() {
Self::load(file)
} else {
Ok(Self::new(Some(file)))
}
}
/// Save the history to the internal autosave file.
pub fn save(&mut self) -> Result<(), SaveError> {
// Garbage collect
self.gc();
// Get the path
let path = self.autosave.as_ref().ok_or(SaveError::NoPath)?;
// If we have no files, remove the history file if it exists
if self.files.is_empty() {
if path.is_file() {
fs::remove_file(&path).map_err(SaveError::Delete)?;
}
return Ok(());
}
// Ensure the file parent directories are available
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
// Build the data to write to a file
let data = toml::to_string(self)?;
// Write the file, enforcing user-only (0o600) permissions on Unix on
// every save. The history file contains share secrets and owner
// tokens; relying on permissions set only at first-create time would
// miss the case where the file was created by something else with
// looser permissions.
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)
.map_err(SaveError::Write)?;
// If the file existed already, force-restore restrictive
// permissions: the mode flag on OpenOptions only applies on create.
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
file.set_permissions(Permissions::from_mode(0o600))
.map_err(SaveError::SetPermissions)?;
file.write_all(data.as_bytes()).map_err(SaveError::Write)?;
}
#[cfg(not(unix))]
fs::write(&path, data)?;
// There are no new changes, set the flag
self.changed = false;
Ok(())
}
/// Add the given remote file to the history.
/// If a file with the same ID as the given file exists,
/// the files are merged, see `RemoteFile::merge()`.
///
/// If `overwrite` is set to true, the given file will overwrite
/// properties on the existing file.
pub fn add(&mut self, file: RemoteFile, overwrite: bool) {
// Merge any existing file with the same ID
{
// Find anything to merge
let merge_info: Vec<bool> = self
.files
.iter_mut()
.filter(|f| f.id() == file.id())
.map(|ref mut f| f.merge(&file, overwrite))
.collect();
let merged = !merge_info.is_empty();
let changed = merge_info.iter().any(|i| *i);
// Return if merged, update the changed state
if merged {
if changed {
self.changed = true;
}
return;
}
}
// Add the file to the list
self.files.push(file);
self.changed = true;
}
/// Remove a file, matched by it's file ID.
///
/// If any file was removed, true is returned.
pub fn remove(&mut self, id: &str) -> bool {
// Get the indices of files that have expired
let expired_indices: Vec<usize> = self
.files
.iter()
.enumerate()
.filter(|&(_, f)| f.id() == id)
.map(|(i, _)| i)
.collect();
// Remove these specific files
for i in expired_indices.iter().rev() {
self.files.remove(*i);
}
// Set the changed flag if something was actually removed, and return
let removed = !expired_indices.is_empty();
if removed {
self.changed = true;
}
removed
}
/// Remove a file by the given URL.
///
/// If any file was removed, true is returned.
pub fn remove_url(&mut self, url: Url) -> Result<bool, FileParseError> {
Ok(self.remove(RemoteFile::parse_url(url, None)?.id()))
}
/// Get all files.
pub fn files(&self) -> &Vec<RemoteFile> {
&self.files
}
/// Get a file from the history, based on the given remote file.
/// The file ID and host will be compared against all files in this history.
/// If multiple files exist within the history that are equal, only one is returned.
/// If no matching file was found, `None` is returned.
pub fn get_file(&self, file: &RemoteFile) -> Option<&RemoteFile> {
self.files
.iter()
.find(|f| f.id() == file.id() && f.host() == file.host())
}
/// Clear all history.
pub fn clear(&mut self) {
self.changed = !self.files.is_empty();
self.files.clear();
}
/// Garbage collect (remove) all files that have been expired,
/// as defined by their `expire_at` property.
///
/// If the expiry property is None (thus unknown), the file will be kept.
///
/// The number of expired files is returned.
pub fn gc(&mut self) -> usize {
// Get a list of expired files
let expired: Vec<RemoteFile> = self
.files
.iter()
.filter(|f| f.has_expired())
.cloned()
.collect();
// Remove the files
for f in &expired {
self.remove(f.id());
}
// Set the changed flag
if !expired.is_empty() {
self.changed = true;
}
// Return the number of expired files
expired.len()
}
}
impl Drop for History {
fn drop(&mut self) {
// Automatically save if enabled and something was changed
if self.autosave.is_some() && self.changed {
// Save and report errors
if let Err(err) = self.save() {
print_error(err.context("failed to auto save history, ignoring"));
}
}
}
}
impl Default for History {
fn default() -> Self {
Self {
version: Some(crate_version!().into()),
files: Vec::new(),
changed: false,
autosave: None,
}
}
}
#[derive(Debug, Fail)]
pub enum Error {
/// An error occurred while loading the history from a file.
#[fail(display = "failed to load history from file")]
Load(#[cause] LoadError),
/// An error occurred while saving the history to a file.
#[fail(display = "failed to save history to file")]
Save(#[cause] SaveError),
}
impl From<LoadError> for Error {
fn from(err: LoadError) -> Self {
Error::Load(err)
}
}
impl From<SaveError> for Error {
fn from(err: SaveError) -> Self {
Error::Save(err)
}
}
#[derive(Debug, Fail)]
pub enum LoadError {
/// Failed to read the file contents from the given file.
#[fail(display = "failed to read from the history file")]
Read(#[cause] IoError),
/// Failed to parse the loaded file.
#[fail(display = "failed to parse the file contents")]
Parse(#[cause] DeError),
}
impl From<IoError> for LoadError {
fn from(err: IoError) -> Self {
LoadError::Read(err)
}
}
impl From<DeError> for LoadError {
fn from(err: DeError) -> Self {
LoadError::Parse(err)
}
}
#[derive(Debug, Fail)]
pub enum SaveError {
/// No autosave file path was present, failed to save.
#[fail(display = "no autosave file path specified")]
NoPath,
/// Failed to serialize the history for saving.
#[fail(display = "failed to serialize the history for saving")]
Serialize(#[cause] SerError),
/// Failed to write to the history file.
#[fail(display = "failed to write to the history file")]
Write(#[cause] IoError),
/// Failed to set file permissions to the history file.
#[fail(display = "failed to set permissions to the history file")]
SetPermissions(#[cause] IoError),
/// Failed to delete the history file, which was tried because there
/// are no history items to save.
#[fail(display = "failed to delete history file, because history is empty")]
Delete(#[cause] IoError),
}
impl From<SerError> for SaveError {
fn from(err: SerError) -> Self {
SaveError::Serialize(err)
}
}
impl From<IoError> for SaveError {
fn from(err: IoError) -> Self {
SaveError::Write(err)
}
}