Spaces:
Running
Running
| import 'package:sqflite/sqflite.dart'; | |
| import 'storage_service.dart'; | |
| import '../kavacha/kavacha_pipeline.dart'; | |
| import '../kavacha/models/kavacha_models.dart'; | |
| // Represents the result of a scan | |
| class ScamResult { | |
| final bool isScam; | |
| final double confidence; | |
| final String category; | |
| final String threatLevel; | |
| final int triggeredLayer; | |
| final String layerLabel; | |
| ScamResult({ | |
| required this.isScam, | |
| required this.confidence, | |
| required this.category, | |
| required this.threatLevel, | |
| this.triggeredLayer = 0, | |
| this.layerLabel = '', | |
| }); | |
| } | |
| class ScamService { | |
| static final ScamService _instance = ScamService._internal(); | |
| factory ScamService() => _instance; | |
| ScamService._internal(); | |
| final StorageService _storage = StorageService(); | |
| final KavachaPipeline _pipeline = KavachaPipeline(); | |
| bool _isInit = false; | |
| Future<void> init() async { | |
| if (_isInit) return; | |
| try { | |
| await _pipeline.init(); | |
| _isInit = true; | |
| } catch (_) { | |
| // Handle initialization error | |
| } | |
| } | |
| Future<ScamResult> analyzeSms(String sender, String message) async { | |
| // Pipeline does the heavily lifting including whitelist, vector searches, etc. | |
| final result = await _pipeline.analyze(sender, message); | |
| final scamResult = result.verdict == Verdict.block ? result.asThreat() : result.asSafe(); | |
| if (scamResult.isScam) { | |
| // 3. Log to SQLite | |
| try { | |
| await _storage.insertScamLog({ | |
| 'sender': sender, | |
| 'message_preview': message.length > 100 ? message.substring(0, 100) : message, | |
| 'category': scamResult.category, | |
| 'confidence': scamResult.confidence, | |
| 'threat_level': scamResult.threatLevel, | |
| 'user_feedback': 'pending', | |
| 'created_at': DateTime.now().millisecondsSinceEpoch, | |
| }); | |
| } catch (e) { | |
| // Log error silently or use a logger | |
| } | |
| } | |
| return scamResult; | |
| } | |
| Future<void> processFeedback(String sender, String message, bool isScam) async { | |
| try { | |
| final Database db = await _storage.database; | |
| if (isScam) { | |
| await db.insert('scam_patterns', { | |
| 'pattern': message.length > 50 ? message.substring(0, 50) : message, | |
| 'category': 'User Confirmed', | |
| 'user_confirmed': 1, | |
| 'created_at': DateTime.now().millisecondsSinceEpoch, | |
| }); | |
| } else { | |
| await db.insert('whitelist', { | |
| 'sender': sender, | |
| 'created_at': DateTime.now().millisecondsSinceEpoch, | |
| }); | |
| } | |
| } catch (e) { | |
| print('Feedback write error: \$e'); | |
| } | |
| } | |
| } | |