main.rs 5.4 KB
Newer Older
Robert Czechowski's avatar
Robert Czechowski committed
1
2
3
4
5
6
7
#[macro_use]
extern crate iron;
#[macro_use]
extern crate router;
#[macro_use]
extern crate serde_derive;

8
9
10
#[macro_use]
extern crate structopt;

11
extern crate rusqlite;
Robert Czechowski's avatar
Robert Czechowski committed
12
13
14
15
16
17
18
19
20
extern crate iron_sessionstorage;
extern crate urlencoded;
extern crate time;
extern crate persistent;
extern crate rand;
extern crate mount;
extern crate staticfile;
extern crate handlebars_iron;
extern crate serde_json;
21
22
23
extern crate params;
extern crate reqwest;
extern crate serde_yaml;
24
25
26
27
28
29
30
31
32
33
34
35

use rusqlite::Connection;

mod db_apply_migrations;
mod db_conn_sqlite;
mod db_conn;
mod db_objects;

use db_conn::{MedalConnection, MedalObject};

use db_objects::*;

Robert Czechowski's avatar
Robert Czechowski committed
36
mod webfw_iron;
37
mod configreader_yaml;
Robert Czechowski's avatar
Robert Czechowski committed
38
39
40
41
42
43
44
45

use webfw_iron::start_server;

mod functions;

use std::path;
use std::fs;

46
47
48
use std::path::{Path,PathBuf};
use structopt::StructOpt;

49
#[derive(Serialize, Deserialize, Clone)]
50
pub struct Config {
51
52
53
54
    host: Option<String>,
    port: Option<u16>,
    self_url: Option<String>,
    oauth_url: Option<String>,
55
56
57
58
    oauth_client_id: Option<String>,
    oauth_client_secret: Option<String>,
    oauth_access_token_url: Option<String>,
    oauth_user_data_url: Option<String>,
59
    database_file: Option<PathBuf>,
60
61
}

62
fn read_config_from_file(file: &Path) -> Config {
63
    use std::io::Read;
64
65

    println!("Reading Config file '{}'", file.to_str().unwrap_or("<Encoding error>"));
66
    
67
    let mut config = if let Ok(mut file) = fs::File::open(file) {
68
69
70
71
        let mut contents = String::new();
        file.read_to_string(&mut contents).unwrap();
        serde_json::from_str(&contents).unwrap()
    } else {
72
        println!("Configuration file '{}' not found.", file.to_str().unwrap_or("<Encoding error>"));
73
        Config {
74
75
76
77
            host: None,
            port: None,
            self_url: None,
            oauth_url: None,
78
79
80
81
            oauth_client_id: None,
            oauth_client_secret: None,
            oauth_access_token_url: None,
            oauth_user_data_url: None,
82
            database_file: None,
83
        }
84
85
86
87
    };

    if config.host.is_none() {config.host = Some("[::]".to_string())}
    if config.port.is_none() {config.port = Some(8080)}
88
    if config.self_url.is_none() {config.self_url = Some("http://localhost:8080".to_string())}
89

90
91
    println!("I will ask OAuth-providers to redirect to {}", config.self_url.as_ref().unwrap());
    
92
    config
93
}
94

95
96
97
98
99
100
101
102
103
104
#[derive(StructOpt, Debug)]
#[structopt()]
struct Opt {
    /// Config file to use (default: 'config.json')
    #[structopt(short = "c", long = "config", default_value = "config.json", parse(from_os_str))]
    configfile: PathBuf,

    /// Database file to use (default: from config file or 'medal.db')
    #[structopt(short = "d", long = "database", parse(from_os_str))]
    databasefile: Option<PathBuf>,
105
106
107
108

    /// Port to listen on (default: from config file or 8080)
    #[structopt(short = "p", long = "port")]
    port: Option<u16>,
109
110
111
112
}



Robert Czechowski's avatar
Robert Czechowski committed
113
fn read_contest(p: &path::PathBuf) -> Option<Contest> {
114
115
    use std::fs::File;
    use std::io::Read;
Robert Czechowski's avatar
Robert Czechowski committed
116
    println!("Try to read some file …");
117

118
119
120
121
    let mut file = File::open(p).unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
    
Robert Czechowski's avatar
Robert Czechowski committed
122
    configreader_yaml::parse_yaml(&contents, p.file_name().to_owned()?.to_str()?, &format!("{}/", p.parent().unwrap().to_str()?)) 
Robert Czechowski's avatar
Robert Czechowski committed
123
124
125
126
127
128
129
130
131
132
133
134
}

fn get_all_contest_info(task_dir: &str) -> Vec<Contest> {
    fn walk_me_recursively(p: &path::PathBuf, contests: &mut Vec<Contest>) {
        match fs::read_dir(p) {
            Ok(paths) => for path in paths {
                let p = path.unwrap().path();
                walk_me_recursively(&p, contests);
            },
            _ => (),
        }
        
135
        if p.file_name().unwrap().to_string_lossy().to_string().ends_with(".yaml") {
Robert Czechowski's avatar
Robert Czechowski committed
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
            match read_contest(p) {
                Some(contest) => contests.push(contest),
                _ => (),
            }
        };                   
    };

    
    let mut contests = Vec::new();
    match fs::read_dir(task_dir) {
        Err(why) => println!("Error opening tasks directory! {:?}", why.kind()),
        Ok(paths) => for path in paths {
            walk_me_recursively(&path.unwrap().path(), &mut contests);
        },
    };

    contests
}

fn refresh_all_contests(conn : &mut Connection) {
    let v = get_all_contest_info("tasks/");

    for mut contest_info in v {
        contest_info.save(conn);
    }
}

fn main() {
164
165
166
167
168
169
    let opt = Opt::from_args();
    println!("{:?}", opt);
    
    let mut config = read_config_from_file(&opt.configfile);

    if opt.databasefile.is_some() { config.database_file = opt.databasefile; }
170
    if opt.port.is_some() { config.port = opt.port; }
171
    
172
    let mut conn = match config.database_file {
173
        Some(ref path) => {println!("Using database file {}", &path.to_str().unwrap_or("<unprintable filename>"));  Connection::create(path)},
174
        None => {println!("Using default database file ./medal.db"); Connection::create(&Path::new("medal.db"))},
175
176
    };
        
Robert Czechowski's avatar
Robert Czechowski committed
177
178
179
    db_apply_migrations::test(&mut conn);

    refresh_all_contests(&mut conn);
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        
    println!("Hello, world!");

    let contest = conn.get_contest_by_id_complete(1);

    println!("Contest {}", contest.name);
    
    for taskgroup in contest.taskgroups {
        print!("  Task {}: ", taskgroup.name);
        for task in taskgroup.tasks {
            print!("{} ({}) ", task.stars, task.location);
        }
        println!("");
    }
194
    
195
    start_server(conn, config);
Robert Czechowski's avatar
Robert Czechowski committed
196

197
    println!("Could not run server. Is the port already in use?");
198
}