Share reward and less robot load on shared links
The first visit of a shared link by someone else earns the sharer one free natal analysis, once per user. The share page reports visits from the visitor's browser; robots, the logged-in sharer and the address the link was made at do not count. The share button is a proper card that says so in small print; /v1/me tells whether the reward is used up. Robots: reading a share writes nothing (view_count counts people only), the frontend keeps shared content for five minutes (cleared when a link is revoked), and robots.txt turns away the known AI crawlers while leaving the link preview robots alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -33,6 +33,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let birth_change = crate::birth_changes::view(&mut conn, &auth).await?;
|
||||
let persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
|
||||
let package = crate::packages::current(&mut conn, auth.id()).await?;
|
||||
let share_reward = super::shares::reward_granted(&state.db, auth.id()).await?;
|
||||
Ok(Json(json!({
|
||||
"user": UserView::from(&auth.user),
|
||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||
@@ -41,6 +42,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
"birth_change": birth_change,
|
||||
"persons": persons.view(),
|
||||
"package": package.map(|(p, since)| json!({ "id": p.id, "name": p.name, "since": rfc3339(since) })),
|
||||
// The free analysis for a shared link is used up (once per user).
|
||||
"share_reward_granted": share_reward,
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -100,6 +100,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/shares/{id}", delete(shares::revoke))
|
||||
// public, no login
|
||||
.route("/v1/public/shares/{slug}", get(shares::public_view))
|
||||
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
|
||||
.route("/v1/public/invites/{token}", get(synastries::public_invite))
|
||||
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
|
||||
.route("/v1/public/invitations/{token}", get(invitations::public_view))
|
||||
|
||||
@@ -4,13 +4,21 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
@@ -19,7 +27,7 @@ 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};
|
||||
use crate::auth::AuthUser;
|
||||
use crate::auth::{AuthUser, user_agent};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{public_chart, rfc3339, rfc3339_opt};
|
||||
|
||||
@@ -45,10 +53,53 @@ struct ShareRow {
|
||||
view_count: i64,
|
||||
created_at: OffsetDateTime,
|
||||
revoked_at: Option<OffsetDateTime>,
|
||||
owner_ip_hash: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
||||
view_count, created_at, revoked_at";
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 96 random bits, 16 URL-safe characters.
|
||||
fn new_slug() -> String {
|
||||
@@ -89,6 +140,7 @@ pub struct CreateShare {
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
headers: HeaderMap,
|
||||
WithRejection(Json(req), _): Body<CreateShare>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
|
||||
@@ -130,19 +182,22 @@ pub async fn create(
|
||||
if let Some(row) = open {
|
||||
return Ok((StatusCode::OK, Json(row.view(&state.config.public_base_url))));
|
||||
}
|
||||
let slug = new_slug();
|
||||
let row: ShareRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {SHARE_COLUMNS}"
|
||||
"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}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(new_slug())
|
||||
.bind(&slug)
|
||||
.bind(kind)
|
||||
.bind(chart_id)
|
||||
.bind(synastry_id)
|
||||
.bind(analysis_id)
|
||||
.bind(title)
|
||||
.bind(req.show_birth_data)
|
||||
.bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip)))
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
|
||||
@@ -242,14 +297,61 @@ async fn latest_summary(db: &PgPool, chart_id: Uuid) -> Result<Value, sqlx::Erro
|
||||
})
|
||||
}
|
||||
|
||||
/// Public: the shared content for the share page and its OG image.
|
||||
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).
|
||||
pub async fn public_view(State(state): St, Path(slug): Path<String>) -> ApiResult<Json<Value>> {
|
||||
let share: ShareRow = sqlx::query_as(&format!(
|
||||
"UPDATE shares SET view_count = view_count + 1 WHERE slug = $1 AND revoked_at IS NULL RETURNING {SHARE_COLUMNS}"
|
||||
))
|
||||
.bind(slug.trim())
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("share"))?;
|
||||
let share = open_share(&state.db, &slug).await?;
|
||||
Ok(Json(public_body(&state.db, &share).await?))
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user