[capture] Phones: strict Shortcut post and bank-notification templates (registry empty until real samples)
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
//! Android bank notifications. A notification is read only if it comes from a bank app the person selected,
|
||||
//! and becomes a payment only if a template **written from real samples** matches it exactly. Anything else
|
||||
//! is `Unknown`: counted by the app, never guessed.
|
||||
|
||||
use crate::{amount, card_ok, merchant_ok, Capture};
|
||||
use fiscus_ledger::{Date, Timestamp};
|
||||
|
||||
/// One notification format of one bank app. `text` (and `title`, if given) are literal text with holes:
|
||||
/// `{amount}`, `{merchant}`, `{card}` and `{_}` (anything, ignored). Each hole matches at least one character.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Template {
|
||||
/// The Android package name of the bank app.
|
||||
pub app: &'static str,
|
||||
/// The bank, as `fixtures/notifications/<bank>/` names it.
|
||||
pub bank: &'static str,
|
||||
pub title: Option<&'static str>,
|
||||
pub text: &'static str,
|
||||
}
|
||||
|
||||
/// The registry. Empty: no bank notification samples exist yet (`fixtures/notifications/README.md`).
|
||||
pub const TEMPLATES: &[Template] = &[];
|
||||
|
||||
/// Notifications longer than this are not read.
|
||||
pub const MAX_TEXT: usize = 1000;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Recognised {
|
||||
/// From an app the person did not select: not read at all.
|
||||
NotSelected,
|
||||
/// From a selected app, but no template matches (or two readings disagree).
|
||||
Unknown,
|
||||
Payment(Capture),
|
||||
}
|
||||
|
||||
/// [`recognise_with`] over the registry.
|
||||
pub fn recognise(app: &str, title: &str, text: &str, date: Date, at: Timestamp, selected: &[&str]) -> Recognised {
|
||||
recognise_with(TEMPLATES, app, title, text, date, at, selected)
|
||||
}
|
||||
|
||||
/// `date` and `at` are when the notification was posted (the phone's local date and the instant).
|
||||
pub fn recognise_with(
|
||||
templates: &[Template],
|
||||
app: &str,
|
||||
title: &str,
|
||||
text: &str,
|
||||
date: Date,
|
||||
at: Timestamp,
|
||||
selected: &[&str],
|
||||
) -> Recognised {
|
||||
if !selected.contains(&app) {
|
||||
return Recognised::NotSelected;
|
||||
}
|
||||
if text.chars().count() > MAX_TEXT || title.chars().count() > MAX_TEXT {
|
||||
return Recognised::Unknown;
|
||||
}
|
||||
let mut found: Option<Capture> = None;
|
||||
for t in templates.iter().filter(|t| t.app == app) {
|
||||
if t.title.is_some_and(|pat| matches(pat, title).is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let all = matches(t.text, text);
|
||||
if all.len() > MAX_READINGS {
|
||||
return Recognised::Unknown;
|
||||
}
|
||||
for fields in all {
|
||||
let Some(c) = capture(&fields, date, at) else { continue };
|
||||
match &found {
|
||||
None => found = Some(c),
|
||||
Some(prev) if *prev == c => {}
|
||||
Some(_) => return Recognised::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
found.map(Recognised::Payment).unwrap_or(Recognised::Unknown)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Hole {
|
||||
Amount,
|
||||
Merchant,
|
||||
Card,
|
||||
Any,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Piece<'a> {
|
||||
Lit(&'a str),
|
||||
Hole(Hole),
|
||||
}
|
||||
|
||||
fn pieces(pattern: &str) -> Vec<Piece<'_>> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = pattern;
|
||||
while let Some(i) = rest.find('{') {
|
||||
let Some(j) = rest[i..].find('}') else { break };
|
||||
let hole = match &rest[i + 1..i + j] {
|
||||
"amount" => Some(Hole::Amount),
|
||||
"merchant" => Some(Hole::Merchant),
|
||||
"card" => Some(Hole::Card),
|
||||
"_" => Some(Hole::Any),
|
||||
_ => None,
|
||||
};
|
||||
match hole {
|
||||
Some(h) => {
|
||||
if i > 0 {
|
||||
out.push(Piece::Lit(&rest[..i]));
|
||||
}
|
||||
out.push(Piece::Hole(h));
|
||||
}
|
||||
None => out.push(Piece::Lit(&rest[..i + j + 1])),
|
||||
}
|
||||
rest = &rest[i + j + 1..];
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
out.push(Piece::Lit(rest));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
type Fields<'a> = Vec<(Hole, &'a str)>;
|
||||
|
||||
/// More readings than this of one notification is not a format, it is noise.
|
||||
const MAX_READINGS: usize = 16;
|
||||
|
||||
/// Every way `text` matches `pattern` exactly, as the text of each hole.
|
||||
fn matches<'a>(pattern: &str, text: &'a str) -> Vec<Fields<'a>> {
|
||||
let ps = pieces(pattern);
|
||||
let mut out = Vec::new();
|
||||
walk(&ps, text, Vec::new(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn walk<'a>(ps: &[Piece], text: &'a str, acc: Fields<'a>, out: &mut Vec<Fields<'a>>) {
|
||||
if out.len() > MAX_READINGS {
|
||||
return; // the caller treats this many readings as unknown
|
||||
}
|
||||
match ps.first() {
|
||||
None => {
|
||||
if text.is_empty() {
|
||||
out.push(acc);
|
||||
}
|
||||
}
|
||||
Some(Piece::Lit(l)) => {
|
||||
if let Some(rest) = text.strip_prefix(l) {
|
||||
walk(&ps[1..], rest, acc, out);
|
||||
}
|
||||
}
|
||||
Some(Piece::Hole(h)) => {
|
||||
// The hole takes 1.. characters; with nothing after it, all the rest.
|
||||
let ends: Vec<usize> = match ps.get(1) {
|
||||
None => vec![text.len()],
|
||||
Some(Piece::Lit(l)) => text.match_indices(l).map(|(i, _)| i).filter(|i| *i > 0).collect(),
|
||||
Some(Piece::Hole(_)) => text.char_indices().map(|(i, _)| i).skip(1).chain([text.len()]).collect(),
|
||||
};
|
||||
for end in ends {
|
||||
if end == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut next = acc.clone();
|
||||
next.push((*h, &text[..end]));
|
||||
walk(&ps[1..], &text[end..], next, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn capture(fields: &Fields, date: Date, at: Timestamp) -> Option<Capture> {
|
||||
let get = |h: Hole| fields.iter().find(|(k, _)| *k == h).map(|(_, v)| v.trim());
|
||||
let amount = amount::parse_positive(get(Hole::Amount)?)?.checked_neg().ok()?;
|
||||
let merchant = get(Hole::Merchant)?;
|
||||
if !merchant_ok(merchant) {
|
||||
return None;
|
||||
}
|
||||
let card = get(Hole::Card);
|
||||
if card.is_some_and(|c| !card_ok(c)) {
|
||||
return None;
|
||||
}
|
||||
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string) })
|
||||
}
|
||||
Reference in New Issue
Block a user