Merge pull request 'feat: Publish links to exports page and list puiblicly list all campaigns' (#16) from publish-results into master
ci/woodpecker/push/woodpecker Pipeline failed Details

Reviewed-on: #16
This commit is contained in:
Aravinth Manivannan 2023-03-14 20:20:40 +05:30
commit 6620cc6857
10 changed files with 272 additions and 6 deletions

View File

@ -143,6 +143,32 @@ pub mod runners {
Ok(uuid)
}
pub async fn list_all_campaigns(
data: &AppData,
) -> ServiceResult<Vec<ListCampaignResp>> {
struct ListCampaign {
name: String,
id: Uuid,
}
let mut campaigns = sqlx::query_as!(
ListCampaign,
"SELECT name, id FROM survey_campaigns ORDER BY id;"
)
.fetch_all(&data.db)
.await?;
let mut list_resp = Vec::with_capacity(campaigns.len());
campaigns.drain(0..).for_each(|c| {
list_resp.push(ListCampaignResp {
name: c.name,
uuid: c.id.to_string(),
});
});
Ok(list_resp)
}
pub async fn list_campaign_runner(
username: &str,
data: &AppData,

View File

@ -58,6 +58,8 @@ lazy_static! {
FILES.get("./static/cache/bundle/glue.js").unwrap();
}
pub const DOWNLOAD_SCOPE: &str = "/download";
pub const CACHE_AGE: u32 = 604800;
pub const COMPILED_DATE: &str = env!("COMPILED_DATE");
@ -109,7 +111,9 @@ async fn main() -> std::io::Result<()> {
.wrap(actix_middleware::NormalizePath::new(
actix_middleware::TrailingSlash::Trim,
))
.service(Files::new("/download", &settings.publish.dir).show_files_listing())
.service(
Files::new(DOWNLOAD_SCOPE, &settings.publish.dir).show_files_listing(),
)
.configure(services)
.app_data(data.clone())
})

View File

@ -66,10 +66,13 @@ pub const FOOTER: TemplateFile =
pub const PANEL_NAV: TemplateFile =
TemplateFile::new("panel_nav", "panel/nav/index.html");
pub const PUBLIC_NAV: TemplateFile =
TemplateFile::new("pub_nav", "panel/nav/public.html");
lazy_static! {
pub static ref TEMPLATES: Tera = {
let mut tera = Tera::default();
for t in [BASE, FOOTER, PANEL_NAV].iter() {
for t in [BASE, FOOTER, PANEL_NAV, PUBLIC_NAV].iter() {
t.register(&mut tera).unwrap();
}
errors::register_templates(&mut tera);

149
src/pages/panel/export.rs Normal file
View File

@ -0,0 +1,149 @@
/*
* Copyright (C) 2023 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_web::http::header::ContentType;
use actix_web::{HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use tera::Context;
use crate::api::v1::admin::campaigns::{runners, ListCampaignResp};
use crate::settings::Settings;
use crate::AppData;
use super::*;
pub use crate::pages::errors::*;
pub struct ExportPage {
ctx: RefCell<Context>,
}
pub const EXPORT_CAMPAIGNS: TemplateFile =
TemplateFile::new("export_campaigns", "panel/export.html");
impl CtxError for ExportPage {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct ExportPagePayload {
pub campaigns: Vec<ExportListCampaign>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct ExportListCampaign {
pub uuid: String,
pub name: String,
pub export_link: String,
pub route: String,
}
impl From<ListCampaignResp> for ExportListCampaign {
fn from(value: ListCampaignResp) -> Self {
use crate::DOWNLOAD_SCOPE;
let route = PAGES.panel.campaigns.get_bench_route(&value.uuid);
let export_link = format!("{DOWNLOAD_SCOPE}/{}", value.uuid);
Self {
uuid: value.uuid,
name: value.name,
export_link,
route,
}
}
}
impl ExportPage {
pub fn new(settings: &Settings, payload: Option<ExportPagePayload>) -> Self {
let ctx = RefCell::new(context(settings, "Results"));
if let Some(payload) = payload {
ctx.borrow_mut().insert(PAYLOAD_KEY, &payload);
}
Self { ctx }
}
pub fn render(&self) -> String {
TEMPLATES
.render(EXPORT_CAMPAIGNS.name, &self.ctx.borrow())
.unwrap()
}
}
#[actix_web_codegen_const_routes::get(path = "PAGES.panel.export")]
pub async fn export_campaigns(data: AppData) -> PageResult<impl Responder, ExportPage> {
let mut campaigns = runners::list_all_campaigns(&data)
.await
.map_err(|e| PageError::new(ExportPage::new(&data.settings, None), e))?;
let campaigns = campaigns.drain(0..).map(|c| c.into()).collect();
let payload = ExportPagePayload { campaigns };
let results_page = ExportPage::new(&data.settings, Some(payload)).render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(results_page))
}
pub fn services(cfg: &mut actix_web::web::ServiceConfig) {
cfg.service(export_campaigns);
}
#[cfg(test)]
mod tests {
use actix_web::test;
use super::*;
use crate::tests::*;
use crate::*;
use actix_web::http::StatusCode;
#[actix_rt::test]
async fn export_campaigns_works() {
const NAME: &str = "pubexportcampaignuser";
const EMAIL: &str = "pubexportcampaignuser@aaa.com";
const PASSWORD: &str = "longpassword";
const CAMPAIGN_NAME: &str = "pubexportcampaignusercampaign";
let data = get_test_data().await;
let app = get_app!(data).await;
delete_user(NAME, &data).await;
let (_, _, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await;
let cookies = get_cookie!(signin_resp);
let uuid =
create_new_campaign(CAMPAIGN_NAME, data.clone(), cookies.clone()).await;
let home_resp = get_request!(
&app,
&PAGES
.panel
.campaigns
.get_about_route(&data.settings.default_campaign)
);
assert_eq!(home_resp.status(), StatusCode::OK);
let body = String::from_utf8(test::read_body(home_resp).await.to_vec()).unwrap();
assert!(body.contains(PAGES.panel.export));
let export_page_resp = get_request!(&app, PAGES.panel.export);
assert_eq!(export_page_resp.status(), StatusCode::OK);
let body =
String::from_utf8(test::read_body(export_page_resp).await.to_vec()).unwrap();
assert!(body.contains(&uuid.campaign_id.to_string()));
}
}

View File

@ -19,12 +19,13 @@ pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
use crate::AppData;
mod campaigns;
mod export;
pub fn register_templates(t: &mut tera::Tera) {
campaigns::register_templates(t);
// for template in [REGISTER].iter() {
// template.register(t).expect(template.name);
// }
for template in [export::EXPORT_CAMPAIGNS].iter() {
template.register(t).expect(template.name);
}
}
pub mod routes {
@ -34,6 +35,7 @@ pub mod routes {
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct Panel {
pub home: &'static str,
pub export: &'static str,
pub campaigns: Campaigns,
}
impl Panel {
@ -41,6 +43,7 @@ pub mod routes {
let campaigns = Campaigns::new();
Panel {
home: "/",
export: "/export",
campaigns,
}
}
@ -55,6 +58,7 @@ pub mod routes {
pub fn services(cfg: &mut actix_web::web::ServiceConfig) {
cfg.service(home);
campaigns::services(cfg);
export::services(cfg);
}
#[actix_web_codegen_const_routes::get(path = "PAGES.panel.home")]

View File

@ -126,7 +126,9 @@ macro_rules! get_app {
.wrap(actix_web::middleware::NormalizePath::new(
actix_web::middleware::TrailingSlash::Trim,
))
.service(Files::new("/download", &$settings.publish.dir).show_files_listing())
.service(
Files::new("/download", &$settings.publish.dir).show_files_listing(),
)
.configure($crate::services)
};

View File

@ -1,4 +1,10 @@
{% extends 'base' %}
{% block nav %}
{% include "pub_nav" %}
{% endblock nav %}
{% block body %}
<body class="survey__body">
<main class="survey__container">

View File

@ -1,4 +1,9 @@
{% extends 'base' %}
{% block nav %}
{% include "pub_nav" %}
{% endblock nav %}
{% block body %}
<body class="survey__body">
<main class="survey__container">

View File

@ -0,0 +1,43 @@
{% extends 'base' %}
{% block body %}
<body class="panel__body">
<main class="panel__container">
{% if payload %}
<table class="campaign__table">
<thead class="campaign__heading">
<tr>
<th class="campaign__title-text">ID</th>
<th class="campaign__title-text">Name</th>
<th class="campaign__title-text">Export Link</th>
</tr>
</thead>
<tbody class="campaign__body">
{% for campaign in payload.campaigns %}
<tr class="campaign__item">
<td>
<a href="{{ campaign.route }}">
<p class="campaign__item-heading">{{ campaign.name }}</p>
</a>
</td>
<td>
<a href="{{ campaign.route }}">
<p class="campaign__item-text">{{ campaign.uuid }}</p></a
>
</td>
<td>
<a href="{{ campaign.export_link }}">
<p class="campaign__item-text">Click Here</p></a
>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Looks like there are no campaigns on this instance</p>
{% endif %}
</main>
</body>
{% endblock body %}

View File

@ -0,0 +1,24 @@
<nav class="nav__container">
<input type="checkbox" class="nav__toggle" id="nav__toggle" />
<div class="nav__header">
<a class="nav__logo-container" href="{{ page.home }}">
<img src="{{ assets.logo.path }}" alt="{{ assets.logo.name }}" class="nav__logo" />
<p class="nav__logo-text">mCaptcha Survey</p>
</a>
<label class="nav__hamburger-menu" for="nav__toggle">
<span class="nav__hamburger-inner"></span>
</label>
</div>
<div class="nav__spacer"></div>
<div class="nav__link-group">
<div class="nav__link-container">
<a class="nav__link" rel="noreferrer" href="{{ page.panel.export }}"
>Export Results</a
>
</div>
</div>
</div>
</nav>