Added notifications, image preview generator
This commit is contained in:
Generated
+722
-79
File diff suppressed because it is too large
Load Diff
+4
-1
@@ -2,6 +2,7 @@
|
||||
name = "web-petting"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
default-run = "web-petting"
|
||||
|
||||
[dependencies]
|
||||
cot = { version = "0.6.0", default-features = false, features = ["postgres", "json"] }
|
||||
@@ -15,9 +16,11 @@ serde_json = "1"
|
||||
multer = "3"
|
||||
futures = "0.3"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
tokio = { version = "1", features = ["fs"] }
|
||||
tokio = { version = "1", features = ["fs", "rt-multi-thread"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
base64 = "0.22"
|
||||
urlencoding = "2"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
web-push-native = "0.5"
|
||||
async-trait = "0.1"
|
||||
|
||||
+163
-1
@@ -15,7 +15,7 @@ use serde::Deserialize;
|
||||
use std::io::Cursor;
|
||||
|
||||
use crate::i18n::{Lang, Translations};
|
||||
use crate::models::{Client, Lead, Media, Setting, Testimonial, User, Visit};
|
||||
use crate::models::{Client, Lead, Media, PushSubscription, Setting, Testimonial, User, Visit};
|
||||
use crate::telegram;
|
||||
|
||||
const SESSION_USER_ID: &str = "user_id";
|
||||
@@ -155,6 +155,9 @@ async fn save_uploaded_image(
|
||||
crate::uploads::write_db_file(&path, &encoded)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
crate::uploads::ensure_thumbnail(&path)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
Ok(path)
|
||||
} else {
|
||||
let path = crate::uploads::join_db_path(upload_dir, &format!("{file_id}.{ext}"));
|
||||
@@ -336,6 +339,54 @@ struct SettingsTemplate<'a> {
|
||||
saved: bool,
|
||||
auth_password_checked: bool,
|
||||
auth_sso_checked: bool,
|
||||
client_notifications_checked: bool,
|
||||
push_subscribers: Vec<PushSubscriberItem>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PushSubscriberItem {
|
||||
client_name: String,
|
||||
device_count: usize,
|
||||
languages: String,
|
||||
last_updated: String,
|
||||
}
|
||||
|
||||
async fn load_push_subscribers(db: &Database) -> cot::Result<Vec<PushSubscriberItem>> {
|
||||
let clients = Client::objects().all(db).await?;
|
||||
let subscriptions = PushSubscription::objects().all(db).await?;
|
||||
let mut items = Vec::new();
|
||||
for client in clients {
|
||||
let client_id = client.id.unwrap();
|
||||
let active: Vec<_> = subscriptions
|
||||
.iter()
|
||||
.filter(|subscription| {
|
||||
subscription.status == "active"
|
||||
&& subscription.client_id.primary_key().unwrap() == client_id
|
||||
})
|
||||
.collect();
|
||||
if active.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut languages: Vec<&str> = active
|
||||
.iter()
|
||||
.map(|subscription| subscription.language.as_str())
|
||||
.collect();
|
||||
languages.sort_unstable();
|
||||
languages.dedup();
|
||||
let last_updated = active
|
||||
.iter()
|
||||
.map(|subscription| subscription.updated_at)
|
||||
.max()
|
||||
.unwrap();
|
||||
items.push(PushSubscriberItem {
|
||||
client_name: client.name,
|
||||
device_count: active.len(),
|
||||
languages: languages.join(", "),
|
||||
last_updated: last_updated.format("%d.%m.%Y %H:%M").to_string(),
|
||||
});
|
||||
}
|
||||
items.sort_by(|a, b| a.client_name.cmp(&b.client_name));
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
#[derive(Debug, Template)]
|
||||
@@ -1196,6 +1247,11 @@ async fn settings_page(request: Request, session: Session, db: Database) -> cot:
|
||||
.find(|s| s.key == "auth_sso_enabled")
|
||||
.map(|s| s.value == "true")
|
||||
.unwrap_or(false);
|
||||
let client_notifications_checked = settings
|
||||
.iter()
|
||||
.find(|s| s.key == "client_notifications_enabled")
|
||||
.map(|s| s.value == "true")
|
||||
.unwrap_or(false);
|
||||
let body = SettingsTemplate {
|
||||
t: lang.t(),
|
||||
lang,
|
||||
@@ -1204,6 +1260,8 @@ async fn settings_page(request: Request, session: Session, db: Database) -> cot:
|
||||
saved: false,
|
||||
auth_password_checked,
|
||||
auth_sso_checked,
|
||||
client_notifications_checked,
|
||||
push_subscribers: load_push_subscribers(&db).await?,
|
||||
}
|
||||
.render()?;
|
||||
html_response(body, lang)
|
||||
@@ -1283,10 +1341,15 @@ struct SettingsForm {
|
||||
oidc_client_id: String,
|
||||
oidc_client_secret: String,
|
||||
oidc_allowed_groups: String,
|
||||
vapid_public_key: String,
|
||||
vapid_private_key: String,
|
||||
vapid_subject: String,
|
||||
#[serde(default)]
|
||||
auth_password_enabled: Option<String>,
|
||||
#[serde(default)]
|
||||
auth_sso_enabled: Option<String>,
|
||||
#[serde(default)]
|
||||
client_notifications_enabled: Option<String>,
|
||||
}
|
||||
|
||||
async fn save_settings(request: Request, session: Session, db: Database) -> cot::Result<Response> {
|
||||
@@ -1296,6 +1359,20 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
|
||||
Err(resp) => return Ok(resp),
|
||||
};
|
||||
|
||||
let old_settings = Setting::objects().all(&db).await?;
|
||||
let old_value = |key: &str| {
|
||||
old_settings
|
||||
.iter()
|
||||
.find(|setting| setting.key == key)
|
||||
.map(|setting| setting.value.as_str())
|
||||
.unwrap_or("")
|
||||
};
|
||||
let had_vapid_keys = !old_value("vapid_public_key").trim().is_empty()
|
||||
|| !old_value("vapid_private_key").trim().is_empty();
|
||||
let vapid_keys_changed = had_vapid_keys
|
||||
&& (old_value("vapid_public_key").trim() != form.vapid_public_key.trim()
|
||||
|| old_value("vapid_private_key").trim() != form.vapid_private_key.trim());
|
||||
|
||||
for (key, value) in [
|
||||
("telegram_bot_token", form.telegram_bot_token),
|
||||
("contact_info", form.contact_info),
|
||||
@@ -1309,6 +1386,9 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
|
||||
("oidc_client_id", form.oidc_client_id),
|
||||
("oidc_client_secret", form.oidc_client_secret),
|
||||
("oidc_allowed_groups", form.oidc_allowed_groups),
|
||||
("vapid_public_key", form.vapid_public_key),
|
||||
("vapid_private_key", form.vapid_private_key),
|
||||
("vapid_subject", form.vapid_subject),
|
||||
(
|
||||
"auth_password_enabled",
|
||||
if form.auth_password_enabled.is_some() {
|
||||
@@ -1325,6 +1405,14 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
|
||||
"false".to_string()
|
||||
},
|
||||
),
|
||||
(
|
||||
"client_notifications_enabled",
|
||||
if form.client_notifications_enabled.is_some() {
|
||||
"true".to_string()
|
||||
} else {
|
||||
"false".to_string()
|
||||
},
|
||||
),
|
||||
] {
|
||||
let k = key.to_string();
|
||||
let existing = query!(Setting, $key == k).get(&db).await?;
|
||||
@@ -1346,6 +1434,16 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
|
||||
}
|
||||
}
|
||||
|
||||
if vapid_keys_changed {
|
||||
for mut subscription in PushSubscription::objects().all(&db).await? {
|
||||
if subscription.status == "active" {
|
||||
subscription.status = "archived".to_string();
|
||||
subscription.updated_at = now_utc();
|
||||
subscription.save(&db).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let settings = Setting::objects().all(&db).await?;
|
||||
let auth_password_checked = settings
|
||||
.iter()
|
||||
@@ -1357,6 +1455,11 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
|
||||
.find(|s| s.key == "auth_sso_enabled")
|
||||
.map(|s| s.value == "true")
|
||||
.unwrap_or(false);
|
||||
let client_notifications_checked = settings
|
||||
.iter()
|
||||
.find(|s| s.key == "client_notifications_enabled")
|
||||
.map(|s| s.value == "true")
|
||||
.unwrap_or(false);
|
||||
let rendered = SettingsTemplate {
|
||||
t: lang.t(),
|
||||
lang,
|
||||
@@ -1365,6 +1468,8 @@ async fn save_settings(request: Request, session: Session, db: Database) -> cot:
|
||||
saved: true,
|
||||
auth_password_checked,
|
||||
auth_sso_checked,
|
||||
client_notifications_checked,
|
||||
push_subscribers: load_push_subscribers(&db).await?,
|
||||
}
|
||||
.render()?;
|
||||
html_response(rendered, lang)
|
||||
@@ -1895,6 +2000,7 @@ async fn schedule_edit_submit(
|
||||
if visit.status == "deleted" {
|
||||
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
|
||||
}
|
||||
let became_completed = visit.status != "completed" && form.status == "completed";
|
||||
visit.user_id = ForeignKey::PrimaryKey(Auto::fixed(form.user_id));
|
||||
if let Ok(d) = chrono::NaiveDate::parse_from_str(&form.visit_date, "%Y-%m-%d") {
|
||||
visit.visit_date = d;
|
||||
@@ -1906,6 +2012,9 @@ async fn schedule_edit_submit(
|
||||
visit.public_notes = form.public_notes.filter(|s| !s.trim().is_empty());
|
||||
visit.updated_at = now_utc();
|
||||
visit.save(&db).await?;
|
||||
if became_completed {
|
||||
crate::web_push::notify_visit_completed(&db, &visit).await;
|
||||
}
|
||||
}
|
||||
Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response()
|
||||
}
|
||||
@@ -1942,9 +2051,13 @@ async fn visit_set_done(
|
||||
if visit.status == "deleted" {
|
||||
return Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response();
|
||||
}
|
||||
let became_completed = visit.status != "completed";
|
||||
visit.status = "completed".to_string();
|
||||
visit.updated_at = now_utc();
|
||||
visit.save(&db).await?;
|
||||
if became_completed {
|
||||
crate::web_push::notify_visit_completed(&db, &visit).await;
|
||||
}
|
||||
}
|
||||
Redirect::new(format!("/admin/schedule?lang={}", lang.code())).into_response()
|
||||
}
|
||||
@@ -2261,6 +2374,12 @@ async fn media_delete(
|
||||
"failed to remove uploaded file"
|
||||
);
|
||||
}
|
||||
let thumbnail_path = crate::uploads::thumbnail_db_path(&file_path);
|
||||
if let Err(error) = crate::uploads::remove_db_file(&thumbnail_path).await {
|
||||
if error.kind() != std::io::ErrorKind::NotFound {
|
||||
tracing::warn!(%error, %thumbnail_path, "failed to remove media thumbnail");
|
||||
}
|
||||
}
|
||||
}
|
||||
let redirect_url = referer
|
||||
.filter(|r| r.contains("/schedule/") && r.contains("/edit"))
|
||||
@@ -2268,6 +2387,44 @@ async fn media_delete(
|
||||
Redirect::new(redirect_url).into_response()
|
||||
}
|
||||
|
||||
async fn serve_upload_thumbnail(
|
||||
request: Request,
|
||||
session: Session,
|
||||
db: Database,
|
||||
Path(media_id): Path<i64>,
|
||||
) -> cot::Result<Response> {
|
||||
let lang = detect_lang(&request);
|
||||
if require_auth(&session, lang).await.is_err() {
|
||||
return Redirect::new(format!("/admin/login?lang={}", lang.code())).into_response();
|
||||
}
|
||||
let media = match query!(Media, $id == media_id).get(&db).await? {
|
||||
Some(media) if media.status == "active" && media.file_type == "photo" => media,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
match crate::uploads::ensure_thumbnail(&media.file_path).await {
|
||||
Ok(path) => {
|
||||
let mut response = crate::uploads::ranged_file_response(&path, "image/jpeg", None)
|
||||
.await
|
||||
.map_err(|error| cot::Error::internal(error.to_string()))?;
|
||||
response.headers_mut().insert(
|
||||
"cache-control",
|
||||
"private, max-age=31536000, immutable".parse().unwrap(),
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(media_id, %error, "failed to create media thumbnail");
|
||||
crate::uploads::ranged_file_response(
|
||||
&media.file_path,
|
||||
crate::uploads::content_type_for_path(&media.file_path),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| cot::Error::internal(error.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve uploaded files by media ID.
|
||||
async fn serve_upload(
|
||||
request: Request,
|
||||
@@ -2767,6 +2924,11 @@ pub fn admin_router() -> Router {
|
||||
"admin-media-delete",
|
||||
),
|
||||
Route::with_handler_and_name("/uploads/{media_id}", serve_upload, "admin-uploads"),
|
||||
Route::with_handler_and_name(
|
||||
"/uploads/{media_id}/thumbnail",
|
||||
serve_upload_thumbnail,
|
||||
"admin-upload-thumbnail",
|
||||
),
|
||||
Route::with_handler_and_name("/testimonials", testimonials_page, "admin-testimonials"),
|
||||
Route::with_handler_and_name(
|
||||
"/testimonials/add",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use web_push_native::jwt_simple::algorithms::ES256KeyPair;
|
||||
use web_push_native::p256::SecretKey;
|
||||
use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint;
|
||||
|
||||
fn main() {
|
||||
let key_pair = ES256KeyPair::generate();
|
||||
let private = key_pair.to_bytes();
|
||||
let public = SecretKey::from_slice(&private)
|
||||
.expect("generated key must be valid")
|
||||
.public_key()
|
||||
.to_encoded_point(false);
|
||||
println!(
|
||||
"WEB_PETTING_VAPID_PRIVATE_KEY={}",
|
||||
URL_SAFE_NO_PAD.encode(&private)
|
||||
);
|
||||
println!(
|
||||
"WEB_PETTING_VAPID_PUBLIC_KEY={}",
|
||||
URL_SAFE_NO_PAD.encode(public.as_bytes())
|
||||
);
|
||||
println!("WEB_PETTING_VAPID_SUBJECT=mailto:admin@example.com");
|
||||
}
|
||||
+66
@@ -151,6 +151,19 @@ pub struct Translations {
|
||||
pub settings_section_captcha: &'static str,
|
||||
pub settings_section_oidc: &'static str,
|
||||
pub settings_section_general: &'static str,
|
||||
pub settings_client_notifications_enabled: &'static str,
|
||||
pub settings_client_notifications_help: &'static str,
|
||||
pub settings_vapid_public_key: &'static str,
|
||||
pub settings_vapid_private_key: &'static str,
|
||||
pub settings_vapid_subject: &'static str,
|
||||
pub settings_vapid_warning: &'static str,
|
||||
pub settings_vapid_generate: &'static str,
|
||||
pub settings_push_subscribers: &'static str,
|
||||
pub settings_push_no_subscribers: &'static str,
|
||||
pub settings_push_client: &'static str,
|
||||
pub settings_push_devices: &'static str,
|
||||
pub settings_push_language: &'static str,
|
||||
pub settings_push_updated: &'static str,
|
||||
pub landing_contact_label: &'static str,
|
||||
pub landing_pricing_title: &'static str,
|
||||
|
||||
@@ -292,6 +305,15 @@ pub struct Translations {
|
||||
pub portal_feedback_submit: &'static str,
|
||||
pub portal_feedback_thanks: &'static str,
|
||||
pub portal_link: &'static str,
|
||||
pub portal_notifications: &'static str,
|
||||
pub portal_notifications_text: &'static str,
|
||||
pub portal_notifications_enable: &'static str,
|
||||
pub portal_notifications_disable: &'static str,
|
||||
pub portal_notifications_denied: &'static str,
|
||||
pub portal_calendar: &'static str,
|
||||
pub portal_future_visit: &'static str,
|
||||
pub portal_previous: &'static str,
|
||||
pub portal_next: &'static str,
|
||||
|
||||
// Common
|
||||
pub no_value: &'static str,
|
||||
@@ -386,6 +408,19 @@ static RU: Translations = Translations {
|
||||
settings_section_captcha: "Защита от ботов",
|
||||
settings_section_oidc: "Единый вход (SSO / OIDC)",
|
||||
settings_section_general: "Сайт",
|
||||
settings_client_notifications_enabled: "Разрешить клиентам браузерные уведомления",
|
||||
settings_client_notifications_help: "Показывает клиентам настройку уведомлений о завершённых визитах.",
|
||||
settings_vapid_public_key: "VAPID — публичный ключ",
|
||||
settings_vapid_private_key: "VAPID — приватный ключ",
|
||||
settings_vapid_subject: "VAPID — контакт (например mailto:admin@example.com)",
|
||||
settings_vapid_warning: "Важно: смена пары VAPID-ключей сделает недействительными подписки всех клиентов. Им потребуется снова включить уведомления.",
|
||||
settings_vapid_generate: "Для генерации новой пары ключей выполните:",
|
||||
settings_push_subscribers: "Активные подписки клиентов",
|
||||
settings_push_no_subscribers: "Активных подписок пока нет.",
|
||||
settings_push_client: "Клиент",
|
||||
settings_push_devices: "Устройства",
|
||||
settings_push_language: "Язык",
|
||||
settings_push_updated: "Обновлено",
|
||||
landing_contact_label: "Или свяжитесь с нами напрямую",
|
||||
landing_pricing_title: "Стоимость",
|
||||
|
||||
@@ -416,6 +451,15 @@ static RU: Translations = Translations {
|
||||
portal_feedback_submit: "Отправить",
|
||||
portal_feedback_thanks: "Спасибо за отзыв!",
|
||||
portal_link: "Ссылка клиента",
|
||||
portal_notifications: "Уведомления",
|
||||
portal_notifications_text: "Получайте уведомления о завершённых визитах, даже когда страница закрыта. На iPhone сначала добавьте сайт на экран «Домой» и откройте его оттуда.",
|
||||
portal_notifications_enable: "Включить уведомления",
|
||||
portal_notifications_disable: "Отключить уведомления",
|
||||
portal_notifications_denied: "Уведомления заблокированы в настройках браузера.",
|
||||
portal_calendar: "Календарь визитов",
|
||||
portal_future_visit: "Будущий визит",
|
||||
portal_previous: "Назад",
|
||||
portal_next: "Далее",
|
||||
|
||||
login_title: "Вход в систему",
|
||||
login_button: "Войти",
|
||||
@@ -611,6 +655,19 @@ static EN: Translations = Translations {
|
||||
settings_section_captcha: "Bot protection",
|
||||
settings_section_oidc: "Single Sign-On (SSO / OIDC)",
|
||||
settings_section_general: "Site",
|
||||
settings_client_notifications_enabled: "Allow client browser notifications",
|
||||
settings_client_notifications_help: "Shows clients the completed-visit notification setting.",
|
||||
settings_vapid_public_key: "VAPID public key",
|
||||
settings_vapid_private_key: "VAPID private key",
|
||||
settings_vapid_subject: "VAPID contact (for example mailto:admin@example.com)",
|
||||
settings_vapid_warning: "Important: changing the VAPID key pair invalidates every client subscription. Clients will need to enable notifications again.",
|
||||
settings_vapid_generate: "To generate a new key pair, run:",
|
||||
settings_push_subscribers: "Active client subscriptions",
|
||||
settings_push_no_subscribers: "There are no active subscriptions yet.",
|
||||
settings_push_client: "Client",
|
||||
settings_push_devices: "Devices",
|
||||
settings_push_language: "Language",
|
||||
settings_push_updated: "Updated",
|
||||
landing_contact_label: "Or contact us directly",
|
||||
landing_pricing_title: "Pricing",
|
||||
|
||||
@@ -641,6 +698,15 @@ static EN: Translations = Translations {
|
||||
portal_feedback_submit: "Submit",
|
||||
portal_feedback_thanks: "Thank you for your feedback!",
|
||||
portal_link: "Client link",
|
||||
portal_notifications: "Notifications",
|
||||
portal_notifications_text: "Receive completed-visit notifications even when this page is closed. On iPhone, first add this site to the Home Screen and open it from there.",
|
||||
portal_notifications_enable: "Enable notifications",
|
||||
portal_notifications_disable: "Disable notifications",
|
||||
portal_notifications_denied: "Notifications are blocked in your browser settings.",
|
||||
portal_calendar: "Visit calendar",
|
||||
portal_future_visit: "Future visit",
|
||||
portal_previous: "Previous",
|
||||
portal_next: "Next",
|
||||
|
||||
login_title: "Sign In",
|
||||
login_button: "Sign In",
|
||||
|
||||
+40
-5
@@ -7,6 +7,7 @@ mod telegram;
|
||||
mod turnstile;
|
||||
mod tz;
|
||||
mod uploads;
|
||||
mod web_push;
|
||||
|
||||
use tracing_subscriber;
|
||||
|
||||
@@ -17,7 +18,7 @@ use cot::config::{
|
||||
};
|
||||
use cot::db::migrations::SyncDynMigration;
|
||||
use cot::middleware::SessionMiddleware;
|
||||
use cot::project::{MiddlewareContext, RegisterAppsContext, RootHandler};
|
||||
use cot::project::{MiddlewareContext, ProjectContext, RegisterAppsContext, RootHandler};
|
||||
use cot::router::Router;
|
||||
use cot::session::db::SessionApp;
|
||||
use cot::{App, AppBuilder, Project};
|
||||
@@ -40,11 +41,17 @@ impl App for PettingApp {
|
||||
|
||||
struct PublicApp;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl App for PublicApp {
|
||||
fn name(&self) -> &'static str {
|
||||
"public"
|
||||
}
|
||||
|
||||
async fn init(&self, context: &mut ProjectContext) -> cot::Result<()> {
|
||||
web_push::initialize(context.database()).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn router(&self) -> Router {
|
||||
public::public_router()
|
||||
}
|
||||
@@ -73,7 +80,13 @@ fn debug_enabled(config_name: &str) -> bool {
|
||||
fn database_url() -> String {
|
||||
std::env::var("WEB_PETTING_DATABASE_URL")
|
||||
.or_else(|_| std::env::var("DATABASE_URL"))
|
||||
.unwrap_or_else(|_| "postgresql://postgres:postgres@localhost:5432/web_petting".to_string())
|
||||
.unwrap_or_else(|_| {
|
||||
eprintln!(
|
||||
"WEB_PETTING_DATABASE_URL and DATABASE_URL are not set; using the local default \
|
||||
postgresql://postgres:postgres@localhost:5432/web_petting"
|
||||
);
|
||||
"postgresql://postgres:postgres@localhost:5432/web_petting".to_string()
|
||||
})
|
||||
}
|
||||
|
||||
impl Project for PettingProject {
|
||||
@@ -120,10 +133,32 @@ impl Project for PettingProject {
|
||||
}
|
||||
}
|
||||
|
||||
#[cot::main]
|
||||
fn main() -> impl Project {
|
||||
fn main() {
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
|
||||
let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
|
||||
PettingProject
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to build Tokio runtime");
|
||||
if let Err(error) = runtime.block_on(cot::run_cli(PettingProject)) {
|
||||
let message = error.to_string();
|
||||
let details = format!("{error:?}");
|
||||
eprintln!("Failed to start web-petting: {message}\nDetails: {details}");
|
||||
if details.contains("28P01") || details.contains("password authentication failed") {
|
||||
eprintln!(
|
||||
"\nPostgreSQL rejected the configured username or password.\n\
|
||||
Set the connection string before starting the application, for example:\n\n \
|
||||
WEB_PETTING_DATABASE_URL='postgresql://postgres:YOUR_PASSWORD@localhost:5432/web_petting' cargo run\n\n\
|
||||
WEB_PETTING_DATABASE_URL takes priority over DATABASE_URL.\n\
|
||||
Check the current value with: printenv WEB_PETTING_DATABASE_URL"
|
||||
);
|
||||
} else if message.to_ascii_lowercase().contains("database") {
|
||||
eprintln!(
|
||||
"\nConfigure PostgreSQL with WEB_PETTING_DATABASE_URL or DATABASE_URL.\n\
|
||||
Example:\n\n WEB_PETTING_DATABASE_URL='postgresql://postgres:YOUR_PASSWORD@localhost:5432/web_petting' cargo run"
|
||||
);
|
||||
}
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
+5
-1
@@ -3,5 +3,9 @@
|
||||
//! Squashed for the PostgreSQL migration on 2026-07-11.
|
||||
|
||||
pub mod m_0001_initial;
|
||||
pub mod m_0002_push_subscription;
|
||||
/// The list of migrations for current app.
|
||||
pub const MIGRATIONS: &[&::cot::db::migrations::SyncDynMigration] = &[&m_0001_initial::Migration];
|
||||
pub const MIGRATIONS: &[&::cot::db::migrations::SyncDynMigration] = &[
|
||||
&m_0001_initial::Migration,
|
||||
&m_0002_push_subscription::Migration,
|
||||
];
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Store browser Web Push subscriptions for client devices.
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(super) struct Migration;
|
||||
|
||||
impl ::cot::db::migrations::Migration for Migration {
|
||||
const APP_NAME: &'static str = "web-petting";
|
||||
const MIGRATION_NAME: &'static str = "m_0002_push_subscription";
|
||||
const DEPENDENCIES: &'static [::cot::db::migrations::MigrationDependency] =
|
||||
&[::cot::db::migrations::MigrationDependency::migration(
|
||||
"web-petting",
|
||||
"m_0001_initial",
|
||||
)];
|
||||
const OPERATIONS: &'static [::cot::db::migrations::Operation] = &[
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__push_subscription"))
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("endpoint"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false).unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("p256dh"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("auth"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("language"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
])
|
||||
.build(),
|
||||
];
|
||||
}
|
||||
@@ -217,3 +217,21 @@ pub struct Setting {
|
||||
pub value: String,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
/// A browser Web Push subscription belonging to a client device.
|
||||
#[derive(Debug, Clone)]
|
||||
#[model]
|
||||
pub struct PushSubscription {
|
||||
#[model(primary_key)]
|
||||
pub id: Auto<i64>,
|
||||
pub client_id: ForeignKey<Client>,
|
||||
#[model(unique)]
|
||||
pub endpoint: String,
|
||||
pub p256dh: String,
|
||||
pub auth: String,
|
||||
pub language: String,
|
||||
/// active | archived
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
+402
-7
@@ -1,5 +1,6 @@
|
||||
use chrono::Datelike;
|
||||
use cot::Template;
|
||||
use cot::db::{Auto, Database, Model};
|
||||
use cot::db::{Auto, Database, ForeignKey, Model};
|
||||
use cot::html::Html;
|
||||
use cot::request::Request;
|
||||
use cot::request::extractors::Path;
|
||||
@@ -11,7 +12,7 @@ use tracing::info;
|
||||
use cot::db::query;
|
||||
|
||||
use crate::i18n::{Lang, Translations};
|
||||
use crate::models::{Client, Lead, Media, Setting, Testimonial, User, Visit};
|
||||
use crate::models::{Client, Lead, Media, PushSubscription, Setting, Testimonial, User, Visit};
|
||||
use crate::telegram;
|
||||
|
||||
fn detect_lang(request: &Request) -> Lang {
|
||||
@@ -215,6 +216,21 @@ struct PortalVisit {
|
||||
media: Vec<Media>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CalendarDay {
|
||||
number: u32,
|
||||
class_name: &'static str,
|
||||
href: Option<String>,
|
||||
title: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CalendarMonth {
|
||||
label: String,
|
||||
leading_blanks: Vec<u8>,
|
||||
days: Vec<CalendarDay>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Template)]
|
||||
#[template(path = "client_portal.html")]
|
||||
struct ClientPortalTemplate<'a> {
|
||||
@@ -225,6 +241,62 @@ struct ClientPortalTemplate<'a> {
|
||||
past: Vec<PortalVisit>,
|
||||
feedback_sent: bool,
|
||||
turnstile_site_key: String,
|
||||
notifications_enabled: bool,
|
||||
vapid_public_key: String,
|
||||
calendar_months: Vec<CalendarMonth>,
|
||||
page: usize,
|
||||
total_pages: usize,
|
||||
has_previous_page: bool,
|
||||
has_next_page: bool,
|
||||
}
|
||||
|
||||
const PORTAL_VISITS_PER_PAGE: usize = 10;
|
||||
|
||||
fn query_page(request: &Request) -> usize {
|
||||
request
|
||||
.uri()
|
||||
.query()
|
||||
.and_then(|query| {
|
||||
query.split('&').find_map(|part| {
|
||||
part.strip_prefix("page=")
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|page| *page > 0)
|
||||
})
|
||||
})
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
fn month_label(year: i32, month: u32, lang: Lang) -> String {
|
||||
const RU: [&str; 12] = [
|
||||
"Январь",
|
||||
"Февраль",
|
||||
"Март",
|
||||
"Апрель",
|
||||
"Май",
|
||||
"Июнь",
|
||||
"Июль",
|
||||
"Август",
|
||||
"Сентябрь",
|
||||
"Октябрь",
|
||||
"Ноябрь",
|
||||
"Декабрь",
|
||||
];
|
||||
const EN: [&str; 12] = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
let names = if lang == Lang::Ru { RU } else { EN };
|
||||
format!("{} {year}", names[(month - 1) as usize])
|
||||
}
|
||||
|
||||
async fn client_portal(
|
||||
@@ -238,6 +310,7 @@ async fn client_portal(
|
||||
.query()
|
||||
.map(|q| q.split('&').any(|p| p == "feedback=ok"))
|
||||
.unwrap_or(false);
|
||||
let requested_page = query_page(&request);
|
||||
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(c) if c.status != "deleted" => c,
|
||||
@@ -291,16 +364,108 @@ async fn client_portal(
|
||||
}
|
||||
};
|
||||
|
||||
let mut upcoming = Vec::new();
|
||||
let mut past = Vec::new();
|
||||
let mut upcoming_visits = Vec::new();
|
||||
let mut past_visits = Vec::new();
|
||||
for v in visits {
|
||||
if v.visit_date >= today && v.status == "scheduled" {
|
||||
upcoming.push(build_portal_visit(v));
|
||||
upcoming_visits.push(v);
|
||||
} else {
|
||||
past.push(build_portal_visit(v));
|
||||
past_visits.push(v);
|
||||
}
|
||||
}
|
||||
past.reverse(); // newest first
|
||||
past_visits.reverse(); // newest first
|
||||
|
||||
let total_pages = past_visits.len().div_ceil(PORTAL_VISITS_PER_PAGE).max(1);
|
||||
let page = requested_page.min(total_pages);
|
||||
let page_start = (page - 1) * PORTAL_VISITS_PER_PAGE;
|
||||
let page_end = (page_start + PORTAL_VISITS_PER_PAGE).min(past_visits.len());
|
||||
let past = past_visits[page_start..page_end]
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(&build_portal_visit)
|
||||
.collect();
|
||||
let upcoming: Vec<_> = upcoming_visits
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(&build_portal_visit)
|
||||
.collect();
|
||||
|
||||
let mut month_keys: Vec<(i32, u32)> = past_visits
|
||||
.iter()
|
||||
.chain(upcoming_visits.iter())
|
||||
.map(|visit| (visit.visit_date.year(), visit.visit_date.month()))
|
||||
.collect();
|
||||
month_keys.sort();
|
||||
month_keys.dedup();
|
||||
month_keys.reverse();
|
||||
let calendar_months = month_keys
|
||||
.into_iter()
|
||||
.map(|(year, month)| {
|
||||
let first = chrono::NaiveDate::from_ymd_opt(year, month, 1).unwrap();
|
||||
let next_month = if month == 12 {
|
||||
chrono::NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap()
|
||||
} else {
|
||||
chrono::NaiveDate::from_ymd_opt(year, month + 1, 1).unwrap()
|
||||
};
|
||||
let days_in_month = (next_month - first).num_days() as u32;
|
||||
let leading_blanks = vec![0; first.weekday().num_days_from_monday() as usize];
|
||||
let days = (1..=days_in_month)
|
||||
.map(|day| {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year, month, day).unwrap();
|
||||
if let Some(_visit) = upcoming_visits
|
||||
.iter()
|
||||
.find(|visit| visit.visit_date == date)
|
||||
{
|
||||
CalendarDay {
|
||||
number: day,
|
||||
class_name: "future",
|
||||
href: None,
|
||||
title: lang.t().portal_future_visit.to_string(),
|
||||
}
|
||||
} else if let Some((index, visit)) = past_visits
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, visit)| visit.visit_date == date)
|
||||
{
|
||||
CalendarDay {
|
||||
number: day,
|
||||
class_name: "past",
|
||||
href: Some(format!(
|
||||
"?page={}#visit-{}",
|
||||
index / PORTAL_VISITS_PER_PAGE + 1,
|
||||
visit.id.unwrap()
|
||||
)),
|
||||
title: lang.t().visit_status(&visit.status).to_string(),
|
||||
}
|
||||
} else {
|
||||
CalendarDay {
|
||||
number: day,
|
||||
class_name: "empty",
|
||||
href: None,
|
||||
title: String::new(),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
CalendarMonth {
|
||||
label: month_label(year, month, lang),
|
||||
leading_blanks,
|
||||
days,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let notification_key = "client_notifications_enabled".to_string();
|
||||
let vapid_public_key = crate::web_push::load_config(&db)
|
||||
.await
|
||||
.map(|config| config.public_key)
|
||||
.unwrap_or_default();
|
||||
let notifications_enabled = !vapid_public_key.is_empty()
|
||||
&& query!(Setting, $key == notification_key)
|
||||
.get(&db)
|
||||
.await?
|
||||
.map(|setting| setting.value == "true")
|
||||
.unwrap_or(false);
|
||||
|
||||
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
|
||||
let body = ClientPortalTemplate {
|
||||
@@ -311,11 +476,170 @@ async fn client_portal(
|
||||
past,
|
||||
feedback_sent,
|
||||
turnstile_site_key,
|
||||
notifications_enabled,
|
||||
vapid_public_key,
|
||||
calendar_months,
|
||||
page,
|
||||
total_pages,
|
||||
has_previous_page: page > 1,
|
||||
has_next_page: page < total_pages,
|
||||
}
|
||||
.render()?;
|
||||
html_response(body, lang)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PushKeysForm {
|
||||
p256dh: String,
|
||||
auth: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PushSubscriptionForm {
|
||||
endpoint: String,
|
||||
keys: PushKeysForm,
|
||||
#[serde(default)]
|
||||
language: String,
|
||||
}
|
||||
|
||||
async fn portal_push_subscribe(
|
||||
request: Request,
|
||||
db: Database,
|
||||
Path(token): Path<String>,
|
||||
) -> cot::Result<Response> {
|
||||
if crate::web_push::load_config(&db).await.is_none() {
|
||||
return Html::new("404").into_response();
|
||||
}
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(client) if client.status != "deleted" => client,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
let bytes = request.into_body().into_bytes().await?;
|
||||
let form: PushSubscriptionForm =
|
||||
serde_json::from_slice(&bytes).map_err(|error| cot::Error::internal(error.to_string()))?;
|
||||
if !form.endpoint.starts_with("https://")
|
||||
|| form.endpoint.len() > 4096
|
||||
|| form.keys.p256dh.len() > 512
|
||||
|| form.keys.auth.len() > 256
|
||||
{
|
||||
return Html::new("400").into_response();
|
||||
}
|
||||
let endpoint = form.endpoint.clone();
|
||||
let now = chrono::Utc::now().naive_utc();
|
||||
if let Some(mut subscription) = query!(PushSubscription, $endpoint == endpoint)
|
||||
.get(&db)
|
||||
.await?
|
||||
{
|
||||
subscription.client_id = ForeignKey::PrimaryKey(Auto::fixed(client.id.unwrap()));
|
||||
subscription.p256dh = form.keys.p256dh;
|
||||
subscription.auth = form.keys.auth;
|
||||
subscription.language = if form.language == "ru" { "ru" } else { "en" }.to_string();
|
||||
subscription.status = "active".to_string();
|
||||
subscription.updated_at = now;
|
||||
subscription.save(&db).await?;
|
||||
} else {
|
||||
let mut subscription = PushSubscription {
|
||||
id: Auto::auto(),
|
||||
client_id: ForeignKey::PrimaryKey(Auto::fixed(client.id.unwrap())),
|
||||
endpoint: form.endpoint,
|
||||
p256dh: form.keys.p256dh,
|
||||
auth: form.keys.auth,
|
||||
language: if form.language == "ru" { "ru" } else { "en" }.to_string(),
|
||||
status: "active".to_string(),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
subscription.save(&db).await?;
|
||||
}
|
||||
let mut response = Response::new(cot::Body::fixed("{\"ok\":true}"));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/json".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn portal_push_unsubscribe(
|
||||
request: Request,
|
||||
db: Database,
|
||||
Path(token): Path<String>,
|
||||
) -> cot::Result<Response> {
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(client) if client.status != "deleted" => client,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
let bytes = request.into_body().into_bytes().await?;
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_slice(&bytes).map_err(|error| cot::Error::internal(error.to_string()))?;
|
||||
let endpoint = value
|
||||
.get("endpoint")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if let Some(mut subscription) = query!(PushSubscription, $endpoint == endpoint)
|
||||
.get(&db)
|
||||
.await?
|
||||
{
|
||||
if subscription.client_id.primary_key().unwrap() == client.id.unwrap() {
|
||||
subscription.status = "archived".to_string();
|
||||
subscription.updated_at = chrono::Utc::now().naive_utc();
|
||||
subscription.save(&db).await?;
|
||||
}
|
||||
}
|
||||
let mut response = Response::new(cot::Body::fixed("{\"ok\":true}"));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/json".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn web_manifest(_request: Request, Path(token): Path<String>) -> cot::Result<Response> {
|
||||
let manifest = serde_json::json!({
|
||||
"id": format!("/client/{token}"),
|
||||
"name": "Pet Sitting Visits",
|
||||
"short_name": "Pet Visits",
|
||||
"start_url": format!("/client/{token}"),
|
||||
"display": "standalone",
|
||||
"background_color": "#f8f7ff",
|
||||
"theme_color": "#7c6cff",
|
||||
"icons": [{ "src": "/favicon.svg", "sizes": "any", "type": "image/svg+xml" }]
|
||||
});
|
||||
let mut response = Response::new(cot::Body::fixed(manifest.to_string()));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/manifest+json".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn service_worker(_request: Request) -> cot::Result<Response> {
|
||||
let script = r#"
|
||||
self.addEventListener('push', function(event) {
|
||||
var data = event.data ? event.data.json() : {};
|
||||
event.waitUntil(self.registration.showNotification(data.title || 'Pet Visits', {
|
||||
body: data.body || '', tag: data.tag || 'visit', data: { url: data.url || '/' },
|
||||
icon: '/favicon.svg', badge: '/favicon.svg'
|
||||
}));
|
||||
});
|
||||
self.addEventListener('notificationclick', function(event) {
|
||||
event.notification.close();
|
||||
var target = new URL(event.notification.data.url || '/', self.location.origin).href;
|
||||
event.waitUntil(clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(list) {
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if ('focus' in list[i]) { list[i].navigate(target); return list[i].focus(); }
|
||||
}
|
||||
return clients.openWindow ? clients.openWindow(target) : undefined;
|
||||
}));
|
||||
});
|
||||
"#;
|
||||
let mut response = Response::new(cot::Body::fixed(script));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/javascript".parse().unwrap());
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("service-worker-allowed", "/".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct FeedbackForm {
|
||||
feedback: String,
|
||||
@@ -430,6 +754,56 @@ async fn portal_media(
|
||||
}
|
||||
}
|
||||
|
||||
async fn portal_media_thumbnail(
|
||||
_request: Request,
|
||||
db: Database,
|
||||
Path((token, media_id)): Path<(String, i64)>,
|
||||
) -> cot::Result<Response> {
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(client) if client.status != "deleted" => client,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
let media = match query!(Media, $id == media_id).get(&db).await? {
|
||||
Some(media)
|
||||
if media.client_id.primary_key().unwrap() == client.id.unwrap()
|
||||
&& media.status == "active"
|
||||
&& media.file_type == "photo" =>
|
||||
{
|
||||
media
|
||||
}
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
if let Some(visit) = &media.visit_id {
|
||||
let visit_id = visit.primary_key().unwrap();
|
||||
match query!(Visit, $id == visit_id).get(&db).await? {
|
||||
Some(visit) if visit.status != "deleted" => {}
|
||||
_ => return Html::new("404").into_response(),
|
||||
}
|
||||
}
|
||||
match crate::uploads::ensure_thumbnail(&media.file_path).await {
|
||||
Ok(path) => {
|
||||
let mut response = crate::uploads::ranged_file_response(&path, "image/jpeg", None)
|
||||
.await
|
||||
.map_err(|error| cot::Error::internal(error.to_string()))?;
|
||||
response.headers_mut().insert(
|
||||
"cache-control",
|
||||
"private, max-age=31536000, immutable".parse().unwrap(),
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(media_id, %error, "failed to create portal media thumbnail");
|
||||
crate::uploads::ranged_file_response(
|
||||
&media.file_path,
|
||||
crate::uploads::content_type_for_path(&media.file_path),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| cot::Error::internal(error.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_testimonial_image(
|
||||
_request: Request,
|
||||
db: Database,
|
||||
@@ -578,6 +952,12 @@ pub fn public_router() -> Router {
|
||||
Router::with_urls([
|
||||
Route::with_handler_and_name("/", landing_page, "landing"),
|
||||
Route::with_handler_and_name("/favicon.svg", favicon, "favicon"),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/manifest.webmanifest",
|
||||
web_manifest,
|
||||
"web-manifest",
|
||||
),
|
||||
Route::with_handler_and_name("/service-worker.js", service_worker, "service-worker"),
|
||||
Route::with_handler_and_name("/static/{filename}", serve_static, "static-file"),
|
||||
Route::with_handler_and_name("/robots.txt", robots_txt, "robots-txt"),
|
||||
Route::with_handler_and_name("/sitemap.xml", sitemap_xml, "sitemap-xml"),
|
||||
@@ -588,6 +968,16 @@ pub fn public_router() -> Router {
|
||||
"testimonial-image",
|
||||
),
|
||||
Route::with_handler_and_name("/client/{token}", client_portal, "client-portal"),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/push/subscribe",
|
||||
portal_push_subscribe,
|
||||
"client-push-subscribe",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/push/unsubscribe",
|
||||
portal_push_unsubscribe,
|
||||
"client-push-unsubscribe",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/{visit_id}/feedback",
|
||||
submit_feedback,
|
||||
@@ -598,5 +988,10 @@ pub fn public_router() -> Router {
|
||||
portal_media,
|
||||
"client-media",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/media/{media_id}/thumbnail",
|
||||
portal_media_thumbnail,
|
||||
"client-media-thumbnail",
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ use cot::response::Response;
|
||||
use cot::{Body, StatusCode};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
||||
|
||||
const THUMBNAIL_MAX_DIMENSION: u32 = 360;
|
||||
const THUMBNAIL_JPEG_QUALITY: u8 = 70;
|
||||
|
||||
const DEFAULT_UPLOAD_DIR: &str = "uploads";
|
||||
const UPLOAD_DIR_ENV: &str = "WEB_PETTING_UPLOAD_DIR";
|
||||
|
||||
@@ -57,6 +60,46 @@ pub async fn read_db_file(db_path: &str) -> std::io::Result<Vec<u8>> {
|
||||
tokio::fs::read(resolve_db_path(db_path)).await
|
||||
}
|
||||
|
||||
pub fn thumbnail_db_path(db_path: &str) -> String {
|
||||
match db_path.rsplit_once('.') {
|
||||
Some((stem, _)) => format!("{stem}.thumb.jpg"),
|
||||
None => format!("{db_path}.thumb.jpg"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn content_type_for_path(path: &str) -> &'static str {
|
||||
match path.rsplit('.').next().unwrap_or("") {
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"png" => "image/png",
|
||||
"heic" | "heif" => "image/heic",
|
||||
"webp" => "image/webp",
|
||||
"mp4" => "video/mp4",
|
||||
"mov" => "video/quicktime",
|
||||
"avi" => "video/x-msvideo",
|
||||
"mkv" => "video/x-matroska",
|
||||
"webm" => "video/webm",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn ensure_thumbnail(db_path: &str) -> std::io::Result<String> {
|
||||
let thumbnail_path = thumbnail_db_path(db_path);
|
||||
if tokio::fs::try_exists(resolve_db_path(&thumbnail_path)).await? {
|
||||
return Ok(thumbnail_path);
|
||||
}
|
||||
let data = read_db_file(db_path).await?;
|
||||
let image = image::load_from_memory(&data)
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
|
||||
let thumbnail = image.thumbnail(THUMBNAIL_MAX_DIMENSION, THUMBNAIL_MAX_DIMENSION);
|
||||
let rgb = thumbnail.to_rgb8();
|
||||
let mut encoded = Vec::new();
|
||||
let mut encoder =
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut encoded, THUMBNAIL_JPEG_QUALITY);
|
||||
encoder.encode_image(&rgb).map_err(std::io::Error::other)?;
|
||||
write_db_file(&thumbnail_path, &encoded).await?;
|
||||
Ok(thumbnail_path)
|
||||
}
|
||||
|
||||
enum ByteRange {
|
||||
Full,
|
||||
Partial { start: u64, end: u64 },
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use cot::db::{Database, Model, query};
|
||||
use serde_json::json;
|
||||
use web_push_native::jwt_simple::algorithms::ES256KeyPair;
|
||||
use web_push_native::p256::PublicKey;
|
||||
use web_push_native::{Auth, WebPushBuilder};
|
||||
|
||||
use crate::models::{Client, PushSubscription, Setting, Visit};
|
||||
|
||||
pub struct VapidConfig {
|
||||
pub public_key: String,
|
||||
private_key: String,
|
||||
subject: String,
|
||||
}
|
||||
|
||||
pub async fn load_config(db: &Database) -> Option<VapidConfig> {
|
||||
let settings = Setting::objects().all(db).await.ok()?;
|
||||
let value = |key: &str| {
|
||||
settings
|
||||
.iter()
|
||||
.find(|setting| setting.key == key)
|
||||
.map(|setting| setting.value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
};
|
||||
let public_key = value("vapid_public_key")?;
|
||||
let private_key = value("vapid_private_key")?;
|
||||
let subject = value("vapid_subject").unwrap_or_else(|| "mailto:admin@localhost".to_string());
|
||||
Some(VapidConfig {
|
||||
public_key,
|
||||
private_key,
|
||||
subject,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn initialize(db: &Database) {
|
||||
if load_config(db).await.is_some() {
|
||||
tracing::info!("VAPID configuration loaded from database");
|
||||
} else {
|
||||
tracing::info!("VAPID configuration is not set; client Web Push is disabled");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn notify_visit_completed(db: &Database, visit: &Visit) {
|
||||
let setting_key = "client_notifications_enabled".to_string();
|
||||
let enabled = query!(Setting, $key == setting_key)
|
||||
.get(db)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|setting| setting.value == "true")
|
||||
.unwrap_or(false);
|
||||
let Some(config) = load_config(db).await else {
|
||||
return;
|
||||
};
|
||||
if !enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let client_id = visit.client_id.primary_key().unwrap();
|
||||
let client = match query!(Client, $id == client_id).get(db).await {
|
||||
Ok(Some(client)) => client,
|
||||
_ => return,
|
||||
};
|
||||
let active = "active".to_string();
|
||||
let subscriptions = match query!(PushSubscription, $status == active).all(db).await {
|
||||
Ok(items) => items
|
||||
.into_iter()
|
||||
.filter(|item| item.client_id.primary_key().unwrap() == client_id)
|
||||
.collect::<Vec<_>>(),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "failed to load Web Push subscriptions");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut visible_visits = match Visit::objects().all(db).await {
|
||||
Ok(visits) => visits
|
||||
.into_iter()
|
||||
.filter(|item| {
|
||||
item.client_id.primary_key().unwrap() == client_id
|
||||
&& item.status != "cancelled"
|
||||
&& item.status != "deleted"
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
visible_visits.sort_by(|a, b| {
|
||||
b.visit_date
|
||||
.cmp(&a.visit_date)
|
||||
.then(b.time_start.cmp(&a.time_start))
|
||||
});
|
||||
let page = visible_visits
|
||||
.iter()
|
||||
.position(|item| item.id.unwrap() == visit.id.unwrap())
|
||||
.map(|index| index / 10 + 1)
|
||||
.unwrap_or(1);
|
||||
|
||||
for mut subscription in subscriptions {
|
||||
let is_ru = subscription.language == "ru";
|
||||
let date = visit.visit_date.format("%d.%m.%Y");
|
||||
let body = if is_ru {
|
||||
format!("Визит {date} завершён. Нажмите для просмотра медиа и комментариев.")
|
||||
} else {
|
||||
format!("Visit {date} is complete. Click to view media and comments.")
|
||||
};
|
||||
let payload = json!({
|
||||
"title": if is_ru { "Визит завершён" } else { "Visit completed" },
|
||||
"body": body,
|
||||
"url": format!("/client/{}?page={}#visit-{}", client.media_token, page, visit.id.unwrap()),
|
||||
"tag": format!("visit-{}", visit.id.unwrap()),
|
||||
});
|
||||
|
||||
match send(&subscription, payload.to_string().into_bytes(), &config).await {
|
||||
Ok(status)
|
||||
if status == reqwest::StatusCode::NOT_FOUND
|
||||
|| status == reqwest::StatusCode::GONE =>
|
||||
{
|
||||
subscription.status = "archived".to_string();
|
||||
subscription.updated_at = chrono::Utc::now().naive_utc();
|
||||
if let Err(error) = subscription.save(db).await {
|
||||
tracing::warn!(%error, "failed to archive expired Web Push subscription");
|
||||
}
|
||||
}
|
||||
Ok(status) if status.is_success() => {}
|
||||
Ok(status) => tracing::warn!(%status, "Web Push gateway rejected notification"),
|
||||
Err(error) => tracing::warn!(%error, "failed to send Web Push notification"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(
|
||||
subscription: &PushSubscription,
|
||||
content: Vec<u8>,
|
||||
config: &VapidConfig,
|
||||
) -> Result<reqwest::StatusCode, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let private = URL_SAFE_NO_PAD.decode(&config.private_key)?;
|
||||
let key_pair = ES256KeyPair::from_bytes(&private)?;
|
||||
let p256dh = URL_SAFE_NO_PAD.decode(&subscription.p256dh)?;
|
||||
let auth = URL_SAFE_NO_PAD.decode(&subscription.auth)?;
|
||||
let builder = WebPushBuilder::new(
|
||||
subscription.endpoint.parse()?,
|
||||
PublicKey::from_sec1_bytes(&p256dh)?,
|
||||
Auth::clone_from_slice(&auth),
|
||||
)
|
||||
.with_vapid(&key_pair, &config.subject);
|
||||
let request = builder.build(content)?;
|
||||
let (parts, body) = request.into_parts();
|
||||
let response = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.build()?
|
||||
.request(parts.method, parts.uri.to_string())
|
||||
.headers(parts.headers)
|
||||
.body(body)
|
||||
.send()
|
||||
.await?;
|
||||
Ok(response.status())
|
||||
}
|
||||
@@ -28,7 +28,7 @@
|
||||
<div class="media-card">
|
||||
{% if item.media.file_type == "photo" %}
|
||||
<a href="/admin/uploads/{{ item.media.id.unwrap() }}" data-lightbox="photo">
|
||||
<img src="/admin/uploads/{{ item.media.id.unwrap() }}" alt="" loading="lazy">
|
||||
<img src="/admin/uploads/{{ item.media.id.unwrap() }}/thumbnail" alt="" loading="lazy">
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="/admin/uploads/{{ item.media.id.unwrap() }}" data-lightbox="video">
|
||||
|
||||
@@ -114,7 +114,7 @@
|
||||
<div class="visit-media-item">
|
||||
{% if m.file_type == "photo" %}
|
||||
<a href="/admin/uploads/{{ m.id.unwrap() }}" data-lightbox="photo">
|
||||
<img src="/admin/uploads/{{ m.id.unwrap() }}" alt="" loading="lazy">
|
||||
<img src="/admin/uploads/{{ m.id.unwrap() }}/thumbnail" alt="" loading="lazy">
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="/admin/uploads/{{ m.id.unwrap() }}" data-lightbox="video">
|
||||
|
||||
@@ -59,6 +59,65 @@
|
||||
</div>
|
||||
|
||||
<h3 class="subtitle is-6 mb-2 has-text-grey" style="margin-top:1.25rem;">{{ t.settings_section_notifications }}</h3>
|
||||
<div class="field">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" name="client_notifications_enabled" value="true"{% if client_notifications_checked %} checked{% endif %}>
|
||||
{{ t.settings_client_notifications_enabled }}
|
||||
</label>
|
||||
<p class="help">{{ t.settings_client_notifications_help }}</p>
|
||||
</div>
|
||||
<blockquote class="notification is-warning is-light" style="padding:0.8rem 1rem;font-size:0.85rem;margin:0.75rem 0;">
|
||||
<p>{{ t.settings_vapid_warning }}</p>
|
||||
<p style="margin-top:0.45rem;">{{ t.settings_vapid_generate }}</p>
|
||||
<code style="display:inline-block;margin-top:0.2rem;user-select:all;">cargo run --bin generate_vapid</code>
|
||||
</blockquote>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_vapid_public_key }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="vapid_public_key" autocomplete="off" value="{% for s in &settings %}{% if s.key == "vapid_public_key" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_vapid_private_key }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="password" name="vapid_private_key" autocomplete="new-password" value="{% for s in &settings %}{% if s.key == "vapid_private_key" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_vapid_subject }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="vapid_subject" placeholder="mailto:admin@example.com" value="{% for s in &settings %}{% if s.key == "vapid_subject" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<details style="margin:0.9rem 0 1.25rem;border:1px solid #e8e5f5;border-radius:8px;background:#faf9ff;">
|
||||
<summary style="cursor:pointer;padding:0.7rem 0.85rem;font-weight:600;font-size:0.9rem;">
|
||||
{{ t.settings_push_subscribers }} ({{ push_subscribers.len() }})
|
||||
</summary>
|
||||
<div style="padding:0 0.85rem 0.85rem;overflow-x:auto;">
|
||||
{% if push_subscribers.is_empty() %}
|
||||
<p class="help">{{ t.settings_push_no_subscribers }}</p>
|
||||
{% else %}
|
||||
<table class="table is-fullwidth is-striped is-narrow" style="font-size:0.8rem;background:transparent;">
|
||||
<thead><tr>
|
||||
<th>{{ t.settings_push_client }}</th>
|
||||
<th>{{ t.settings_push_devices }}</th>
|
||||
<th>{{ t.settings_push_language }}</th>
|
||||
<th>{{ t.settings_push_updated }}</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{% for subscriber in &push_subscribers %}
|
||||
<tr>
|
||||
<td>{{ subscriber.client_name }}</td>
|
||||
<td>{{ subscriber.device_count }}</td>
|
||||
<td>{{ subscriber.languages }}</td>
|
||||
<td style="white-space:nowrap;">{{ subscriber.last_updated }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% endif %}
|
||||
</div>
|
||||
</details>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_telegram_bot_token }}</label>
|
||||
<div class="control">
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ t.portal_title }} — {{ client.name }}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="manifest" href="/client/{{ client.media_token }}/manifest.webmanifest">
|
||||
<meta name="theme-color" content="#7c6cff">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
|
||||
{% endif %}
|
||||
@@ -17,12 +20,15 @@
|
||||
padding: 0 0 2rem;
|
||||
}
|
||||
.portal-header {
|
||||
position: relative;
|
||||
background: linear-gradient(135deg, #7c6cff, #b06cff);
|
||||
color: #fff; padding: 2rem 1.5rem 1.5rem; text-align: center;
|
||||
}
|
||||
.portal-header h1 { font-size: 1.5rem; font-weight: 700; }
|
||||
.portal-header .sub { opacity: 0.85; font-size: 0.9rem; margin-top: 0.25rem; }
|
||||
.container { max-width: 700px; margin: 0 auto; padding: 0 1rem; }
|
||||
.container { max-width: 1100px; margin: 0 auto; padding: 0 1rem; }
|
||||
.portal-grid { display: grid; grid-template-columns: minmax(0, 700px) 320px; gap: 1.25rem; align-items: start; }
|
||||
.portal-settings { position: absolute; right: 1rem; bottom: 1rem; width: 38px; height: 38px; border: 0; border-radius: 50%; background: rgba(255,255,255,.2); color: #fff; font-size: 1.1rem; cursor: pointer; }
|
||||
.section-title {
|
||||
font-size: 1.15rem; font-weight: 700; margin: 1.5rem 0 0.75rem;
|
||||
padding-bottom: 0.4rem; border-bottom: 2px solid #ede7f6;
|
||||
@@ -110,6 +116,33 @@
|
||||
font-weight: 700; min-width: 5.5rem;
|
||||
}
|
||||
.upcoming-row .up-time { color: #7a7599; }
|
||||
.calendar-panel { position: sticky; top: 1rem; margin-top: 1.5rem; background: #fff; border: 1px solid #eee; border-radius: 12px; padding: .85rem; }
|
||||
.calendar-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: .65rem; }
|
||||
.calendar-head button { border: 0; background: #f0edff; color: #6255c7; width: 30px; height: 30px; border-radius: 50%; cursor: pointer; }
|
||||
.calendar-title { font-size: .95rem; font-weight: 700; }
|
||||
.calendar-weekdays, .calendar-days { display: grid; grid-template-columns: repeat(7, 1fr); gap: 3px; text-align: center; }
|
||||
.calendar-weekdays { color: #999; font-size: .68rem; margin-bottom: 3px; }
|
||||
.calendar-day { aspect-ratio: 1; display: flex; align-items: center; justify-content: center; border-radius: 7px; font-size: .78rem; color: #aaa; }
|
||||
.calendar-day.past { background: #ede9ff; color: #5145a6; font-weight: 700; text-decoration: none; }
|
||||
.calendar-day.past:hover { background: #dcd5ff; }
|
||||
.calendar-day.future { background: #f3f3f3; color: #bbb; border: 1px dashed #ddd; }
|
||||
.calendar-month[hidden] { display: none; }
|
||||
.calendar-legend { margin-top: .65rem; font-size: .72rem; color: #999; }
|
||||
.pagination { display: flex; justify-content: center; align-items: center; gap: .75rem; margin: 1rem 0; font-size: .85rem; }
|
||||
.pagination a { color: #6558c8; text-decoration: none; padding: .35rem .7rem; background: #fff; border: 1px solid #e5e1ff; border-radius: 8px; }
|
||||
.modal-bg { display: none; position: fixed; inset: 0; z-index: 1000; background: rgba(20,18,40,.55); align-items: center; justify-content: center; padding: 1rem; }
|
||||
.modal-bg.open { display: flex; }
|
||||
.notification-modal { width: min(420px, 100%); background: #fff; border-radius: 14px; padding: 1.2rem; box-shadow: 0 15px 50px rgba(0,0,0,.25); }
|
||||
.notification-modal h2 { font-size: 1.15rem; margin-bottom: .45rem; }
|
||||
.notification-modal p { font-size: .88rem; color: #777; }
|
||||
.notification-actions { display: flex; gap: .5rem; margin-top: 1rem; }
|
||||
.notification-actions button { border: 0; border-radius: 8px; padding: .55rem .9rem; cursor: pointer; }
|
||||
.notification-primary { background: #7567e8; color: #fff; }
|
||||
@media (max-width: 800px) {
|
||||
.portal-grid { display: flex; flex-direction: column; }
|
||||
.calendar-panel { position: static; order: -1; width: 100%; margin-top: 1rem; }
|
||||
.visits-column { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -121,6 +154,7 @@
|
||||
<div class="portal-header">
|
||||
<h1>{{ t.portal_title }}</h1>
|
||||
<div class="sub">{{ client.name }}</div>
|
||||
{% if notifications_enabled %}<button class="portal-settings" type="button" onclick="openNotificationSettings()" aria-label="{{ t.portal_notifications }}">⚙</button>{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
@@ -129,13 +163,15 @@
|
||||
<div class="success-msg">{{ t.portal_feedback_thanks }}</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="portal-grid">
|
||||
<main class="visits-column">
|
||||
<!-- Past visits with media first -->
|
||||
<h2 class="section-title">{{ t.portal_past }}</h2>
|
||||
{% if past.is_empty() %}
|
||||
<p class="empty-msg">{{ t.portal_no_past }}</p>
|
||||
{% else %}
|
||||
{% for pv in &past %}
|
||||
<div class="visit-card">
|
||||
<div class="visit-card" id="visit-{{ pv.visit.id.unwrap() }}">
|
||||
<div class="visit-card-head">
|
||||
<span class="date">{{ pv.visit.visit_date }}</span>
|
||||
<span class="badge-sm badge-{{ pv.visit.status }}">
|
||||
@@ -156,7 +192,7 @@
|
||||
{% for m in &pv.media %}
|
||||
{% if m.file_type == "photo" %}
|
||||
<a href="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}" data-lightbox="photo">
|
||||
<img src="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}" alt="" loading="lazy">
|
||||
<img src="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}/thumbnail" alt="" loading="lazy">
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}" data-lightbox="video">
|
||||
@@ -200,6 +236,13 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% if total_pages > 1 %}
|
||||
<nav class="pagination">
|
||||
{% if has_previous_page %}<a href="?page={{ page - 1 }}">← {{ t.portal_previous }}</a>{% endif %}
|
||||
<span>{{ page }} / {{ total_pages }}</span>
|
||||
{% if has_next_page %}<a href="?page={{ page + 1 }}">{{ t.portal_next }} →</a>{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
<!-- Compact upcoming schedule -->
|
||||
@@ -209,14 +252,55 @@
|
||||
{% for pv in &upcoming %}
|
||||
<div class="upcoming-row">
|
||||
<span class="up-date">{{ pv.visit.visit_date }}</span>
|
||||
<span class="up-time">{{ pv.visit.time_start }} — {{ pv.visit.time_end }}</span>
|
||||
<span class="up-time">{{ t.portal_future_visit }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</main>
|
||||
|
||||
{% if !calendar_months.is_empty() %}
|
||||
<aside class="calendar-panel">
|
||||
<div class="calendar-head">
|
||||
<button type="button" onclick="moveCalendar(1)" aria-label="{{ t.portal_previous }}">‹</button>
|
||||
<span class="calendar-title" id="calendarTitle">{{ t.portal_calendar }}</span>
|
||||
<button type="button" onclick="moveCalendar(-1)" aria-label="{{ t.portal_next }}">›</button>
|
||||
</div>
|
||||
<div class="calendar-weekdays"><span>Пн</span><span>Вт</span><span>Ср</span><span>Чт</span><span>Пт</span><span>Сб</span><span>Вс</span></div>
|
||||
{% for month in &calendar_months %}
|
||||
<div class="calendar-month" data-label="{{ month.label }}"{% if !loop.first %} hidden{% endif %}>
|
||||
<div class="calendar-days">
|
||||
{% for _blank in &month.leading_blanks %}<span></span>{% endfor %}
|
||||
{% for day in &month.days %}
|
||||
{% if let Some(href) = day.href.as_deref() %}
|
||||
<a class="calendar-day {{ day.class_name }}" href="{{ href }}" title="{{ day.title }}">{{ day.number }}</a>
|
||||
{% else %}
|
||||
<span class="calendar-day {{ day.class_name }}" title="{{ day.title }}">{{ day.number }}</span>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div class="calendar-legend">{{ t.portal_future_visit }} — ···</div>
|
||||
</aside>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{% if notifications_enabled %}
|
||||
<div class="modal-bg" id="notificationModal" onclick="if(event.target===this) closeNotificationSettings()">
|
||||
<div class="notification-modal">
|
||||
<h2>{{ t.portal_notifications }}</h2>
|
||||
<p id="notificationText">{{ t.portal_notifications_text }}</p>
|
||||
<div class="notification-actions">
|
||||
<button type="button" class="notification-primary" id="notificationToggle">{{ t.portal_notifications_enable }}</button>
|
||||
<button type="button" onclick="closeNotificationSettings()">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<script>
|
||||
function showFbEdit(id) {
|
||||
document.getElementById('fb-view-' + id).style.display = 'none';
|
||||
@@ -226,6 +310,73 @@ function hideFbEdit(id) {
|
||||
document.getElementById('fb-form-' + id).style.display = 'none';
|
||||
document.getElementById('fb-view-' + id).style.display = '';
|
||||
}
|
||||
var calendarIndex = 0;
|
||||
function renderCalendar() {
|
||||
var months = document.querySelectorAll('.calendar-month');
|
||||
if (!months.length) return;
|
||||
months.forEach(function(month, index) { month.hidden = index !== calendarIndex; });
|
||||
document.getElementById('calendarTitle').textContent = months[calendarIndex].dataset.label;
|
||||
}
|
||||
function moveCalendar(delta) {
|
||||
var months = document.querySelectorAll('.calendar-month');
|
||||
calendarIndex = Math.max(0, Math.min(months.length - 1, calendarIndex + delta));
|
||||
renderCalendar();
|
||||
}
|
||||
renderCalendar();
|
||||
{% if notifications_enabled %}
|
||||
(function() {
|
||||
var toggle = document.getElementById('notificationToggle');
|
||||
var registration;
|
||||
var subscription;
|
||||
function decodeKey(value) {
|
||||
var padding = '='.repeat((4 - value.length % 4) % 4);
|
||||
var raw = atob((value + padding).replace(/-/g, '+').replace(/_/g, '/'));
|
||||
return Uint8Array.from(raw, function(char) { return char.charCodeAt(0); });
|
||||
}
|
||||
async function refresh() {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) return;
|
||||
registration = await navigator.serviceWorker.register('/service-worker.js');
|
||||
subscription = await registration.pushManager.getSubscription();
|
||||
toggle.textContent = subscription ? '{{ t.portal_notifications_disable }}' : '{{ t.portal_notifications_enable }}';
|
||||
}
|
||||
window.openNotificationSettings = function() { document.getElementById('notificationModal').classList.add('open'); refresh().catch(console.error); };
|
||||
window.closeNotificationSettings = function() { document.getElementById('notificationModal').classList.remove('open'); };
|
||||
toggle.addEventListener('click', async function() {
|
||||
try {
|
||||
if (!registration) await refresh();
|
||||
if (subscription) {
|
||||
await fetch('/client/{{ client.media_token }}/push/unsubscribe', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({endpoint: subscription.endpoint})
|
||||
});
|
||||
await subscription.unsubscribe();
|
||||
subscription = null;
|
||||
} else {
|
||||
var permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') {
|
||||
document.getElementById('notificationText').textContent = '{{ t.portal_notifications_denied }}';
|
||||
return;
|
||||
}
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: decodeKey('{{ vapid_public_key }}')
|
||||
});
|
||||
var payload = subscription.toJSON();
|
||||
payload.language = '{{ lang.code() }}';
|
||||
var response = await fetch('/client/{{ client.media_token }}/push/subscribe', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
|
||||
});
|
||||
if (!response.ok) { await subscription.unsubscribe(); subscription = null; throw new Error('subscribe failed'); }
|
||||
closeNotificationSettings();
|
||||
}
|
||||
toggle.textContent = subscription ? '{{ t.portal_notifications_disable }}' : '{{ t.portal_notifications_enable }}';
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
refresh().catch(console.error);
|
||||
})();
|
||||
{% endif %}
|
||||
</script>
|
||||
{% include "partials/lightbox.html" %}
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user