Initial commit

This commit is contained in:
Dmitry Belyaev 2019-08-02 13:47:16 +03:00
commit a7b1233a0c
Signed by: b4tman
GPG Key ID: 41A00BF15EA7E5F3
10 changed files with 2768 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target
**/*.rs.bk
/db

2396
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

24
Cargo.toml Normal file
View File

@ -0,0 +1,24 @@
[package]
name = "qchgk_web"
version = "0.1.0"
authors = ["Dmitry <b4tm4n@mail.ru>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-files="0.1"
actix-web = "1.0"
serde="1.0"
serde_derive="1.0"
serde_json="1.0"
ledb="0.2"
ledb-derive="0.2"
ledb-types="0.2"
lmdb-zero="0.4"
rand="0.7"
env_logger = "0.6"
tera = "0.11"
# actix="0.7"
# tokio="0.1"
# futures="0.1"

235
src/main.rs Normal file
View File

@ -0,0 +1,235 @@
// extern crate actix;
extern crate actix_files;
extern crate actix_web;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate ledb;
#[macro_use]
extern crate ledb_derive;
extern crate env_logger;
extern crate ledb_types;
#[macro_use]
extern crate tera;
use tera::Context;
// extern crate futures;
// extern crate tokio;
use actix_web::{
error, guard, http::header, http::Method, middleware::Logger, middleware::NormalizePath, web,
App, Error, HttpRequest, HttpResponse, HttpServer, Responder, Result,
};
use std::cell::Cell;
use rand::seq::IteratorRandom;
use std::time::Instant;
use std::{fs, io};
// use tokio::spawn;
// use futures::{Future};
// use actix::Actor;
// use actix::System;
//use crate::tokio::prelude::Future;
//use ledb_actix::{Document, Options, Storage, StorageAddrExt};
use ledb::{Options, Storage};
#[derive(Debug, Default, Clone, Serialize, Deserialize, Document)]
struct BatchInfo {
#[document(primary)]
#[serde(default)]
filename: String,
#[serde(default)]
description: String,
#[serde(default)]
author: String,
#[serde(default)]
comment: String,
#[serde(default)]
url: String,
#[serde(default)]
date: String,
#[serde(default)]
processed_by: String,
#[serde(default)]
redacted_by: String,
#[serde(default)]
copyright: String,
#[serde(default)]
theme: String,
#[serde(default)]
kind: String,
#[serde(default)]
source: String,
#[serde(default)]
rating: String,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize, Document)]
struct Question {
#[document(primary)]
#[serde(default)]
num: u32,
#[document(index)]
id: String,
description: String,
answer: String,
#[serde(default)]
author: String,
#[serde(default)]
comment: String,
#[serde(default)]
comment1: String,
#[serde(default)]
tour: String,
#[serde(default)]
url: String,
#[serde(default)]
date: String,
#[serde(default)]
processed_by: String,
#[serde(default)]
redacted_by: String,
#[serde(default)]
copyright: String,
#[serde(default)]
theme: String,
#[serde(default)]
kind: String,
#[serde(default)]
source: String,
#[serde(default)]
rating: String,
#[document(nested)]
#[serde(default)]
batch_info: BatchInfo,
}
struct AppState {
storage: Storage,
template: tera::Tera,
}
fn get_question(storage: &Storage, id: u32) -> Result<Option<Question>, Error> {
if 0 == id {
return Ok(None);
}
let collection = storage.collection("questions").unwrap();
let last_id = collection.last_id().unwrap();
if id > last_id {
Err(Error::from(()))
} else {
let question = collection.get::<Question>(id);
if question.is_err() {
Err(Error::from(()))
} else {
Ok(question.unwrap())
}
}
}
fn show_question_details(template_file: &str, data: web::Data<AppState>, id: web::Path<u32>) -> Result<HttpResponse, Error> {
let id = id.into_inner();
let question = get_question(&data.storage, id);
if question.is_ok() {
let question = question.unwrap();
if question.is_some() {
let question = question.unwrap();
let body = data.template.render(template_file, &question).unwrap();
Ok(HttpResponse::Ok().content_type("text/html").body(body))
} else {
Ok(HttpResponse::Found()
.header(header::LOCATION, "/q/")
.finish())
}
} else {
let context = Context::new();
Ok(HttpResponse::with_body(
actix_web::http::StatusCode::NOT_FOUND,
actix_web::dev::Body::from(data.template.render("404.html", &context).unwrap()),
))
}
}
fn show_question(data: web::Data<AppState>, id: web::Path<u32>) -> Result<HttpResponse, Error> {
show_question_details("question.html", data, id)
}
fn show_answer(data: web::Data<AppState>, id: web::Path<u32>) -> Result<HttpResponse, Error> {
show_question_details("answer.html", data, id)
}
fn index(data: web::Data<AppState>, req: HttpRequest) -> Result<HttpResponse, Error> {
let collection = data.storage.collection("questions").unwrap();
let mut rng = rand::thread_rng();
let last_id = collection.last_id().unwrap();
let id = (1..(last_id + 1)).choose(&mut rng).unwrap();
let url = req.url_for("question", &[format!("{}", id)])?;
Ok(HttpResponse::Found()
.header(header::LOCATION, url.as_str())
.finish())
}
fn main() {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let options: Options = serde_json::from_value(json!({
"read_only": true,
"no_lock": true,
}))
.unwrap();
let storage = Storage::new("db", options).unwrap();
HttpServer::new(move || {
let data = AppState {
storage: storage.clone(),
template: compile_templates!("./templates/**/*"),
};
App::new()
.wrap(Logger::default())
.data(data)
.route("/q", web::to(index))
.service(
web::scope("/q")
.service(actix_files::Files::new("/static", "./static"))
.service(
web::resource("/{id}")
.name("question") // <- set resource name, then it could be used in `url_for`
.guard(guard::Get())
.to(show_question),
)
.service(
web::resource("/{id}/a/")
.name("answer") // <- set resource name, then it could be used in `url_for`
.guard(guard::Get())
.to(show_answer),
)
.route("/", web::to(index))
)
.route("/", web::to(index))
})
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}

11
static/style.css Normal file
View File

@ -0,0 +1,11 @@
body {
background-color: rgb(235, 213, 205);
}
.content-block {
display: flex;
}
.content-block-inner {
margin: auto;
}

5
templates/404.html Normal file
View File

@ -0,0 +1,5 @@
{% extends "base.html" %}
{% block title %}404{% endblock title %}
{% block content %}
<h1>404 - Could not find that page</h1>
{% endblock content %}

60
templates/answer.html Normal file
View File

@ -0,0 +1,60 @@
{% extends "base.html" %} {% block title %} Ответ {% endblock title %}
{% block content %}
<!-- <h1>{{ id }}</h1> -->
<div class="content-block">
<div id="question" class="content-block-inner">
<p><font color="#544669">
<h4> {{ description }} </h4>
</font>
</p>
</div>
</div><br />
<div class="content-block">
<div id="answer" class="content-block-inner">
<hr/>
<p>
<!-- <h2> Ответ: </h2> -->
<h1>{{ answer }}</h1>
</p>
<hr/><br><br/><details>
<div id="details">
{% if comment | length or comment1 | length %}
<p><span>Комментарии:</span>
{% if comment | length %}
{{ comment }}
{% endif %}
{% if comment1 | length %}
<br/>
{{ comment1 }}
{% endif %}
</p>
{% endif %}
{% if author | length %}
<p><span>Автор: </span> {{ author }}</p>
{% endif %}
{% if copyright | length %}
<p><span>Копирайт: </span> {{ copyright }}</p>
{% endif %}
{% if source | length %}
<p><span>Источник: </span> {{ source }}</p>
{% endif %}
{% if theme | length %}
<p><span>Тема: </span> {{ theme }}</p>
{% endif %}
{% if rating | length %}
<p><span>Рейтинг: </span> {{ author }}</p>
{% endif %}
{% if batch_info.description | length %}
<p><span>Чемпионат: </span> {{ batch_info.description }}</p>
{% endif %}
{% if tour | length %}
<p><span>Тур: </span> {{ tour }}</p>
{% endif %}
{% if id | length %}
<p><span>Номер: </span> {{ id }}</p>
{% endif %}
</div></details>
</div>
<br />
{% endblock content %}

13
templates/base.html Normal file
View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="/q/static/style.css" />
<title>{% block title %}{% endblock title %}</title>
</head>
<body>
{% include "nav.html" %}
<div id="content" class="container">{% block content %}{% endblock content %}</div>
</body>
</html>

3
templates/nav.html Normal file
View File

@ -0,0 +1,3 @@
<nav class="nav nav-pills container justify-content-center">
<a class="nav-link" href="/q/">Ещё</a>
</nav>

17
templates/question.html Normal file
View File

@ -0,0 +1,17 @@
{% extends "base.html" %} {% block title %} Вопрос {% endblock title %}
{% block content %}
<!-- <h1>{{ id }}</h1> -->
<div class="content-block"><div id="question" class="content-block-inner">
<p>
<h3> {{ description }} </h3>
</p>
</div></div>
<br/>
<br/>
<br/><details>
<nav class="nav nav-pills container justify-content-center">
<a class="nav-link" href="/q/{{ num }}/a/">Ответ</a>
</nav></details>
{% endblock content %}