Merge upstream/dev (9 commits) [upstream-sync]

Konflikt v lib/screens/channel_chat_screen.dart: upstream přidal do
_buildMessageBubble parametr showFilterBanner (filtr spamu), my tam máme
terminálový styl. V terminálovém režimu se banner (není spam / skrýt)
vykreslí nad řádkem zprávy, jinak by filtrované zprávy přišly o akce.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-08 00:43:30 +01:00
commit 8a9d9ba0b7
86 files changed
+13643 -301

No files matched your search

+14
View File
@@ -710,4 +710,18 @@ class AppSettingsService extends ChangeNotifier {
),
);
}
Future<void> resetRoutingSettingsToDefault() async {
await updateSettings(
_settings.copyWith(
maxRouteWeight: AppSettings.defaultMaxRouteWeight,
initialRouteWeight: AppSettings.defaultInitialRouteWeight,
routeWeightSuccessIncrement:
AppSettings.defaultRouteWeightSuccessIncrement,
routeWeightFailureDecrement:
AppSettings.defaultRouteWeightFailureDecrement,
maxMessageRetries: AppSettings.defaultMaxMessageRetries,
),
);
}
}
@@ -0,0 +1,158 @@
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 same-sender rule only applies to texts of at least
/// [sameSenderMinWords] words and [sameSenderMinLength] characters: people
/// naturally repeat short replies ("ok", "yes", "test" when checking reach),
/// while spam that gets re-posted is a whole sentence.
///
/// 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.sameSenderMinLength = 10,
this.sameSenderMinWords = 3,
this.crossSenderWindow = const Duration(minutes: 30),
this.crossSenderMinSenders = 3,
this.crossSenderMinLength = 10,
this.crossSenderMinWords = 6,
this.maxEntriesPerChannel = 1000,
});
final Duration sameSenderWindow;
/// Minimum length / word count for the same-sender rule (see class docs).
final int sameSenderMinLength;
final int sameSenderMinWords;
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 &&
key.length >= sameSenderMinLength &&
_wordCount(key) >= sameSenderMinWords) {
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,488 @@
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';
/// Trains a spam model from a job (see [MessageFilterService.new]).
typedef SpamTrainer = Future<SpamModel?> Function(SpamTrainingJob job);
/// 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,
SpamTrainer? trainer,
}) : _trainer = trainer ?? _trainInBackground,
_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;
/// Runs classifier training; a background isolate by default. Widget tests
/// pass [trainInline], since an isolate's result is never delivered under
/// the fake clock `testWidgets` runs on.
final SpamTrainer _trainer;
static Future<SpamModel?> _trainInBackground(SpamTrainingJob job) =>
compute(NgramSpamClassifier.fitInBackground, job);
/// Trains on the calling isolate. For tests.
@visibleForTesting
static Future<SpamModel?> trainInline(SpamTrainingJob job) async =>
NgramSpamClassifier.fitInBackground(job);
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;
/// Bumped on each retrain; a background result for an older generation is
/// discarded because newer examples have arrived since.
int _trainGeneration = 0;
Future<void> _training = Future<void>.value();
int _rulesRevision = 0;
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;
/// Changes whenever rules are added, edited or removed, so listeners can
/// re-apply rules to messages already stored.
int get rulesRevision => _rulesRevision;
/// Completes when the most recently started classifier training has been
/// applied (or discarded).
Future<void> get trainingSettled => _training;
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;
// Training runs in the background so app start-up does not wait for it.
unawaited(_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(),
);
final byRule = _matchRules(sender, text);
if (byRule != null) return byRule;
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;
}
/// The user-rule verdict for a message already stored, or null when no
/// enabled rule matches or [channelId] is not filtered. Unlike [evaluate]
/// it does not record anything, so it can be re-run over stored history
/// when the rules change.
FilterVerdict? ruleVerdict({
required String channelId,
required String sender,
required String text,
}) {
if (!isChannelFiltered(channelId)) return null;
if (text.trim().isEmpty || MessageFilterText.isStructuredPayload(text)) {
return null;
}
return _matchRules(sender, text);
}
FilterVerdict? _matchRules(String sender, String text) {
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,
);
}
}
return null;
}
/// Remembers an unfiltered incoming message in [channelId] as an implicit
/// "not spam" training example (rolling buffer of [maxRecentClean]).
///
/// Channels excluded from filtering are skipped: the user has stopped
/// judging them, so their unfiltered messages (spam included) say nothing
/// about what is clean.
void recordClean({
required String channelId,
required String sender,
required String text,
}) {
if (!isChannelFiltered(channelId) || !_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(() {
if (_disposed || _classifier.isTrained) {
_retrainPending = false;
return;
}
_retrain().whenComplete(() => _retrainPending = false);
});
}
/// 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);
final training = _retrain();
_notify();
await _guardSave(() async {
await _store.saveSpamExamples(_spamExamples);
await _store.saveHamExamples(_hamExamples);
await _flushRecentClean();
});
await training;
}
/// 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);
final training = _retrain();
_notify();
await _guardSave(() async {
await _store.saveSpamExamples(_spamExamples);
await _store.saveHamExamples(_hamExamples);
});
await training;
}
Future<void> updateSettings(MessageFilterSettings settings) async {
final learningTurnedOn = settings.learning && !_settings.learning;
_settings = settings;
final training = learningTurnedOn ? _retrain() : null;
_notify();
await _guardSave(() => _store.saveSettings(_settings));
if (training != null) await training;
}
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;
_rulesRevision++;
_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;
_rulesRevision++;
_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;
_rulesRevision++;
_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;
_trainGeneration++; // drop any training still running
_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);
}
/// Retrains from the current examples in a background isolate (training
/// is up to ~700 documents x 200 SGD epochs, too slow for the UI thread).
/// The previous model keeps scoring until the new one is ready. Completes
/// once the result is applied, or discarded because a newer retrain or a
/// reset started meanwhile.
Future<void> _retrain() {
final generation = ++_trainGeneration;
if (_spamExamples.isEmpty) {
_classifier.reset();
return _training = Future<void>.value();
}
final job = _classifier.trainingJob(List.of(_spamExamples), [
..._hamExamples,
..._recentClean,
]);
final stopwatch = Stopwatch()..start();
return _training = _trainer(job)
.then((model) {
if (_disposed || generation != _trainGeneration) return;
if (stopwatch.elapsedMilliseconds > 1000) {
debugPrint(
'MessageFilterService: classifier training took '
'${stopwatch.elapsedMilliseconds} ms',
);
}
if (model == null) {
_classifier.reset();
} else {
_classifier.use(model);
}
_notify();
})
.catchError((Object e) {
debugPrint('MessageFilterService: training failed: $e');
});
}
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,232 @@
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,
);
/// Shortest run of one character that counts as repeated characters.
static const int repeatedCharacterRun = 20;
// Digits are left out: long numbers (frequencies, coordinates, ids) are
// legitimate. Shorter runs are too: "Noooooooo!", "--------" separators
// and a row of emoji are ordinary chat.
static final RegExp _repeatedChars = RegExp(
'([^\\s\\p{N}])\\1{${repeatedCharacterRun - 1},}',
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 [repeatedCharacterRun] or
/// more times in a row (keyboard-mash floods such as "aaaaaaaaaaaaaaaaaaaa").
///
/// Whitespace and digit runs are ignored.
static bool hasRepeatedCharacters(String text) {
if (text.length < repeatedCharacterRun) 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,301 @@
import 'dart:math' as math;
import 'dart:typed_data';
import '../../models/message_filter.dart';
import 'message_filter_text.dart';
/// Weights and bias of a trained [NgramSpamClassifier]. Plain data, so
/// training can run in a background isolate and hand the result back.
class SpamModel {
final Map<int, double> weights;
final double bias;
const SpamModel(this.weights, this.bias);
}
/// Inputs for [NgramSpamClassifier.fitInBackground].
typedef SpamTrainingJob = ({
int epochs,
double learningRate,
double lambda,
int seed,
List<FilterExample> spam,
List<FilterExample> ham,
});
/// 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) {
final model = fit(
spam,
ham,
epochs: epochs,
learningRate: learningRate,
lambda: lambda,
seed: seed,
);
if (model == null) {
reset();
} else {
use(model);
}
}
/// The job [fitInBackground] runs for this classifier's settings.
SpamTrainingJob trainingJob(
List<FilterExample> spam,
List<FilterExample> ham,
) => (
epochs: epochs,
learningRate: learningRate,
lambda: lambda,
seed: seed,
spam: spam,
ham: ham,
);
/// Entry point for `compute`: trains on [job] and returns the model, or
/// null when either class has no usable examples.
static SpamModel? fitInBackground(SpamTrainingJob job) => fit(
job.spam,
job.ham,
epochs: job.epochs,
learningRate: job.learningRate,
lambda: job.lambda,
seed: job.seed,
);
/// Switches to [model] (from [fit] or [fitInBackground]).
void use(SpamModel model) {
_weights = model.weights;
_bias = model.bias;
_trained = true;
}
/// Pure training step: same inputs, same model. Null when either class has
/// no usable examples.
static SpamModel? fit(
List<FilterExample> spam,
List<FilterExample> ham, {
required int epochs,
required double learningRate,
required double lambda,
required int seed,
}) {
if (spam.isEmpty || ham.isEmpty) return null;
// 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 null;
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;
});
return SpamModel(compact, bias);
}
/// 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);
}
}