Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 75 additions & 12 deletions crates/chatd/src/adapters/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,11 @@ struct Account {
send_tx: std::sync::mpsc::Sender<SendWork>,
/// Dedicated low-priority background crawl / media fetch worker channel.
bg_tx: std::sync::mpsc::Sender<BgWork>,
/// The links looked up for this account, each with its preview or with none. What had no
/// preview is kept in the store, so a restart does not ask for it again.
unfurls: Arc<Mutex<crate::unfurl::Cache>>,
/// Where links wait for the one thread that looks them up.
unfurl_queue: crate::unfurl::Queue,
}

impl Account {
Expand Down Expand Up @@ -987,6 +992,8 @@ fn connect(
sims: Mutex::default(),
send_tx: send_tx.clone(),
bg_tx: bg_tx.clone(),
unfurls: Arc::new(Mutex::new(load_unfurls(ctx))),
unfurl_queue: crate::unfurl::Queue::start(),
});
ctx.capabilities(capability_ceiling());
let _ = ctx.describe(
Expand Down Expand Up @@ -1672,6 +1679,17 @@ fn is_known_contact(account: &Account, chat: Option<&Chat>, outgoing: bool) -> b
true
}

/// Where the links are kept that an earlier run looked up and found no preview for.
const UNFURL_NOTE: &str = "messages-unfurls";

/// The cache as an earlier run left it. Only links without a preview are in it: one with a
/// preview keeps that on its message.
fn load_unfurls(ctx: &Context) -> crate::unfurl::Cache {
ctx.note(UNFURL_NOTE)
.map(|kept| crate::unfurl::Cache::read(&kept))
.unwrap_or_default()
}

fn maybe_unfurl(account: &Account, conversation: &str, message_id: &str, text: &str, outgoing: bool) {
let Some(url) = crate::unfurl::extract_url(text) else {
return;
Expand All @@ -1689,22 +1707,43 @@ fn maybe_unfurl(account: &Account, conversation: &str, message_id: &str, text: &
if !should_unfurl(chat.as_ref(), known, link_previews, allow_unknown) {
return;
}
// Looked up before, on this or an earlier run, and there is no preview to show.
if account
.unfurls
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(&url)
.is_some_and(|kept| kept.is_none())
{
return;
}
let ctx = account.ctx.clone();
let unfurls = account.unfurls.clone();
let conversation = conversation.to_owned();
let message_id = message_id.to_owned();
let _ = std::thread::Builder::new()
.name("messages-unfurl".into())
.spawn(move || {
let Some(preview) = crate::unfurl::fetch(&url) else {
return;
};
if let Ok(Some(mut stored)) = ctx.stored_message(&conversation, &message_id) {
if stored.previews.is_empty() {
stored.previews.push(preview);
let _ = ctx.message(&conversation, &stored);
}
account.unfurl_queue.add(Box::new(move || {
// A signed-out account has no message left to show a preview on, so its page is not asked for.
if ctx.stopped() {
return;
}
let (preview, changed) = crate::unfurl::fetch_with_cache(&url, &unfurls);
if changed {
let kept = unfurls
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.kept();
ctx.set_note(UNFURL_NOTE, &kept);
}
let Some(preview) = preview else {
return;
};
if let Ok(Some(mut stored)) = ctx.stored_message(&conversation, &message_id) {
if stored.previews.is_empty() {
stored.previews.push(preview);
let _ = ctx.message(&conversation, &stored);
}
});
}
}));
}

fn message(account: &Account, note: &bugle::Note, page: &[bugle::Note]) -> Message {
Expand Down Expand Up @@ -4582,6 +4621,28 @@ mod tests {
assert_eq!(filled_note("42"), "messages-filled:42");
}

#[test]
fn the_links_without_a_preview_from_an_earlier_run_are_found_again() {
let hub = Arc::new(crate::hub::Hub::new(
crate::store::Store::open(std::path::Path::new(":memory:")).expect("memory store"),
));
let key = protocol::AccountKey { network: protocol::Network::Messages, account: "phone-unfurls".into() };
let (_adapter, ctx, _inbox) = crate::adapters::local(key, hub);
assert_eq!(load_unfurls(&ctx).get("https://example.com/gone"), None, "nothing was kept yet");

let mut lookups = crate::unfurl::Cache::default();
lookups.insert("https://example.com/gone", None);
lookups.insert(
"https://example.com/page",
crate::unfurl::parse_html("https://example.com/page", "<title>Page</title>"),
);
ctx.set_note(UNFURL_NOTE, &lookups.kept());

let again = load_unfurls(&ctx);
assert_eq!(again.get("https://example.com/gone"), Some(None), "a link without a preview is not asked for again");
assert_eq!(again.get("https://example.com/page"), None, "a link with a preview keeps it on its message");
}

#[test]
fn a_scheduled_text_survives_a_restart_and_one_missed_while_off_fails() {
let hub = Arc::new(crate::hub::Hub::new(
Expand Down Expand Up @@ -4736,6 +4797,8 @@ mod tests {
sims: Mutex::default(),
send_tx: std::sync::mpsc::channel().0,
bg_tx: std::sync::mpsc::channel().0,
unfurls: Arc::default(),
unfurl_queue: crate::unfurl::Queue::start(),
}
}

Expand Down
31 changes: 26 additions & 5 deletions crates/chatd/src/adapters/messages/fake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ impl Fake {
mine: ME.into(),
peer: GRACE_PARTICIPANT.into(),
carrier: 0,
updated: 0,
updated: scripted_updated(GRACE),
phones: false,
status: 1,
read_only: false,
Expand Down Expand Up @@ -135,7 +135,7 @@ impl Fake {
mine: ME.into(),
peer: String::new(),
carrier: 0,
updated: 0,
updated: scripted_updated(CLUB),
phones: false,
status: 1,
read_only: false,
Expand Down Expand Up @@ -297,14 +297,35 @@ impl Fake {
}
}

/// True while `TINYCLIENT_MESSAGES_MANY=100` scripts one conversation of 100 messages.
fn many() -> bool {
std::env::var("TINYCLIENT_MESSAGES_MANY").ok().as_deref() == Some("100")
}

/// When the phone's chat list says the newest message of `conversation` was sent. chatd compares
/// it with the newest message it stored, and asks nothing of a chat nothing arrived in. 0: this
/// phone holds nothing for it.
fn scripted_updated(conversation: &str) -> i64 {
if conversation == GRACE && many() {
SCRIPTED_AT + SCRIPTED_LINES
} else {
0
}
}

/// When the scripted lines were sent: line `n` at `SCRIPTED_AT + n` seconds, so the newest
/// line is the newest message the phone holds for Grace's chat.
const SCRIPTED_AT: i64 = 1_700_000_000;
const SCRIPTED_LINES: i64 = 100;

/// `TINYCLIENT_MESSAGES_MANY=100` is one conversation of 100 messages, newest page first.
/// A cursor id `m-NNNN` is exclusive: the next page ends at the message before it.
fn scripted_page(conversation: &str, before: Option<&str>) -> Vec<Note> {
if conversation != GRACE || std::env::var("TINYCLIENT_MESSAGES_MANY").ok().as_deref() != Some("100") {
if conversation != GRACE || !many() {
return Vec::new();
}
let end = match before {
None => 100,
None => SCRIPTED_LINES,
Some(id) => {
let Some(n) = id.strip_prefix("m-").and_then(|n| n.parse::<i64>().ok()) else {
return Vec::new();
Expand All @@ -319,7 +340,7 @@ fn scripted_page(conversation: &str, before: Option<&str>) -> Vec<Note> {
(start..=end)
.map(|n| {
let mut line = note(GRACE, "Grace Ombra", GRACE, &format!("m-{n:04}"), &format!("line {n}"), false, Vec::new(), Vec::new());
line.sent = 1_700_000_000 + n;
line.sent = SCRIPTED_AT + n;
// The 90th-newest line. A photo here is older than the first page, so a shared
// search that only saw that page would miss it.
if n == 11 {
Expand Down
Loading
Loading