Skip to content
Merged
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
3 changes: 3 additions & 0 deletions settings-ui/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@
"Reintegrar à janela": "Return to the main window",
"Abrir em janela separada": "Open in a separate window",
"Usar ao iniciar": "Use on startup",
"Ativar notificações desta conta": "Turn notifications on for this account",
"Desativar notificações desta conta": "Turn notifications off for this account",
"Notificações desativadas para esta conta": "Notifications are off for this account",
"Renomear": "Rename",
"Renomear conta": "Rename account",
"Informe um nome.": "Enter a name.",
Expand Down
2 changes: 2 additions & 0 deletions settings-ui/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@ function accountMenu(a, accounts, anchor) {
["Abrir conta", () => accountAction(() => invoke("open_account", {id:a.id}))],
...( /Win/.test(navigator.platform || navigator.userAgent) ? [[a.detached ? "Reintegrar à janela" : "Abrir em janela separada", () => accountAction(() => invoke(a.detached?"attach_account":"detach_account",{id:a.id}))]] : []),
["Usar ao iniciar",()=>accountAction(()=>invoke("set_default_account",{id:a.id}))],
[a.notifications===false?"Ativar notificações desta conta":"Desativar notificações desta conta",()=>accountAction(()=>invoke("set_account_notifications",{id:a.id,on:a.notifications===false}))],
["Alterar foto",()=>pickAccountPhoto(a.id)],
...(a.photo?[["Remover foto",()=>accountAction(()=>invoke("remove_account_photo",{id:a.id}))]]:[]),
["Renomear",async()=>{const name=await Dlg.prompt("",{title:"Renomear conta",value:a.name,okLabel:"Renomear",requiredMessage:"Informe um nome."});if(name!==null&&name!==a.name)await accountAction(()=>invoke("rename_account",{id:a.id,name}));}],
Expand Down Expand Up @@ -397,6 +398,7 @@ function renderAccounts(accounts) {
const info=document.createElement("span");info.className="acct-subtitle";info.textContent=a.detached?"Em janela separada":a.is_default?"Conta ao iniciar":"WhatsApp";open.append(name,info);open.onclick=()=>accountAction(()=>invoke("open_account",{id:a.id}));
row.append(avatar,open);
if(a.unread){const badge=document.createElement("span");badge.className="acct-unread";badge.textContent=a.unread;badge.title=t("{0} conversas não lidas",[a.unread]);row.appendChild(badge);}
if(a.notifications===false){const off=document.createElement("span");off.className="acct-muted";off.textContent="🔕";off.title=t("Notificações desativadas para esta conta");off.setAttribute("role","img");off.setAttribute("aria-label",off.title);row.appendChild(off);}
const more=document.createElement("button");more.type="button";more.className="account-more";more.textContent="⋮";more.setAttribute("aria-label",t("Opções de {0}",[a.name]));more.setAttribute("aria-haspopup","menu");more.onclick=()=>accountMenu(a,accounts,more);row.appendChild(more);list.appendChild(row);
}
}
Expand Down
1 change: 1 addition & 0 deletions settings-ui/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ select option { background: var(--bg); color: var(--fg); }
.account-more:hover:not(:disabled), .account-more:focus-visible, .account-more[aria-expanded="true"] { background: var(--control-hover); color: var(--fg); filter: none; }
.account-more:active:not(:disabled) { background: var(--control-active); }
@media(prefers-reduced-motion:reduce) { .account-more { transition:none; } }
.acct-muted { font-size: 12px; opacity: .7; margin-inline-start: 6px; }
.acct-unread { background: var(--green); color: var(--on-green); font-size: 12px; padding: 2px 7px; border-radius: 10px; }
.account-actions { position: fixed; inset: auto; border: 1px solid var(--border); border-radius: 8px; background: var(--card); color: var(--fg); box-shadow: 0 2px 12px #0004; padding: 6px 0; width: 245px; max-width:calc(100vw - 24px); margin: 0; max-height: calc(100vh - 24px);overflow-y:auto;overscroll-behavior:contain; }
.account-actions button { display: block; width: 100%; border-radius: 0; background: transparent; color: inherit; text-align: left; font-size: 14px; font-weight: 400; padding: 12px 22px; }
Expand Down
1 change: 1 addition & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ webkit2gtk = "=2.0.2"
# recovery bar (GtkBox child packing). Same 0.18 line wry uses.
gtk = "0.18"
zbus = "5"
# Already in the tree through tauri-plugin-notification (same default features);
# named directly so Linux notifications can carry the desktop-entry hint (#119).
notify-rust = "4.11"
zbus_polkit = "5.0.0"

[target.'cfg(windows)'.dependencies]
Expand Down
1 change: 1 addition & 0 deletions src-tauri/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ fn main() {
"add_account",
"remove_account",
"rename_account",
"set_account_notifications",
"open_account",
"set_default_account",
"set_app_lock_password",
Expand Down
1 change: 1 addition & 0 deletions src-tauri/capabilities/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"allow-add-account",
"allow-remove-account",
"allow-rename-account",
"allow-set-account-notifications",
"allow-open-account",
"allow-set-default-account",
"allow-get-lock-status",
Expand Down
39 changes: 32 additions & 7 deletions src-tauri/resources/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -631,17 +631,42 @@
lastTitle = document.title;
invoke("set_unread", { title: document.title, settled: Date.now() - pageStart > SETTLE_MS });
}
// WhatsApp rewrites the title itself whenever its own unread state changes
// (new message, opening a chat, "Mark all as read"), so the title is the
// page's own count. The old code only watched the <title> node and polled
// every 2 s, so a swapped <title> node or a quick change could leave the
// badge stale (issue #98). Now: watch <title>, watch <head> (catches a
// replaced <title>), and re-read the title as soon as the chat list changes
// (debounced), so the badge follows within a fraction of a second. The
// poll is only a last resort.
var UNREAD_DEBOUNCE_MS = 120;
var unreadTimer = null;
function reportSoon() {
if (unreadTimer !== null) return;
unreadTimer = setTimeout(function () {
unreadTimer = null;
report();
}, UNREAD_DEBOUNCE_MS);
}
window.__whatrustReportUnread = report;
function start() {
try {
var opts = { childList: true, characterData: true, subtree: true };
var el = document.querySelector("title");
if (el) {
new MutationObserver(report).observe(el, {
childList: true,
characterData: true,
subtree: true,
});
if (el) new MutationObserver(report).observe(el, opts);
if (document.head) new MutationObserver(report).observe(document.head, { childList: true, subtree: true, characterData: true });
// The chat list is built after load: attach once it exists.
var paneWatched = false;
function watchPane() {
if (paneWatched) return;
var pane = document.querySelector("#pane-side");
if (!pane) return;
paneWatched = true;
new MutationObserver(reportSoon).observe(pane, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["aria-label", "class"] });
}
setInterval(report, 2000); // fallback if <title> node is swapped
watchPane();
setInterval(function () { watchPane(); report(); }, 500);
if (document.addEventListener) document.addEventListener("visibilitychange", report);
report();
} catch (e) {}
}
Expand Down
36 changes: 33 additions & 3 deletions src-tauri/resources/bridge.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ function makeHarness(options = {}) {
return [];
},
querySelector(sel) {
if (sel === "title") return null;
if (sel === "title") return options.titleEl || null;
if (sel === "#pane-side") return options.paneEl || null;
if (options.lazyInputs) {
if (sel === '[data-icon="plus"]') return plusButton;
const first = this.querySelectorAll(sel)[0];
Expand Down Expand Up @@ -251,7 +252,7 @@ function makeHarness(options = {}) {
this.type = type;
}
},
MutationObserver: class {
MutationObserver: options.MutationObserver || class {
observe() {}
},
atob: options.atob || ((s) => Buffer.from(s, "base64").toString("binary")),
Expand All @@ -264,7 +265,7 @@ function makeHarness(options = {}) {
return t;
},
clearTimeout,
setInterval: () => 0,
setInterval: options.setInterval || (() => 0),
};
// Evaluate bridge.js with our stubs shadowing the real globals.
const params = Object.keys(sandboxGlobals);
Expand Down Expand Up @@ -751,6 +752,34 @@ async function testUnreadReportsSayWhenThePageHasSettled() {
assert(first && first.args.settled === false, "the first report after load is not settled");
}

async function testUnreadFollowsTitleAndChatListImmediately() {
console.log("unread follows WhatsApp's title and chat-list changes at once (#98)");
const observers = [];
class Obs {
constructor(cb) { this.cb = cb; }
observe(target) { observers.push({ target, cb: this.cb }); }
}
const titleEl = { name: "title" };
const paneEl = { name: "pane" };
const { document, invocations } = makeHarness({ MutationObserver: Obs, titleEl, paneEl });
const sent = () => invocations.filter((x) => x.cmd === "set_unread").map((x) => x.args.title);
assert(observers.some((o) => o.target === titleEl), "the <title> node is watched");
assert(observers.some((o) => o.target === document.head), "<head> is watched, so a replaced <title> is seen");
assert(observers.some((o) => o.target === paneEl), "the chat list is watched");
document.title = "(3) WhatsApp";
observers.find((o) => o.target === titleEl).cb();
assert(sent().includes("(3) WhatsApp"), "a title change is reported without waiting for a poll");
// 'Mark all as read': the title loses its count and the chat list mutates.
document.title = "WhatsApp";
observers.find((o) => o.target === paneEl).cb();
await sleep(250);
assert(sent().at(-1) === "WhatsApp", "a chat-list change re-reads the title and clears the count");
const before = sent().length;
observers.find((o) => o.target === paneEl).cb();
await sleep(250);
assert(sent().length === before, "an unchanged title is not reported again");
}

async function testWindowsNativePreferenceAndFallback() {
let nativeCalls=0;
const healthy=makeHarness({windows:true,preferNative:true,nativeNotification:class {static permission="granted";constructor(){nativeCalls++;}}});
Expand Down Expand Up @@ -1050,6 +1079,7 @@ const tests = [
testDownloadToastOffersOpenAndShowInFolder,
testRiskyDownloadsAndFailures,
testChromeShimsOnlyForAChromeUserAgent,
testUnreadFollowsTitleAndChatListImmediately,
testNotificationsReachTheNativeNotifyCommand,
testNotificationPictureIsForwardedAsPng,
testNotificationSoundMutesAlertTones,
Expand Down
3 changes: 2 additions & 1 deletion src-tauri/resources/notifications.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ test('a throwing privacy mask never drops the notification', () => {

test('unread initialization, changes and clearing reach Rust without repeating unchanged titles', () => {
const { document, calls, intervals } = harness();
const poll = intervals.find(timer => timer.delay === 2000).callback;
const polls = intervals.filter(timer => timer.delay === 500).map(timer => timer.callback);
const poll = () => polls.forEach(callback => { try { callback(); } catch {} });
poll();
document.title = '(4) WhatsApp'; poll();
document.title = 'WhatsApp'; poll(); poll();
Expand Down
51 changes: 51 additions & 0 deletions src-tauri/src/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ pub struct Account {
pub order: u32,
#[serde(default)]
pub store_uuid: Option<[u8; 16]>,
/// Per-account switch for OS notifications and WhatsApp's alert tones.
/// On by default; files written before it existed read as on.
#[serde(default = "default_true")]
pub notifications: bool,
}

fn default_true() -> bool {
true
}

/// The persisted accounts file. `next_seq` is a monotonic counter so a removed-then
Expand All @@ -52,6 +60,7 @@ impl Default for AccountsFile {
name: "WhatsApp".to_string(),
order: 0,
store_uuid: None,
notifications: true,
}],
next_seq: 1,
startup_account: None,
Expand Down Expand Up @@ -79,6 +88,7 @@ pub fn add(f: &mut AccountsFile, name: &str) -> Account {
name: name.to_string(),
order,
store_uuid: Some(gen_store_uuid()),
notifications: true,
};
f.accounts.push(acct.clone());
acct
Expand Down Expand Up @@ -125,6 +135,23 @@ pub fn rename(f: &mut AccountsFile, id: &str, name: &str) -> Result<(), String>
Ok(())
}

/// Turn one account's notifications on or off. Errors if the id is unknown.
pub fn set_notifications(f: &mut AccountsFile, id: &str, on: bool) -> Result<(), String> {
let Some(acct) = f.accounts.iter_mut().find(|a| a.id == id) else {
return Err(trf("Conta não encontrada: {0}", &[&id]));
};
acct.notifications = on;
Ok(())
}

/// Whether the account behind a window label may notify. Unknown accounts
/// count as on, so a stale label never swallows a message.
pub fn notifications_on(f: &AccountsFile, label: &str) -> bool {
id_from_label(label)
.and_then(|id| f.accounts.iter().find(|a| a.id == id))
.is_none_or(|a| a.notifications)
}

/// Exact permutation only: no omitted or repeated accounts.
pub fn reorder(f: &mut AccountsFile, ids: &[String]) -> Result<(), String> {
let unique: std::collections::HashSet<_> = ids.iter().collect();
Expand Down Expand Up @@ -299,6 +326,30 @@ pub fn gen_store_uuid() -> [u8; 16] {
mod tests {
use super::*;

#[test]
fn notifications_default_on_and_old_files_read_as_on() {
let f = AccountsFile::default();
assert!(notifications_on(&f, "wa-default"));
let old: AccountsFile = serde_json::from_str(
r#"{"accounts":[{"id":"default","name":"WhatsApp","order":0}],"next_seq":1}"#,
)
.unwrap();
assert!(old.accounts[0].notifications);
}

#[test]
fn notifications_switch_is_per_account_and_roundtrips() {
let mut f = AccountsFile::default();
let other = add(&mut f, "Work");
set_notifications(&mut f, &other.id, false).unwrap();
assert!(notifications_on(&f, "wa-default"));
assert!(!notifications_on(&f, &window_label(&other.id)));
assert!(notifications_on(&f, "wa-unknown"));
assert!(set_notifications(&mut f, "nope", false).is_err());
let back: AccountsFile = serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap();
assert_eq!(back, f);
}

#[test]
fn reorder_requires_an_exact_permutation_without_changing_profiles() {
let mut f = AccountsFile::default();
Expand Down
27 changes: 27 additions & 0 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,8 @@ pub struct AccountView {
pub detached: bool,
/// Profile photo as a `data:` URL, when the user picked one.
pub photo: Option<String>,
/// Whether this account may raise OS notifications and play alert tones.
pub notifications: bool,
}

fn account_views(app: &tauri::AppHandle) -> Vec<AccountView> {
Expand All @@ -674,6 +676,7 @@ fn account_views(app: &tauri::AppHandle) -> Vec<AccountView> {
.is_some_and(|v| v.window().label().starts_with("detached-")),
is_default: accounts::startup_account(&f).is_some_and(|startup| startup.id == a.id),
photo: crate::accountphoto::data_url(app, &a.id),
notifications: a.notifications,
})
.collect();
views.sort_by_key(|v| v.order);
Expand Down Expand Up @@ -839,6 +842,7 @@ pub async fn add_account(
is_default,
detached: false,
photo: None,
notifications: true,
})
}

Expand Down Expand Up @@ -906,6 +910,29 @@ pub async fn remove_account(
Ok(())
}

/// Per-account notifications switch (issues #118, #103). Off: no OS
/// notification and no WhatsApp alert tone from that account. Its unread count
/// still shows.
#[tauri::command]
pub async fn set_account_notifications(
window: tauri::Webview,
app: tauri::AppHandle,
id: String,
on: bool,
) -> Result<(), String> {
if is_remote(&window) {
return Err("forbidden".into());
}
lock::require_unlocked(&app)?;
let _guard = accounts::lock_mutations();
let mut f = accounts::load(&app);
accounts::set_notifications(&mut f, &id, on)?;
accounts::save(&app, &f).map_err(|e| e.to_string())?;
crate::window::apply_notification_sound(&app, crate::settings::load(&app).notification_sound);
crate::integration::broadcast(&app);
Ok(())
}

#[tauri::command]
pub async fn rename_account(
window: tauri::Webview,
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/ipc_acl_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const SETTINGS_COMMANDS: &[&str] = &[
"add_account",
"remove_account",
"rename_account",
"set_account_notifications",
"open_account",
"set_default_account",
"get_lock_status",
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ pub fn run() {
commands::add_account,
commands::remove_account,
commands::rename_account,
commands::set_account_notifications,
commands::open_account,
commands::set_default_account,
commands::get_lock_status,
Expand Down
Loading
Loading