main.dart 12 KB

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