Browse Source

serve: split main into index

master
Astro 10 months ago
parent
commit
9a1a106e0e
2 changed files with 119 additions and 115 deletions
  1. 113
    0
      ticker-serve/src/index.rs
  2. 6
    115
      ticker-serve/src/main.rs

+ 113
- 0
ticker-serve/src/index.rs View File

@@ -0,0 +1,113 @@
1
+use gotham::{
2
+    helpers::http::response::create_response,
3
+    hyper::{Body, Response},
4
+    state::{FromState, State},
5
+};
6
+use http::status::StatusCode;
7
+use mime::TEXT_HTML;
8
+
9
+use typed_html::{html, text, dom::DOMTree};
10
+use diesel::prelude::*;
11
+use chrono::{offset::Local, NaiveDate};
12
+
13
+use libticker::{
14
+    schema::{self, events::dsl::events},
15
+    model::Event,
16
+};
17
+use crate::AppState;
18
+
19
+
20
+fn fix_url(s: &str) -> std::borrow::Cow<str> {
21
+    if s.starts_with("http:") || s.starts_with("https:") {
22
+        s.into()
23
+    } else {
24
+        format!("http://{}", s).into()
25
+    }
26
+}
27
+
28
+struct DayEvents<'e> {
29
+    date: NaiveDate,
30
+    events: &'e [Event],
31
+}
32
+
33
+/// assumes pre-sorted input
34
+fn group_by_day(es: &[Event]) -> Vec<DayEvents> {
35
+    let mut results = vec![];
36
+
37
+    let mut prev_date = None;
38
+    let mut date_start = 0;
39
+    for (i, event) in es.iter().enumerate() {
40
+        if prev_date.is_some() && prev_date != Some(event.dtstart.date()) {
41
+            if i > date_start {
42
+                results.push(DayEvents {
43
+                    date: prev_date.unwrap().clone(),
44
+                    events: &es[date_start..i],
45
+                });
46
+                date_start = i;
47
+            }
48
+        }
49
+        prev_date = Some(event.dtstart.date());
50
+    }
51
+
52
+    results
53
+}
54
+
55
+fn render_index(app_state: &AppState) -> String {
56
+    let db = app_state.db.lock().unwrap();
57
+    let today = Local::today().naive_local().and_hms(0, 0, 0);
58
+    let es = events
59
+        .filter(schema::events::dtstart.ge(&today))
60
+        .order_by(schema::events::dtstart.asc())
61
+        .then_order_by(schema::events::dtend.desc())
62
+        .load::<Event>(&*db)
63
+        .unwrap();
64
+    let days = group_by_day(&es);
65
+
66
+    let doc: DOMTree<String> = html!(
67
+      <html>
68
+        <head>
69
+          <title>"Ticker"</title>
70
+          <meta charset="utf-8" />
71
+        </head>
72
+        <body>
73
+          { days.iter().map(|day| html!(<div>
74
+            <nav><h2>{ text!("{}", &day.date) }</h2></nav>
75
+
76
+            { day.events.iter().map(|e| html!(
77
+                <article class="event">
78
+                  { match &e.url {
79
+                      None => html!(
80
+                        <h3>{ text!("{}", &e.summary) }</h3>
81
+                      ),
82
+                      Some(url) => html!(
83
+                        <h3>
84
+                          <a href={ fix_url(url) }>
85
+                            { text!("{}", &e.summary) }
86
+                          </a>
87
+                        </h3>
88
+                      ),
89
+                  } }
90
+
91
+                <p class="dtstart">{ text!("{}", &e.dtstart) }</p>
92
+                { e.location.as_ref().map(|location| html!(
93
+                  <p>
94
+                    { text!("{}", location) }
95
+                    </p>
96
+                )) }
97
+              </article>
98
+            )) }
99
+          </div>)) }
100
+        </body>
101
+      </html>
102
+    );
103
+    format!("<DOCTYPE html>\n{}", doc.to_string())
104
+}
105
+
106
+pub fn index(state: State) -> (State, Response<Body>) {
107
+    let message = {
108
+        let app_state = AppState::borrow_from(&state);
109
+        render_index(app_state)
110
+    };
111
+    let res = create_response(&state, StatusCode::OK, TEXT_HTML, message);
112
+    (state, res)
113
+}

+ 6
- 115
ticker-serve/src/main.rs View File

@@ -6,129 +6,20 @@ extern crate gotham_derive;
6 6
 use std::sync::{Arc, Mutex};
7 7
 use gotham::{
8 8
     handler::assets::FileOptions,
9
-    helpers::http::response::create_response,
10
-    hyper::{Body, Response},
11 9
     router::builder::{DefineSingleRoute, DrawRoutes},
12 10
     middleware::state::StateMiddleware,
13 11
     pipeline::single::single_pipeline,
14 12
     pipeline::single_middleware,
15 13
     router::builder::*,
16
-    state::{FromState, State},
17 14
 };
18
-use http::status::StatusCode;
19
-use mime::TEXT_HTML;
15
+use diesel::{Connection, pg::PgConnection};
20 16
 
21
-use typed_html::{html, text, dom::DOMTree};
22
-use diesel::{Connection, pg::PgConnection, prelude::*};
23
-use chrono::{offset::Local, NaiveDate};
24
-
25
-use libticker::{
26
-    config::{Config, CalendarOptions},
27
-    schema::{self, events::dsl::events},
28
-    model::{Calendar, Event},
29
-    ics::{Object, Timestamp, GetValue},
30
-};
31
-
32
-fn fix_url(s: &str) -> std::borrow::Cow<str> {
33
-    if s.starts_with("http:") || s.starts_with("https:") {
34
-        s.into()
35
-    } else {
36
-        format!("http://{}", s).into()
37
-    }
38
-}
39
-
40
-struct DayEvents<'e> {
41
-    date: NaiveDate,
42
-    events: &'e [Event],
43
-}
44
-
45
-/// assumes pre-sorted input
46
-fn group_by_day(es: &[Event]) -> Vec<DayEvents> {
47
-    let mut results = vec![];
48
-
49
-    let mut prev_date = None;
50
-    let mut date_start = 0;
51
-    for (i, event) in es.iter().enumerate() {
52
-        if prev_date.is_some() && prev_date != Some(event.dtstart.date()) {
53
-            if i > date_start {
54
-                results.push(DayEvents {
55
-                    date: prev_date.unwrap().clone(),
56
-                    events: &es[date_start..i],
57
-                });
58
-                date_start = i;
59
-            }
60
-        }
61
-        prev_date = Some(event.dtstart.date());
62
-    }
63
-
64
-    results
65
-}
17
+use libticker::config::Config;
18
+mod index;
66 19
 
67 20
 #[derive(Clone, StateData)]
68
-struct AppState {
69
-    db: Arc<Mutex<PgConnection>>,
70
-}
71
-
72
-fn render_index(app_state: &AppState) -> String {
73
-    let db = app_state.db.lock().unwrap();
74
-    let today = Local::today().naive_local().and_hms(0, 0, 0);
75
-    let es = events
76
-        .filter(schema::events::dtstart.ge(&today))
77
-        .order_by(schema::events::dtstart.asc())
78
-        .then_order_by(schema::events::dtend.desc())
79
-        .load::<Event>(&*db)
80
-        .unwrap();
81
-    let days = group_by_day(&es);
82
-
83
-    let doc: DOMTree<String> = html!(
84
-      <html>
85
-        <head>
86
-          <title>"Ticker"</title>
87
-          <meta charset="utf-8" />
88
-        </head>
89
-        <body>
90
-          <h1>"Ticker"</h1>
91
-
92
-          { days.iter().map(|day| html!(<div>
93
-            <nav><h2>{ text!("{}", &day.date) }</h2></nav>
94
-
95
-            { day.events.iter().map(|e| html!(
96
-                <article class="event">
97
-                  { match &e.url {
98
-                      None => html!(
99
-                        <h3>{ text!("{}", &e.summary) }</h3>
100
-                      ),
101
-                      Some(url) => html!(
102
-                        <h3>
103
-                          <a href={ fix_url(url) }>
104
-                            { text!("{}", &e.summary) }
105
-                          </a>
106
-                        </h3>
107
-                      ),
108
-                  } }
109
-
110
-                <p class="dtstart">{ text!("{}", &e.dtstart) }</p>
111
-                { e.location.as_ref().map(|location| html!(
112
-                  <p>
113
-                    { text!("{}", location) }
114
-                    </p>
115
-                )) }
116
-              </article>
117
-            )) }
118
-          </div>)) }
119
-        </body>
120
-      </html>
121
-    );
122
-    format!("<DOCTYPE html>\n{}", doc.to_string())
123
-}
124
-
125
-fn index(state: State) -> (State, Response<Body>) {
126
-    let message = {
127
-        let app_state = AppState::borrow_from(&state);
128
-        render_index(app_state)
129
-    };
130
-    let res = create_response(&state, StatusCode::OK, TEXT_HTML, message);
131
-    (state, res)
21
+pub struct AppState {
22
+    pub db: Arc<Mutex<PgConnection>>,
132 23
 }
133 24
 
134 25
 fn main() {
@@ -145,7 +36,7 @@ fn main() {
145 36
         )
146 37
     );
147 38
     let router = build_router(chain, pipelines, |route| {
148
-        route.get("/").to(index);
39
+        route.get("/").to(index::index);
149 40
         route.get("static/*").to_dir(
150 41
             FileOptions::new(&"static")
151 42
                 // TODO:

Loading…
Cancel
Save