~saiko/modsite

ref: 18244534210ceb0b200b3a4a6317999c72693baf modsite/site/src/site/main_page.rs -rw-r--r-- 4.3 KiB
182445342xsaiko Properly do inter page links 4 months ago
                                                                                
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
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use futures_util::TryStreamExt;
use handlebars::Handlebars;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgConnection, Pool};

use crate::db::types::Environment;
use crate::site::db_access::{Db, map_db_err};
use crate::site::geninfo::GenInfo;

use super::pagestates::{MainPage as PageState, self};
use url::Url;

pub async fn main_page(req: HttpRequest, page_state: web::Query<PageState<'_>>, hb: web::Data<Handlebars<'_>>, db: Db) -> Result<impl Responder, actix_web::Error> {
    let sorting = SortLinks::from(&page_state, &req);

    let body = hb.render("index", &Data {
        current_query: page_state.query.as_deref(),
        mods: ModData::get_all(&db, &req).await.map_err(map_db_err)?,
        geninfo: GenInfo::current(),
        sorting,
    }).unwrap();

    Ok(HttpResponse::Ok().body(body))
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum SortType {
    #[serde(rename = "name")]
    Name,
    #[serde(rename = "created")]
    Created,
    #[serde(rename = "updated")]
    Updated,
}

impl Default for SortType {
    fn default() -> Self { SortType::Updated }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum SortOrder {
    #[serde(rename = "asc")]
    Asc,
    #[serde(rename = "desc")]
    Desc,
}

impl SortOrder {
    fn next(self) -> SortOrder {
        match self {
            SortOrder::Asc => SortOrder::Desc,
            SortOrder::Desc => SortOrder::Asc,
        }
    }
}

impl Default for SortOrder {
    fn default() -> Self { SortOrder::Desc }
}

#[derive(Serialize)]
struct Data<'a> {
    current_query: Option<&'a str>,
    mods: Vec<ModData>,
    geninfo: GenInfo,
    sorting: SortLinks,
}

#[derive(Serialize)]
struct ModData {
    link: Url,
    display_name: String,
    from_db: FromDb,
}

#[derive(FromRow, Serialize)]
struct FromDb {
    id: String,
    modid: String,
    name: Option<String>,
    description: Option<String>,
    homepage: Option<String>,
    issues: Option<String>,
    source: Option<String>,
    license: Option<String>,
    download_link: String,
    environment: Environment,
}

impl ModData {
    async fn get_all(db: &Pool<PgConnection>, req: &HttpRequest) -> sqlx::Result<Vec<ModData>> {
        let from_db: Vec<FromDb> = sqlx::query_as_unchecked!(FromDb,
                "SELECT b.id, v.id as modid, v.name, v.description, v.homepage, v.issues, v.source, v.license, v.download_link, v.environment \
                 FROM mod_base b \
                 INNER JOIN mod_version v ON (v.file_version = b.display_version AND v.mod_base = b.uuid)")
            .fetch(db)
            .try_collect().await?;

        Ok(from_db.into_iter()
            .map(|data| ModData {
                link: pagestates::ModPage::from_id(&data.id).link(req),
                display_name: data.name.clone().unwrap_or_else(|| data.id.clone()),
                from_db: data,
            }).collect())
    }
}

#[derive(Serialize)]
struct SortLinks {
    name: SortLink,
    created: SortLink,
    updated: SortLink,
}

#[derive(Serialize)]
struct SortLink {
    link: Url,
    prefix: &'static str,
}

impl SortLink {
    fn from(typ: SortType, page_state: &PageState, req: &HttpRequest) -> SortLink {
        if page_state.sort() != typ {
            let mut new_state = page_state.clone();
            new_state.sort = Some(typ);
            new_state.order = Some(Default::default());
            SortLink {
                link: new_state.link(req),
                prefix: "",
            }
        } else {
            let mut new_state = page_state.clone();
            new_state.sort = Some(new_state.sort());
            new_state.order = Some(new_state.order().next());
            let prefix = match new_state.order() {
                SortOrder::Asc => "▴ ",
                SortOrder::Desc => "▾ ",
            };
            SortLink {
                link: new_state.link(req),
                prefix,
            }
        }
    }
}

impl SortLinks {
    fn from(page_state: &PageState, req: &HttpRequest) -> SortLinks {
        SortLinks {
            name: SortLink::from(SortType::Name, page_state, req),
            created: SortLink::from(SortType::Created, page_state, req),
            updated: SortLink::from(SortType::Updated, page_state, req),
        }
    }
}