LCOV - code coverage report
Current view: top level - lib/src/repository - arp_repository_impl.dart (source / functions) Coverage Total Hit
Test: lcov.info Lines: 100.0 % 58 58
Test Date: 2026-11-15 16:52:47 Functions: - 0 0

            Line data    Source code
       1              : import 'dart:async';
       2              : 
       3              : import 'package:drift/drift.dart';
       4              : import 'package:injectable/injectable.dart';
       5              : import 'package:logging/logging.dart';
       6              : import 'package:network_tools/network_tools.dart';
       7              : import 'package:network_tools/src/database/database_service.dart';
       8              : import 'package:network_tools/src/database/drift_database.dart';
       9              : import 'package:network_tools/src/device_info/arp_table_helper.dart';
      10              : import 'package:network_tools/src/repository/repository.dart';
      11              : 
      12              : @Injectable(as: Repository<ARPData>)
      13              : class ARPRepository implements Repository<ARPData> {
      14            6 :   const ARPRepository(this._database);
      15              : 
      16           18 :   static final arpDriftLogger = Logger("arp-drift-logger");
      17              :   final DatabaseService<AppDatabase> _database;
      18              : 
      19            6 :   @override
      20              :   Future<void> build() async {
      21           12 :     final database = await _database.open();
      22              :     // Counting is much cheaper than loading (and sorting) every entry.
      23              :     final row = await database!
      24            6 :         .customSelect('SELECT COUNT(*) AS arp_count FROM a_r_p_drift')
      25            6 :         .getSingle();
      26           12 :     if (row.read<int>('arp_count') > 0) {
      27            6 :       arpDriftLogger.fine("Skipping ARP table build, old entries found");
      28              :       return;
      29              :     }
      30           12 :     arpDriftLogger.fine("Building ARP table...");
      31              :     try {
      32              :       // Resolving every entry's host name here used to block startup for
      33              :       // seconds on macOS. Host names are resolved per discovered host by the
      34              :       // scanner instead, so only the numeric table is needed here.
      35           12 :       final entries = (await ARPTableHelper().buildNumericTable())
      36            6 :           .map(
      37           12 :             (e) => ARPDriftCompanion.insert(
      38            6 :               iPAddress: e.iPAddress,
      39            6 :               macAddress: e.macAddress,
      40            6 :               hostname: e.hostname,
      41            6 :               interfaceName: e.interfaceName,
      42            6 :               interfaceType: e.interfaceType,
      43            6 :               createdAt: DateTime.now(),
      44              :             ),
      45              :           )
      46            6 :           .toList();
      47            6 :       if (entries.isNotEmpty) {
      48           12 :         await database.batch((batch) {
      49           12 :           batch.insertAll(database.aRPDrift, entries);
      50              :         });
      51           24 :         arpDriftLogger.fine("ARP table built with ${entries.length} entries");
      52              :       }
      53              :     } catch (error, stackTrace) {
      54            3 :       arpDriftLogger.warning(
      55              :         "Failed to build ARP table, MAC addresses and vendor names will be "
      56              :         "unavailable: $error",
      57              :         error,
      58              :         stackTrace,
      59              :       );
      60              :     }
      61              :   }
      62              : 
      63            1 :   @override
      64              :   Future<void> close() async {
      65            2 :     final database = await _database.open();
      66              :     // Awaited: drift tears the connection and its background isolate down
      67              :     // asynchronously, so returning early leaves both alive.
      68            1 :     await database!.close();
      69              :   }
      70              : 
      71            2 :   Future<List<ARPDriftData>> _fullEntries() async {
      72            4 :     final database = await _database.open();
      73            2 :     final records = await (database!.select(
      74            2 :       database.aRPDrift,
      75           12 :     )..orderBy([(t) => OrderingTerm(expression: t.id)])).get();
      76              : 
      77            2 :     return records.toList();
      78              :   }
      79              : 
      80            2 :   @override
      81              :   Future<List<String>> entries() async {
      82            4 :     final database = await _database.open();
      83            2 :     final records = await (database!.select(
      84            2 :       database.aRPDrift,
      85           12 :     )..orderBy([(t) => OrderingTerm(expression: t.id)])).get();
      86              : 
      87            8 :     return records.map((e) => e.iPAddress).toList();
      88              :   }
      89              : 
      90            2 :   @override
      91              :   Future<ARPData?> entryFor(String address) async {
      92            4 :     final database = await _database.open();
      93            2 :     final records = await (database!.select(
      94            2 :       database.aRPDrift,
      95           10 :     )..where((t) => t.iPAddress.equals(address))).get();
      96            2 :     if (records.isNotEmpty) {
      97            3 :       arpDriftLogger.fine("Found ARP entry for address: $address");
      98            2 :       return ARPData.fromDriftData(records.first);
      99              :     }
     100            6 :     arpDriftLogger.fine("No ARP entry found for address: $address");
     101              :     return null;
     102              :   }
     103              : 
     104            2 :   @override
     105              :   Future<bool> clear() async {
     106            4 :     final database = await _database.open();
     107            2 :     final oldEnteries = await _fullEntries();
     108            2 :     if (oldEnteries.isNotEmpty) {
     109            4 :       arpDriftLogger.fine("Skipping ARP table build, old entries found");
     110              :       bool hasOldEntries = false;
     111            4 :       for (final entry in oldEnteries) {
     112              :         // Delete records older than 1 hour
     113            4 :         if (entry.createdAt.isBefore(
     114            4 :           DateTime.now().subtract(const Duration(hours: 1)),
     115              :         )) {
     116              :           hasOldEntries = true;
     117              :           break;
     118              :         }
     119              :       }
     120              :       if (hasOldEntries) {
     121              :         //Delete entire table data
     122            6 :         await database!.delete(database.aRPDrift).go();
     123            4 :         arpDriftLogger.fine("Deleting all ARP entries older than 1 hour");
     124              :       }
     125              :       return true;
     126              :     }
     127              :     return false;
     128              :   }
     129              : }
        

Generated by: LCOV version 2.0-1