~goorzhel/sota-slack-spotter

ref: ed7300e431a66cc9875ab4fdc8b4c8d1c76db8e9 sota-slack-spotter/src/main.rs -rw-r--r-- 1.7 KiB
ed7300e4 — Antonio Gurgel Use camino::Utf8PathBuf 4 months ago
                                                                                
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
use std::{env::var, time::Duration};

use anyhow::{Context, Result};
use log::info;

mod activation;
mod cache;
mod callsign;
mod slack;
mod sota;
#[cfg(test)]
mod test;

use crate::{
    activation::Activations,
    cache::Cache,
    slack::Slack,
    sota::{all_alerts, all_spots},
};

fn main() -> Result<()> {
    env_logger::init();

    let slack = Slack::from_env().context("Couldn't init Slack client")?;
    let cache_dir = var("CACHE_DIR").unwrap_or_else(|_| "/tmp".into());
    let cache_dir = |filename: &str| format!("{}/{}", cache_dir, filename);

    // TODO: This could be macroed.
    let activation_cache = Cache::new(cache_dir("activations.json"));
    let callsign_cache = Cache::new(cache_dir("calls.json"));
    let spot_cache = Cache::new(cache_dir("spots.json"));
    let alert_cache = Cache::new(cache_dir("alerts.json"));

    let callsigns = match callsign_cache.is_stale(Duration::from_secs(3600)) {
        true => {
            let c = slack.callsigns()?;
            callsign_cache.save(&c)?;
            c
        }
        false => callsign_cache.load()?,
    };

    let mut activations = Activations::from_cache(&activation_cache);
    let new_spots =
        spot_cache.new_data(&|| all_spots(1).context("Couldn't get spots"), &callsigns)?;
    info!("Found {} new spots", &new_spots.len());
    activations.emit_spots(&slack, &new_spots)?;
    spot_cache.reconcile(new_spots)?;
    activations.save_cache(&activation_cache)?;

    let new_alerts =
        alert_cache.new_data(&|| all_alerts().context("Couldn't get alerts"), &callsigns)?;
    info!("Found {} new alerts", &new_alerts.len());
    slack.message_batch(&new_alerts)?;
    alert_cache.reconcile(new_alerts)?;

    Ok(())
}