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
use std::fs::{File, create_dir_all};
use std::io::Write;
use std::env;
use std::error::Error;
use std::ops::Drop;
use std::path::Path;
use std::process::Command;

use notify_rust::{Notification, Timeout, Urgency};
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use serde_json;

#[derive(Deserialize)]
pub struct AnityaResponse {
    items: Vec<AnityaProject>,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct AnityaProject {
    name: String,
    version: String
}

pub struct Config {
    pub config: Vec<AnityaProject>,
    path: String,
}

impl Config {
    pub fn new() -> Result<Config, Box<dyn Error>> {
        let path = format!("{}/.config/aytina.json", env!("HOME"));
        let config_path = Path::new(&path);

        if !config_path.is_file() {
            File::create(&config_path)?;
        }

        let config_file = File::open(&config_path)?;
        let config = serde_json::from_reader(&config_file)?;

        Ok(Config {
            config: config,
            path: path,
        })
    }

    pub fn add(&mut self, name: &[&str]) -> Result<(), Box<dyn Error>> {
        let client = Client::new();

        for n in name {
            let response: AnityaResponse = client.get(&format!(
                "https://release-monitoring.org/api/v2/projects/?name={}", n))
                .send()?.json()?;

            if response.items.len() == 0 {
                println!("No project named {} was found.", n);
                continue
            }

            self.config.push(response.items[0].clone());
            println!("Project {} has been added.", n);
        }
        Ok(())
    }

    pub fn remove(&mut self, name: &[&str]) -> Result<(), Box<dyn Error>> {
        self.config = self.config.iter()
            .filter_map(|x| {
                if name.contains(&x.name.as_str()) {
                    println!("The project {} has been removed.", x.name);
                    return None;
                }

                Some(x.clone())
            })
            .collect();
        Ok(())
    }
}

impl Drop for Config {
    fn drop(&mut self) {
        let config_path = Path::new(&self.path);
        let config_file = File::create(&config_path).unwrap();
        serde_json::to_writer_pretty(config_file, &self.config).unwrap();
    }
}

pub fn check(do_notify: bool) -> Result<(), Box<dyn Error>> {
    let mut config = Config::new()?;

    let client = Client::new();

    for p in &mut config.config {
        let response: AnityaResponse = client.get(&format!(
            "https://release-monitoring.org/api/v2/projects/?name={}", p.name))
            .send()?.json()?;

        if p.version != response.items[0].version {
            if do_notify {
                notify(&response.items[0])?;
            } else {
                println!("{} {} was released (OLD: {})",
                    response.items[0].name,
                    response.items[0].version,
                    p.version);
            }

            p.version = response.items[0].version.clone();
        }
    }

    Ok(())
}

pub fn notify(project: &AnityaProject) -> Result<(), Box<dyn Error>> {
    Notification::new()
        .appname("Aytina: A software had a new release")
        .summary(&format!("New release: {}", &project.name))
        .body(&format!("{} {} was released", &project.name, &project.version))
        .icon("software-update-available-symbolic")
        .urgency(Urgency::Critical)
        .timeout(Timeout::Never)
        .show()?;
 
    Ok(())
}

pub fn autocheck(time: &str) -> Result<(), Box<dyn Error>> {
    match time {
        "never" => {
            Command::new("systemctl")
                .args(&["disable", "--user", "--now", "aytina.timer"])
                .output()?;
            println!("Automatic release checking disabled.");
            return Ok(());
        },
        _ => {
            let len = time.len();
            match time[0..len - 1].parse::<usize>() {
                Err(_) => {
                    println!("Incorrect TIME value.");
                    return Ok(());
                },
                _ => {}
            }
        }
    };

    let exec_path = env::current_exe()?;
    let exec_path = Path::new(&exec_path);
    let unit_path = format!("{}/.local/share/systemd/user/", env!("HOME"));
    let unit_path = Path::new(&unit_path);

    if !unit_path.is_dir() {
        create_dir_all(unit_path)?;
    }

    let serv_path = unit_path.join("aytina.service");
    let serv_content = format!(
"[Unit]
Description=Automatic checking service for Aytina

[Service]
Type=simple
ExecStart={} check --notify
", exec_path.to_str().unwrap()
    );

    File::create(&serv_path)?.write_all(serv_content.as_bytes())?;

    let timer_path = unit_path.join("aytina.timer");

    let timer_content = format!(
"[Unit]
Description=The timer for the Aytina autochecker

[Timer]
OnBootSec=15min
OnUnitActiveSec={}

[Install]
WantedBy=timers.target
", time
    );

    File::create(&timer_path)?.write_all(timer_content.as_bytes())?;

    Command::new("systemctl")
        .args(&["enable", "--user", "--now", "aytina.timer"])
        .output()?;
    println!("Automatic release checking enabled.");

    Ok(())
}