initial commit

This commit is contained in:
Sebastian Hugentobler 2017-02-10 13:41:41 +01:00
commit e279281330
52 changed files with 916 additions and 0 deletions

72
src/main.rs Normal file
View file

@ -0,0 +1,72 @@
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate glob;
extern crate rand;
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
mod static_files;
// mod tunes;
use glob::glob;
use rand::Rng;
use rocket_contrib::Template;
#[derive(Serialize)]
struct IndexContext {
title: String,
}
#[derive(Serialize)]
struct RandomContext {
title: String,
music_file: String,
music_title: String,
interval: u8,
}
#[get("/")]
fn index() -> Template {
let context = IndexContext { title: String::from("Lern die Märsch!") };
Template::render("index", &context)
}
#[get("/random")]
fn random() -> Template {
println!("looking for a random tune...");
// let (file_name, file_title) = tunes::random_tune();
let files = glob("static/sound/*.ogg")
.expect("Failed to read glob pattern")
.collect::<Vec<_>>();
let chosen_one = match *rand::thread_rng().choose(&files).unwrap() {
Ok(ref path) => path,
Err(_) => panic!(""),
};
let file_name = chosen_one.file_name().unwrap().to_str().unwrap();
let file_title = chosen_one.file_stem().unwrap().to_str().unwrap();
let context = RandomContext {
title: String::from(format!("{}", file_title)),
music_file: String::from(file_name),
music_title: String::from(file_title),
interval: 5,
};
Template::render("random", &context)
}
fn main() {
rocket::ignite()
.mount("/", routes![index, random])
.mount("/static", routes![static_files::all])
.launch();
}

8
src/static_files.rs Normal file
View file

@ -0,0 +1,8 @@
use rocket::response::NamedFile;
use std::io;
use std::path::{Path, PathBuf};
#[get("/<path..>")]
fn all(path: PathBuf) -> io::Result<NamedFile> {
NamedFile::open(Path::new("static/").join(path))
}

26
src/tunes.rs Normal file
View file

@ -0,0 +1,26 @@
extern crate rand;
use std::path::PathBuf;
use glob::glob;
use glob::GlobError;
use rand::Rng;
pub fn all() -> Vec<Result<PathBuf, GlobError>> {
glob("static/sound/*.opus")
.expect("Failed to read glob pattern")
.collect::<Vec<_>>()
}
pub fn random_tune<'a>() -> (&'a str, &'a str) {
let all_files = all();
let chosen_one = match *rand::thread_rng().choose(&all_files).unwrap() {
Ok(ref path) => path,
Err(_) => panic!(""),
};
let file_name = chosen_one.file_name().unwrap().to_str().unwrap();
let file_title = chosen_one.file_stem().unwrap().to_str().unwrap();
return (file_name, file_title);
}