summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 7afba146c90f501ea925ddbac8971bb49375e093 (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
#![feature(str_strip)]
extern crate fern;
#[macro_use]
extern crate log;
#[macro_use]
extern crate diesel_migrations;

use chrono::Utc;
use structopt::StructOpt;
use diesel::connection::Connection;
use diesel::pg::PgConnection;
use pjournal::db;
use pjournal::importer;
use pjournal::models;
use serde_json::to_value;

embed_migrations!();

/// Practice Journal
#[derive(Debug, StructOpt)]
struct Opt {
    /// URL to postgresql database
    #[structopt(long)]
    database_url: String,

    /// Endpoint for this web server
    #[structopt(long, default_value = "http://localhost:8080/")]
    base_url: String,

    /// Path to directory containing templates
    #[structopt(long, default_value = "./templates")]
    template_path: String,

    /// Path to directory containing static files
    #[structopt(long, default_value = "./static")]
    static_path: String,

    /// Port on which to server HTTP requests
    #[structopt(long, default_value = "8000")]
    port: u16,

    #[structopt(subcommand)]
    cmd: Option<Command>,
}

#[derive(Debug, StructOpt)]
enum Command {
    /// Initialize config table in the database
    Init {
        /// Secret passed to rocket for encrypting cookies
        rocket_secret_key: String,

        /// Client secret for strava authentication
        strava_client_secret: String,

        /// Client id for strava authentication
        strava_client_id: String,
    },
    /// Add a user account
    AddUser {
        username: String,
        password: String,
    },
    /// Create a ProcessAllRawData task
    ProcessAllData,
}

fn setup_logger() -> Result<(), fern::InitError> {
    use fern::colors::{Color, ColoredLevelConfig};
    let colors = ColoredLevelConfig::new();

    fern::Dispatch::new()
        .format(move |out, message, record| {
            let thread = std::thread::current();

            let thread_id = &format!("{:?}", thread.id())[..];
            let prefix = "ThreadId(";
            let thread_id = if thread_id.find(prefix).is_some() {
                &thread_id[prefix.len()..thread_id.len() - 1]
            } else {
                thread_id
            };

            let thread_colors = [
                Color::Red,
                Color::Green,
                Color::Magenta,
                Color::Cyan,
                Color::White,
                Color::Yellow,
                Color::BrightRed,
                Color::BrightGreen,
                Color::BrightMagenta,
                Color::BrightCyan,
                Color::BrightBlue,
                Color::BrightWhite,
            ];
            use std::collections::hash_map::DefaultHasher;
            use std::hash::{Hash, Hasher};
            let mut hasher = DefaultHasher::new();
            thread_id.hash(&mut hasher);
            let thread_color = thread_colors[hasher.finish() as usize % thread_colors.len()];

            out.finish(format_args!(
                "[{}] \x1B[{}m{}@{}\x1B[0m {}",
                colors.color(record.level()),
                thread_color.to_fg_str(),
                thread.name().unwrap_or(""),
                thread_id,
                message
            ))
        })
        .level(log::LevelFilter::Info)
        .chain(std::io::stdout())
        .apply()?;
    Ok(())
}

fn main() {
    setup_logger().expect("logger");

    let opt = Opt::from_args();

    let conn = PgConnection::establish(&opt.database_url).unwrap();
    embedded_migrations::run(&conn).unwrap();

    match opt.cmd {
        Some(Command::Init { rocket_secret_key, strava_client_secret, strava_client_id }) => {
            let config = models::Config {
                strava_client_id,
                strava_client_secret,
                rocket_secret_key,
                singleton: true,
            };

            db::create_config(&conn, &config).unwrap();
            info!("config created");
        },
        Some(Command::AddUser { username, password }) => {
            db::adduser(&conn, &username, &password).unwrap();
            info!("added user {}", username);
        },
        Some(Command::ProcessAllData) => {
            let command = importer::Command::ProcessAllRawData;
            db::insert_task(
                &conn,
                &models::NewTask {
                    start_at: Utc::now(),
                    state: models::TaskState::NEW,
                    username: "system",
                    payload: &to_value(command).unwrap(),
                },
            )
                .expect("insert");
            info!("ProcessAllRawData: task inserted");
        },
        None => {
            info!("starting server with options {:?}", opt);
            pjournal::server::start(conn,
                                    &opt.database_url,
                                    &opt.base_url,
                                    &opt.static_path,
                                    opt.port,
                                    &opt.template_path);
        }
    }
}