summaryrefslogtreecommitdiffstats
path: root/src/trash.rs
blob: e6711ee571015b0fd59eabbdcf880bc3b43994e5 (plain)
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
use std::fs::{create_dir, read_dir, remove_dir_all};
use std::io::prelude::*;
use std::path::{Path, PathBuf};

use chrono::{Local, NaiveDateTime};
use log::info;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};

use crate::constant_strings_paths::{TRASH_FOLDER_FILES, TRASH_FOLDER_INFO};
use crate::fm_error::{FmError, FmResult};
use crate::impl_selectable_content;
use crate::utils::read_lines;

static TRASHINFO_DATETIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";

/// Holds the information about a trashed file.
/// Follow the specifications of .trashinfo files as described in
/// [Trash freedesktop specs](https://specifications.freedesktop.org/trash-spec/trashspec-latest.html)
/// It knows
/// - where the file came from,
/// - what name it was given when trashed,
/// - when it was trashed
#[derive(Debug, Clone)]
pub struct TrashInfo {
    origin: PathBuf,
    dest_name: String,
    deletion_date: String,
}

impl TrashInfo {
    /// Returns a new `TrashInfo` instance.
    /// The deletion_date is calculated on creation, before the file is actually trashed.
    pub fn new(origin: &Path, dest_name: &str) -> Self {
        let date = Local::now();
        let deletion_date = format!("{}", date.format(TRASHINFO_DATETIME_FORMAT));
        let dest_name = dest_name.to_owned();
        Self {
            origin: PathBuf::from(origin),
            dest_name,
            deletion_date,
        }
    }

    fn to_string(&self) -> FmResult<String> {
        Ok(format!(
            "[Trash Info]
Path={}
DeletionDate={}
",
            url_escape::encode_fragment(path_to_string(&self.origin)?),
            self.deletion_date
        ))
    }

    /// Write itself into a .trashinfo file.
    /// The format looks like :
    ///
    /// [TrashInfo]
    /// Path=/home/quentin/Documents
    /// DeletionDate=2022-12-31T22:45:55
    pub fn write_trash_info(&self, dest: &Path) -> FmResult<()> {
        info!("writing trash_info {} for {:?}", self, dest);

        let mut file = std::fs::File::create(dest)?;
        if let Err(e) = write!(file, "{}", self.to_string()?) {
            info!("Couldn't write to trash file: {}", e)
        }
        Ok(())
    }

    /// Reads a .trashinfo file and parse it into a new instance.
    ///
    /// Let say `Document.trashinfo` contains :
    ///
    /// [TrashInfo]
    /// Path=/home/quentin/Documents
    /// DeletionDate=2022-12-31T22:45:55
    ///
    /// It will be parsed into
    /// TrashInfo { PathBuf::from("/home/quentin/Documents"), "Documents", "2022-12-31T22:45:55" }
    pub fn from_trash_info_file(trash_info_file: &Path) -> FmResult<Self> {
        let mut option_path: Option<PathBuf> = None;
        let mut option_deleted_time: Option<String> = None;
        let mut found_trash_info_line: bool = false;
        if let Some(dest_name) = trash_info_file.file_name() {
            let dest_name = Self::remove_extension(dest_name.to_str().unwrap().to_owned())?;
            if let Ok(lines) = read_lines(trash_info_file) {
                for (index, line_result) in lines.enumerate() {
                    let Ok(line) = line_result.as_ref() else { continue };
                    if line.starts_with("[Trash Info]") {
                        if index == 0 {
                            found_trash_info_line = true;
                            continue;
                        } else {
                            return trashinfo_error("[TrashInfo] was found after first line");
                        }
                    }
                    if line.starts_with("Path=") && option_path.is_none() {
                        if !found_trash_info_line {
                            return trashinfo_error("Found Path line before TrashInfo");
                        }
                        let path_part = &line[5..];
                        let cow_path_str = url_escape::decode(path_part);
                        let path_str = cow_path_str.as_ref();
                        option_path = Some(PathBuf::from(path_str));
                    } else if line.starts_with("DeletionDate=") && option_deleted_time.is_none() {
                        if !found_trash_info_line {
                            return trashinfo_error("Found DeletionDate line before TrashInfo");
                        }
                        let deletion_date_str = &line[13..];
                        match parsed_date_from_path_info(deletion_date_str) {
                            Ok(()) => (),
                            Err(e) => return Err(e),
                        }
                        option_deleted_time = Some(deletion_date_str.to_owned())
                    }
                }
            }
            match (option_path, option_deleted_time) {
                (Some(origin), Some(deletion_date)) => Ok(Self {
                    dest_name,
                    deletion_date,
                    origin,
                }),
                _ => trashinfo_error("Couldn't parse the trash info file"),
            }
        } else {
            trashinfo_error("Couldn't parse the trash info filename")
        }
    }

    fn remove_extension(mut destname: String) -> FmResult<String> {
        if destname.ends_with(".trashinfo") {
            destname.truncate(destname.len() - 10);
            Ok(destname)
        } else {
            Err(FmError::custom(
                "trahsinfo",
                "filename doesn't contain .trashfino",
            ))
        }
    }
}

impl std::fmt::Display for TrashInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{} - trashed on {}",
            path_to_string(&self.origin).unwrap_or_default(),
            self.deletion_date
        )
    }
}

/// Represent a view of the trash.
/// It's content is navigable so we use a Vector to hold the content.
#[derive(Clone)]
pub struct Trash {
    /// Trashed files info.
    pub content: Vec<TrashInfo>,
    index: usize,
    /// The path to the trashed files
    pub trash_folder_files: String,
    trash_folder_info: String,
}

impl Trash {
    fn pick_dest_name(&self, origin: &Path) -> FmResult<String> {
        if let Some(file_name) = origin.file_name() {
            let mut dest = file_name
                .to_str()
                .ok_or_else(|| {
                    FmError::custom(
                        "pick_dest_name",
                        "Couldn't parse the origin filename into a string",
                    )
                })?
                .to_owned();
            let mut dest_path = PathBuf::from(&self.trash_folder_files);
            dest_path.push(&dest);
            while dest_path.exists() {
                dest.push_str(&rand_string());
                dest_path = PathBuf::from(&self.trash_folder_files);
                dest_path.push(&dest);
            }
            return Ok(dest);
        }
        Err(FmError::custom(
            "pick_dest_name",
            "Couldn't extract the filename",
        ))
    }

    /// Creates an empty view of the trash.
    /// No file is read here, we wait for the user to open the trash first.
    pub fn new() -> FmResult<Self> {
        let trash_folder_files = shellexpand::tilde(TRASH_FOLDER_FILES).to_string();
        let trash_folder_info = shellexpand::tilde(TRASH_FOLDER_INFO).to_string();
        create_if_not_exists(&trash_folder_files)?;
        create_if_not_exists(&trash_folder_info)?;

        let index = 0;
        let content = vec![];

        Ok(Self {
            content,
            index,
            trash_folder_files,
            trash_folder_info,
        })
    }

    fn parse_updated_content(trash_folder_info: &str) -> FmResult<Vec<TrashInfo>><