feat: view site details, deploy secret and latest events

closes: #10
This commit is contained in:
Aravinth Manivannan 2022-12-05 15:48:16 +05:30
parent 5917e5e29f
commit 398f08c07a
Signed by: realaravinth
GPG key ID: AD9F0F08E855ED88
7 changed files with 285 additions and 22 deletions

View file

@ -40,8 +40,20 @@ pub struct Home {
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct TemplateSite { pub struct TemplateSite {
site: Site, pub site: Site,
last_update: Option<TemplateSiteEvent>, pub view: String,
pub last_update: Option<TemplateSiteEvent>,
}
impl TemplateSite {
pub fn new(site: Site, last_update: Option<TemplateSiteEvent>) -> Self {
let view = PAGES.dash.site.get_view(site.pub_id.clone());
Self {
site,
last_update,
view,
}
}
} }
impl CtxError for Home { impl CtxError for Home {
@ -77,7 +89,7 @@ async fn get_site_data(ctx: &AppCtx, id: &Identity) -> ServiceResult<Vec<Templat
.get_latest_update_event(&site.hostname) .get_latest_update_event(&site.hostname)
.await? .await?
.map(|e| e.into()); .map(|e| e.into());
sites.push(TemplateSite { site, last_update }); sites.push(TemplateSite::new(site, last_update));
} }
Ok(sites) Ok(sites)
} }

View file

@ -88,15 +88,16 @@ pub async fn post_add_site(
repo_url: payload.repo_url, repo_url: payload.repo_url,
owner, owner,
}; };
let _page = ctx let page = ctx
.add_site(msg) .add_site(msg)
.await .await
.map_err(|e| PageError::new(Add::new(&ctx.settings), e))?; .map_err(|e| PageError::new(Add::new(&ctx.settings), e))?;
// TODO: redirect to deployment view
Ok(HttpResponse::Found() Ok(HttpResponse::Found()
.append_header((http::header::LOCATION, PAGES.dash.home)) .append_header((
http::header::LOCATION,
PAGES.dash.site.get_view(page.pub_id),
))
.finish()) .finish())
} }
@ -131,7 +132,7 @@ mod tests {
let _ = ctx.delete_user(NAME, PASSWORD).await; let _ = ctx.delete_user(NAME, PASSWORD).await;
let (_, signin_resp) = ctx.register_and_signin(NAME, EMAIL, PASSWORD).await; let (_, signin_resp) = ctx.register_and_signin(NAME, EMAIL, PASSWORD).await;
let cookies = get_cookie!(signin_resp); let cookies = get_cookie!(signin_resp);
let app = get_app!(ctx).await; let app = get_app!(ctx.clone()).await;
let resp = get_request!(&app, PAGES.dash.site.add, cookies.clone()); let resp = get_request!(&app, PAGES.dash.site.add, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
@ -151,22 +152,32 @@ mod tests {
) )
.await; .await;
assert_eq!(add_site.status(), StatusCode::FOUND); assert_eq!(add_site.status(), StatusCode::FOUND);
let mut site = ctx.db.list_all_sites(NAME).await.unwrap();
let site = site.pop().unwrap();
let mut event = ctx.db.list_all_site_events(&site.hostname).await.unwrap();
let event = event.pop().unwrap();
let headers = add_site.headers(); let headers = add_site.headers();
let view_site = &PAGES.dash.site.get_view(site.pub_id.clone());
assert_eq!( assert_eq!(
headers.get(actix_web::http::header::LOCATION).unwrap(), headers.get(actix_web::http::header::LOCATION).unwrap(),
&PAGES.dash.home view_site
); );
// let page = ctx.add_test_site(NAME.into()).await; // view site
// let resp = get_request!(&app, view_site, cookies.clone());
// let resp = get_request!(&app, PAGES.dash.home, cookies.clone()); assert_eq!(resp.status(), StatusCode::OK);
// assert_eq!(resp.status(), StatusCode::OK); let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
// let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap(); assert!(res.contains(&site.site_secret));
// println!("after adding site: {res}"); assert!(res.contains(&site.hostname));
// assert!(!res.contains("Nothing here")); assert!(res.contains(&site.repo_url));
// assert!(res.contains(&page.domain)); assert!(res.contains(&site.branch));
// assert!(res.contains(&page.repo));
// assert!(res.contains(&event.event_type.name));
assert!(res.contains(&event.id.to_string()));
let _ = ctx.delete_user(NAME, PASSWORD).await; let _ = ctx.delete_user(NAME, PASSWORD).await;
} }
} }

View file

@ -17,16 +17,22 @@
use actix_web::*; use actix_web::*;
use super::get_auth_middleware; use super::get_auth_middleware;
pub use super::home::TemplateSite;
pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES}; pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
pub mod add; pub mod add;
pub mod view;
pub fn register_templates(t: &mut tera::Tera) { pub fn register_templates(t: &mut tera::Tera) {
add::DASH_SITE_ADD add::DASH_SITE_ADD
.register(t) .register(t)
.expect(add::DASH_SITE_ADD.name); .expect(add::DASH_SITE_ADD.name);
view::DASH_SITE_VIEW
.register(t)
.expect(view::DASH_SITE_VIEW.name);
} }
pub fn services(cfg: &mut web::ServiceConfig) { pub fn services(cfg: &mut web::ServiceConfig) {
add::services(cfg); add::services(cfg);
view::services(cfg);
} }

View file

@ -0,0 +1,152 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_identity::Identity;
use actix_web::http::header::ContentType;
use serde::{Deserialize, Serialize};
use tera::Context;
use uuid::Uuid;
use super::get_auth_middleware;
use crate::db::Site;
use crate::pages::dash::TemplateSiteEvent;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub const DASH_SITE_VIEW: TemplateFile =
TemplateFile::new("dash_site_view", "pages/dash/sites/view.html");
const SHOW_DEPLOY_SECRET_KEY: &str = "show_deploy_secret";
pub struct View {
ctx: RefCell<Context>,
}
impl CtxError for View {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl View {
pub fn new(settings: &Settings, payload: Option<TemplateSiteWithEvents>) -> Self {
let ctx = RefCell::new(context(settings));
if let Some(payload) = payload {
ctx.borrow_mut().insert(PAYLOAD_KEY, &payload);
}
Self { ctx }
}
pub fn show_deploy_secret(&mut self) {
self.ctx.borrow_mut().insert(SHOW_DEPLOY_SECRET_KEY, &true);
}
pub fn render(&self) -> String {
TEMPLATES
.render(DASH_SITE_VIEW.name, &self.ctx.borrow())
.unwrap()
}
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct TemplateSiteWithEvents {
pub site: Site,
pub view: String,
pub last_update: Option<TemplateSiteEvent>,
pub events: Vec<TemplateSiteEvent>,
}
impl TemplateSiteWithEvents {
pub fn new(
site: Site,
last_update: Option<TemplateSiteEvent>,
events: Vec<TemplateSiteEvent>,
) -> Self {
let view = PAGES.dash.site.get_view(site.pub_id.clone());
Self {
site,
last_update,
view,
events,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct ViewOptions {
show_deploy_secret: Option<bool>
}
#[actix_web_codegen_const_routes::get(
path = "PAGES.dash.site.view",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Dashboard add site webpage", skip(ctx, id))]
pub async fn get_view_site(
ctx: AppCtx,
id: Identity,
path: web::Path<Uuid>,
query: web::Query<ViewOptions>
) -> PageResult<impl Responder, View> {
let site_id = path.into_inner();
let owner = id.identity().unwrap();
let site = ctx
.db
.get_site_from_pub_id(site_id, owner)
.await
.map_err(|e| PageError::new(View::new(&ctx.settings, None), e))?;
let last_update = ctx
.db
.get_latest_update_event(&site.hostname)
.await
.map_err(|e| PageError::new(View::new(&ctx.settings, None), e))?;
let last_update = last_update.map(|e| e.into());
let mut db_events = ctx
.db
.list_all_site_events(&site.hostname)
.await
.map_err(|e| PageError::new(View::new(&ctx.settings, None), e))?;
let mut events = Vec::with_capacity(db_events.len());
for e in db_events.drain(0..) {
events.push(e.into());
}
let payload = TemplateSiteWithEvents::new(site, last_update, events);
let mut page = View::new(&ctx.settings, Some(payload));
if let Some(true) = query.show_deploy_secret {
page.show_deploy_secret();
}
let add = page.render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(add))
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(get_view_site);
}

View file

@ -16,6 +16,7 @@
*/ */
use actix_auth_middleware::{Authentication, GetLoginRoute}; use actix_auth_middleware::{Authentication, GetLoginRoute};
use serde::*; use serde::*;
use uuid::Uuid;
/// constant [Pages](Pages) instance /// constant [Pages](Pages) instance
pub const PAGES: Pages = Pages::new(); pub const PAGES: Pages = Pages::new();
@ -85,15 +86,25 @@ impl Dash {
#[derive(Serialize)] #[derive(Serialize)]
/// Dashboard Site routes /// Dashboard Site routes
pub struct DashSite { pub struct DashSite {
/// home route /// add site route
pub add: &'static str, pub add: &'static str,
/// view site route
pub view: &'static str,
} }
impl DashSite { impl DashSite {
/// create new instance of DashSite route /// create new instance of DashSite route
pub const fn new() -> DashSite { pub const fn new() -> DashSite {
let add = "/dash/site/add"; let add = "/dash/site/add";
DashSite { add } let view = "/dash/site/view/{deployment_pub_id}";
DashSite { add, view }
}
pub fn get_view(&self, deployment_pub_id: Uuid) -> String {
self.view.replace(
"{deployment_pub_id}",
deployment_pub_id.to_string().as_ref(),
)
} }
} }

View file

@ -10,7 +10,7 @@
</div> </div>
{% if payload|length > 0 %} {% if payload|length > 0 %}
{% for deployment in payload %} {% for deployment in payload %}
<a href="/sites/view/{{ deployment.site.hostname }}" class="site__container"> <a href="{{ deployment.view }}" class="site__container">
<div class="site__info--head"> <div class="site__info--head">
<img <img
class="site__container--preview" class="site__container--preview"

View file

@ -0,0 +1,71 @@
{% extends 'base' %}{% block title %} Add Site{% endblock title %} {% block nav
%} {% include "auth_nav" %} {% endblock nav %} {% block main %}
<main class="sites__main">
<div class="add-site__container">
<section>
<table>
<tr>
<th>Hostname</th>
<td>{{ payload.site.hostname }}</td>
</tr>
<tr>
<th>Repository</th>
<td>{{ payload.site.repo_url }}</td>
</tr>
<tr>
<th>Secret</th>
<td>
{% if show_deploy_secret %}
{{ payload.site.site_secret }} <a href="{{ payload.view }}">Hide</a>
{% else %}
****
<a href="{{ payload.view }}?show_deploy_secret=true">
Show
</a>
{% endif %}
</td>
</tr>
<tr>
<th>Branch</th>
<td>{{ payload.site.branch }}</td>
</tr>
<tr>
<th>Last Updated</th>
{% if payload.last_updated %}
<td>{{ payload.last_updated.time }}</td>
{% else %}
<td>N/A</td>
{% endif %}
</tr>
</table>
</section>
<section>
<h2>Events</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Event Type</th>
<th>Time</th>
</tr>
</thead>
<tbody>
{% for event in payload.events %}
<tr>
<td>{{ event.id }}</td>
<td>{{ event.event_type.name }}</td>
<td>{{ event.time }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
</div>
</main>
{% endblock main %}