main.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'dart:ui';
  4. import 'package:auto_route/auto_route.dart';
  5. import 'package:easy_localization/easy_localization.dart';
  6. import 'package:firebase_core/firebase_core.dart';
  7. import 'package:firebase_messaging/firebase_messaging.dart';
  8. import 'package:flutter/foundation.dart';
  9. import 'package:flutter/material.dart';
  10. import 'package:flutter/services.dart';
  11. import 'package:flutter_local_notifications/flutter_local_notifications.dart';
  12. // import 'package:flutter_native_splash/flutter_native_splash.dart';
  13. import 'package:fluttertoast/fluttertoast.dart';
  14. import 'package:page_transition/page_transition.dart';
  15. import 'package:provider/provider.dart';
  16. import 'package:quick_notify_2/quick_notify.dart';
  17. import 'package:shared_preferences/shared_preferences.dart';
  18. import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
  19. import 'package:telnow_mobile_new/src/injector/injector.dart';
  20. import 'package:telnow_mobile_new/src/layouts/mobile/history_forum.dart';
  21. import 'package:telnow_mobile_new/src/layouts/mobile/message_list.dart';
  22. import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
  23. import 'package:telnow_mobile_new/src/utils/U.dart';
  24. import 'package:telnow_mobile_new/src/utils/dio_logging_interceptors.dart';
  25. import 'package:telnow_mobile_new/src/utils/provider.dart';
  26. import 'package:upgrader/upgrader.dart';
  27. import 'package:http/http.dart' as http;
  28. import 'package:telnow_mobile_new/src/api/jwt_token.dart';
  29. import 'app_router.dart';
  30. // final SharedPreferencesManager _sharedPreferencesManager = locator<SharedPreferencesManager>();
  31. var isDebug = true;
  32. class MyHttpOverrides extends HttpOverrides {
  33. @override
  34. HttpClient createHttpClient(SecurityContext? context) {
  35. return super.createHttpClient(context)..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
  36. }
  37. }
  38. void main() async{
  39. WidgetsFlutterBinding.ensureInitialized();
  40. await EasyLocalization.ensureInitialized();
  41. try{
  42. if (kIsWeb){
  43. await Firebase.initializeApp(
  44. options: FirebaseOptions(
  45. apiKey: "AIzaSyDlJQaEV9aPnPFeFA7QeiVijoGZXqemCRw",
  46. authDomain: "telmessenger-d3935.firebaseapp.com",
  47. databaseURL: "https://telmessenger-d3935.firebaseio.com",
  48. projectId: "telmessenger-d3935",
  49. storageBucket: "telmessenger-d3935.appspot.com",
  50. messagingSenderId: "647562261340",
  51. appId: "1:647562261340:web:01b97a27460e4bfd5b0799",
  52. measurementId: "G-BFCBWCK70H"
  53. )
  54. );
  55. }
  56. else{
  57. await Firebase.initializeApp();
  58. await U.flutterLocalNotificationsPlugin.cancelAll();
  59. await U.flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(U.channel);
  60. }
  61. await setupLocator();
  62. SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  63. HttpOverrides.global = new MyHttpOverrides();
  64. // WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  65. // FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  66. runApp(
  67. EasyLocalization(
  68. path: 'assets/lang',
  69. supportedLocales: [
  70. Locale('en'),
  71. Locale('id'),
  72. Locale('ja'),
  73. Locale('zh'),
  74. Locale('ko'),
  75. Locale('ar'),
  76. Locale('fr'),
  77. Locale('de'),
  78. Locale('hi'),
  79. Locale('nl')
  80. ],
  81. startLocale: Locale('id'),
  82. saveLocale: true,
  83. child: MyApp()
  84. )
  85. );
  86. } catch (error, stacktrace) {
  87. print('$error & $stacktrace');
  88. }
  89. }
  90. class MyCustomScrollBehavior extends MaterialScrollBehavior {
  91. // Override behavior methods and getters like dragDevices
  92. @override
  93. Set<PointerDeviceKind> get dragDevices {
  94. return {
  95. PointerDeviceKind.touch,
  96. PointerDeviceKind.mouse,
  97. };
  98. }
  99. }
  100. class MyApp extends StatelessWidget {
  101. MyApp({super.key});
  102. final _appRouter = AppRouter();
  103. // This widget is the root of your application.
  104. @override
  105. Widget build(BuildContext context) {
  106. return MultiProvider(
  107. providers: [
  108. ChangeNotifierProvider(create: (_) => UserModule()),
  109. ChangeNotifierProvider(create: (_) => ServiceModule()),
  110. ChangeNotifierProvider(create: (_) => HistoryModule()),
  111. ChangeNotifierProvider(create: (_) => RequestModule()),
  112. ChangeNotifierProvider(create: (_) => CreateSerModule()),
  113. ChangeNotifierProvider(create: (_) => MessageModule()),
  114. ],
  115. child: MaterialApp.router(
  116. scrollBehavior: MyCustomScrollBehavior(),
  117. debugShowCheckedModeBanner: false,
  118. localizationsDelegates: context.localizationDelegates,
  119. supportedLocales: context.supportedLocales,
  120. locale: context.locale,
  121. key: NavigationService.navigatorKey,
  122. theme: ThemeData(useMaterial3: false, fontFamily: 'SF Compact Display', appBarTheme: AppBarTheme(
  123. systemOverlayStyle: SystemUiOverlayStyle(
  124. statusBarColor: Colors.transparent,
  125. statusBarIconBrightness: Brightness.dark,
  126. statusBarBrightness: Brightness.dark
  127. ),
  128. ), colorScheme: ColorScheme.fromSeed(seedColor: Color(0xff078C84))),
  129. routerConfig: _appRouter.config(),
  130. ),
  131. );
  132. }
  133. }
  134. class NavigationService {
  135. static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  136. }
  137. @RoutePage()
  138. class HomeGuardPage extends StatefulWidget {
  139. const HomeGuardPage({Key? key}) : super(key: key);
  140. @override
  141. State<HomeGuardPage> createState() => _HomeGuardPageState();
  142. }
  143. class _HomeGuardPageState extends State<HomeGuardPage> {
  144. late DateTime currentBackPressTime;
  145. JwtToken token = JwtToken();
  146. @override
  147. Widget build(BuildContext context) {
  148. eventBus.on().listen((event) {
  149. print("eventBus => ${event.toString()}");
  150. if(event.toString() == 'logout') {
  151. // token.logout();
  152. context.navigateToPath('/end-session');
  153. // return;
  154. }
  155. });
  156. // TODO: implement build
  157. return Scaffold(
  158. body: !kIsWeb ? UpgradeAlert(child: AutoRouter()):AutoRouter(),
  159. );
  160. }
  161. Future<bool> onWillPop() {
  162. DateTime now = DateTime.now();
  163. if (now.difference(currentBackPressTime) > Duration(seconds: 2)) {
  164. currentBackPressTime = now;
  165. Fluttertoast.showToast(msg: 'pressAgain'.tr());
  166. return Future.value(false);
  167. }
  168. return Future.value(true);
  169. }
  170. }
  171. class NotificationClass {
  172. final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();
  173. initFirebaseMessaging(BuildContext context) {
  174. FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
  175. var mid = message.data['mid'];
  176. var token = await U.getFcmToken();
  177. // print('tokennya');
  178. // print(token);
  179. if (token != null) {
  180. _apiAuthProvider.postDataNoAuth('/api/notifications/received/$token/$mid').then((value) =>
  181. print('sukses kirim confirm')
  182. );
  183. }
  184. if(kIsWeb){
  185. QuickNotify.notify(
  186. title: message.data['subject'],
  187. content: context.locale.toString() == 'id' ? message.data['description'] : message.data['descriptionEn'],
  188. );
  189. }
  190. else{
  191. const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('notification_icon');
  192. final InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid);
  193. // U.flutterLocalNotificationsPlugin.initialize(initializationSettings,);
  194. U.flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) async {
  195. if (notificationResponse.payload != null) {
  196. var list = jsonDecode(notificationResponse.payload!);
  197. goNotification(list, context);
  198. }
  199. });
  200. var androidPlatformChannelSpecifics = AndroidNotificationDetails(
  201. 'notification_channel2', // id
  202. 'Normal Notification', // title
  203. channelDescription: 'This channel is used for normal notifications.', // description
  204. importance: Importance.max,
  205. priority: Priority.high,
  206. color: Color(0xff0D497F),
  207. styleInformation: BigTextStyleInformation(''),
  208. playSound: true,
  209. enableVibration: true,
  210. // sound: RawResourceAndroidNotificationSound('notification_alarm'),
  211. largeIcon: DrawableResourceAndroidBitmap('banner_icon_blue'),
  212. setAsGroupSummary: true,
  213. groupKey: message.data['subject']
  214. );
  215. var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
  216. U.flutterLocalNotificationsPlugin.show(0, message.data['subject'],
  217. context.locale.toString() == 'id' ? message.data['description'] : message.data['descriptionEn'], platformChannelSpecifics,
  218. payload: jsonEncode(message.data));
  219. }
  220. });
  221. FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  222. FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
  223. if (message != null && !U.hidePayload) {
  224. // print(message.data);
  225. goNotification(message.data, context);
  226. }
  227. });
  228. FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  229. U.setHidePayload(false);
  230. goNotification(message.data, context);
  231. });
  232. }
  233. getActiveNotif() async {
  234. List<ActiveNotification>? activeNotif = await U.flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.getActiveNotifications();
  235. return activeNotif;
  236. }
  237. startNotification(BuildContext context, {code}) async {
  238. var token = await U.getFcmToken();
  239. if (token != null) {
  240. Map data = {'token': token, 'language': code ?? context.locale.toString().toUpperCase()};
  241. var res = _apiAuthProvider.postData('/api/fcmTokens/register', null, data, context);
  242. return res;
  243. }
  244. }
  245. stopNotification(BuildContext context) async {
  246. var token = await U.getFcmToken();
  247. if (token != null) {
  248. var res = _apiAuthProvider.postData('/api/fcmTokens/remove/$token', null, null, context);
  249. return res;
  250. }
  251. }
  252. goNotification(list, BuildContext context) {
  253. if (list['type'] == 'MESSAGE') {
  254. Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: MobMessageListPage(null)));
  255. }
  256. else if (list['type'] == 'FORUM') {
  257. // print(list['requestHistory']);
  258. Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: MobHistoryForumPage(data: jsonDecode(list['requestHistory']))));
  259. }
  260. else{
  261. var pid = U.getPidFromUrl(context.router.currentUrl);
  262. context.router.removeLast();
  263. context.navigateToPath("/app/$pid/menu/history");
  264. }
  265. // if (list['type'] == 'FORUM') {
  266. // Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: Forum(list['info'], list['currentStatus'] == 'DIMULAI' || list['currentStatus'] == 'DISELESAIKAN' ? true : false)));
  267. // } else {
  268. // Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: DetailMisi(list['info'])));
  269. // }
  270. }
  271. }
  272. Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  273. await Firebase.initializeApp();
  274. SharedPreferences prefs = await SharedPreferences.getInstance();
  275. await prefs.reload();
  276. // print('background : ${message.data}');
  277. String accCode = prefs.getString(SharedPreferencesManager.keyAccessCode)!;
  278. var decAccCode = U.decodeBase64Url(accCode);
  279. var mid = message.data['mid'];
  280. FirebaseMessaging.instance.getToken().then((token) async {
  281. if (token != null) {
  282. http.post(Uri.https(U.decodeBase64Url(prefs.getString(SharedPreferencesManager.keyBaseUrl)!).split('//')[1], '$decAccCode/api/notifications/received/$token/$mid')).then((value) {
  283. print("kirim confirm");
  284. prefs.setString(SharedPreferencesManager.lastMid, mid);
  285. });
  286. }
  287. });
  288. }