import 'dart:math'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; /// Identifiers for this handset: one stable device id, one push token. /// /// ── Neither of these may ever fail a sign-in ── /// /// [ensureDeviceId] used to `throw` on every unhappy path — on an empty /// hardware id, on a `PlatformException`, and on anything else it caught. It is /// awaited on the line *before* the PIN check posts, inside the sign-in's outer /// `try`, so a throw here never reached the network at all: the rider got /// "Could not reach the server", pressed Retry, and the MPIN screen painted /// **"Incorrect MPIN"** at him. For every phone number, on every attempt. /// /// Two things made that certain rather than unlucky: /// /// • It asked for `androidInfo` **unconditionally**. On iOS that call throws, /// so no iPhone could ever complete a PIN login. /// • The value is not even sent. `POST /miler/verify-pin` takes `phone`, /// `pin`, `configid` and `device_token` — `deviceId` is dropped on the floor /// inside `AuthProvider.login`. The sign-in was being aborted by a field the /// sign-in does not use. /// /// So: this file hands back a best-effort answer and **never throws**. A caller /// that wants to know whether the answer is real can compare against /// [unknownDeviceId]; nothing currently needs to. class DeviceUtils { static const String _deviceIdKey = 'deviceId'; static const String _fcmTokenKey = 'fcmToken'; /// Prefix on ids this class generated rather than read off the hardware. static const String unknownDeviceId = 'generated-'; /// A stable id for this install, persisted on first use. /// /// Hardware id where the platform has one — Android's `id`, iOS's /// `identifierForVendor` — and a persisted random id everywhere else, which /// is what the backend actually needs: something that does not change /// between launches. Never throws. static Future ensureDeviceId(SharedPreferences prefs) async { final String? existing = prefs.getString(_deviceIdKey); if (existing != null && existing.isNotEmpty) return existing; String resolved = ''; try { final info = DeviceInfoPlugin(); switch (defaultTargetPlatform) { case TargetPlatform.android: resolved = (await info.androidInfo).id; case TargetPlatform.iOS: resolved = (await info.iosInfo).identifierForVendor ?? ''; case TargetPlatform.macOS: resolved = (await info.macOsInfo).systemGUID ?? ''; case TargetPlatform.windows: resolved = (await info.windowsInfo).deviceId; case TargetPlatform.linux: resolved = (await info.linuxInfo).machineId ?? ''; case TargetPlatform.fuchsia: resolved = ''; } } catch (e) { // A missing plugin, a denied permission, a simulator with no vendor id. // None of these are reasons to stop a rider signing in. debugPrint('[DEVICE] hardware id unavailable, generating one: $e'); } if (resolved.trim().isEmpty) resolved = _generateId(); await prefs.setString(_deviceIdKey, resolved); return resolved; } /// 128 bits of hex behind [unknownDeviceId], so a generated id is /// self-identifying in a log and cannot collide with a hardware one. static String _generateId() { final rand = Random.secure(); final bytes = List.generate(16, (_) => rand.nextInt(256)); final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); return '$unknownDeviceId$hex'; } /// The FCM registration token, or `''` when push is unavailable. /// /// Already total, and stays that way: a rider who declined notifications /// still has a day's work to do. static Future ensureFcmToken(SharedPreferences prefs) async { try { final String? existing = prefs.getString(_fcmTokenKey); if (existing != null && existing.isNotEmpty) { return existing; } if (Firebase.apps.isEmpty) { try { await Firebase.initializeApp(); } catch (_) { return ''; } } final FirebaseMessaging messaging = FirebaseMessaging.instance; final NotificationSettings settings = await messaging.requestPermission( alert: true, badge: true, sound: true, ); if (settings.authorizationStatus == AuthorizationStatus.authorized || settings.authorizationStatus == AuthorizationStatus.provisional) { final String? token = await messaging.getToken(); if (token != null && token.isNotEmpty) { await prefs.setString(_fcmTokenKey, token); return token; } } } catch (_) {} return ''; } }