forked from eatvio/eatvio_app
81 lines
2.4 KiB
Dart
81 lines
2.4 KiB
Dart
import 'dart:developer';
|
|
import 'dart:io';
|
|
|
|
import 'package:device_info_plus/device_info_plus.dart';
|
|
import 'package:dio/dio.dart';
|
|
import 'package:eatvio_app/core/locator_service.dart';
|
|
import 'package:eatvio_app/core/token_storage.dart';
|
|
import 'package:firebase_messaging/firebase_messaging.dart';
|
|
import 'package:huawei_push/huawei_push.dart';
|
|
|
|
class FirebaseApi {
|
|
final _firebaseMessaging = FirebaseMessaging.instance;
|
|
|
|
Future<String?> getToken() async {
|
|
await _firebaseMessaging.requestPermission();
|
|
|
|
String? token = await _firebaseMessaging.getToken();
|
|
|
|
if (token == null && Platform.isAndroid) {
|
|
final isHuawei = await _isHuaweiDevice();
|
|
if (isHuawei) {
|
|
token = await _getHuaweiPushToken();
|
|
}
|
|
}
|
|
|
|
return token;
|
|
}
|
|
|
|
Future<void> registerPushToken() async {
|
|
if (await TokenStorage.haveTokenInStorage()) {
|
|
try {
|
|
final deviceInfo = DeviceInfoPlugin();
|
|
await sl<Dio>().post(
|
|
'/api/profile/notification/token/register',
|
|
data: {
|
|
'platform': Platform.isIOS ? 'ios' : 'android',
|
|
'hw_id': Platform.isIOS ? (await deviceInfo.iosInfo).identifierForVendor : (await deviceInfo.androidInfo).id,
|
|
'token': await getToken(),
|
|
},
|
|
);
|
|
} catch (e, st) {
|
|
log(e.toString(), stackTrace: st);
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<bool> _isHuaweiDevice() async {
|
|
if (!Platform.isAndroid) return false;
|
|
try {
|
|
final android = await DeviceInfoPlugin().androidInfo;
|
|
final brand = android.brand.toLowerCase();
|
|
final manufacturer = android.manufacturer.toLowerCase();
|
|
return brand.contains('huawei') || manufacturer.contains('huawei') || brand.contains('honor') || manufacturer.contains('honor');
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
Future<String?> _getHuaweiPushToken() async {
|
|
try {
|
|
await Push.turnOnPush();
|
|
|
|
String? resolvedToken;
|
|
final sub = Push.getTokenStream.listen((t) => resolvedToken ??= t, onError: (_) {});
|
|
|
|
Push.getToken('');
|
|
|
|
final started = DateTime.now();
|
|
while (resolvedToken == null && DateTime.now().difference(started).inSeconds < 5) {
|
|
await Future<void>.delayed(const Duration(milliseconds: 100));
|
|
}
|
|
|
|
await sub.cancel();
|
|
return resolvedToken;
|
|
} catch (e, st) {
|
|
log('Huawei Push token error: $e', stackTrace: st);
|
|
return null;
|
|
}
|
|
}
|
|
}
|