//! Generic profile harvesting from JSON API responses.
use std::collections::HashMap;
use serde_json::Value;
use super::Profile;
use crate::util;
const NAME_KEYS: &[&str] = &[
"display_name",
"displayname",
"full_name",
"fullname",
"realname",
"real_name",
"name",
"nickname",
"title",
];
const BIO_KEYS: &[&str] = &[
"bio",
"about",
"aboutme",
"about_me",
"biography",
"description",
"summary",
"note",
"public_description",
"tagline",
"status_text",
];
const AVATAR_KEYS: &[&str] = &[
"avatar_url",
"avatarurl",
"avatar",
"profile_image_url",
"profile_image",
"icon_img",
"avatar_static",
"picture",
"image",
"thumbnail",
"photo",
"logo",
"thumbnailurl",
"thumbnail_url",
];
const LOCATION_KEYS: &[&str] = &[
"location",
"city",
"country",
"region",
"geo",
"home_location",
];
const WEBSITE_KEYS: &[&str] = &[
"website",
"blog",
"homepage",
"website_url",
"websiteurl",
"site_url",
"personal_url",
"url",
"html_url",
"link",
];
const JOINED_KEYS: &[&str] = &[
"created_at",
"createdat",
"created",
"joined",
"joined_at",
"registered",
"registration",
"date_joined",
"datejoined",
"member_since",
"created_utc",
"join_date",
"registration_date",
];
const FOLLOWERS_KEYS: &[&str] = &[
"followers_count",
"followerscount",
"follower_count",
"followers",
"subscribers_count",
"subscribers",
"subscriber_count",
"fans",
];
const FOLLOWING_KEYS: &[&str] = &[
"following_count",
"followingcount",
"following",
"friends_count",
"friends",
"follows",
];
const USERNAME_KEYS: &[&str] = &[
"login",
"username",
"handle",
"screen_name",
"acct",
"user_name",
"nick",
];
const EXTRA_KEYS: &[&str] = &[
"public_repos",
"public_gists",
"total_karma",
"comment_karma",
"link_karma",
"statuses_count",
"posts_count",
"editcount",
"reputation",
"rating",
"level",
"verified",
"is_verified",
"gender",
"company",
"job_title",
"jobtitle",
"pronouns",
"timezone",
"language",
"locale",
"country_code",
"twitter_username",
"github_username",
"discord",
];
const LINK_LIST_KEYS: &[&str] = &[
"urls",
"links",
"sameas",
"same_as",
"external_urls",
"social_links",
"socials",
"accounts",
"fields",
"profiles",
"websites",
];
#[derive(Default)]
struct Depths {
d: HashMap<&'static str, usize>,
}
impl Depths {
fn better(&mut self, field: &'static str, depth: usize) -> bool {
match self.d.get(field) {
Some(&cur) if cur <= depth => false,
_ => {
self.d.insert(field, depth);
true
}
}
}
}
fn clean(s: &str, max: usize) -> Option<String> {
let t = util::strip_tags(s);
let t = t.trim();
if t.is_empty() {
None
} else {
Some(util::truncate(t, max))
}
}
fn as_count(v: &Value) -> Option<u64> {
match v {
Value::Number(n) => n
.as_u64()
.or_else(|| n.as_f64().filter(|f| *f >= 0.0).map(|f| f as u64)),
Value::String(s) => s.trim().replace([',', ' '], "").parse::<u64>().ok(),
_ => None,
}
}
fn as_date(v: &Value) -> Option<String> {
match v {
Value::String(s) => clean(s, 40).map(|d| {
if d.len() >= 10 && d.as_bytes()[4] == b'-' {
d[..10].to_string()
} else {
d
}
}),
Value::Number(n) => {
let f = n.as_f64()?;
let secs = if f > 1e11 { f / 1000.0 } else { f };
if !(1e8..1e11).contains(&secs) {
return None;
}
chrono::DateTime::from_timestamp(secs as i64, 0)
.map(|d| d.format("%Y-%m-%d").to_string())
}
_ => None,
}
}
fn is_http(s: &str) -> bool {
s.starts_with("http://") || s.starts_with("https://")
}
fn key_rank(keys: &[&str], key: &str) -> Option<usize> {
keys.iter().position(|k| *k == key)
}
struct Walker<'a> {
profile: Profile,
links: Vec<String>,
depths: Depths,
website_rank: usize,
name_rank: usize,
account: &'a str,
}
impl Walker<'_> {
fn consider(&mut self, key: &str, val: &Value, depth: usize) {
let k = key.to_ascii_lowercase();
let ks = k.as_str();
if let Some(rank) = key_rank(NAME_KEYS, ks) {
if let Some(s) = val.as_str().and_then(|s| clean(s, 120)) {
// Prefer explicit display-name keys over a bare `name`/`title`.
if self.depths.better("name", depth)
|| (self.depths.d.get("name") == Some(&depth) && rank < self.name_rank)
{
self.profile.name = Some(s);
self.name_rank = rank;
self.depths.d.insert("name", depth);
}
}
} else if BIO_KEYS.contains(&ks) {
if let Some(s) = val.as_str().and_then(|s| clean(s, 400)) {
if self.depths.better("bio", depth) {
self.profile.bio = Some(s);
}
}
} else if AVATAR_KEYS.contains(&ks) {
let url = match val {
Value::String(s) => Some(s.clone()),
Value::Object(o) => o
.get("url")
.or_else(|| o.get("src"))
.and_then(Value::as_str)
.map(String::from),
_ => None,
};
if let Some(u) = url.filter(|u| is_http(u) || u.starts_with("//")) {
if self.depths.better("avatar", depth) {
self.profile.avatar = Some(if u.starts_with("//") {
format!("https:{u}")
} else {
u
});
}
}
} else if LOCATION_KEYS.contains(&ks) {
if let Some(s) = val.as_str().and_then(|s| clean(s, 80)) {
if self.depths.better("location", depth) {
self.profile.location = Some(s);
}
}
} else if let Some(rank) = key_rank(WEBSITE_KEYS, ks) {
if let Some(s) = val.as_str().map(str::trim).filter(|s| is_http(s)) {
self.links.push(s.to_string());
let lower = s.to_ascii_lowercase();
let self_ref =
!self.account.is_empty() && lower.contains(&self.account.to_ascii_lowercase());
let api_ref = lower.contains("://api.")
|| lower.contains("/api/")
|| lower.contains("/oauth");
if !self_ref
&& !api_ref
&& (self.profile.website.is_none() || rank < self.website_rank)
{
self.profile.website = Some(util::truncate(s, 200));
self.website_rank = rank;
}
}
} else if JOINED_KEYS.contains(&ks) {
if let Some(d) = as_date(val) {
if self.depths.better("joined", depth) {
self.profile.joined = Some(d);
}
}
} else if FOLLOWERS_KEYS.contains(&ks) {
if let Some(n) = as_count(val) {
if self.depths.better("followers", depth) {
self.profile.followers = Some(n);
}
}
} else if FOLLOWING_KEYS.contains(&ks) {
if let Some(n) = as_count(val) {
if self.depths.better("following", depth) {
self.profile.following = Some(n);
}
}
} else if ks == "email" {
if let Some(s) = val.as_str().filter(|s| s.contains('@') && s.len() < 120) {
if self.depths.better("email", depth) {
self.profile.email = Some(s.trim().to_string());
}
}
} else if USERNAME_KEYS.contains(&ks) {
if let Some(s) = val.as_str().and_then(|s| clean(s, 80)) {
if self.depths.better("username", depth) {
self.profile.extra.insert("username".into(), s);
}
}
} else if ks == "id" && depth <= 2 {
let id = match val {
Value::String(s) => clean(s, 64),
Value::Number(n) => Some(n.to_string()),
_ => None,
};
if let Some(id) = id {
if self.depths.better("id", depth) {
self.profile.extra.insert("id".into(), id);
}
}
} else if EXTRA_KEYS.contains(&ks) {
let s = match val {
Value::String(s) => clean(s, 80),
Value::Number(n) => Some(n.to_string()),
Value::Bool(b) => Some(b.to_string()),
_ => None,
};
if let Some(s) = s {
if self.depths.better(
EXTRA_KEYS[EXTRA_KEYS.iter().position(|k| *k == ks).unwrap()],
depth,
) {
self.profile.extra.insert(k.clone(), s);
}
}
} else if LINK_LIST_KEYS.contains(&ks) {
match val {
Value::Array(items) => {
for item in items.iter().take(40) {
match item {
Value::String(s) if is_http(s) => self.links.push(s.clone()),
Value::Object(o) => {
for key in ["url", "value", "href", "link"] {
if let Some(s) = o.get(key).and_then(Value::as_str) {
self.links.extend(urls_in(s));
}
}
}
_ => {}
}
}
}
Value::String(s) => self.links.extend(urls_in(s)),
Value::Object(o) => {
for (_, v) in o {
if let Some(s) = v.as_str() {
self.links.extend(urls_in(s));
}
}
}
_ => {}
}
}
}
fn walk(&mut self, v: &Value, depth: usize) {
match v {
Value::Object(map) => {
for (k, val) in map {
self.consider(k, val, depth);
if depth < 5 {
self.walk(val, depth + 1);
}
}
}
Value::Array(items) => {
for item in items.iter().take(25) {
if depth < 5 {
self.walk(item, depth + 1);
}
}
}
Value::String(s) if depth <= 3 && is_http(s) && s.len() < 300 => {
self.links.push(s.clone());
}
_ => {}
}
}
}
/// Pull every URL out of a string (Mastodon fields carry HTML).
pub fn urls_in(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = s;
while let Some(idx) = rest.find("http") {
let tail = &rest[idx..];
if !(tail.starts_with("http://") || tail.starts_with("https://")) {
rest = &tail[4..];
continue;
}
let end = tail
.find(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '<' | '>' | ')' | ']'))
.unwrap_or(tail.len());
out.push(tail[..end].trim_end_matches(['.', ',']).to_string());
rest = &tail[end..];
}
out
}
/// Harvest a profile from an arbitrary JSON document. Also returns every URL seen.
pub fn extract(body: &str, account: &str) -> (Profile, Vec<String>) {
let Ok(v) = serde_json::from_str::<Value>(body) else {
return (Profile::default(), Vec::new());
};
let mut w = Walker {
profile: Profile::default(),
links: Vec::new(),
depths: Depths::default(),
website_rank: usize::MAX,
name_rank: usize::MAX,
account,
};
w.walk(&v, 0);
(w.profile, w.links)
}
/// Merge a JSON-LD value (Person / ProfilePage) into an existing profile.
pub fn merge_jsonld(v: &Value, profile: &mut Profile, links: &mut Vec<String>) {
fn find_person<'a>(v: &'a Value, out: &mut Vec<&'a Value>, depth: usize) {
if depth > 6 {
return;
}
match v {
Value::Object(o) => {
let ty = o.get("@type").map(|t| match t {
Value::String(s) => s.to_ascii_lowercase(),
Value::Array(a) => a
.iter()
.filter_map(Value::as_str)
.map(|s| s.to_ascii_lowercase())
.collect::<Vec<_>>()
.join(","),
_ => String::new(),
});
if ty
.as_deref()
.is_some_and(|t| t.contains("person") || t.contains("organization"))
{
out.push(v);
}
for (_, val) in o {
find_person(val, out, depth + 1);
}
}
Value::Array(a) => {
for x in a {
find_person(x, out, depth + 1);
}
}
_ => {}
}
}
let mut people = Vec::new();
find_person(v, &mut people, 0);
for p in people.into_iter().take(2) {
let mut w = Walker {
profile: std::mem::take(profile),
links: Vec::new(),
depths: Depths::default(),
website_rank: usize::MAX,
name_rank: usize::MAX,
account: "",
};
// Existing fields count as depth 0 so JSON-LD only fills gaps.
for f in [
"name",
"bio",
"avatar",
"location",
"joined",
"followers",
"following",
"email",
"username",
"id",
] {
let present = match f {
"name" => w.profile.name.is_some(),
"bio" => w.profile.bio.is_some(),
"avatar" => w.profile.avatar.is_some(),
"location" => w.profile.location.is_some(),
"joined" => w.profile.joined.is_some(),
"followers" => w.profile.followers.is_some(),
"following" => w.profile.following.is_some(),
"email" => w.profile.email.is_some(),
_ => w.profile.extra.contains_key(f),
};
if present {
w.depths.d.insert(f, 0);
}
}
w.walk(p, 1);
*profile = w.profile;
links.extend(w.links);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn github_like() {
let body = r#"{"login":"octocat","id":583231,"avatar_url":"https://avatars.githubusercontent.com/u/583231?v=4","html_url":"https://github.com/octocat","name":"The Octocat","company":"@github","blog":"https://github.blog","location":"San Francisco","email":null,"bio":"Loves <b>cats</b>","twitter_username":"octocat","public_repos":8,"followers":19000,"following":9,"created_at":"2011-01-25T18:44:36Z"}"#;
let (p, links) = extract(body, "octocat");
assert_eq!(p.name.as_deref(), Some("The Octocat"));
assert_eq!(p.bio.as_deref(), Some("Loves cats"));
assert_eq!(p.location.as_deref(), Some("San Francisco"));
assert_eq!(p.website.as_deref(), Some("https://github.blog"));
assert_eq!(p.followers, Some(19000));
assert_eq!(p.following, Some(9));
assert_eq!(p.joined.as_deref(), Some("2011-01-25"));
assert_eq!(p.extra.get("username").map(String::as_str), Some("octocat"));
assert_eq!(p.extra.get("public_repos").map(String::as_str), Some("8"));
assert!(p.avatar.as_deref().unwrap().starts_with("https://avatars"));
assert!(links.iter().any(|l| l == "https://github.com/octocat"));
}
#[test]
fn reddit_like_nested_and_timestamps() {
let body = r#"{"kind":"t2","data":{"name":"spez","subreddit":{"title":"Steve","public_description":"admin"},"icon_img":"https://img/x.png","total_karma":12345,"created_utc":1118030400.0}}"#;
let (p, _) = extract(body, "spez");
assert_eq!(p.name.as_deref(), Some("spez"));
assert_eq!(p.bio.as_deref(), Some("admin"));
assert_eq!(p.joined.as_deref(), Some("2005-06-06"));
assert_eq!(
p.extra.get("total_karma").map(String::as_str),
Some("12345")
);
}
#[test]
fn mastodon_fields_and_jsonld() {
let body = r#"{"username":"alice","display_name":"Alice","note":"<p>hi</p>","followers_count":"1,200","fields":[{"name":"Web","value":"<a href=\"https://alice.example\">alice.example</a>"}]}"#;
let (p, links) = extract(body, "alice");
assert_eq!(p.name.as_deref(), Some("Alice"));
assert_eq!(p.followers, Some(1200));
assert!(links.contains(&"https://alice.example".to_string()));
let ld: Value = serde_json::from_str(r#"{"@context":"https://schema.org","@type":"ProfilePage","mainEntity":{"@type":"Person","name":"Bob","description":"dev","sameAs":["https://twitter.com/bob"]}}"#).unwrap();
let mut p = Profile::default();
let mut l = Vec::new();
merge_jsonld(&ld, &mut p, &mut l);
assert_eq!(p.name.as_deref(), Some("Bob"));
assert_eq!(p.bio.as_deref(), Some("dev"));
assert!(l.contains(&"https://twitter.com/bob".to_string()));
assert_eq!(
urls_in("see https://a.b/c, and <a href=\"https://d.e\">"),
vec!["https://a.b/c", "https://d.e"]
);
}
}