bg bugfix

This commit is contained in:
yves committed 2026-11-20 23:48:30 +01:00
1 parent 7eace57528
commit c30fddb1ef
14 files changed
+3809 -12

No files matched your search

+611
View File
@@ -0,0 +1,611 @@
//! The Dart-facing API: one opaque [`Meow`] object per open identity.
//!
//! An open identity always runs its background synchronisation (`meow_client`
//! `ClientHandle`); the app listens to [`Meow::events`] and calls methods, all
//! `async`. Types ending in `View` are plain data copied to Dart.
//!
//! Every call runs on a crate-owned multi-threaded tokio runtime (HTTP, timers and the
//! background task need tokio, whatever executor flutter_rust_bridge uses).
use std::future::Future;
use std::sync::{Arc, Mutex, OnceLock};
use anyhow::{anyhow, Result};
use flutter_rust_bridge::frb;
use meow_client::{BackgroundOptions, ClientHandle, Content, Event, MeowClient, ReceiptKind, Settings, Status};
use meow_crypto::password::KdfParams;
use tokio::sync::broadcast::error::RecvError;
use crate::frb_generated::StreamSink;
const INVITATION_TTL: u64 = meow_client::DEFAULT_INVITATION_TTL;
fn runtime() -> &'static tokio::runtime::Runtime {
static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
RT.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("meow")
.enable_all()
.build()
.unwrap_or_else(|e| panic!("cannot start the meow runtime: {e}"))
})
}
/// Run `f` on the meow runtime.
async fn run<T: Send + 'static>(f: impl Future<Output = Result<T>> + Send + 'static) -> Result<T> {
runtime()
.spawn(f)
.await
.map_err(|e| anyhow!("internal task failed: {e}"))?
}
/// Called once by the generated Dart `RustLib.init()`.
#[frb(init)]
pub fn init_app() {
flutter_rust_bridge::setup_default_user_utils();
}
// ───────────────────────────── views ─────────────────────────────
pub struct ServerView {
pub url: String,
pub name: String,
/// Short fingerprint of the server signing key (to compare out of band).
pub fingerprint: String,
}
pub enum ContactStatus {
/// I invited them; waiting for their answer.
OfferSent,
/// I answered their invitation; waiting for their confirmation.
AnswerSent,
/// I confirmed; I can already write, waiting for their acknowledgement.
ConfirmSent,
Active,
}
pub struct ContactView {
pub id: String,
/// My name for this contact.
pub name: String,
/// The name I present to them.
pub my_name: String,
/// The name they gave themselves.
pub peer_name: Option<String>,
pub status: ContactStatus,
/// Lives in an (unlocked) hidden space.
pub hidden: bool,
/// To compare with the contact (same on both sides) once active.
pub safety_number: Option<String>,
pub created_at: i64,
}
pub enum MessageStatus {
/// Outbound, no server accepted it yet.
Queued,
/// Outbound, accepted by a server.
Sent,
/// Reached the recipient's device (inbound: received, unread).
Delivered,
Read,
}
pub struct MessageView {
pub id: Vec<u8>,
pub outbound: bool,
pub sent_at_ms: i64,
pub received_at: i64,
pub text: Option<String>,
pub file_name: Option<String>,
pub file_size: Option<i64>,
pub status: MessageStatus,
}
/// One segment of a conversation, oldest message first.
pub struct HistoryPageView {
pub messages: Vec<MessageView>,
pub page: u32,
/// Older segment to load next, if any.
pub previous: Option<u32>,
}
pub struct InvitationInfo {
pub from: String,
pub message: String,
pub expires_at: i64,
pub servers: Vec<String>,
}
pub struct SendResult {
pub message_id: Vec<u8>,
/// Servers that took the message now; 0 = queued, retried automatically.
pub delivered_to: u32,
}
pub struct PendingSendView {
pub contact: String,
/// Empty for protocol messages (receipts, handshake).
pub message_id: Vec<u8>,
pub accepted: u32,
pub attempts: u32,
pub next_attempt: i64,
}
pub struct SettingsView {
pub delivered_receipts: bool,
pub read_receipts: bool,
}
pub enum MeowEvent {
InvitationAccepted {
contact: String,
},
ContactActivated {
contact: String,
},
Message {
contact: String,
id: Vec<u8>,
text: String,
sent_at_ms: i64,
},
/// The content is in the store: [`Meow::file`].
File {
contact: String,
id: Vec<u8>,
name: String,
size: i64,
},
Receipt {
contact: String,
read: bool,
message_ids: Vec<Vec<u8>>,
},
SendFailed {
contact: String,
message_id: Vec<u8>,
},
/// The listener fell behind and missed events: reload what is displayed.
Lagged {
missed: i64,
},
}
impl From<Event> for MeowEvent {
fn from(e: Event) -> Self {
match e {
Event::InvitationAccepted { contact } => MeowEvent::InvitationAccepted { contact },
Event::ContactActivated { contact } => MeowEvent::ContactActivated { contact },
Event::Message {
contact,
id,
text,
sent_at_ms,
} => MeowEvent::Message {
contact,
id,
text,
sent_at_ms: sent_at_ms as i64,
},
Event::File {
contact,
id,
name,
data,
} => MeowEvent::File {
contact,
id,
name,
size: data.len() as i64,
},
Event::Receipt {
contact,
kind,
message_ids,
} => MeowEvent::Receipt {
contact,
read: kind == ReceiptKind::Read,
message_ids,
},
Event::SendFailed { contact, message_id } => MeowEvent::SendFailed { contact, message_id },
}
}
}
fn message_view(h: meow_client::HistoryEntry) -> MessageView {
let (text, file_name, file_size) = match h.content {
Content::Text(t) => (Some(t), None, None),
Content::File { name, size } => (None, Some(name), Some(size as i64)),
};
MessageView {
id: h.id,
outbound: h.outbound,
sent_at_ms: h.sent_at_ms as i64,
received_at: h.received_at as i64,
text,
file_name,
file_size,
status: match h.status {
Status::Queued => MessageStatus::Queued,
Status::Sent => MessageStatus::Sent,
Status::Delivered => MessageStatus::Delivered,
Status::Read => MessageStatus::Read,
},
}
}
fn server_view(s: &meow_client::ServerInfo) -> ServerView {
ServerView {
url: s.url.clone(),
name: s.name.clone(),
fingerprint: s.sign_key.fingerprint(),
}
}
fn opt(s: Option<String>) -> Option<String> {
s.filter(|x| !x.is_empty())
}
// ───────────────────────────── Meow ─────────────────────────────
/// An open identity, synchronising in the background until [`Meow::close`].
#[frb(opaque)]
pub struct Meow {
inner: Mutex<Option<Arc<ClientHandle>>>,
}
/// Run `$body` with `$c: &mut MeowClient`, on the meow runtime.
macro_rules! with_client {
($self:ident, |$c:ident| $body:expr) => {{
let h = $self.handle()?;
run(async move {
let mut guard = h.lock().await;
let $c: &mut MeowClient = &mut guard;
$body
})
.await
}};
}
impl Meow {
fn start(client: MeowClient) -> Meow {
Meow {
inner: Mutex::new(Some(Arc::new(client.start(BackgroundOptions::default())))),
}
}
fn handle(&self) -> Result<Arc<ClientHandle>> {
self.inner
.lock()
.map_err(|_| anyhow!("poisoned"))?
.clone()
.ok_or_else(|| anyhow!("identity closed"))
}
// ── lifecycle ──
/// Create an identity file. `insecure_fast_kdf` is for tests only.
pub async fn create(
path: String,
nickname: String,
password: String,
overwrite: bool,
insecure_fast_kdf: bool,
) -> Result<Meow> {
let kdf = if insecure_fast_kdf {
KdfParams::INSECURE_TEST
} else {
KdfParams::DEFAULT
};
run(async move {
let c = MeowClient::create(path.as_ref(), &nickname, &password, kdf, overwrite).await?;
Ok(Meow::start(c))
})
.await
}
/// Open an identity with its main password.
pub async fn open(path: String, password: String) -> Result<Meow> {
run(async move { Ok(Meow::start(MeowClient::open(path.as_ref(), &password).await?)) }).await
}
/// Stop synchronising and release the identity file.
pub async fn close(&self) -> Result<()> {
let h = self.inner.lock().map_err(|_| anyhow!("poisoned"))?.take();
if let Some(h) = h {
run(async move {
match Arc::try_unwrap(h) {
Ok(h) => drop(h.stop().await),
// A call is still running: the task stops when it ends.
Err(h) => drop(h),
}
Ok(())
})
.await?;
}
Ok(())
}
/// Every event from now on (messages, receipts, invitations…). The stream ends when
/// the identity is closed: call [`Meow::close`] before cancelling the subscription
/// (a cancel only completes once Rust closes the stream).
pub fn events(&self, sink: StreamSink<MeowEvent>) -> Result<()> {
let mut rx = self.handle()?.subscribe();
runtime().spawn(async move {
loop {
let ev = match rx.recv().await {
Ok(e) => MeowEvent::from(e),
Err(RecvError::Lagged(n)) => MeowEvent::Lagged { missed: n as i64 },
Err(RecvError::Closed) => break,
};
if sink.add(ev).is_err() {
break; // Dart stopped listening
}
}
});
Ok(())
}
pub async fn nickname(&self) -> Result<String> {
with_client!(self, |c| Ok(c.nickname().to_string()))
}
pub async fn change_password(&self, new_password: String) -> Result<()> {
with_client!(self, |c| Ok(c.change_password(&new_password).await?))
}
pub async fn settings(&self) -> Result<SettingsView> {
with_client!(self, |c| {
let s = c.settings();
Ok(SettingsView {
delivered_receipts: s.delivered_receipts,
read_receipts: s.read_receipts,
})
})
}
pub async fn set_settings(&self, settings: SettingsView) -> Result<()> {
with_client!(self, |c| {
c.set_settings(Settings {
delivered_receipts: settings.delivered_receipts,
read_receipts: settings.read_receipts,
})
.await?;
Ok(())
})
}
// ── hidden spaces ──
/// Try a password on the hidden spaces; `true` if one opened (its contacts appear).
/// Silent and equally slow when nothing opens.
pub async fn unlock(&self, password: String) -> Result<bool> {
with_client!(self, |c| Ok(c.unlock(&password).await?))
}
pub async fn hide_contact(&self, name: String, space_password: String) -> Result<()> {
with_client!(self, |c| Ok(c.hide_contact(&name, &space_password).await?))
}
pub async fn reveal_contact(&self, name: String) -> Result<()> {
with_client!(self, |c| Ok(c.reveal_contact(&name).await?))
}
// ── servers ──
pub async fn servers(&self) -> Result<Vec<ServerView>> {
with_client!(self, |c| Ok(c.servers().iter().map(server_view).collect()))
}
/// Fetch, verify and pin a server's card.
pub async fn add_server(&self, url: String) -> Result<ServerView> {
with_client!(self, |c| Ok(server_view(&c.add_server(&url).await?)))
}
pub async fn remove_server(&self, url_or_name: String) -> Result<()> {
with_client!(self, |c| Ok(c.remove_server(&url_or_name).await?))
}
// ── contacts ──
pub async fn contacts(&self) -> Result<Vec<ContactView>> {
with_client!(self, |c| {
let mut out = Vec::new();
for k in c.contacts() {
out.push(ContactView {
id: k.id.0.clone(),
name: k.name.clone(),
my_name: k.my_name.clone(),
peer_name: k.peer.as_ref().map(|p| p.name.clone()),
status: match k.state {
meow_client::State::OfferSent => ContactStatus::OfferSent,
meow_client::State::AnswerSent => ContactStatus::AnswerSent,
meow_client::State::ConfirmSent => ContactStatus::ConfirmSent,
meow_client::State::Active => ContactStatus::Active,
},
hidden: c.is_hidden(&k.name)?,
safety_number: k.safety_number(),
created_at: k.created_at as i64,
});
}
Ok(out)
})
}
/// Delete a contact with its conversation.
pub async fn remove_contact(&self, name: String) -> Result<()> {
with_client!(self, |c| Ok(c.remove_contact(&name).await?))
}
// ── invitations ──
// `space_password`: create the contact directly in that hidden space.
/// Step 1 (file / QR): returns the invitation bytes to hand over.
pub async fn create_invitation(
&self,
contact_name: String,
message: String,
servers: Vec<String>,
space_password: Option<String>,
) -> Result<Vec<u8>> {
with_client!(self, |c| Ok(c
.create_invitation(
&contact_name,
&servers,
&message,
INVITATION_TTL,
opt(space_password).as_deref()
)
.await?))
}
pub async fn inspect_invitation(&self, invitation: Vec<u8>) -> Result<InvitationInfo> {
with_client!(self, |c| {
let i = c.inspect_invitation(&invitation)?;
Ok(InvitationInfo {
from: i.initiator_name,
message: i.message,
expires_at: i.expires_at as i64,
servers: i.answer_servers.iter().map(|s| s.url.clone()).collect(),
})
})
}
/// Step 2 (file / QR): returns the answer bytes to hand back.
pub async fn answer_invitation(
&self,
invitation: Vec<u8>,
contact_name: Option<String>,
servers: Vec<String>,
space_password: Option<String>,
) -> Result<Vec<u8>> {
with_client!(self, |c| Ok(c
.answer_invitation(
&invitation,
opt(contact_name).as_deref(),
&servers,
opt(space_password).as_deref()
)
.await?))
}
/// Step 3 (file / QR): returns the confirmation bytes to hand over.
pub async fn accept_answer(&self, answer: Vec<u8>) -> Result<Vec<u8>> {
with_client!(self, |c| Ok(c.accept_answer(&answer).await?))
}
/// Step 4 (file / QR): returns the contact's name.
pub async fn finalize_invitation(&self, confirmation: Vec<u8>) -> Result<String> {
with_client!(self, |c| Ok(c.finalize_invitation(&confirmation).await?))
}
/// Server invitation: returns the link to share (with the password, out of band).
pub async fn publish_invitation(
&self,
contact_name: String,
message: String,
password: String,
servers: Vec<String>,
space_password: Option<String>,
) -> Result<String> {
with_client!(self, |c| Ok(c
.publish_invitation(
&contact_name,
&servers,
&message,
&password,
INVITATION_TTL,
opt(space_password).as_deref()
)
.await?))
}
/// Answer a server invitation link; returns the inviter's name. The rest of the
/// handshake completes in the background.
pub async fn accept_published_invitation(
&self,
url: String,
password: String,
contact_name: Option<String>,
servers: Vec<String>,
space_password: Option<String>,
) -> Result<String> {
with_client!(self, |c| Ok(c
.accept_published_invitation(
&url,
&password,
opt(contact_name).as_deref(),
&servers,
opt(space_password).as_deref()
)
.await?))
}
// ── messages ──
pub async fn send_text(&self, contact: String, text: String) -> Result<SendResult> {
with_client!(self, |c| {
let r = c.send_text(&contact, &text).await?;
Ok(SendResult {
message_id: r.message_id,
delivered_to: r.delivered_to as u32,
})
})
}
pub async fn send_file(&self, contact: String, file_name: String, data: Vec<u8>) -> Result<SendResult> {
with_client!(self, |c| {
let r = c.send_file_data(&contact, &file_name, data).await?;
Ok(SendResult {
message_id: r.message_id,
delivered_to: r.delivered_to as u32,
})
})
}
/// A segment of the conversation (`None`: the latest), oldest first.
pub async fn history(&self, contact: String, page: Option<u32>) -> Result<HistoryPageView> {
with_client!(self, |c| {
let p = c.history_page(&contact, page.map(|p| p as usize))?;
Ok(HistoryPageView {
messages: p.entries.into_iter().map(message_view).collect(),
page: p.page as u32,
previous: p.prev.map(|p| p as u32),
})
})
}
/// Content of a received file.
pub async fn file(&self, contact: String, message_id: Vec<u8>) -> Result<Option<Vec<u8>>> {
with_client!(self, |c| Ok(c.file(&contact, &message_id)?))
}
/// Mark the conversation read (sends a read receipt unless disabled).
pub async fn mark_read(&self, contact: String) -> Result<u32> {
with_client!(self, |c| Ok(c.mark_read(&contact).await? as u32))
}
/// Messages not yet accepted by every server.
pub async fn pending_sends(&self) -> Result<Vec<PendingSendView>> {
with_client!(self, |c| Ok(c
.pending_sends()
.into_iter()
.map(|p| PendingSendView {
contact: p.contact,
message_id: p.message_id,
accepted: p.accepted,
attempts: p.attempts,
next_attempt: p.next_attempt as i64,
})
.collect()))
}
/// Retry queued messages now (e.g. when the network comes back).
pub async fn flush_outbox(&self) -> Result<()> {
with_client!(self, |c| {
c.flush_outbox().await?;
Ok(())
})
}
}
+1
View File
@@ -0,0 +1 @@
pub mod meow;
File diff suppressed because it is too large. Load diff
+9
View File
@@ -0,0 +1,9 @@
//! Flutter bindings for Meow v2, generated by `flutter_rust_bridge` from [`api`].
//!
//! Everything public in `api` becomes Dart. Hand-written code stays free of `unsafe`;
//! `frb_generated.rs` is generated (`flutter_rust_bridge_codegen generate`, run from
//! the Flutter app) and must not be edited.
pub mod api;
#[rustfmt::skip]
mod frb_generated;