trcr/lib/push_service.dart

70 lines
2.6 KiB
Dart
Raw Normal View History

2025-06-30 21:50:26 -07:00
import 'dart:developer' as developer;
import 'dart:io';
2026-02-02 20:20:58 -08:00
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
2025-06-30 21:50:26 -07:00
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
2025-07-14 07:39:30 -07:00
import 'package:traccar_client/password_service.dart';
2025-06-30 21:50:26 -07:00
import 'preferences.dart';
class PushService {
static Future<void> init() async {
await FirebaseMessaging.instance.requestPermission();
2025-07-01 11:32:51 -07:00
FirebaseMessaging.onBackgroundMessage(pushServiceBackgroundHandler);
2025-06-30 21:50:26 -07:00
FirebaseMessaging.onMessage.listen(_onMessage);
FirebaseMessaging.instance.onTokenRefresh.listen(_uploadToken);
bg.BackgroundGeolocation.onEnabledChange((enabled) async {
if (enabled) {
2025-07-05 07:29:28 -07:00
try {
_uploadToken(await FirebaseMessaging.instance.getToken());
} catch (error) {
developer.log('Failed to get notificaion token', error: error);
}
2025-06-30 21:50:26 -07:00
}
});
}
static Future<void> _onMessage(RemoteMessage message) async {
final command = message.data['command'];
2026-02-02 20:20:58 -08:00
FirebaseCrashlytics.instance.log('push_command: $command');
2025-07-01 11:32:51 -07:00
switch (command) {
case 'positionSingle':
try {
await bg.BackgroundGeolocation.getCurrentPosition(samples: 1, persist: true, extras: {'remote': true});
} catch (error) {
developer.log('Failed to get position', error: error);
}
case 'positionPeriodic':
await bg.BackgroundGeolocation.start();
case 'positionStop':
await bg.BackgroundGeolocation.stop();
2025-07-14 07:39:30 -07:00
case 'factoryReset':
await PasswordService.setPassword('');
2025-06-30 21:50:26 -07:00
}
}
static Future<void> _uploadToken(String? token) async {
if (token == null) return;
final id = Preferences.instance.getString(Preferences.id);
final url = Preferences.instance.getString(Preferences.url);
if (id == null || url == null) return;
try {
final request = await HttpClient().postUrl(Uri.parse(url));
request.headers.contentType = ContentType.parse('application/x-www-form-urlencoded');
request.write('id=${Uri.encodeComponent(id)}&notificationToken=${Uri.encodeComponent(token)}');
await request.close();
} catch (error) {
developer.log('Failed to upload token', error: error);
}
}
}
2025-07-01 11:33:47 -07:00
@pragma('vm:entry-point')
Future<void> pushServiceBackgroundHandler(RemoteMessage message) async {
await Preferences.init();
2026-02-02 20:20:58 -08:00
await bg.BackgroundGeolocation.ready(Preferences.geolocationConfig());
FirebaseCrashlytics.instance.log('push_background_handler');
2025-07-01 11:33:47 -07:00
await PushService._onMessage(message);
}