Add channel message filter for spam and repeated messages

Client-side filter for channel messages, with no model download:
- User rules on message text and/or sender name (contains, whole word,
  exact), normalised for case, accents, zero-width and look-alike letters.
- Automatic checks: repeated characters, same-sender repeats within 10
  minutes, and the same sentence (>= 6 words) from 3+ senders within 30
  minutes. Windows use send times, so synced history is not a flood.
- On-device n-gram classifier trained by Mark as spam / Not spam taps.

Filtered messages are kept, never notify or count as unread, are not
auto-translated or used for channel previews, and are concealed in reply
quotes. They show as a calm, collapsible placeholder that animates open
and closed, or can be hidden completely. Includes a Filtered messages
list, per-channel toggle, settings screen, translations for all locales
and documentation.
This commit is contained in:
zjs81 committed 2026-11-05 23:35:27 -07:00
1 parent 5ef2c2cd7d
commit 1332c35884
75 files changed
+12527 -254

No files matched your search

@@ -0,0 +1,283 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/duplicate_tracker.dart';
void main() {
final t0 = DateTime(2026, 1, 1, 12);
test('same sender repeat within 10 minutes is a duplicate', () {
final tracker = DuplicateTracker();
expect(
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'hello!',
at: t0.add(const Duration(minutes: 9)),
),
FilterReason.duplicate,
);
});
test('same sender repeat after the window is not a duplicate', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Hello',
at: t0.add(const Duration(minutes: 11)),
),
isNull,
);
});
test('channels are tracked separately', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'a', sender: 'Bob', text: 'Hello', at: t0);
expect(
tracker.check(channelId: 'b', sender: 'Bob', text: 'Hello', at: t0),
isNull,
);
});
test('short greetings from many senders are never cross-sender', () {
final tracker = DuplicateTracker();
// New Year's Eve: everyone sends the same few words at once.
const greetings = [
'Happy New Year!',
'happy new year',
'HAPPY NEW YEAR!!',
'Happy new year 🎉',
'Happy New Year everyone!',
];
for (var i = 0; i < 8; i++) {
expect(
tracker.check(
channelId: 'c',
sender: 'person$i',
text: greetings[i % greetings.length],
at: t0.add(Duration(minutes: i)),
),
isNull,
reason: 'greeting from person$i must stay visible',
);
}
// Five words is still a greeting, not a campaign.
for (var i = 0; i < 4; i++) {
expect(
tracker.check(
channelId: 'c',
sender: 'friend$i',
text: 'Merry Christmas to you all',
at: t0.add(Duration(minutes: 10 + i)),
),
isNull,
);
}
});
test('third distinct sender of the same long text is cross-sender', () {
final tracker = DuplicateTracker();
const text = 'Join the best mesh client now, it is free';
expect(
tracker.check(channelId: 'c', sender: 'A', text: text, at: t0),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'B',
text: text,
at: t0.add(const Duration(minutes: 5)),
),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'C',
text: text,
at: t0.add(const Duration(minutes: 20)),
),
FilterReason.crossSenderDuplicate,
);
});
test('short texts never count as cross-sender duplicates', () {
final tracker = DuplicateTracker();
for (final sender in ['A', 'B', 'C', 'D']) {
expect(
tracker.check(channelId: 'c', sender: sender, text: 'hi all', at: t0),
isNull,
);
}
});
test('cross-sender window is 30 minutes', () {
final tracker = DuplicateTracker();
const text = 'Join the best mesh now';
tracker.check(channelId: 'c', sender: 'A', text: text, at: t0);
tracker.check(
channelId: 'c',
sender: 'B',
text: text,
at: t0.add(const Duration(minutes: 1)),
);
expect(
tracker.check(
channelId: 'c',
sender: 'C',
text: text,
at: t0.add(const Duration(minutes: 31)),
),
isNull,
);
});
test('filtered texts are still recorded so floods keep being caught', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'c', sender: 'Bob', text: 'buy now', at: t0);
for (var i = 1; i <= 5; i++) {
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'buy now',
at: t0.add(Duration(minutes: 8 * i)),
),
FilterReason.duplicate,
);
}
});
test('allow exempts the text in that channel', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0);
tracker.allow('c', 'HELLO!');
expect(tracker.isAllowed('c', 'hello'), isTrue);
expect(tracker.isAllowed('other', 'hello'), isFalse);
expect(
tracker.check(channelId: 'c', sender: 'Bob', text: 'Hello', at: t0),
isNull,
);
tracker.clear();
expect(tracker.isAllowed('c', 'hello'), isFalse);
});
test('empty normalized text is ignored', () {
final tracker = DuplicateTracker();
tracker.check(channelId: 'c', sender: 'Bob', text: '👍', at: t0);
expect(
tracker.check(channelId: 'c', sender: 'Bob', text: '👍', at: t0),
isNull,
);
});
group('send-time windows', () {
test('history synced in a burst is not a duplicate', () {
final tracker = DuplicateTracker();
// Sent three hours apart, delivered seconds apart after reconnecting.
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Heading out now',
at: t0,
receivedAt: t0.add(const Duration(hours: 5)),
),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Heading out now',
at: t0.add(const Duration(hours: 3)),
receivedAt: t0.add(const Duration(hours: 5, seconds: 2)),
),
isNull,
);
});
test('out-of-order delivery is still caught', () {
final tracker = DuplicateTracker();
// The newer copy arrives first.
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Buy cheap nodes',
at: t0.add(const Duration(minutes: 5)),
receivedAt: t0.add(const Duration(minutes: 30)),
),
isNull,
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Buy cheap nodes',
at: t0,
receivedAt: t0.add(const Duration(minutes: 30, seconds: 1)),
),
FilterReason.duplicate,
);
const campaign = 'the meshcore trademark grab is theft, boycott him';
final now = t0.add(const Duration(hours: 1));
for (final (i, sender) in ['x', 'y'].indexed) {
expect(
tracker.check(
channelId: 'c',
sender: sender,
text: campaign,
at: t0.add(Duration(minutes: 20 - i * 10)),
receivedAt: now,
),
isNull,
);
}
expect(
tracker.check(
channelId: 'c',
sender: 'z',
text: campaign,
at: t0,
receivedAt: now,
),
FilterReason.crossSenderDuplicate,
);
});
test('a sender clock years ahead does not evict other entries', () {
final tracker = DuplicateTracker();
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Morning all, testing my node',
at: t0,
);
tracker.check(
channelId: 'c',
sender: 'Wonky',
text: 'Clock is way off',
at: t0.add(const Duration(days: 900)),
receivedAt: t0.add(const Duration(minutes: 1)),
);
expect(
tracker.check(
channelId: 'c',
sender: 'Bob',
text: 'Morning all, testing my node',
at: t0.add(const Duration(minutes: 2)),
),
FilterReason.duplicate,
);
});
});
}
@@ -0,0 +1,307 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/message_filter_service.dart';
import 'package:meshcore_open/storage/message_filter_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _channel = 'chan1';
const _chat = [
'Good morning everyone',
'Anyone hearing the repeater on the hill today?',
'I just got back from the hike, signal was great',
'Testing from the north side of town',
'Thanks for the advert, I can see you now',
'How many hops is your path to the city?',
'Weather looks rough tonight, stay safe',
'My battery is at 40 percent after two days',
'Who is running the new solar node?',
'Copy that, heard you loud and clear',
'Is the meetup still on for Saturday?',
'Yes, 10am at the library parking lot',
'I moved my antenna higher, let me know if it helps',
'Reception improved a lot, thanks',
'Lunch break, back in an hour',
'Does anyone have a spare LoRa board to lend?',
'Ping from the coffee shop downtown',
'See you all tomorrow',
'Happy birthday Carol!',
'Can someone check if my messages are getting through?',
];
void main() {
late DateTime now;
late MessageFilterService service;
Future<MessageFilterService> create() async {
final s = MessageFilterService(
store: MessageFilterStore(),
clock: () => now,
);
await s.load();
return s;
}
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
now = DateTime(2026, 1, 1, 12);
service = await create();
});
FilterVerdict? eval(
String sender,
String text, {
String channel = _channel,
}) => service.evaluate(channelId: channel, sender: sender, text: text);
test('defaults: enabled, nothing filtered for normal chat', () {
expect(service.settings.enabled, isTrue);
expect(service.settings.displayMode, FilterDisplayMode.placeholder);
expect(service.isChannelFiltered(_channel), isTrue);
expect(eval('Bob', 'hello there'), isNull);
});
test('skips outgoing, reactions, payloads, disabled and excluded', () async {
await service.addRule(
FilterRule(id: MessageFilterService.newRuleId(), pattern: 'bad'),
);
expect(
service.evaluate(
channelId: _channel,
sender: 'me',
text: 'bad',
isOutgoing: true,
),
isNull,
);
expect(
service.evaluate(
channelId: _channel,
sender: 'a',
text: 'bad',
isReaction: true,
),
isNull,
);
expect(eval('a', 'g:bad-gif'), isNull);
expect(eval('a', 'm:bad'), isNull);
await service.setChannelExcluded(_channel, true);
expect(service.isChannelFiltered(_channel), isFalse);
expect(eval('a', 'bad'), isNull);
expect(eval('a', 'bad', channel: 'other')?.reason, FilterReason.textRule);
await service.setChannelExcluded(_channel, false);
await service.updateSettings(service.settings.copyWith(enabled: false));
expect(eval('a', 'bad'), isNull);
});
test(
'sender rules win over text rules; disabled rules are ignored',
() async {
await service.addRule(
const FilterRule(
id: 't',
pattern: 'promo',
field: FilterRuleField.text,
),
);
await service.addRule(
const FilterRule(
id: 's',
pattern: 'Spammer',
field: FilterRuleField.sender,
match: FilterRuleMatch.exact,
),
);
expect(
eval('spammer', 'promo time'),
const FilterVerdict(reason: FilterReason.senderRule, detail: 'Spammer'),
);
expect(
eval('Bob', 'big PROMO'),
const FilterVerdict(reason: FilterReason.textRule, detail: 'promo'),
);
await service.updateRule(
const FilterRule(id: 't', pattern: 'promo', enabled: false),
);
expect(eval('Bob', 'another promo'), isNull);
await service.removeRule('s');
expect(service.rules.map((r) => r.id), ['t']);
},
);
test('repeated characters, togglable', () async {
expect(eval('a', 'nooooooooo')?.reason, FilterReason.repeatedCharacters);
await service.updateSettings(
service.settings.copyWith(repeatedCharacters: false),
);
expect(eval('b', 'yesssssssss'), isNull);
});
test('duplicates: same sender and cross sender', () {
expect(eval('a', 'meet at the park'), isNull);
now = now.add(const Duration(minutes: 2));
expect(
eval('a', 'Meet at the park!'),
const FilterVerdict(reason: FilterReason.duplicate),
);
const campaign = 'the meshcore trademark grab is theft, boycott him';
expect(eval('b', campaign), isNull);
expect(eval('d', campaign), isNull);
expect(eval('c', campaign)?.reason, FilterReason.crossSenderDuplicate);
// Short greetings from several senders are left alone.
expect(eval('e', 'Happy New Year!'), isNull);
expect(eval('f', 'Happy New Year!'), isNull);
expect(eval('g', 'Happy New Year!'), isNull);
});
test('duplicates setting off still records but does not filter', () async {
await service.updateSettings(service.settings.copyWith(duplicates: false));
expect(eval('a', 'meet at the park'), isNull);
expect(eval('a', 'meet at the park'), isNull);
await service.updateSettings(service.settings.copyWith(duplicates: true));
expect(eval('a', 'meet at the park')?.reason, FilterReason.duplicate);
});
test('rule-filtered texts are still recorded for duplicates', () async {
await service.addRule(const FilterRule(id: 'x', pattern: 'buy'));
expect(eval('a', 'buy stuff')?.reason, FilterReason.textRule);
await service.removeRule('x');
expect(eval('a', 'buy stuff')?.reason, FilterReason.duplicate);
});
test('not spam exempts duplicates in that channel', () async {
eval('a', 'meet at the park');
await service.markNotSpam(
channelId: _channel,
sender: 'a',
text: 'meet at the park',
);
expect(eval('a', 'meet at the park'), isNull);
expect(service.notSpamExampleCount, 1);
});
test('learning needs two spam taps, then catches similar promos', () async {
for (var i = 0; i < _chat.length; i++) {
service.recordClean(sender: 'User$i', text: _chat[i]);
}
await service.markSpam(
sender: 'PromoBot',
text: 'Download MeshOS now! Free firmware at meshos.example',
);
expect(service.spamExampleCount, 1);
expect(
eval('X', 'Free MeshOS firmware download at meshos.example'),
isNull,
);
await service.markSpam(
sender: 'Deals',
text: 'Free MeshOS firmware upgrade, download at meshos.example now',
);
expect(service.spamExampleCount, 2);
expect(
eval('Y', 'Get free MeshOS firmware download now meshos.example')?.reason,
FilterReason.learned,
);
expect(eval('Z', 'Anyone on the hill repeater tonight?'), isNull);
await service.updateSettings(service.settings.copyWith(learning: false));
expect(
eval('W', 'Get the MeshOS firmware download free meshos.example'),
isNull,
);
});
test('marking spam twice for the same text keeps one example', () async {
await service.markSpam(sender: 'a', text: 'Buy now');
await service.markSpam(sender: 'a', text: 'buy NOW');
expect(service.spamExampleCount, 1);
await service.markNotSpam(
channelId: _channel,
sender: 'a',
text: 'buy now',
);
expect(service.spamExampleCount, 0);
expect(service.notSpamExampleCount, 1);
});
test('state persists across instances and reset keeps rules', () async {
await service.addRule(const FilterRule(id: 'r1', pattern: 'promo'));
await service.updateSettings(
service.settings.copyWith(displayMode: FilterDisplayMode.hide),
);
await service.markSpam(sender: 'a', text: 'spam one');
await service.markNotSpam(channelId: _channel, sender: 'b', text: 'hi');
final reloaded = await create();
expect(reloaded.rules.single.pattern, 'promo');
expect(reloaded.settings.displayMode, FilterDisplayMode.hide);
expect(reloaded.spamExampleCount, 1);
expect(reloaded.notSpamExampleCount, 1);
await reloaded.resetLearning();
expect(reloaded.spamExampleCount, 0);
expect(reloaded.notSpamExampleCount, 0);
expect(reloaded.rules, hasLength(1));
final again = await create();
expect(again.spamExampleCount, 0);
expect(again.rules, hasLength(1));
});
test('notifies listeners on changes', () async {
var count = 0;
service.addListener(() => count++);
await service.addRule(const FilterRule(id: 'n', pattern: 'x'));
await service.markSpam(sender: 'a', text: 'b');
await service.setChannelExcluded('c', true);
expect(count, 3);
});
test('addRule with index restores a deleted rule in place', () async {
for (final id in ['a', 'b', 'c']) {
await service.addRule(FilterRule(id: id, pattern: id));
}
final b = service.rules[1];
await service.removeRule('b');
await service.addRule(b, index: 1);
expect(service.rules.map((r) => r.id), ['a', 'b', 'c']);
await service.addRule(const FilterRule(id: 'z', pattern: 'z'), index: 99);
expect(service.rules.last.id, 'z');
});
test('newRuleId is unique', () {
final ids = List.generate(100, (_) => MessageFilterService.newRuleId());
expect(ids.toSet(), hasLength(100));
});
test(
'learning activates once clean examples arrive after spam taps',
() async {
// The first two messages received are the ones marked spam, so training
// has no clean examples yet and the classifier stays inactive.
await service.markSpam(
sender: 'PromoBot',
text: 'Download MeshOS now! Free firmware at meshos.example',
);
await service.markSpam(
sender: 'Deals',
text: 'Free MeshOS firmware upgrade, download at meshos.example now',
);
const probe = 'Get free MeshOS firmware download now meshos.example';
expect(eval('A', probe), isNull);
// Ordinary chat then arrives; no further taps.
for (var i = 0; i < _chat.length; i++) {
service.recordClean(sender: 'User$i', text: _chat[i]);
}
await Future<void>.delayed(Duration.zero); // let the queued retrain run
expect(eval('B', probe)?.reason, FilterReason.learned);
expect(eval('C', 'Anyone on the hill repeater tonight?'), isNull);
},
);
}
@@ -0,0 +1,155 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/message_filter_text.dart';
FilterRule _rule(
String pattern, {
FilterRuleField field = FilterRuleField.text,
FilterRuleMatch match = FilterRuleMatch.contains,
}) => FilterRule(id: 'r', pattern: pattern, field: field, match: match);
void main() {
group('normalize', () {
test('lower-cases, collapses whitespace and trims', () {
expect(
MessageFilterText.normalize(' Hello \n\t WORLD '),
'hello world',
);
});
test('strips accents', () {
expect(MessageFilterText.normalize('Ça vá Ñoño Öl'), 'ca va nono ol');
// Decomposed form (combining marks).
expect(MessageFilterText.normalize('Café'), 'cafe');
});
test('maps Cyrillic and Greek look-alikes to Latin', () {
// Cyrillic М е о and Greek Ο.
expect(MessageFilterText.normalize('Мeshоs'), 'meshos');
expect(MessageFilterText.normalize('MeshΟS'), 'meshos');
});
test('removes zero-width and soft hyphen characters', () {
expect(MessageFilterText.normalize('me​sh‌‍o⁠s­'), 'meshos');
});
test('folds fullwidth and styled letters', () {
expect(MessageFilterText.normalize('MESH'), 'mesh');
expect(MessageFilterText.normalize('\u{1D400}\u{1D41B}'), 'ab');
});
});
group('normalizeForDuplicates', () {
test('drops mentions, punctuation and emoji', () {
expect(
MessageFilterText.normalizeForDuplicates('@[Bob] Hello, world!!! 😀'),
'hello world',
);
expect(
MessageFilterText.normalizeForDuplicates('Hello world'),
MessageFilterText.normalizeForDuplicates('hello... WORLD?'),
);
});
});
group('matchesRule', () {
test('contains', () {
final rule = _rule('MeshOS');
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'try meshos!'),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'mesh os'),
isFalse,
);
});
test('whole word uses unicode boundaries', () {
final rule = _rule('cat', match: FilterRuleMatch.wholeWord);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'my cat!'),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'Cat'),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'category'),
isFalse,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'catß'),
isFalse,
);
final phrase = _rule('free (offer)', match: FilterRuleMatch.wholeWord);
expect(
MessageFilterText.matchesRule(
phrase,
sender: 'a',
text: 'a FREE (offer) now',
),
isTrue,
);
});
test('exact', () {
final rule = _rule('hello', match: FilterRuleMatch.exact);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: ' HELLO '),
isTrue,
);
expect(
MessageFilterText.matchesRule(rule, sender: 'a', text: 'hello there'),
isFalse,
);
});
test('respects the field', () {
final sender = _rule('spammer', field: FilterRuleField.sender);
expect(
MessageFilterText.matchesRule(sender, sender: 'Spammer', text: 'hi'),
isTrue,
);
expect(
MessageFilterText.matchesRule(sender, sender: 'bob', text: 'spammer'),
isFalse,
);
final both = _rule('spammer', field: FilterRuleField.both);
expect(
MessageFilterText.matchesRule(both, sender: 'bob', text: 'spammer'),
isTrue,
);
expect(
MessageFilterText.matchesRule(both, sender: 'SPAMMER', text: 'hi'),
isTrue,
);
});
test('empty pattern never matches', () {
expect(
MessageFilterText.matchesRule(_rule(' '), sender: 'a', text: 'b'),
isFalse,
);
});
});
test('repeated characters', () {
expect(MessageFilterText.hasRepeatedCharacters('aaaaaaaa'), isTrue);
expect(MessageFilterText.hasRepeatedCharacters('wow!!!!!!!!'), isTrue);
expect(MessageFilterText.hasRepeatedCharacters('AAAAaaaa'), isTrue);
expect(MessageFilterText.hasRepeatedCharacters('😀' * 8), isTrue);
expect(MessageFilterText.hasRepeatedCharacters('aaaaaaa'), isFalse);
expect(
MessageFilterText.hasRepeatedCharacters('hello there'),
isFalse,
);
});
test('structured payloads', () {
expect(MessageFilterText.isStructuredPayload('g:abc'), isTrue);
expect(MessageFilterText.isStructuredPayload(' m:xyz'), isTrue);
expect(MessageFilterText.isStructuredPayload('good morning'), isFalse);
});
}
@@ -0,0 +1,149 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/message_filter.dart';
import 'package:meshcore_open/services/message_filter/ngram_spam_classifier.dart';
FilterExample _ex(String sender, String text) =>
FilterExample(sender: sender, text: text, addedAtMs: 0);
final _spam = [
_ex(
'PromoBot',
'Download MeshOS now! Free firmware upgrade at meshos.example',
),
_ex(
'MeshDeals',
'FREE upgrade!!! Get MeshOS firmware today, visit meshos.example',
),
_ex(
'PromoBot',
'Best firmware ever: MeshOS. Download free at meshos.example now',
),
_ex('Promo2', 'Limited offer: MeshOS firmware download free, meshos.example'),
_ex(
'MeshDeals',
'Upgrade your node with MeshOS! Free download at meshos.example',
),
_ex('Promo3', 'Get the free MeshOS firmware now - meshos.example download'),
];
final _ham = [
_ex('Alice', 'Good morning everyone'),
_ex('Bob', 'Anyone hearing the repeater on the hill today?'),
_ex('Carol', 'I just got back from the hike, signal was great'),
_ex('Dave', 'Testing from the north side of town'),
_ex('Alice', 'Thanks for the advert, I can see you now'),
_ex('Eve', 'How many hops is your path to the city?'),
_ex('Bob', 'Weather looks rough tonight, stay safe'),
_ex('Frank', 'My battery is at 40 percent after two days'),
_ex('Carol', 'Who is running the new solar node?'),
_ex('Dave', 'Copy that, heard you loud and clear'),
_ex('Grace', 'Is the meetup still on for Saturday?'),
_ex('Heidi', 'Yes, 10am at the library parking lot'),
_ex('Ivan', 'I moved my antenna higher, let me know if it helps'),
_ex('Judy', 'Reception improved a lot, thanks'),
_ex('Alice', 'Lunch break, back in an hour'),
_ex('Bob', 'Does anyone have a spare LoRa board to lend?'),
_ex('Frank', 'Ping from the coffee shop downtown'),
_ex('Grace', 'See you all tomorrow'),
_ex('Eve', 'The traffic on the highway is terrible right now'),
_ex('Heidi', 'Happy birthday Carol!'),
_ex('Ivan', 'Can someone check if my messages are getting through?'),
_ex('Judy', 'Got it, three hops via the hill repeater'),
_ex('Carol', 'Thank you all, great community here'),
_ex('Dave', 'Power is out in my area, running on battery'),
_ex('Alice', 'Nice sunset from the ridge'),
_ex('Bob', 'Updating my node settings, brb'),
_ex('Eve', 'Good night folks'),
_ex('Frank', 'Anyone near the river trail?'),
_ex('Grace', 'The new channel works well for our group'),
_ex('Heidi', 'Is there a map of the repeaters somewhere?'),
];
void main() {
test('untrained classifier returns 0', () {
final classifier = NgramSpamClassifier();
expect(classifier.isTrained, isFalse);
expect(classifier.probability('x', 'anything'), 0.0);
});
test('needs both classes to train', () {
final classifier = NgramSpamClassifier()..train(_spam, const []);
expect(classifier.isTrained, isFalse);
});
test('FNV-1a 32 matches reference vectors', () {
expect(NgramSpamClassifier.fnv1a32(''), 0x811C9DC5);
expect(NgramSpamClassifier.fnv1a32('a'), 0xE40C292C);
expect(NgramSpamClassifier.fnv1a32('foobar'), 0xBF9CF968);
});
test('feature strings include char n-grams, words, bigrams, sender', () {
final features = NgramSpamClassifier.featureStrings('Bob', 'Hi there');
expect(features, contains('c: hi '));
expect(features, contains('c: th'));
expect(features, contains('c:there'));
expect(features, contains('w:there'));
expect(features, contains('b:hi there'));
expect(features, contains('s:bob'));
});
test('scores held-out promo high and ordinary chat low', () {
final classifier = NgramSpamClassifier()..train(_spam, _ham);
expect(classifier.isTrained, isTrue);
final promo = classifier.probability(
'NewPromo',
'Free MeshOS firmware download now at meshos.example!',
);
expect(promo, greaterThanOrEqualTo(0.8));
for (final text in [
'Anyone on the hill repeater tonight?',
'Good morning, heading out for a hike',
'My node battery lasted three days',
'See you at the meetup on Saturday',
]) {
expect(classifier.probability('Zoe', text), lessThan(0.5), reason: text);
}
});
test('look-alike characters do not dodge the classifier', () {
final classifier = NgramSpamClassifier()..train(_spam, _ham);
// Cyrillic "е"/"о" and a zero-width space.
final p = classifier.probability(
'NewPromo',
'Frеe MeshОS firm​ware download now at meshos.example',
);
expect(p, greaterThanOrEqualTo(0.8));
});
test('training is deterministic', () {
final a = NgramSpamClassifier()..train(_spam, _ham);
final b = NgramSpamClassifier()..train(_spam, _ham);
const text = 'free firmware download';
expect(a.probability('x', text), b.probability('x', text));
});
test('trains 500 documents quickly', () {
final spam = <FilterExample>[];
final ham = <FilterExample>[];
for (var i = 0; i < 200; i++) {
final s = _spam[i % _spam.length];
spam.add(_ex('${s.sender}$i', '${s.text} code $i'));
}
for (var i = 0; i < 300; i++) {
final h = _ham[i % _ham.length];
ham.add(_ex('${h.sender}$i', '${h.text} number $i'));
}
final classifier = NgramSpamClassifier();
// Warm up the JIT once, then measure.
classifier.train(spam.take(20).toList(), ham.take(20).toList());
final stopwatch = Stopwatch()..start();
classifier.train(spam, ham);
stopwatch.stop();
expect(classifier.isTrained, isTrue);
expect(stopwatch.elapsedMilliseconds, lessThan(500));
// ignore: avoid_print
print('Trained 500 docs in ${stopwatch.elapsedMilliseconds} ms');
});
}