/* * Copyright (C) 2022 Aravinth Manivannan * * 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 . */ use std::cell::RefCell; use actix_identity::Identity; use actix_web::http::header::ContentType; use serde::{Deserialize, Serialize}; use tera::Context; use url::Url; use super::get_auth_middleware; use crate::ctx::api::v1::pages; use crate::errors::ServiceResult; use crate::pages::errors::*; use crate::settings::Settings; use crate::AppCtx; pub use super::*; pub const ADD_SITE: TemplateFile = TemplateFile::new("dash_add_site", "pages/dash/sites/add.html"); pub struct AddSite { ctx: RefCell, } impl CtxError for AddSite { fn with_error(&self, e: &ReadableError) -> String { self.ctx.borrow_mut().insert(ERROR_KEY, e); self.render() } } impl AddSite { pub fn new(settings: &Settings) -> Self { let ctx = RefCell::new(context(settings)); Self { ctx } } pub fn render(&self) -> String { TEMPLATES.render(ADD_SITE.name, &self.ctx.borrow()).unwrap() } } #[actix_web_codegen_const_routes::get(path = "PAGES.dash.add_site", wrap = "get_auth_middleware()")] #[tracing::instrument(name = "get add site", skip(ctx, id))] pub async fn get_add_site(ctx: AppCtx, id: Identity) -> PageResult { let home = AddSite::new(&ctx.settings).render(); let html = ContentType::html(); Ok(HttpResponse::Ok().content_type(html).body(home)) } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] /// Data required to add site pub struct TemplatePayloadAddSite { pub url: Url, } #[actix_web_codegen_const_routes::post( path = "PAGES.dash.add_site", wrap = "get_auth_middleware()" )] #[tracing::instrument(name = "Post add site", skip(ctx, id))] pub async fn post_add_site( ctx: AppCtx, id: Identity, payload: web::Form, ) -> PageResult { let payload = payload.into_inner(); let owner = id.identity().unwrap(); let location = format!("{}?url={}", PAGES.serve.catch_all, &payload.url); ctx.add_site(pages::AddSite { url: payload.url, owner, }) .await .unwrap(); Ok(HttpResponse::Found() .append_header((http::header::LOCATION, location)) .finish()) } pub fn services(cfg: &mut web::ServiceConfig) { cfg.service(get_add_site); cfg.service(post_add_site); }