Line data Source code
1 : import 'dart:convert';
2 :
3 : import 'package:csv/csv.dart';
4 : import 'package:http/http.dart' as http;
5 : import 'package:network_tools/network_tools.dart';
6 : import 'package:network_tools/src/network_tools_utils.dart';
7 : import 'package:path/path.dart' as p;
8 : import 'package:universal_io/io.dart';
9 :
10 : /// Provides utilities for mapping MAC addresses to vendor information using a local CSV file.
11 : class VendorTable {
12 2 : static String noColonString(String macAddress) {
13 2 : final pattern = macAddress.contains(':') ? ':' : '-';
14 8 : return macAddress.split(pattern).sublist(0, 3).join().toUpperCase();
15 : }
16 :
17 4 : static Future<List<Vendor>> fetchVendorTable({http.Client? client}) async {
18 : //Download and store
19 8 : final csvPath = p.join(dbDirectory, "mac-vendors-export.csv");
20 4 : final file = File(csvPath);
21 4 : if (!await file.exists()) {
22 6 : logger.fine("Downloading mac-vendors-export.csv from network_tools");
23 2 : final httpClient = client ?? http.Client();
24 3 : final response = await httpClient.get(
25 3 : Uri.https(
26 : "raw.githubusercontent.com",
27 : "osociety/network_tools/main/lib/assets/mac-vendors-export.csv",
28 : ),
29 : );
30 6 : file.writeAsBytesSync(response.bodyBytes);
31 6 : logger.fine("Downloaded mac-vendors-export.csv successfully");
32 : if (client == null) {
33 2 : httpClient.close();
34 : }
35 : } else {
36 4 : logger.fine("File mac-vendors-export.csv already exists");
37 : }
38 :
39 4 : final input = file.openRead();
40 : List<List<String>> fields =
41 24 : (await input.transform(utf8.decoder).transform(csv.decoder).toList())
42 24 : .map<List<String>>((row) => row.map((e) => e.toString()).toList())
43 4 : .toList();
44 : // Remove header from csv
45 4 : fields = fields.sublist(1);
46 : // Filter out empty or malformed rows
47 : fields = fields
48 4 : .where(
49 4 : (field) =>
50 8 : field.length >= 2 &&
51 12 : field[0].trim().isNotEmpty &&
52 12 : field[1].trim().isNotEmpty,
53 : )
54 4 : .toList();
55 16 : return fields.map((field) => Vendor.fromCSVField(field)).toList();
56 : }
57 : }
|