Compare commits

..

5 commits

13 changed files with 506 additions and 24 deletions

View file

@ -209,6 +209,33 @@
}, },
"query": "UPDATE librepages_users set email = $1\n WHERE name = $2" "query": "UPDATE librepages_users set email = $1\n WHERE name = $2"
}, },
"77612c85be99e6de2e4a6e3105ebaeb470d6cc57b2999b673a085da41c035f9e": {
"describe": {
"columns": [
{
"name": "time",
"ordinal": 0,
"type_info": "Timestamptz"
},
{
"name": "pub_id",
"ordinal": 1,
"type_info": "Uuid"
}
],
"nullable": [
false,
false
],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "SELECT\n time,\n pub_id\n FROM\n librepages_site_deploy_events\n WHERE\n site = (SELECT ID FROM librepages_sites WHERE hostname = $1)\n AND\n event_type = (SELECT ID FROM librepages_deploy_event_type WHERE name = $2)\n AND\n time = (\n SELECT MAX(time) \n FROM\n librepages_site_deploy_events\n WHERE\n site = (SELECT ID FROM librepages_sites WHERE hostname = $1)\n )\n "
},
"8735b654bc261571e6a5908d55a8217474c76bdff7f3cbcc71500a0fe13249db": { "8735b654bc261571e6a5908d55a8217474c76bdff7f3cbcc71500a0fe13249db": {
"describe": { "describe": {
"columns": [ "columns": [
@ -466,6 +493,51 @@
}, },
"query": "SELECT EXISTS (SELECT 1 from librepages_deploy_event_type WHERE name = $1)" "query": "SELECT EXISTS (SELECT 1 from librepages_deploy_event_type WHERE name = $1)"
}, },
"f4957eeddb139c82ef68cfc3ed2ddf52ff292fdf66cf0fddf0aa302723c26c53": {
"describe": {
"columns": [
{
"name": "repo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "branch",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "hostname",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "owned_by",
"ordinal": 3,
"type_info": "Int4"
},
{
"name": "site_secret",
"ordinal": 4,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false,
false,
false
],
"parameters": {
"Left": [
"Uuid",
"Text"
]
}
},
"query": "SELECT repo_url, branch, hostname, owned_by, site_secret\n FROM librepages_sites\n WHERE pub_id = $1\n AND\n owned_by = (SELECT ID from librepages_users WHERE name = $2)\n "
},
"f651da8f411b7977cb87dd8d4bd5d167661d7ef1d865747e76219453d386d593": { "f651da8f411b7977cb87dd8d4bd5d167661d7ef1d865747e76219453d386d593": {
"describe": { "describe": {
"columns": [], "columns": [],

121
src/db.rs
View file

@ -273,6 +273,42 @@ impl Database {
Ok(()) Ok(())
} }
pub async fn get_site_from_pub_id(&self, pub_id: Uuid, owner: String) -> ServiceResult<Site> {
struct S {
repo_url: String,
branch: String,
hostname: String,
owned_by: i32,
site_secret: String,
}
let site = sqlx::query_as!(
S,
"SELECT repo_url, branch, hostname, owned_by, site_secret
FROM librepages_sites
WHERE pub_id = $1
AND
owned_by = (SELECT ID from librepages_users WHERE name = $2)
",
&pub_id,
&owner,
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebsiteNotFound))?;
let site = Site {
site_secret: site.site_secret,
branch: site.branch,
hostname: site.hostname,
owner: owner,
repo_url: site.repo_url,
pub_id,
};
Ok(site)
}
pub async fn get_site_from_secret(&self, site_secret: &str) -> ServiceResult<Site> { pub async fn get_site_from_secret(&self, site_secret: &str) -> ServiceResult<Site> {
struct S { struct S {
repo_url: String, repo_url: String,
@ -484,6 +520,65 @@ impl Database {
}) })
} }
pub async fn get_latest_update_event(
&self,
hostname: &str,
) -> ServiceResult<Option<LibrePagesEvent>> {
self.get_latest_event_of_type(hostname, &EVENT_TYPE_UPDATE)
.await
}
async fn get_latest_event_of_type(
&self,
hostname: &str,
event_type: &Event,
) -> ServiceResult<Option<LibrePagesEvent>> {
struct InnerLibrepagesEventNameless {
time: OffsetDateTime,
pub_id: Uuid,
}
let event = sqlx::query_as!(
InnerLibrepagesEventNameless,
"SELECT
time,
pub_id
FROM
librepages_site_deploy_events
WHERE
site = (SELECT ID FROM librepages_sites WHERE hostname = $1)
AND
event_type = (SELECT ID FROM librepages_deploy_event_type WHERE name = $2)
AND
time = (
SELECT MAX(time)
FROM
librepages_site_deploy_events
WHERE
site = (SELECT ID FROM librepages_sites WHERE hostname = $1)
)
",
hostname,
event_type.name
)
.fetch_one(&self.pool)
.await;
match event {
Ok(event) => Ok(Some(LibrePagesEvent {
id: event.pub_id,
time: event.time,
event_type: event_type.clone(),
site: hostname.to_owned(),
})),
Err(sqlx::Error::RowNotFound) => Ok(None),
Err(e) => Err(map_register_err(e)),
}
// map_row_not_found_err(e, ServiceError::AccountNotFound))?;
}
pub async fn list_all_site_events( pub async fn list_all_site_events(
&self, &self,
hostname: &str, hostname: &str,
@ -896,6 +991,32 @@ mod tests {
vec![event] vec![event]
); );
// when no update event exist, None is returned
assert!(db
.get_latest_update_event(&site.hostname)
.await
.unwrap()
.is_none());
// add multiple update events, see if latest is returned
db.log_event(&site.hostname, &EVENT_TYPE_UPDATE)
.await
.unwrap();
let latest_update_event_id = db
.log_event(&site.hostname, &EVENT_TYPE_UPDATE)
.await
.unwrap();
let latest_update_event_id_from_db = db
.get_latest_update_event(&site.hostname)
.await
.unwrap()
.unwrap();
assert_eq!(
latest_update_event_id_from_db.event_type,
*EVENT_TYPE_UPDATE
);
assert_eq!(latest_update_event_id_from_db.id, latest_update_event_id);
// delete site // delete site
db.delete_site(p.username, &site.hostname).await.unwrap(); db.delete_site(p.username, &site.hostname).await.unwrap();

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 {
@ -72,9 +84,12 @@ async fn get_site_data(ctx: &AppCtx, id: &Identity) -> ServiceResult<Vec<Templat
let mut sites = Vec::with_capacity(db_sites.len()); let mut sites = Vec::with_capacity(db_sites.len());
for site in db_sites { for site in db_sites {
// TODO: impl method on DB to get latest "update" event // TODO: impl method on DB to get latest "update" event
let mut events = ctx.db.list_all_site_events(&site.hostname).await?; let last_update = ctx
let last_update = events.pop().map(|event| event.into()); .db
sites.push(TemplateSite { site, last_update }); .get_latest_update_event(&site.hostname)
.await?
.map(|e| e.into());
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

@ -35,6 +35,22 @@ pub mod routes {
lazy_static! { lazy_static! {
pub static ref ASSETS: Assets = Assets::new(); pub static ref ASSETS: Assets = Assets::new();
} }
#[derive(Serialize)]
pub struct Svg {
pub eye_off: &'static str,
pub eye: &'static str,
}
impl Svg {
/// create new instance of Routes
pub fn new() -> Svg {
Svg {
eye: &static_files::assets::CSS,
eye_off: &static_files::assets::CSS,
}
}
}
#[derive(Serialize)] #[derive(Serialize)]
/// Top-level routes data structure for V1 AP1 /// Top-level routes data structure for V1 AP1
@ -42,6 +58,7 @@ pub mod routes {
/// Authentication routes /// Authentication routes
pub css: &'static str, pub css: &'static str,
pub mobile_css: &'static str, pub mobile_css: &'static str,
pub svg: Svg,
} }
impl Assets { impl Assets {
@ -50,6 +67,7 @@ pub mod routes {
Assets { Assets {
css: &static_files::assets::CSS, css: &static_files::assets::CSS,
mobile_css: &static_files::assets::CSS, mobile_css: &static_files::assets::CSS,
svg: Svg::new(),
} }
} }
} }

View file

@ -29,6 +29,9 @@ pub mod assets {
lazy_static! { lazy_static! {
pub static ref CSS: &'static str = FILES.get("./static/cache/css/main.css").unwrap(); pub static ref CSS: &'static str = FILES.get("./static/cache/css/main.css").unwrap();
pub static ref EYE: &'static str = FILES.get("./static/cache/img/svg/eye.svg").unwrap();
pub static ref EYE_OFF: &'static str =
FILES.get("./static/cache/img/svg/eye-off.svg").unwrap();
pub static ref MOBILE_CSS: &'static str = pub static ref MOBILE_CSS: &'static str =
FILES.get("./static/cache/css/mobile.css").unwrap(); FILES.get("./static/cache/css/mobile.css").unwrap();
} }

1
static/cache/img/svg/eye-off.svg vendored Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" id="icon" class="feather feather-eye-off"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>

After

Width:  |  Height:  |  Size: 470 B

1
static/cache/img/svg/eye.svg vendored Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" id="icon" class="feather feather-eye"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>

After

Width:  |  Height:  |  Size: 326 B

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 %}