main.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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/components/template.dart';
  21. import 'package:telnow_mobile_new/src/layouts/mobile/history_forum.dart';
  22. import 'package:telnow_mobile_new/src/layouts/mobile/message_list.dart';
  23. import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
  24. import 'package:telnow_mobile_new/src/utils/U.dart';
  25. import 'package:telnow_mobile_new/src/utils/dio_logging_interceptors.dart';
  26. import 'package:telnow_mobile_new/src/utils/provider.dart';
  27. import 'package:upgrader/upgrader.dart';
  28. import 'package:http/http.dart' as http;
  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. ],
  76. startLocale: Locale('id'),
  77. saveLocale: true,
  78. child: MyApp()
  79. )
  80. );
  81. } catch (error, stacktrace) {
  82. print('$error & $stacktrace');
  83. }
  84. }
  85. class MyCustomScrollBehavior extends MaterialScrollBehavior {
  86. // Override behavior methods and getters like dragDevices
  87. @override
  88. Set<PointerDeviceKind> get dragDevices {
  89. return {
  90. PointerDeviceKind.touch,
  91. PointerDeviceKind.mouse,
  92. };
  93. }
  94. }
  95. class MyApp extends StatelessWidget {
  96. MyApp({super.key});
  97. final _appRouter = AppRouter();
  98. // This widget is the root of your application.
  99. @override
  100. Widget build(BuildContext context) {
  101. return MultiProvider(
  102. providers: [
  103. ChangeNotifierProvider(create: (_) => UserModule()),
  104. ChangeNotifierProvider(create: (_) => ServiceModule()),
  105. ChangeNotifierProvider(create: (_) => HistoryModule()),
  106. ChangeNotifierProvider(create: (_) => RequestModule()),
  107. ChangeNotifierProvider(create: (_) => CreateSerModule()),
  108. ChangeNotifierProvider(create: (_) => MessageModule()),
  109. ],
  110. child: MaterialApp.router(
  111. scrollBehavior: MyCustomScrollBehavior(),
  112. debugShowCheckedModeBanner: false,
  113. localizationsDelegates: context.localizationDelegates,
  114. supportedLocales: context.supportedLocales,
  115. locale: context.locale,
  116. key: NavigationService.navigatorKey,
  117. theme: ThemeData(useMaterial3: false, fontFamily: 'SF Compact Display', appBarTheme: AppBarTheme(
  118. systemOverlayStyle: SystemUiOverlayStyle(
  119. statusBarColor: Colors.transparent,
  120. statusBarIconBrightness: Brightness.dark,
  121. statusBarBrightness: Brightness.dark
  122. ),
  123. )),
  124. routerConfig: _appRouter.config(),
  125. ),
  126. );
  127. }
  128. }
  129. class NavigationService {
  130. static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  131. }
  132. @RoutePage()
  133. class HomeGuardPage extends StatefulWidget {
  134. const HomeGuardPage({Key? key}) : super(key: key);
  135. @override
  136. State<HomeGuardPage> createState() => _HomeGuardPageState();
  137. }
  138. class _HomeGuardPageState extends State<HomeGuardPage> {
  139. late DateTime currentBackPressTime;
  140. @override
  141. Widget build(BuildContext context) {
  142. eventBus.on().listen((event) {
  143. print("eventBus => ${event.toString()}");
  144. if(event.toString() == 'logout') {
  145. // token.logout();
  146. context.navigateToPath('/end-session');
  147. return;
  148. }
  149. });
  150. // TODO: implement build
  151. return Scaffold(
  152. body: !kIsWeb ? UpgradeAlert(child: AutoRouter()):AutoRouter(),
  153. );
  154. }
  155. Future<bool> onWillPop() {
  156. DateTime now = DateTime.now();
  157. if (now.difference(currentBackPressTime) > Duration(seconds: 2)) {
  158. currentBackPressTime = now;
  159. Fluttertoast.showToast(msg: 'pressAgain'.tr());
  160. return Future.value(false);
  161. }
  162. return Future.value(true);
  163. }
  164. }
  165. class NotificationClass {
  166. final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();
  167. initFirebaseMessaging(BuildContext context) {
  168. FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
  169. var mid = message.data['mid'];
  170. var token = await U.getFcmToken();
  171. // print('tokennya');
  172. // print(token);
  173. if (token != null) {
  174. _apiAuthProvider.postDataNoAuth('/api/notifications/received/$token/$mid').then((value) =>
  175. print('sukses kirim confirm')
  176. );
  177. }
  178. if(kIsWeb){
  179. QuickNotify.notify(
  180. title: message.data['subject'],
  181. content: context.locale.toString() == 'id' ? message.data['description'] : message.data['descriptionEn'],
  182. );
  183. }
  184. else{
  185. const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('notification_icon');
  186. final InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid);
  187. // U.flutterLocalNotificationsPlugin.initialize(initializationSettings,);
  188. U.flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) async {
  189. if (notificationResponse.payload != null) {
  190. var list = jsonDecode(notificationResponse.payload!);
  191. goNotification(list, context);
  192. }
  193. });
  194. var androidPlatformChannelSpecifics = AndroidNotificationDetails(
  195. 'notification_channel2', // id
  196. 'Normal Notification', // title
  197. channelDescription: 'This channel is used for normal notifications.', // description
  198. importance: Importance.max,
  199. priority: Priority.high,
  200. color: Color(0xff0D497F),
  201. styleInformation: BigTextStyleInformation(''),
  202. playSound: true,
  203. enableVibration: true,
  204. // sound: RawResourceAndroidNotificationSound('notification_alarm'),
  205. largeIcon: DrawableResourceAndroidBitmap('banner_icon_blue'),
  206. setAsGroupSummary: true,
  207. groupKey: message.data['subject']
  208. );
  209. var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
  210. U.flutterLocalNotificationsPlugin.show(0, message.data['subject'],
  211. context.locale.toString() == 'id' ? message.data['description'] : message.data['descriptionEn'], platformChannelSpecifics,
  212. payload: jsonEncode(message.data));
  213. }
  214. });
  215. FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  216. FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
  217. if (message != null && !U.hidePayload) {
  218. // print(message.data);
  219. goNotification(message.data, context);
  220. }
  221. });
  222. FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  223. U.setHidePayload(false);
  224. goNotification(message.data, context);
  225. });
  226. }
  227. getActiveNotif() async {
  228. List<ActiveNotification>? activeNotif = await U.flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.getActiveNotifications();
  229. return activeNotif;
  230. }
  231. startNotification(BuildContext context) async {
  232. var token = await U.getFcmToken();
  233. if (token != null) {
  234. Map data = {'token': token, 'language': context.locale.toString().toUpperCase()};
  235. var res = _apiAuthProvider.postData('/api/fcmTokens/register', null, data, context);
  236. return res;
  237. }
  238. }
  239. stopNotification(BuildContext context) async {
  240. var token = await U.getFcmToken();
  241. if (token != null) {
  242. var res = _apiAuthProvider.postData('/api/fcmTokens/remove/$token', null, null, context);
  243. return res;
  244. }
  245. }
  246. goNotification(list, BuildContext context) {
  247. if (list['type'] == 'MESSAGE') {
  248. Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: MobMessageListPage(null)));
  249. }
  250. else if (list['type'] == 'FORUM') {
  251. // print(list['requestHistory']);
  252. Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: MobHistoryForumPage(data: jsonDecode(list['requestHistory']))));
  253. }
  254. else{
  255. var pid = U.getPidFromUrl(context.router.currentUrl);
  256. context.router.removeLast();
  257. context.navigateToPath("/app/$pid/menu/history");
  258. }
  259. // if (list['type'] == 'FORUM') {
  260. // Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: Forum(list['info'], list['currentStatus'] == 'DIMULAI' || list['currentStatus'] == 'DISELESAIKAN' ? true : false)));
  261. // } else {
  262. // Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: DetailMisi(list['info'])));
  263. // }
  264. }
  265. }
  266. Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  267. await Firebase.initializeApp();
  268. SharedPreferences prefs = await SharedPreferences.getInstance();
  269. await prefs.reload();
  270. // print('background : ${message.data}');
  271. String accCode = prefs.getString(SharedPreferencesManager.keyAccessCode)!;
  272. var decAccCode = U.decodeBase64Url(accCode);
  273. var mid = message.data['mid'];
  274. FirebaseMessaging.instance.getToken().then((token) async {
  275. if (token != null) {
  276. http.post(Uri.https(U.decodeBase64Url(prefs.getString(SharedPreferencesManager.keyBaseUrl)!).split('//')[1], '$decAccCode/api/notifications/received/$token/$mid')).then((value) {
  277. print("kirim confirm");
  278. prefs.setString(SharedPreferencesManager.lastMid, mid);
  279. });
  280. }
  281. });
  282. }