2026-11-15 10:25:35 +00:00
|
|
|
//! Public sharing links. Creating and revoking a link needs login; opening
|
|
|
|
|
//! one (`GET /v1/public/shares/{slug}`) does not. The public view never
|
|
|
|
|
//! contains birth data unless the owner allowed it for their own chart.
|
2026-11-19 07:37:06 +00:00
|
|
|
//! A shared chart comes with its newest short summary (the share page and
|
|
|
|
|
//! its preview image show both). Sharing the same thing again returns the
|
|
|
|
|
//! link that is already open.
|
2026-11-19 09:26:06 +00:00
|
|
|
//!
|
|
|
|
|
//! Reading a share writes nothing, so robots cost no database writes. The
|
|
|
|
|
//! share page reports a visit from the visitor's browser
|
|
|
|
|
//! (`POST /v1/public/shares/{slug}/visit`): it is counted unless it comes
|
|
|
|
|
//! from a robot or from the sharer (logged in, or from the address the link
|
|
|
|
|
//! was made at). The sharer's first such visit earns one free natal analysis,
|
|
|
|
|
//! once per user.
|
2026-11-15 10:25:35 +00:00
|
|
|
|
|
|
|
|
use axum::Json;
|
|
|
|
|
use axum::extract::{Path, State};
|
2026-11-19 09:26:06 +00:00
|
|
|
use axum::http::{HeaderMap, StatusCode};
|
2026-11-15 10:25:35 +00:00
|
|
|
use axum_extra::extract::WithRejection;
|
|
|
|
|
use serde::Deserialize;
|
|
|
|
|
use serde_json::{Value, json};
|
2026-11-19 09:26:06 +00:00
|
|
|
use sha2::{Digest, Sha256};
|
2026-11-15 10:25:35 +00:00
|
|
|
use sqlx::PgPool;
|
|
|
|
|
use time::OffsetDateTime;
|
|
|
|
|
use uuid::Uuid;
|
|
|
|
|
|
|
|
|
|
use super::analyses::{can_see, find_analysis};
|
|
|
|
|
use super::charts::{ChartRow, find_chart, owned_chart};
|
|
|
|
|
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
|
|
|
|
|
use super::{Body, IdPath, St};
|
2026-11-19 09:26:06 +00:00
|
|
|
use crate::auth::{AuthUser, user_agent};
|
2026-11-15 10:25:35 +00:00
|
|
|
use crate::error::{ApiError, ApiResult};
|
|
|
|
|
use crate::views::{public_chart, rfc3339, rfc3339_opt};
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
|
|
|
|
#[serde(rename_all = "snake_case")]
|
|
|
|
|
pub enum ShareKind {
|
|
|
|
|
Chart,
|
|
|
|
|
Synastry,
|
|
|
|
|
Analysis,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, sqlx::FromRow)]
|
|
|
|
|
struct ShareRow {
|
|
|
|
|
id: Uuid,
|
|
|
|
|
owner_id: Uuid,
|
|
|
|
|
slug: String,
|
|
|
|
|
kind: String,
|
|
|
|
|
chart_id: Option<Uuid>,
|
|
|
|
|
synastry_id: Option<Uuid>,
|
|
|
|
|
analysis_id: Option<Uuid>,
|
|
|
|
|
title: Option<String>,
|
|
|
|
|
show_birth_data: bool,
|
|
|
|
|
view_count: i64,
|
|
|
|
|
created_at: OffsetDateTime,
|
|
|
|
|
revoked_at: Option<OffsetDateTime>,
|
2026-11-19 09:26:06 +00:00
|
|
|
owner_ip_hash: Option<Vec<u8>>,
|
2026-11-15 10:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
2026-11-19 09:26:06 +00:00
|
|
|
view_count, created_at, revoked_at, owner_ip_hash";
|
|
|
|
|
|
|
|
|
|
/// The visitor's address: the first `X-Forwarded-For` entry (Caddy writes it
|
|
|
|
|
/// from Cloudflare's, the frontend passes it on).
|
|
|
|
|
fn client_ip(headers: &HeaderMap) -> Option<String> {
|
|
|
|
|
let first = headers.get("x-forwarded-for")?.to_str().ok()?.split(',').next()?.trim();
|
|
|
|
|
(!first.is_empty()).then(|| first.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// An address salted with the slug, so the stored value says nothing by itself.
|
|
|
|
|
fn ip_hash(slug: &str, ip: &str) -> Vec<u8> {
|
|
|
|
|
Sha256::digest(format!("{slug}:{ip}").as_bytes()).to_vec()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Link preview robots, crawlers and scripts (they do not run the page's
|
|
|
|
|
/// script anyway; this also stops a direct call).
|
|
|
|
|
fn is_robot(user_agent: Option<&str>) -> bool {
|
|
|
|
|
const MARKS: [&str; 16] = [
|
|
|
|
|
"bot",
|
|
|
|
|
"crawl",
|
|
|
|
|
"spider",
|
|
|
|
|
"slurp",
|
|
|
|
|
"facebookexternalhit",
|
|
|
|
|
"preview",
|
|
|
|
|
"fetch",
|
|
|
|
|
"curl",
|
|
|
|
|
"wget",
|
|
|
|
|
"python",
|
|
|
|
|
"headless",
|
|
|
|
|
"http-client",
|
|
|
|
|
"okhttp",
|
|
|
|
|
"java/",
|
|
|
|
|
"go-http",
|
|
|
|
|
"scrapy",
|
|
|
|
|
];
|
|
|
|
|
match user_agent {
|
|
|
|
|
Some(ua) if !ua.trim().is_empty() => {
|
|
|
|
|
let ua = ua.to_lowercase();
|
|
|
|
|
MARKS.iter().any(|m| ua.contains(m))
|
|
|
|
|
}
|
|
|
|
|
_ => true,
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-11-15 10:25:35 +00:00
|
|
|
|
|
|
|
|
/// 96 random bits, 16 URL-safe characters.
|
|
|
|
|
fn new_slug() -> String {
|
|
|
|
|
db::random_token(12)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ShareRow {
|
|
|
|
|
fn view(&self, base_url: &str) -> Value {
|
|
|
|
|
json!({
|
|
|
|
|
"id": self.id,
|
|
|
|
|
"slug": self.slug,
|
|
|
|
|
"url": format!("{base_url}/s/{}", self.slug),
|
|
|
|
|
"kind": self.kind,
|
|
|
|
|
"chart_id": self.chart_id,
|
|
|
|
|
"synastry_id": self.synastry_id,
|
|
|
|
|
"analysis_id": self.analysis_id,
|
|
|
|
|
"title": self.title,
|
|
|
|
|
"show_birth_data": self.show_birth_data,
|
|
|
|
|
"view_count": self.view_count,
|
|
|
|
|
"created_at": rfc3339(self.created_at),
|
|
|
|
|
"revoked_at": rfc3339_opt(self.revoked_at),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
|
#[serde(deny_unknown_fields)]
|
|
|
|
|
pub struct CreateShare {
|
|
|
|
|
kind: ShareKind,
|
|
|
|
|
/// Id of the chart, synastry or analysis.
|
|
|
|
|
target_id: Uuid,
|
|
|
|
|
title: Option<String>,
|
|
|
|
|
/// Show birth date, time and place (only ever of the sharer's own charts).
|
|
|
|
|
#[serde(default)]
|
|
|
|
|
show_birth_data: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn create(
|
|
|
|
|
State(state): St,
|
|
|
|
|
auth: AuthUser,
|
2026-11-19 09:26:06 +00:00
|
|
|
headers: HeaderMap,
|
2026-11-15 10:25:35 +00:00
|
|
|
WithRejection(Json(req), _): Body<CreateShare>,
|
|
|
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
|
|
|
|
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
|
|
|
|
|
ShareKind::Chart => {
|
|
|
|
|
owned_chart(&state.db, req.target_id, auth.id()).await?;
|
|
|
|
|
(Some(req.target_id), None, None, "chart")
|
|
|
|
|
}
|
|
|
|
|
ShareKind::Synastry => {
|
|
|
|
|
visible_synastry(&state.db, req.target_id, auth.id()).await?;
|
|
|
|
|
(None, Some(req.target_id), None, "synastry")
|
|
|
|
|
}
|
|
|
|
|
ShareKind::Analysis => {
|
|
|
|
|
let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
|
|
|
|
if !can_see(&state.db, &analysis, auth.id()).await? {
|
|
|
|
|
return Err(ApiError::NotFound("analysis"));
|
|
|
|
|
}
|
|
|
|
|
if analysis.status != "done" {
|
|
|
|
|
return Err(ApiError::conflict("analysis_not_ready", "only finished analyses can be shared"));
|
|
|
|
|
}
|
|
|
|
|
(None, None, Some(req.target_id), "analysis")
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
|
2026-11-19 07:37:06 +00:00
|
|
|
let open: Option<ShareRow> = sqlx::query_as(&format!(
|
|
|
|
|
"SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \
|
|
|
|
|
AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \
|
|
|
|
|
AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \
|
|
|
|
|
ORDER BY created_at DESC LIMIT 1"
|
|
|
|
|
))
|
|
|
|
|
.bind(auth.id())
|
|
|
|
|
.bind(kind)
|
|
|
|
|
.bind(chart_id)
|
|
|
|
|
.bind(synastry_id)
|
|
|
|
|
.bind(analysis_id)
|
|
|
|
|
.bind(&title)
|
|
|
|
|
.bind(req.show_birth_data)
|
|
|
|
|
.fetch_optional(&state.db)
|
|
|
|
|
.await?;
|
|
|
|
|
if let Some(row) = open {
|
|
|
|
|
return Ok((StatusCode::OK, Json(row.view(&state.config.public_base_url))));
|
|
|
|
|
}
|
2026-11-19 09:26:06 +00:00
|
|
|
let slug = new_slug();
|
2026-11-15 10:25:35 +00:00
|
|
|
let row: ShareRow = sqlx::query_as(&format!(
|
2026-11-19 09:26:06 +00:00
|
|
|
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
|
|
|
|
owner_ip_hash) \
|
|
|
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}"
|
2026-11-15 10:25:35 +00:00
|
|
|
))
|
|
|
|
|
.bind(Uuid::now_v7())
|
|
|
|
|
.bind(auth.id())
|
2026-11-19 09:26:06 +00:00
|
|
|
.bind(&slug)
|
2026-11-15 10:25:35 +00:00
|
|
|
.bind(kind)
|
|
|
|
|
.bind(chart_id)
|
|
|
|
|
.bind(synastry_id)
|
|
|
|
|
.bind(analysis_id)
|
|
|
|
|
.bind(title)
|
|
|
|
|
.bind(req.show_birth_data)
|
2026-11-19 09:26:06 +00:00
|
|
|
.bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip)))
|
2026-11-15 10:25:35 +00:00
|
|
|
.fetch_one(&state.db)
|
|
|
|
|
.await?;
|
|
|
|
|
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
|
|
|
|
let rows: Vec<ShareRow> =
|
|
|
|
|
sqlx::query_as(&format!("SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 ORDER BY created_at DESC"))
|
|
|
|
|
.bind(auth.id())
|
|
|
|
|
.fetch_all(&state.db)
|
|
|
|
|
.await?;
|
|
|
|
|
let base = &state.config.public_base_url;
|
|
|
|
|
Ok(Json(json!({ "shares": rows.iter().map(|r| r.view(base)).collect::<Vec<_>>() })))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn revoke(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
|
|
|
|
let result =
|
|
|
|
|
sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL")
|
|
|
|
|
.bind(id)
|
|
|
|
|
.bind(auth.id())
|
|
|
|
|
.execute(&state.db)
|
|
|
|
|
.await?;
|
|
|
|
|
if result.rows_affected() == 0 {
|
|
|
|
|
return Err(ApiError::NotFound("share"));
|
|
|
|
|
}
|
|
|
|
|
Ok(StatusCode::NO_CONTENT)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- public view -------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
|
|
|
|
|
// Birth data only of the sharer's own chart, never of a partner's.
|
|
|
|
|
let show = share.show_birth_data && chart.owner_id == share.owner_id;
|
|
|
|
|
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value {
|
|
|
|
|
json!({
|
|
|
|
|
"chart1": public_chart_block(&s.chart1, share),
|
|
|
|
|
"chart2": public_chart_block(&s.chart2, share),
|
|
|
|
|
"synastry": s.synastry.result,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
|
|
|
|
|
let mut body = json!({
|
|
|
|
|
"kind": share.kind,
|
|
|
|
|
"title": share.title,
|
|
|
|
|
"created_at": rfc3339(share.created_at),
|
|
|
|
|
});
|
|
|
|
|
if let Some(chart_id) = share.chart_id {
|
|
|
|
|
let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?;
|
|
|
|
|
body["chart"] = public_chart_block(&chart, share);
|
2026-11-19 07:37:06 +00:00
|
|
|
body["summary"] = latest_summary(db, chart_id).await?;
|
2026-11-15 10:25:35 +00:00
|
|
|
} else if let Some(synastry_id) = share.synastry_id {
|
|
|
|
|
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
|
|
|
|
|
body["synastry"] = public_synastry_block(&s, share);
|
|
|
|
|
} else if let Some(analysis_id) = share.analysis_id {
|
|
|
|
|
let analysis = find_analysis(db, analysis_id).await?.ok_or(ApiError::NotFound("share"))?;
|
|
|
|
|
body["analysis"] = json!({
|
|
|
|
|
"kind": analysis.kind,
|
|
|
|
|
"language": analysis.language,
|
|
|
|
|
"content": analysis.content,
|
|
|
|
|
"completed_at": rfc3339_opt(analysis.completed_at),
|
|
|
|
|
});
|
|
|
|
|
if let Some(chart_id) = analysis.chart_id {
|
|
|
|
|
let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?;
|
|
|
|
|
body["chart"] = public_chart_block(&chart, share);
|
|
|
|
|
}
|
|
|
|
|
if let Some(synastry_id) = analysis.synastry_id {
|
|
|
|
|
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
|
|
|
|
|
body["synastry"] = public_synastry_block(&s, share);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(body)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-19 07:37:06 +00:00
|
|
|
/// The newest finished short summary of a chart (`null` if none).
|
|
|
|
|
async fn latest_summary(db: &PgPool, chart_id: Uuid) -> Result<Value, sqlx::Error> {
|
|
|
|
|
type Row = (Uuid, String, Option<Value>, Option<OffsetDateTime>);
|
|
|
|
|
let row: Option<Row> = sqlx::query_as(
|
|
|
|
|
"SELECT id, language, content, completed_at FROM analyses \
|
|
|
|
|
WHERE chart_id = $1 AND kind = 'summary' AND status = 'done' ORDER BY completed_at DESC LIMIT 1",
|
|
|
|
|
)
|
|
|
|
|
.bind(chart_id)
|
|
|
|
|
.fetch_optional(db)
|
|
|
|
|
.await?;
|
|
|
|
|
Ok(match row {
|
|
|
|
|
Some((id, language, content, completed_at)) => json!({
|
|
|
|
|
"id": id,
|
|
|
|
|
"language": language,
|
|
|
|
|
"title": content.as_ref().and_then(|c| c["title"].as_str()),
|
|
|
|
|
"summary": content.as_ref().and_then(|c| c["summary"].as_str()),
|
|
|
|
|
"completed_at": rfc3339_opt(completed_at),
|
|
|
|
|
}),
|
|
|
|
|
None => Value::Null,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-19 09:26:06 +00:00
|
|
|
async fn open_share(db: &PgPool, slug: &str) -> Result<ShareRow, ApiError> {
|
|
|
|
|
sqlx::query_as(&format!("SELECT {SHARE_COLUMNS} FROM shares WHERE slug = $1 AND revoked_at IS NULL"))
|
|
|
|
|
.bind(slug.trim())
|
|
|
|
|
.fetch_optional(db)
|
|
|
|
|
.await?
|
|
|
|
|
.ok_or(ApiError::NotFound("share"))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Public: the shared content for the share page and its OG image (read only).
|
2026-11-15 10:25:35 +00:00
|
|
|
pub async fn public_view(State(state): St, Path(slug): Path<String>) -> ApiResult<Json<Value>> {
|
2026-11-19 09:26:06 +00:00
|
|
|
let share = open_share(&state.db, &slug).await?;
|
2026-11-15 10:25:35 +00:00
|
|
|
Ok(Json(public_body(&state.db, &share).await?))
|
|
|
|
|
}
|
2026-11-19 09:26:06 +00:00
|
|
|
|
|
|
|
|
/// Public: the share page reports that someone opened it. Counted unless a
|
|
|
|
|
/// robot or the sharer; the sharer's first counted visit ever earns the reward.
|
|
|
|
|
pub async fn visit(
|
|
|
|
|
State(state): St,
|
|
|
|
|
auth: Result<AuthUser, ApiError>,
|
|
|
|
|
headers: HeaderMap,
|
|
|
|
|
Path(slug): Path<String>,
|
|
|
|
|
) -> ApiResult<Json<Value>> {
|
|
|
|
|
let share = open_share(&state.db, &slug).await?;
|
|
|
|
|
let sharer = auth.as_ref().is_ok_and(|a| a.id() == share.owner_id);
|
|
|
|
|
let same_place = match (client_ip(&headers), &share.owner_ip_hash) {
|
|
|
|
|
(Some(ip), Some(hash)) => ip_hash(&share.slug, &ip) == *hash,
|
|
|
|
|
_ => false,
|
|
|
|
|
};
|
|
|
|
|
if sharer || same_place || is_robot(user_agent(&headers).as_deref()) {
|
|
|
|
|
return Ok(Json(json!({ "counted": false })));
|
|
|
|
|
}
|
|
|
|
|
let mut tx = state.db.begin().await?;
|
|
|
|
|
sqlx::query("UPDATE shares SET view_count = view_count + 1 WHERE id = $1").bind(share.id).execute(&mut *tx).await?;
|
|
|
|
|
let rewarded = sqlx::query(
|
|
|
|
|
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \
|
|
|
|
|
VALUES ($1, $2, 'natal', 1, 'share_reward', $3) ON CONFLICT DO NOTHING",
|
|
|
|
|
)
|
|
|
|
|
.bind(Uuid::now_v7())
|
|
|
|
|
.bind(share.owner_id)
|
|
|
|
|
.bind(format!("first visit of share {}", share.id))
|
|
|
|
|
.execute(&mut *tx)
|
|
|
|
|
.await?
|
|
|
|
|
.rows_affected()
|
|
|
|
|
== 1;
|
|
|
|
|
tx.commit().await?;
|
|
|
|
|
if rewarded {
|
|
|
|
|
tracing::info!(share = %share.id, "share reward granted");
|
|
|
|
|
}
|
|
|
|
|
Ok(Json(json!({ "counted": true })))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Whether the user has already received the reward for sharing.
|
|
|
|
|
pub async fn reward_granted(db: &PgPool, user_id: Uuid) -> Result<bool, sqlx::Error> {
|
|
|
|
|
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM credit_ledger WHERE user_id = $1 AND reason = 'share_reward')")
|
|
|
|
|
.bind(user_id)
|
|
|
|
|
.fetch_one(db)
|
|
|
|
|
.await
|
|
|
|
|
}
|