caffeine_cli/caffeine/
mod.rs

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
use core::fmt;
use std::{
    error::Error,
    fs,
    path::PathBuf,
    process::Command,
    thread,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use chrono::{DateTime, Utc};
use daemonize::Daemonize;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CaffeineSession {
    pub proccess_id: String,
    pub start_time: u64,
    pub session_length: Option<u64>,
}

#[derive(Debug)]
pub enum SessionError {
    ConflictingSession,
    NoActiveSession,
}

impl Error for SessionError {}

impl fmt::Display for SessionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SessionError::ConflictingSession => write!(f, "A session already exists"),
            SessionError::NoActiveSession => write!(f, "Couldn't find an active session"),
        }
    }
}

pub fn get_session_path() -> PathBuf {
    PathBuf::from("/tmp/caffeine-session.json")
}

/**
Inits a caffeine session.
*/
pub fn init_session(seconds: Option<u64>) -> Result<CaffeineSession, Box<dyn Error>> {
    let seconds_str = if let Some(seconds) = seconds {
        seconds.to_string()
    } else {
        String::from("infinity")
    };

    let process = Command::new("systemd-inhibit")
        .arg("--what=idle")
        .arg("sleep")
        .arg(seconds_str)
        .spawn()?;

    let process_id = process.id();

    let start_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();

    Ok(CaffeineSession {
        proccess_id: process_id.to_string(),
        start_time,
        session_length: if let Some(seconds) = seconds {
            Some(seconds)
        } else {
            None
        },
    })
}

pub fn init_protected_session(seconds: Option<u64>) -> Result<CaffeineSession, Box<dyn Error>> {
    let session = get_session();

    if session.is_some() {
        return Err(Box::new(SessionError::ConflictingSession));
    }

    let new_session = init_session(seconds)?;

    let json = serde_json::to_string(&new_session)?;

    fs::write(get_session_path(), &json)?;

    if let Some(seconds) = seconds {
        let daemon = Daemonize::new();

        if let Ok(_) = daemon.start() {
            thread::sleep(Duration::from_secs(seconds));

            let _ = fs::remove_file(get_session_path());
        }
    }

    Ok(new_session)
}

pub fn end_session(session: CaffeineSession) -> Result<(), Box<dyn Error>> {
    Command::new("kill")
        .arg(&session.proccess_id)
        .spawn()
        .expect("Error killing caffeine session");

    Ok(())
}

pub fn end_protected_session() -> Result<(), Box<dyn Error>> {
    let session = get_session();

    if session.is_none() {
        return Err(Box::new(SessionError::NoActiveSession));
    }

    end_session(session.unwrap())?;

    fs::remove_file(get_session_path())?;

    Ok(())
}

pub fn get_session() -> Option<CaffeineSession> {
    let session_json = fs::read_to_string(get_session_path());

    if session_json.is_err() {
        return None;
    }

    let session = serde_json::from_str(&session_json.unwrap());

    if session.is_err() {
        return None;
    }

    Some(session.unwrap())
}

impl CaffeineSession {
    pub fn get_elapsed_time(&self) -> String {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let elapsed = UNIX_EPOCH + Duration::from_secs(now - self.start_time);

        let datetime: DateTime<Utc> = elapsed.into();

        datetime.format("%Hh %Mm %Ss").to_string()
    }

    pub fn get_session_length(&self) -> Option<String> {
        return if let Some(session_length) = self.session_length {
            let timestamp = UNIX_EPOCH + Duration::from_secs(session_length);

            let datetime: DateTime<Utc> = timestamp.into();

            Some(datetime.format("%Hh %Mm %Ss").to_string())
        } else {
            None
        };
    }

    pub fn get_remaining_time(&self) -> Option<String> {
        return if let Some(session_length) = self.session_length {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();

            let timestamp =
                UNIX_EPOCH + Duration::from_secs((session_length + self.start_time) - now);

            let datetime: DateTime<Utc> = timestamp.into();

            Some(datetime.format("%Hh %Mm %Ss").to_string())
        } else {
            None
        };
    }
}