Spaces:
Running

backend / services /click /source_detector.py
paisaly's picture
Upload 321 files
fce020b verified
Raw History Blame Contribute Delete
6.84 kB
"""
Paisaly 3-Layer Social Media Source Detector & Salted Visitor Hash Engine.
Solves two critical real-world monetization challenges:
1. Mobile apps (Instagram, YouTube, Facebook, Telegram, Snapchat, TikTok, WhatsApp)
frequently strip the HTTP `Referer` header when opening links inside their
in-app webviews. We inspect:
- Layer 1: Explicit `?s=` or `utm_source=` query tag (e.g. `?s=ig`, `?s=yt`, `?s=tg`)
- Layer 2: In-App Browser User-Agent signatures (`Instagram`, `FBAN`/`FBAV`, `YouTube`, `Telegram`, `BytedanceWebview`, `Snapchat`, `WhatsApp`, `Twitter`)
- Layer 3: HTTP `Referer` hostname mapping (`youtu.be`, `l.instagram.com`, `t.me`, `t.co`, `reddit.com`, etc.)
2. Privacy-safe Visitor Hash (`visitor_hash`) for 24h unique click deduplication:
- Masks IPv4 to `/24` or IPv6 to `/64` (or full IP + daily salt) and hashes with SHA-256.
- Raw IP is NEVER stored in PostgreSQL (Rule 8).
"""
from __future__ import annotations
import hashlib
import ipaddress
from datetime import date, datetime, timezone
from urllib.parse import urlparse
_SHORT_TAG_MAP: dict[str, str] = {
"ig": "Instagram",
"insta": "Instagram",
"instagram": "Instagram",
"yt": "YouTube",
"youtube": "YouTube",
"tg": "Telegram",
"telegram": "Telegram",
"fb": "Facebook",
"facebook": "Facebook",
"wa": "WhatsApp",
"whatsapp": "WhatsApp",
"tw": "Twitter / X",
"x": "Twitter / X",
"twitter": "Twitter / X",
"rd": "Reddit",
"reddit": "Reddit",
"sc": "Snapchat",
"snapchat": "Snapchat",
"tt": "TikTok",
"tiktok": "TikTok",
"dc": "Discord",
"discord": "Discord",
}
_UA_SIGNATURES: list[tuple[tuple[str, ...], str]] = [
(("instagram",), "Instagram"),
(("fban", "fbav", "fb_iab", "fb4a", "messenger"), "Facebook"),
(("com.google.android.youtube", "youtube/"), "YouTube"),
(("telegram", "tgwebview"), "Telegram"),
(("whatsapp",), "WhatsApp"),
(("snapchat",), "Snapchat"),
(("bytedancewebview", "musical_ly", "tiktok"), "TikTok"),
(("twitter", "twitterandroid"), "Twitter / X"),
(("linkedinapp",), "LinkedIn"),
(("pinterest",), "Pinterest"),
(("reddit",), "Reddit"),
]
_REFERRER_HOST_MAP: list[tuple[tuple[str, ...], str]] = [
(("instagram.com", "ig.me"), "Instagram"),
(("youtube.com", "youtu.be", "m.youtube.com"), "YouTube"),
(("t.me", "telegram.org", "telegram.me", "web.telegram.org"), "Telegram"),
(("facebook.com", "fb.com", "fb.me", "m.facebook.com", "l.facebook.com", "lm.facebook.com"), "Facebook"),
(("whatsapp.com", "wa.me"), "WhatsApp"),
(("t.co", "twitter.com", "x.com"), "Twitter / X"),
(("reddit.com", "out.reddit.com"), "Reddit"),
(("snapchat.com",), "Snapchat"),
(("tiktok.com",), "TikTok"),
(("discord.com", "discordapp.com"), "Discord"),
(("google.", "bing.com", "duckduckgo.com", "search.yahoo.com"), "Search"),
]
def detect_social_source(
*,
user_agent: str | None,
referrer: str | None,
source_param: str | None = None,
utm_source: str | None = None,
) -> str:
"""Detect the social platform / traffic source using our 3-layer waterfall.
Priority:
1. Explicit query parameter (`?s=ig` or `?utm_source=youtube`)
2. In-App Webview User-Agent signature (catches mobile apps that strip Referer)
3. HTTP Referer domain mapping
4. Fallback: "Direct"
"""
# Layer 1: Explicit query tag
for tag in (source_param, utm_source):
if tag:
cleaned = tag.strip().lower()
if cleaned in _SHORT_TAG_MAP:
return _SHORT_TAG_MAP[cleaned]
# Layer 2: In-App Browser User-Agent inspection
ua_lower = (user_agent or "").lower()
if ua_lower:
for tokens, platform_name in _UA_SIGNATURES:
if any(tok in ua_lower for tok in tokens):
return platform_name
# Layer 3: Referer header hostname inspection
if referrer:
try:
parsed = urlparse(referrer.strip())
host = (parsed.hostname or "").lower().rstrip(".")
if host:
for domains, platform_name in _REFERRER_HOST_MAP:
if any(host == d or host.endswith("." + d) or d in host for d in domains):
return platform_name
# Return clean registrable-style host if it's an external website
return host.removeprefix("www.").removeprefix("m.").removeprefix("l.")
except Exception:
pass
return "Direct"
def detect_in_app_browser_name(user_agent: str | None, fallback_browser: str) -> str:
"""Enrich browser family name when opened inside a social media in-app webview."""
ua_lower = (user_agent or "").lower()
if "instagram" in ua_lower:
return "Instagram App"
if any(t in ua_lower for t in ("fban", "fbav", "fb_iab")):
return "Facebook App"
if "telegram" in ua_lower or "tgwebview" in ua_lower:
return "Telegram App"
if "com.google.android.youtube" in ua_lower:
return "YouTube App"
return fallback_browser or "Unknown"
def mask_ip_subnet(ip_str: str) -> str:
"""Mask IPv4 to /24 or IPv6 to /64 for privacy-compliant fingerprinting."""
raw = (ip_str or "").strip()
if not raw:
return "0.0.0.0/24"
try:
addr = ipaddress.ip_address(raw)
if isinstance(addr, ipaddress.IPv4Address):
net = ipaddress.IPv4Network(f"{raw}/24", strict=False)
return str(net.network_address)
net6 = ipaddress.IPv6Network(f"{raw}/64", strict=False)
return str(net6.network_address)
except ValueError:
return raw
def compute_visitor_hash(
*,
client_ip: str,
user_agent: str,
secret_salt: str,
for_date: date | None = None,
) -> str:
"""Compute a privacy-safe daily salted SHA-256 visitor fingerprint.
Never stores the raw IP. Combines the raw IP + normalized UA + daily salt
so the same user on the same IP+device produces the exact same hash within
a 24h window, while preventing reverse IP lookup.
"""
day_str = (for_date or datetime.now(timezone.utc).date()).isoformat()
ua_norm = (user_agent or "").strip().lower()[:256]
ip_norm = (client_ip or "").strip()
payload = f"{day_str}|{ip_norm}|{ua_norm}|{secret_salt}"
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:32]
def compute_earnings_paise(valid_clicks: int, cpm_paise: int) -> int:
"""Compute integer paise earned for `valid_clicks` at `cpm_paise` per 1,000 clicks.
Default `cpm_paise = 500` (₹5.00 per 1,000 clicks):
- 1,000 valid clicks -> 500 paise (₹5.00)
- 200,000 valid clicks -> 100,000 paise (₹1,000.00)
"""
if valid_clicks <= 0 or cpm_paise <= 0:
return 0
return (valid_clicks * cpm_paise) // 1000