rbmenu/
bookmark.rs

1/*
2 * RBMenu - Rust Bookmark Manager
3 * Copyright (C) 2021-2022 DevHyperCoder
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use crate::parser::{get_domain_name, is_url};
20use chrono::prelude::Local;
21use colored::*;
22use serde::{Deserialize, Serialize};
23use std::fmt;
24use substring::Substring;
25
26#[derive(Serialize, Deserialize, Debug, Clone)]
27pub struct Bookmark {
28    pub is_file: bool,
29    pub link: String,
30    pub name: String,
31    pub date: String,
32    pub id: u32,
33}
34
35impl Bookmark {
36    /// Generate a suitable name for Bookmark
37    /// If name is empty or not provided, link is parsed to get the domain name.
38    /// If name contains spaces, it is converted to underscores
39    pub fn generate_name(link: &str, name: Option<String>) -> String {
40        let mut name = name.unwrap_or_else(|| "".to_owned());
41
42        // If name is not provided, use the domain name
43        // If provided, replace ' ' with '_'
44        if name.is_empty() {
45            let m = get_domain_name(link);
46            name = match m {
47                Some(m) => link.substring(m.start(), m.end()).to_owned(),
48                None => link.to_string(),
49            }
50        } else {
51            name = name.replace(' ', "_");
52        }
53
54        name
55    }
56
57    /// Return bookmark with values
58    pub fn generate_bookmark(id: u32, link: String, name: String) -> Bookmark {
59        Bookmark {
60            is_file: !is_url(&link),
61            link,
62            name,
63            date: Local::now().to_string(),
64            id,
65        }
66    }
67
68    /// Print a coloured output
69    /// id -> yellow bold
70    /// name -> cyan bold
71    /// link -> blue
72    pub fn colored_fmt(&self) {
73        println!(
74            "{} {} {}",
75            self.id.to_string().yellow().bold(),
76            self.name.cyan().bold(),
77            self.link.blue()
78        );
79    }
80}
81
82impl fmt::Display for Bookmark {
83    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84        write!(f, "{} {} {}", self.id, self.name, self.link)
85    }
86}