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:
1 parent
5ef2c2cd7d
commit
1332c35884
75 files changed
+12527
-254
No files matched your search
@@ -0,0 +1,145 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import '../../models/message_filter.dart';
|
||||
import 'message_filter_text.dart';
|
||||
|
||||
class _SeenMessage {
|
||||
final String sender;
|
||||
final String key;
|
||||
|
||||
/// When the sender sent it (their clock). Windows compare these.
|
||||
final DateTime sentAt;
|
||||
|
||||
/// When this device saw it (local clock). Only used to forget entries.
|
||||
final DateTime receivedAt;
|
||||
const _SeenMessage(this.sender, this.key, this.sentAt, this.receivedAt);
|
||||
}
|
||||
|
||||
/// In-memory, per-channel tracker of recently seen channel texts used to catch
|
||||
/// repeated messages (same sender) and floods (same text from several senders).
|
||||
///
|
||||
/// Every checked text is recorded, including ones that end up filtered, so a
|
||||
/// flood keeps being caught.
|
||||
///
|
||||
/// Windows are measured between the messages' own send times, as an absolute
|
||||
/// difference, so history downloaded in a burst after reconnecting (sent
|
||||
/// hours apart, delivered seconds apart, possibly out of order) is not
|
||||
/// mistaken for a flood. Entries are forgotten by local receive time instead,
|
||||
/// so a sender whose clock is far off cannot push everyone else's entries
|
||||
/// out early or keep its own around forever.
|
||||
///
|
||||
/// The cross-sender rule only applies to sentence-length texts (at least
|
||||
/// [crossSenderMinWords] words): short greetings like "Happy New Year!" or
|
||||
/// "Good morning everyone" are naturally sent by many people at once, while
|
||||
/// copy-paste campaigns from rotating identities are whole sentences.
|
||||
class DuplicateTracker {
|
||||
DuplicateTracker({
|
||||
this.sameSenderWindow = const Duration(minutes: 10),
|
||||
this.crossSenderWindow = const Duration(minutes: 30),
|
||||
this.crossSenderMinSenders = 3,
|
||||
this.crossSenderMinLength = 10,
|
||||
this.crossSenderMinWords = 6,
|
||||
this.maxEntriesPerChannel = 1000,
|
||||
});
|
||||
|
||||
final Duration sameSenderWindow;
|
||||
final Duration crossSenderWindow;
|
||||
final int crossSenderMinSenders;
|
||||
final int crossSenderMinLength;
|
||||
|
||||
/// Minimum word count for the cross-sender rule (see class docs).
|
||||
final int crossSenderMinWords;
|
||||
final int maxEntriesPerChannel;
|
||||
|
||||
final Map<String, ListQueue<_SeenMessage>> _seen = {};
|
||||
final Map<String, Set<String>> _allowed = {};
|
||||
|
||||
Duration get _retention => sameSenderWindow > crossSenderWindow
|
||||
? sameSenderWindow
|
||||
: crossSenderWindow;
|
||||
|
||||
static String _senderKey(String sender) =>
|
||||
MessageFilterText.normalize(sender);
|
||||
|
||||
void _prune(ListQueue<_SeenMessage> entries, DateTime receivedAt) {
|
||||
// Entries are appended in receive order, so the oldest are at the front.
|
||||
final cutoff = receivedAt.subtract(_retention);
|
||||
while (entries.isNotEmpty && entries.first.receivedAt.isBefore(cutoff)) {
|
||||
entries.removeFirst();
|
||||
}
|
||||
while (entries.length > maxEntriesPerChannel) {
|
||||
entries.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the text and returns [FilterReason.duplicate],
|
||||
/// [FilterReason.crossSenderDuplicate] or null.
|
||||
///
|
||||
/// [at] is when the message was sent (the sender's timestamp); windows are
|
||||
/// compared on it. [receivedAt] (default [at]) is the local time it arrived,
|
||||
/// used only to forget old entries.
|
||||
FilterReason? check({
|
||||
required String channelId,
|
||||
required String sender,
|
||||
required String text,
|
||||
required DateTime at,
|
||||
DateTime? receivedAt,
|
||||
}) {
|
||||
final arrived = receivedAt ?? at;
|
||||
final key = MessageFilterText.normalizeForDuplicates(text);
|
||||
if (key.isEmpty) return null;
|
||||
final senderKey = _senderKey(sender);
|
||||
final entries = _seen.putIfAbsent(channelId, ListQueue<_SeenMessage>.new);
|
||||
_prune(entries, arrived);
|
||||
|
||||
FilterReason? result;
|
||||
if (!isAllowed(channelId, text)) {
|
||||
final senders = <String>{senderKey};
|
||||
var sameSender = false;
|
||||
for (final entry in entries) {
|
||||
if (entry.key != key) continue;
|
||||
// Absolute gap between send times: delivery order does not matter.
|
||||
final gap = entry.sentAt.difference(at).abs();
|
||||
if (entry.sender == senderKey) {
|
||||
if (gap <= sameSenderWindow) sameSender = true;
|
||||
} else if (gap <= crossSenderWindow) {
|
||||
senders.add(entry.sender);
|
||||
}
|
||||
}
|
||||
if (sameSender) {
|
||||
result = FilterReason.duplicate;
|
||||
} else if (key.length >= crossSenderMinLength &&
|
||||
_wordCount(key) >= crossSenderMinWords &&
|
||||
senders.length >= crossSenderMinSenders) {
|
||||
result = FilterReason.crossSenderDuplicate;
|
||||
}
|
||||
}
|
||||
|
||||
entries.addLast(_SeenMessage(senderKey, key, at, arrived));
|
||||
if (entries.length > maxEntriesPerChannel) entries.removeFirst();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// [key] is already whitespace-collapsed by `normalizeForDuplicates`.
|
||||
static int _wordCount(String key) => key.isEmpty ? 0 : key.split(' ').length;
|
||||
|
||||
/// Exempts this text in this channel from duplicate hits for the session
|
||||
/// (used after "Not spam").
|
||||
void allow(String channelId, String text) {
|
||||
final key = MessageFilterText.normalizeForDuplicates(text);
|
||||
if (key.isEmpty) return;
|
||||
_allowed.putIfAbsent(channelId, () => <String>{}).add(key);
|
||||
}
|
||||
|
||||
bool isAllowed(String channelId, String text) {
|
||||
final allowed = _allowed[channelId];
|
||||
if (allowed == null || allowed.isEmpty) return false;
|
||||
return allowed.contains(MessageFilterText.normalizeForDuplicates(text));
|
||||
}
|
||||
|
||||
/// Forgets everything (seen texts and the allow-set).
|
||||
void clear() {
|
||||
_seen.clear();
|
||||
_allowed.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../models/message_filter.dart';
|
||||
import '../../storage/message_filter_store.dart';
|
||||
import 'duplicate_tracker.dart';
|
||||
import 'message_filter_text.dart';
|
||||
import 'ngram_spam_classifier.dart';
|
||||
|
||||
/// Decides whether incoming channel messages should be filtered, and owns the
|
||||
/// filter's settings, user rules and the learned classifier.
|
||||
///
|
||||
/// Filtered messages are never deleted; callers only tag them with the
|
||||
/// returned [FilterVerdict].
|
||||
class MessageFilterService extends ChangeNotifier {
|
||||
MessageFilterService({
|
||||
MessageFilterStore? store,
|
||||
DateTime Function()? clock,
|
||||
DuplicateTracker? duplicateTracker,
|
||||
NgramSpamClassifier? classifier,
|
||||
}) : _store = store ?? MessageFilterStore(),
|
||||
_clock = clock ?? DateTime.now,
|
||||
_tracker = duplicateTracker ?? DuplicateTracker(),
|
||||
_classifier = classifier ?? NgramSpamClassifier();
|
||||
|
||||
/// Minimum classifier probability for a [FilterReason.learned] verdict.
|
||||
static const double learnedThreshold = 0.80;
|
||||
|
||||
/// Spam taps needed before the learned classifier is consulted.
|
||||
static const int minSpamExamplesForLearning = 2;
|
||||
|
||||
static const int maxSpamExamples = 200;
|
||||
static const int maxNotSpamExamples = 200;
|
||||
static const int maxRecentClean = 300;
|
||||
|
||||
/// Longest text kept as a training example (longer text is truncated).
|
||||
static const int maxExampleTextLength = 500;
|
||||
|
||||
/// Recent-clean entries buffered before they are written to storage.
|
||||
static const int _recentCleanSaveEvery = 10;
|
||||
|
||||
final MessageFilterStore _store;
|
||||
final DateTime Function() _clock;
|
||||
final DuplicateTracker _tracker;
|
||||
final NgramSpamClassifier _classifier;
|
||||
|
||||
MessageFilterSettings _settings = MessageFilterSettings.defaults;
|
||||
List<FilterRule> _rules = <FilterRule>[];
|
||||
List<FilterExample> _spamExamples = <FilterExample>[];
|
||||
List<FilterExample> _hamExamples = <FilterExample>[];
|
||||
List<FilterExample> _recentClean = <FilterExample>[];
|
||||
int _unsavedCleanCount = 0;
|
||||
bool _disposed = false;
|
||||
|
||||
/// A retrain is queued (see [_scheduleRetrainIfInactive]).
|
||||
bool _retrainPending = false;
|
||||
|
||||
static int _idCounter = 0;
|
||||
|
||||
/// Unique-enough rule id: microsecond timestamp plus a process counter.
|
||||
static String newRuleId() {
|
||||
final micros = DateTime.now().microsecondsSinceEpoch.toRadixString(36);
|
||||
final counter = (_idCounter++).toRadixString(36);
|
||||
return 'r$micros$counter';
|
||||
}
|
||||
|
||||
MessageFilterSettings get settings => _settings;
|
||||
List<FilterRule> get rules => List.unmodifiable(_rules);
|
||||
int get spamExampleCount => _spamExamples.length;
|
||||
int get notSpamExampleCount => _hamExamples.length;
|
||||
|
||||
/// Implicit "not spam" examples currently remembered (for tests).
|
||||
@visibleForTesting
|
||||
int get recentCleanCount => _recentClean.length;
|
||||
|
||||
/// Loads persisted state and trains the classifier.
|
||||
Future<void> load() async {
|
||||
try {
|
||||
_settings = _store.loadSettings();
|
||||
_rules = _store.loadRules();
|
||||
_spamExamples = _store.loadSpamExamples();
|
||||
_hamExamples = _store.loadHamExamples();
|
||||
_recentClean = _store.loadRecentClean();
|
||||
} catch (e) {
|
||||
debugPrint('MessageFilterService: load failed: $e');
|
||||
}
|
||||
_trimToCap(_spamExamples, maxSpamExamples);
|
||||
_trimToCap(_hamExamples, maxNotSpamExamples);
|
||||
_trimToCap(_recentClean, maxRecentClean);
|
||||
_unsavedCleanCount = 0;
|
||||
_retrain();
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Whether filtering applies to [channelId] (master switch on and the
|
||||
/// channel not excluded).
|
||||
bool isChannelFiltered(String channelId) =>
|
||||
_settings.enabled && !_settings.excludedChannelIds.contains(channelId);
|
||||
|
||||
/// Evaluates an incoming channel message. Returns a verdict when the message
|
||||
/// should be filtered, otherwise null. Records the text for duplicate
|
||||
/// detection whenever the message is eligible for filtering at all.
|
||||
///
|
||||
/// [sentAt] is the message's own timestamp. Duplicate windows are measured
|
||||
/// between send times, so history synced in a burst after reconnecting is
|
||||
/// not mistaken for a flood; without it the local clock is used.
|
||||
FilterVerdict? evaluate({
|
||||
required String channelId,
|
||||
required String sender,
|
||||
required String text,
|
||||
DateTime? sentAt,
|
||||
bool isOutgoing = false,
|
||||
bool isReaction = false,
|
||||
}) {
|
||||
if (!isChannelFiltered(channelId)) return null;
|
||||
if (isOutgoing || isReaction) return null;
|
||||
if (text.trim().isEmpty) return null;
|
||||
if (MessageFilterText.isStructuredPayload(text)) return null;
|
||||
|
||||
// Always record (even when a rule matches) so floods keep being caught.
|
||||
final duplicateReason = _tracker.check(
|
||||
channelId: channelId,
|
||||
sender: sender,
|
||||
text: text,
|
||||
at: sentAt ?? _clock(),
|
||||
receivedAt: _clock(),
|
||||
);
|
||||
|
||||
for (final rule in _rules) {
|
||||
if (!rule.enabled || rule.field == FilterRuleField.text) continue;
|
||||
if (MessageFilterText.matchesSender(rule, sender)) {
|
||||
return FilterVerdict(
|
||||
reason: FilterReason.senderRule,
|
||||
detail: rule.pattern,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (final rule in _rules) {
|
||||
if (!rule.enabled || rule.field == FilterRuleField.sender) continue;
|
||||
if (MessageFilterText.matchesText(rule, text)) {
|
||||
return FilterVerdict(
|
||||
reason: FilterReason.textRule,
|
||||
detail: rule.pattern,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (_settings.repeatedCharacters &&
|
||||
MessageFilterText.hasRepeatedCharacters(text)) {
|
||||
return const FilterVerdict(reason: FilterReason.repeatedCharacters);
|
||||
}
|
||||
|
||||
if (_settings.duplicates && duplicateReason != null) {
|
||||
return FilterVerdict(reason: duplicateReason);
|
||||
}
|
||||
|
||||
if (_settings.learning &&
|
||||
_spamExamples.length >= minSpamExamplesForLearning &&
|
||||
_classifier.isTrained &&
|
||||
!_tracker.isAllowed(channelId, text)) {
|
||||
final probability = _classifier.probability(sender, text);
|
||||
if (probability >= learnedThreshold) {
|
||||
return const FilterVerdict(reason: FilterReason.learned);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Remembers an unfiltered incoming message as an implicit "not spam"
|
||||
/// training example (rolling buffer of [maxRecentClean]).
|
||||
void recordClean({required String sender, required String text}) {
|
||||
if (!_settings.enabled || !_settings.learning) return;
|
||||
if (text.trim().isEmpty || MessageFilterText.isStructuredPayload(text)) {
|
||||
return;
|
||||
}
|
||||
final example = _example(sender, text);
|
||||
if (_recentClean.isNotEmpty) {
|
||||
final last = _recentClean.last;
|
||||
if (last.sender == example.sender && last.text == example.text) return;
|
||||
}
|
||||
_recentClean.add(example);
|
||||
_trimToCap(_recentClean, maxRecentClean);
|
||||
_unsavedCleanCount++;
|
||||
if (_unsavedCleanCount >= _recentCleanSaveEvery) {
|
||||
_saveRecentClean();
|
||||
}
|
||||
_scheduleRetrainIfInactive();
|
||||
}
|
||||
|
||||
/// The classifier needs both spam and clean examples to train. When the
|
||||
/// user has marked enough spam but training had no clean examples yet (for
|
||||
/// example the first messages received were the ones marked), it stays
|
||||
/// untrained; the first clean example to arrive afterwards activates it.
|
||||
/// Runs once, as a microtask, so message intake is not blocked and a burst
|
||||
/// of clean messages trains a single time.
|
||||
void _scheduleRetrainIfInactive() {
|
||||
if (_retrainPending || _classifier.isTrained) return;
|
||||
if (_spamExamples.length < minSpamExamplesForLearning) return;
|
||||
_retrainPending = true;
|
||||
scheduleMicrotask(() {
|
||||
_retrainPending = false;
|
||||
if (_disposed || _classifier.isTrained) return;
|
||||
_retrain();
|
||||
});
|
||||
}
|
||||
|
||||
/// User tapped "Spam": store the example and retrain.
|
||||
Future<void> markSpam({required String sender, required String text}) async {
|
||||
final key = MessageFilterText.normalize(text);
|
||||
if (key.isEmpty) return;
|
||||
_recentClean.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
|
||||
_hamExamples.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
|
||||
_addExample(_spamExamples, _example(sender, text), maxSpamExamples);
|
||||
_retrain();
|
||||
_notify();
|
||||
await _guardSave(() async {
|
||||
await _store.saveSpamExamples(_spamExamples);
|
||||
await _store.saveHamExamples(_hamExamples);
|
||||
await _flushRecentClean();
|
||||
});
|
||||
}
|
||||
|
||||
/// User tapped "Not spam": store the example, exempt this text in this
|
||||
/// channel from duplicate and learned hits for the session, and retrain.
|
||||
Future<void> markNotSpam({
|
||||
required String channelId,
|
||||
required String sender,
|
||||
required String text,
|
||||
}) async {
|
||||
_tracker.allow(channelId, text);
|
||||
final key = MessageFilterText.normalize(text);
|
||||
if (key.isEmpty) {
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
_spamExamples.removeWhere(
|
||||
(e) => MessageFilterText.normalize(e.text) == key,
|
||||
);
|
||||
_addExample(_hamExamples, _example(sender, text), maxNotSpamExamples);
|
||||
_retrain();
|
||||
_notify();
|
||||
await _guardSave(() async {
|
||||
await _store.saveSpamExamples(_spamExamples);
|
||||
await _store.saveHamExamples(_hamExamples);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> updateSettings(MessageFilterSettings settings) async {
|
||||
final learningTurnedOn = settings.learning && !_settings.learning;
|
||||
_settings = settings;
|
||||
if (learningTurnedOn) _retrain();
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveSettings(_settings));
|
||||
}
|
||||
|
||||
Future<void> setChannelExcluded(String channelId, bool excluded) async {
|
||||
final current = _settings.excludedChannelIds;
|
||||
if (current.contains(channelId) == excluded) return;
|
||||
final next = Set<String>.of(current);
|
||||
if (excluded) {
|
||||
next.add(channelId);
|
||||
} else {
|
||||
next.remove(channelId);
|
||||
}
|
||||
await updateSettings(_settings.copyWith(excludedChannelIds: next));
|
||||
}
|
||||
|
||||
/// Adds [rule] (replacing any rule with the same id) at the end, or at
|
||||
/// [index] (clamped) when given, e.g. to undo a delete in place.
|
||||
Future<void> addRule(FilterRule rule, {int? index}) async {
|
||||
final others = _rules.where((r) => r.id != rule.id).toList();
|
||||
if (index == null) {
|
||||
others.add(rule);
|
||||
} else {
|
||||
others.insert(index.clamp(0, others.length), rule);
|
||||
}
|
||||
_rules = others;
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveRules(_rules));
|
||||
}
|
||||
|
||||
Future<void> updateRule(FilterRule rule) async {
|
||||
final index = _rules.indexWhere((r) => r.id == rule.id);
|
||||
if (index < 0) {
|
||||
await addRule(rule);
|
||||
return;
|
||||
}
|
||||
_rules = List.of(_rules)..[index] = rule;
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveRules(_rules));
|
||||
}
|
||||
|
||||
Future<void> removeRule(String id) async {
|
||||
final before = _rules.length;
|
||||
_rules = _rules.where((r) => r.id != id).toList();
|
||||
if (_rules.length == before) return;
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveRules(_rules));
|
||||
}
|
||||
|
||||
/// Forgets all Spam / Not spam taps and implicit examples. Rules are kept.
|
||||
Future<void> resetLearning() async {
|
||||
_spamExamples = <FilterExample>[];
|
||||
_hamExamples = <FilterExample>[];
|
||||
_recentClean = <FilterExample>[];
|
||||
_unsavedCleanCount = 0;
|
||||
_classifier.reset();
|
||||
_notify();
|
||||
await _guardSave(() async {
|
||||
await _store.saveSpamExamples(_spamExamples);
|
||||
await _store.saveHamExamples(_hamExamples);
|
||||
await _store.saveRecentClean(_recentClean);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
if (_unsavedCleanCount > 0) _saveRecentClean();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
FilterExample _example(String sender, String text) {
|
||||
final trimmed = text.trim();
|
||||
return FilterExample(
|
||||
sender: sender,
|
||||
text: trimmed.length > maxExampleTextLength
|
||||
? trimmed.substring(0, maxExampleTextLength)
|
||||
: trimmed,
|
||||
addedAtMs: _clock().millisecondsSinceEpoch,
|
||||
);
|
||||
}
|
||||
|
||||
/// Adds [example] as the newest entry, replacing an identical one.
|
||||
static void _addExample(
|
||||
List<FilterExample> list,
|
||||
FilterExample example,
|
||||
int cap,
|
||||
) {
|
||||
final key = MessageFilterText.normalize(example.text);
|
||||
final sender = MessageFilterText.normalize(example.sender);
|
||||
list.removeWhere(
|
||||
(e) =>
|
||||
MessageFilterText.normalize(e.text) == key &&
|
||||
MessageFilterText.normalize(e.sender) == sender,
|
||||
);
|
||||
list.add(example);
|
||||
_trimToCap(list, cap);
|
||||
}
|
||||
|
||||
static void _trimToCap(List<FilterExample> list, int cap) {
|
||||
if (list.length > cap) list.removeRange(0, list.length - cap);
|
||||
}
|
||||
|
||||
void _retrain() {
|
||||
if (_spamExamples.isEmpty) {
|
||||
_classifier.reset();
|
||||
return;
|
||||
}
|
||||
final stopwatch = Stopwatch()..start();
|
||||
_classifier.train(_spamExamples, [..._hamExamples, ..._recentClean]);
|
||||
stopwatch.stop();
|
||||
if (stopwatch.elapsedMilliseconds > 200) {
|
||||
debugPrint(
|
||||
'MessageFilterService: classifier training took '
|
||||
'${stopwatch.elapsedMilliseconds} ms',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _flushRecentClean() async {
|
||||
_unsavedCleanCount = 0;
|
||||
await _store.saveRecentClean(_recentClean);
|
||||
}
|
||||
|
||||
void _saveRecentClean() {
|
||||
_guardSave(_flushRecentClean);
|
||||
}
|
||||
|
||||
Future<void> _guardSave(Future<void> Function() save) async {
|
||||
try {
|
||||
await save();
|
||||
} catch (e) {
|
||||
debugPrint('MessageFilterService: save failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import '../../models/app_settings.dart' show defaultCyr2LatCharMap;
|
||||
import '../../models/message_filter.dart';
|
||||
|
||||
/// Text helpers shared by the message filter: normalization (so look-alike
|
||||
/// characters, accents and invisible characters cannot dodge a rule), rule
|
||||
/// matching and the structured-payload check.
|
||||
class MessageFilterText {
|
||||
MessageFilterText._();
|
||||
|
||||
static final RegExp _whitespace = RegExp(r'\s+', unicode: true);
|
||||
static final RegExp _mention = RegExp(r'@\[[^\]]*\]');
|
||||
static final RegExp _nonWordChars = RegExp(
|
||||
r'[^\p{L}\p{N}\s]+',
|
||||
unicode: true,
|
||||
);
|
||||
static final RegExp _repeatedChars = RegExp(r'(\S)\1{7,}', unicode: true);
|
||||
|
||||
static final Map<int, String> _foldMap = _buildFoldMap();
|
||||
|
||||
static Map<int, String> _buildFoldMap() {
|
||||
final map = <int, String>{};
|
||||
void addAll(String chars, String replacement) {
|
||||
for (final rune in chars.runes) {
|
||||
map[rune] = replacement;
|
||||
}
|
||||
}
|
||||
|
||||
// Accented Latin (lower case only: input is lower-cased first).
|
||||
addAll('àáâãäåāăąǎȁȃạảấầẩẫậắằẳẵặ', 'a');
|
||||
addAll('çćĉċč', 'c');
|
||||
addAll('ďđ', 'd');
|
||||
addAll('èéêëēĕėęěȅȇẹẻẽếềểễệ', 'e');
|
||||
addAll('ĝğġģ', 'g');
|
||||
addAll('ĥħ', 'h');
|
||||
addAll('ìíîïĩīĭįıǐȉȋỉị', 'i');
|
||||
addAll('ĵ', 'j');
|
||||
addAll('ķ', 'k');
|
||||
addAll('ĺļľŀł', 'l');
|
||||
addAll('ñńņňʼn', 'n');
|
||||
addAll('òóôõöøōŏőǒȍȏọỏốồổỗộớờởỡợơ', 'o');
|
||||
addAll('ŕŗř', 'r');
|
||||
addAll('śŝşšș', 's');
|
||||
addAll('ţťŧț', 't');
|
||||
addAll('ùúûüũūŭůűųǔȕȗụủứừửữựư', 'u');
|
||||
addAll('ŵ', 'w');
|
||||
addAll('ýÿŷỳỵỷỹ', 'y');
|
||||
addAll('źżž', 'z');
|
||||
map['ß'.runes.first] = 'ss';
|
||||
map['æ'.runes.first] = 'ae';
|
||||
map['œ'.runes.first] = 'oe';
|
||||
map['þ'.runes.first] = 'th';
|
||||
|
||||
// Cyrillic look-alikes (reuse the app's Cyr2Lat table, lower-cased).
|
||||
defaultCyr2LatCharMap.forEach((from, to) {
|
||||
map[from.toLowerCase().runes.first] = to.toLowerCase();
|
||||
});
|
||||
|
||||
// Greek look-alikes.
|
||||
const greek = {
|
||||
'ο': 'o',
|
||||
'α': 'a',
|
||||
'ε': 'e',
|
||||
'ι': 'i',
|
||||
'κ': 'k',
|
||||
'ν': 'v',
|
||||
'ρ': 'p',
|
||||
'τ': 't',
|
||||
'υ': 'u',
|
||||
'χ': 'x',
|
||||
};
|
||||
greek.forEach((from, to) => map[from.runes.first] = to);
|
||||
return map;
|
||||
}
|
||||
|
||||
static bool _isInvisible(int rune) =>
|
||||
(rune >= 0x200B && rune <= 0x200D) ||
|
||||
rune == 0x2060 ||
|
||||
rune == 0xFEFF ||
|
||||
rune == 0x00AD;
|
||||
|
||||
static bool _isCombiningMark(int rune) =>
|
||||
(rune >= 0x0300 && rune <= 0x036F) ||
|
||||
(rune >= 0x1AB0 && rune <= 0x1AFF) ||
|
||||
(rune >= 0x1DC0 && rune <= 0x1DFF) ||
|
||||
(rune >= 0x20D0 && rune <= 0x20FF) ||
|
||||
(rune >= 0xFE20 && rune <= 0xFE2F);
|
||||
|
||||
/// Maps fullwidth and "mathematical" styled letters/digits (bold, italic,
|
||||
/// script, …) to plain ASCII, returning null for everything else.
|
||||
static int? _foldStyledAscii(int rune) {
|
||||
// Fullwidth forms.
|
||||
if (rune >= 0xFF41 && rune <= 0xFF5A) return 0x61 + rune - 0xFF41;
|
||||
if (rune >= 0xFF21 && rune <= 0xFF3A) return 0x61 + rune - 0xFF21;
|
||||
if (rune >= 0xFF10 && rune <= 0xFF19) return 0x30 + rune - 0xFF10;
|
||||
// Mathematical alphanumeric symbols: repeating A-Z a-z blocks.
|
||||
if (rune >= 0x1D400 && rune <= 0x1D6A3) {
|
||||
final offset = (rune - 0x1D400) % 52;
|
||||
return 0x61 + (offset < 26 ? offset : offset - 26);
|
||||
}
|
||||
if (rune >= 0x1D7CE && rune <= 0x1D7FF) {
|
||||
return 0x30 + (rune - 0x1D7CE) % 10;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Lower-cases, folds accents and look-alike characters, removes invisible
|
||||
/// characters and leaves the whitespace untouched.
|
||||
static String _fold(String text) {
|
||||
final lower = text.toLowerCase();
|
||||
final buffer = StringBuffer();
|
||||
for (final rune in lower.runes) {
|
||||
if (_isInvisible(rune) || _isCombiningMark(rune)) continue;
|
||||
final styled = _foldStyledAscii(rune);
|
||||
if (styled != null) {
|
||||
buffer.writeCharCode(styled);
|
||||
continue;
|
||||
}
|
||||
final mapped = _foldMap[rune];
|
||||
if (mapped != null) {
|
||||
buffer.write(mapped);
|
||||
} else {
|
||||
buffer.writeCharCode(rune);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/// Canonical form used for rule matching and classifier features.
|
||||
static String normalize(String text) {
|
||||
if (text.isEmpty) return '';
|
||||
return _fold(text).replaceAll(_whitespace, ' ').trim();
|
||||
}
|
||||
|
||||
/// Looser form used to detect repeated messages: also drops `@[name]`
|
||||
/// mentions, punctuation and emoji so trivial variations still match.
|
||||
static String normalizeForDuplicates(String text) {
|
||||
final normalized = normalize(text);
|
||||
if (normalized.isEmpty) return '';
|
||||
return normalized
|
||||
.replaceAll(_mention, ' ')
|
||||
.replaceAll(_nonWordChars, ' ')
|
||||
.replaceAll(_whitespace, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/// True when the same visible character appears 8 or more times in a row.
|
||||
///
|
||||
/// Whitespace runs are ignored (they are layout, not content).
|
||||
static bool hasRepeatedCharacters(String text) {
|
||||
if (text.length < 8) return false;
|
||||
return _repeatedChars.hasMatch(_fold(text));
|
||||
}
|
||||
|
||||
/// GIF / structured payloads (same check as the channel send path).
|
||||
static bool isStructuredPayload(String text) {
|
||||
final trimmed = text.trim();
|
||||
return trimmed.startsWith('g:') || trimmed.startsWith('m:');
|
||||
}
|
||||
|
||||
static final Map<String, RegExp> _wholeWordCache = {};
|
||||
|
||||
static RegExp _wholeWordRegExp(String normalizedPattern) {
|
||||
final cached = _wholeWordCache[normalizedPattern];
|
||||
if (cached != null) return cached;
|
||||
if (_wholeWordCache.length > 256) _wholeWordCache.clear();
|
||||
final regExp = RegExp(
|
||||
'(?<![\\p{L}\\p{N}])${RegExp.escape(normalizedPattern)}(?![\\p{L}\\p{N}])',
|
||||
unicode: true,
|
||||
);
|
||||
_wholeWordCache[normalizedPattern] = regExp;
|
||||
return regExp;
|
||||
}
|
||||
|
||||
static bool _matchesNormalized(
|
||||
String normalizedPattern,
|
||||
FilterRuleMatch match,
|
||||
String normalizedTarget,
|
||||
) {
|
||||
if (normalizedPattern.isEmpty || normalizedTarget.isEmpty) return false;
|
||||
switch (match) {
|
||||
case FilterRuleMatch.contains:
|
||||
return normalizedTarget.contains(normalizedPattern);
|
||||
case FilterRuleMatch.exact:
|
||||
return normalizedTarget == normalizedPattern;
|
||||
case FilterRuleMatch.wholeWord:
|
||||
if (!normalizedTarget.contains(normalizedPattern)) return false;
|
||||
return _wholeWordRegExp(normalizedPattern).hasMatch(normalizedTarget);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether [rule]'s pattern matches [sender] (ignores the rule's field).
|
||||
static bool matchesSender(FilterRule rule, String sender) =>
|
||||
_matchesNormalized(
|
||||
normalize(rule.pattern),
|
||||
rule.match,
|
||||
normalize(sender),
|
||||
);
|
||||
|
||||
/// Whether [rule]'s pattern matches [text] (ignores the rule's field).
|
||||
static bool matchesText(FilterRule rule, String text) =>
|
||||
_matchesNormalized(normalize(rule.pattern), rule.match, normalize(text));
|
||||
|
||||
/// Whether [rule] matches the message, honouring the rule's field.
|
||||
///
|
||||
/// The rule's `enabled` flag is not checked here; callers decide whether
|
||||
/// disabled rules apply.
|
||||
static bool matchesRule(
|
||||
FilterRule rule, {
|
||||
required String sender,
|
||||
required String text,
|
||||
}) {
|
||||
switch (rule.field) {
|
||||
case FilterRuleField.sender:
|
||||
return matchesSender(rule, sender);
|
||||
case FilterRuleField.text:
|
||||
return matchesText(rule, text);
|
||||
case FilterRuleField.both:
|
||||
return matchesSender(rule, sender) || matchesText(rule, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../../models/message_filter.dart';
|
||||
import 'message_filter_text.dart';
|
||||
|
||||
/// A sparse, L2-normalised feature vector (hashed bucket ids and values).
|
||||
class _SparseVector {
|
||||
final Int32List indices;
|
||||
final Float64List values;
|
||||
const _SparseVector(this.indices, this.values);
|
||||
}
|
||||
|
||||
/// Small on-device spam classifier trained from the user's "Spam" and
|
||||
/// "Not spam" taps.
|
||||
///
|
||||
/// Features are hashed character n-grams (3..5, within word boundaries), word
|
||||
/// unigrams/bigrams and the sender name; the model is a class-balanced,
|
||||
/// L2-regularised logistic regression trained with seeded SGD. Training and
|
||||
/// scoring are pure Dart and fully deterministic for the same inputs.
|
||||
class NgramSpamClassifier {
|
||||
NgramSpamClassifier({
|
||||
this.epochs = 200,
|
||||
this.learningRate = 0.5,
|
||||
this.lambda = 1e-4,
|
||||
this.seed = 42,
|
||||
});
|
||||
|
||||
static const int bucketBits = 18;
|
||||
static const int bucketCount = 1 << bucketBits;
|
||||
static const int _bucketMask = bucketCount - 1;
|
||||
static const int minCharGram = 3;
|
||||
static const int maxCharGram = 5;
|
||||
|
||||
final int epochs;
|
||||
final double learningRate;
|
||||
final double lambda;
|
||||
final int seed;
|
||||
|
||||
Map<int, double> _weights = const {};
|
||||
double _bias = 0;
|
||||
bool _trained = false;
|
||||
|
||||
bool get isTrained => _trained;
|
||||
|
||||
/// Number of non-zero weights in the trained model.
|
||||
int get featureCount => _weights.length;
|
||||
|
||||
void reset() {
|
||||
_weights = const {};
|
||||
_bias = 0;
|
||||
_trained = false;
|
||||
}
|
||||
|
||||
static final RegExp _wordToken = RegExp(r'[\p{L}\p{N}]+', unicode: true);
|
||||
|
||||
/// Stable 32-bit FNV-1a over the UTF-16 code units of [value].
|
||||
///
|
||||
/// The prime multiply is split (0x01000193 = 2^24 + 0x193) so intermediate
|
||||
/// values stay below 2^53 and the result is identical on the web.
|
||||
static int fnv1a32(String value) {
|
||||
var hash = 0x811C9DC5;
|
||||
for (var i = 0; i < value.length; i++) {
|
||||
hash = (hash ^ value.codeUnitAt(i)) & 0xFFFFFFFF;
|
||||
hash = (hash * 0x193 + ((hash & 0xFF) << 24)) & 0xFFFFFFFF;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// Raw (unhashed) feature strings for a message, exposed for tests.
|
||||
static List<String> featureStrings(String sender, String text) {
|
||||
final features = <String>[];
|
||||
final normalized = MessageFilterText.normalize(text);
|
||||
if (normalized.isNotEmpty) {
|
||||
for (final word in normalized.split(' ')) {
|
||||
if (word.isEmpty) continue;
|
||||
final padded = ' $word ';
|
||||
if (padded.length <= minCharGram) {
|
||||
features.add('c:$padded');
|
||||
continue;
|
||||
}
|
||||
for (var n = minCharGram; n <= maxCharGram; n++) {
|
||||
if (padded.length < n) {
|
||||
features.add('c:$padded');
|
||||
break;
|
||||
}
|
||||
for (var i = 0; i + n <= padded.length; i++) {
|
||||
features.add('c:${padded.substring(i, i + n)}');
|
||||
}
|
||||
}
|
||||
}
|
||||
final words = _wordToken
|
||||
.allMatches(normalized)
|
||||
.map((m) => m.group(0)!)
|
||||
.toList(growable: false);
|
||||
for (var i = 0; i < words.length; i++) {
|
||||
features.add('w:${words[i]}');
|
||||
if (i + 1 < words.length) {
|
||||
features.add('b:${words[i]} ${words[i + 1]}');
|
||||
}
|
||||
}
|
||||
}
|
||||
final normalizedSender = MessageFilterText.normalize(sender);
|
||||
if (normalizedSender.isNotEmpty) {
|
||||
features.add('s:$normalizedSender');
|
||||
}
|
||||
return features;
|
||||
}
|
||||
|
||||
static _SparseVector _vectorize(String sender, String text) {
|
||||
final counts = <int, int>{};
|
||||
for (final feature in featureStrings(sender, text)) {
|
||||
final bucket = fnv1a32(feature) & _bucketMask;
|
||||
counts[bucket] = (counts[bucket] ?? 0) + 1;
|
||||
}
|
||||
final keys = counts.keys.toList()..sort();
|
||||
final indices = Int32List(keys.length);
|
||||
final values = Float64List(keys.length);
|
||||
var sumSquares = 0.0;
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
final value = 1 + math.log(counts[keys[i]]!);
|
||||
indices[i] = keys[i];
|
||||
values[i] = value;
|
||||
sumSquares += value * value;
|
||||
}
|
||||
if (sumSquares > 0) {
|
||||
final norm = math.sqrt(sumSquares);
|
||||
for (var i = 0; i < values.length; i++) {
|
||||
values[i] /= norm;
|
||||
}
|
||||
}
|
||||
return _SparseVector(indices, values);
|
||||
}
|
||||
|
||||
static double _sigmoid(double z) {
|
||||
if (z >= 0) {
|
||||
return 1 / (1 + math.exp(-z));
|
||||
}
|
||||
final e = math.exp(z);
|
||||
return e / (1 + e);
|
||||
}
|
||||
|
||||
/// Trains from scratch. Needs at least one example of each class; otherwise
|
||||
/// the classifier is left untrained (and [probability] returns 0).
|
||||
void train(List<FilterExample> spam, List<FilterExample> ham) {
|
||||
reset();
|
||||
if (spam.isEmpty || ham.isEmpty) return;
|
||||
|
||||
// Vectorize and remap hashed buckets to a compact local index space.
|
||||
final localIndex = <int, int>{};
|
||||
final docs = <_SparseVector>[];
|
||||
final labels = <double>[];
|
||||
void addDoc(FilterExample example, double label) {
|
||||
final vector = _vectorize(example.sender, example.text);
|
||||
if (vector.indices.isEmpty) return;
|
||||
final local = Int32List(vector.indices.length);
|
||||
for (var i = 0; i < vector.indices.length; i++) {
|
||||
local[i] = localIndex.putIfAbsent(
|
||||
vector.indices[i],
|
||||
() => localIndex.length,
|
||||
);
|
||||
}
|
||||
docs.add(_SparseVector(local, vector.values));
|
||||
labels.add(label);
|
||||
}
|
||||
|
||||
for (final example in spam) {
|
||||
addDoc(example, 1);
|
||||
}
|
||||
for (final example in ham) {
|
||||
addDoc(example, 0);
|
||||
}
|
||||
|
||||
final n = docs.length;
|
||||
final nPos = labels.where((y) => y == 1).length;
|
||||
final nNeg = n - nPos;
|
||||
if (nPos == 0 || nNeg == 0) return;
|
||||
final wPos = n / (2 * nPos);
|
||||
final wNeg = n / (2 * nNeg);
|
||||
|
||||
final weights = Float64List(localIndex.length);
|
||||
var bias = 0.0;
|
||||
final order = List<int>.generate(n, (i) => i);
|
||||
final random = math.Random(seed);
|
||||
// Per-step decay; lambda is the per-sample L2 strength.
|
||||
final decay = 1 - learningRate * lambda;
|
||||
|
||||
for (var epoch = 0; epoch < epochs; epoch++) {
|
||||
order.shuffle(random);
|
||||
final rate = learningRate / (1 + epoch * 0.02);
|
||||
for (final docIndex in order) {
|
||||
final doc = docs[docIndex];
|
||||
final y = labels[docIndex];
|
||||
var z = bias;
|
||||
for (var i = 0; i < doc.indices.length; i++) {
|
||||
z += weights[doc.indices[i]] * doc.values[i];
|
||||
}
|
||||
final sampleWeight = y == 1 ? wPos : wNeg;
|
||||
final gradient = (_sigmoid(z) - y) * sampleWeight;
|
||||
for (var i = 0; i < doc.indices.length; i++) {
|
||||
final j = doc.indices[i];
|
||||
weights[j] = weights[j] * decay - rate * gradient * doc.values[i];
|
||||
}
|
||||
bias -= rate * gradient;
|
||||
}
|
||||
}
|
||||
|
||||
final compact = <int, double>{};
|
||||
localIndex.forEach((bucket, local) {
|
||||
final weight = weights[local];
|
||||
if (weight != 0) compact[bucket] = weight;
|
||||
});
|
||||
_weights = compact;
|
||||
_bias = bias;
|
||||
_trained = true;
|
||||
}
|
||||
|
||||
/// Probability (0..1) that the message is spam; 0 when untrained.
|
||||
double probability(String sender, String text) {
|
||||
if (!_trained) return 0.0;
|
||||
final vector = _vectorize(sender, text);
|
||||
if (vector.indices.isEmpty) return 0.0;
|
||||
var z = _bias;
|
||||
for (var i = 0; i < vector.indices.length; i++) {
|
||||
final weight = _weights[vector.indices[i]];
|
||||
if (weight != null) z += weight * vector.values[i];
|
||||
}
|
||||
return _sigmoid(z);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user