qr.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import 'dart:io';
  2. import 'package:auto_route/auto_route.dart';
  3. import 'package:easy_localization/easy_localization.dart';
  4. import 'package:flutter/foundation.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/services.dart';
  7. import 'package:image_picker/image_picker.dart';
  8. import 'package:mobile_scanner/mobile_scanner.dart';
  9. import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
  10. import 'package:telnow_mobile_new/src/api/api_auth_repository.dart';
  11. import 'package:telnow_mobile_new/src/injector/injector.dart';
  12. import 'package:telnow_mobile_new/src/layouts/components/template.dart';
  13. import 'package:telnow_mobile_new/src/layouts/auth/login.dart';
  14. import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
  15. import 'package:telnow_mobile_new/src/utils/U.dart';
  16. import 'package:toggle_switch/toggle_switch.dart';
  17. import 'package:url_launcher/url_launcher.dart';
  18. import 'package:http/http.dart' as http;
  19. @RoutePage()
  20. class NewQrPage extends StatefulWidget {
  21. const NewQrPage({Key? key}) : super(key: key);
  22. @override
  23. State<NewQrPage> createState() => _NewQrPageState();
  24. }
  25. class _NewQrPageState extends State<NewQrPage> {
  26. final SharedPreferencesManager _sharedPreferencesManager = locator<SharedPreferencesManager>();
  27. final ApiAuthRepository apiAuthRepository = ApiAuthRepository();
  28. final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  29. String? accCode = "";
  30. bool? _isAccCodeExist = false;
  31. String companyName = '';
  32. String serialNumber = '';
  33. String imageUrl = '';
  34. List lang = [];
  35. bool useAsset = false;
  36. @override
  37. void initState() {
  38. try {
  39. imageUrl = apiAuthProvider.baseUrl + U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!))+'/assets/background/tn';
  40. http.head(Uri.parse(imageUrl));
  41. }catch(e){
  42. useAsset = true;
  43. }
  44. getCompanyName();
  45. // TODO: implement initState
  46. super.initState();
  47. }
  48. getCompanyName() async {
  49. if (_sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyAccessCode)!) {
  50. var lics = await U.reloadLicense();
  51. if (lics != null && mounted) {
  52. setState(() {
  53. companyName = lics['companyName']??'';
  54. serialNumber = lics['serialNumber']??'';
  55. if(1698720817 <= lics['serverVersion']){
  56. lang = lics['languages'] != null ? lics['languages'].split(',') : [];
  57. }
  58. });
  59. }
  60. }
  61. }
  62. @override
  63. Widget build(BuildContext context) {
  64. // accCode = _sharedPreferencesManager.getString(SharedPreferencesManager.keyAccessCode);
  65. // _isAccCodeExist = accCode != "" && accCode != null ? true : false;
  66. // var qp = context.router.current.queryParams;
  67. // bool _scanNew = false;
  68. //
  69. // if (qp.isNotEmpty) {
  70. // _scanNew = qp.getString('new') == "true" ? true : false;
  71. // }
  72. // if (_isAccCodeExist! && !kIsWeb && !_scanNew){
  73. // context.router.removeLast();
  74. // context.navigateToPath("/app/${Uri.encodeComponent(accCode!)}/login");
  75. // }
  76. return Scaffold(
  77. resizeToAvoidBottomInset: false,
  78. body: Stack(
  79. children: [
  80. SizedBox(
  81. width: double.infinity, height: double.infinity,
  82. child: !useAsset ? Image.network(imageUrl, fit: BoxFit.cover, width: double.infinity, height: double.infinity,) :
  83. Image.asset('assets/image/background/background.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity),
  84. ),
  85. SingleChildScrollView(
  86. child: Container(
  87. padding: EdgeInsets.fromLTRB(16, kIsWeb?105:200, 16, 16),
  88. width: MediaQuery.of(context).size.width,
  89. height: kIsWeb && MediaQuery.of(context).size.height<700 ? 700 : MediaQuery.of(context).size.height,
  90. decoration: BoxDecoration(
  91. gradient: LinearGradient(
  92. begin: Alignment.topCenter, end: Alignment.bottomCenter,
  93. colors: [
  94. primaryColor.withValues(alpha: 0.50), Colors.black.withValues(alpha: 0.91)
  95. ]
  96. )
  97. ),
  98. child: Column(
  99. crossAxisAlignment: CrossAxisAlignment.center,
  100. children: [
  101. Image.asset('assets/image/logo/logo.png', width: 160),
  102. Expanded(
  103. child: Column(
  104. mainAxisAlignment: MainAxisAlignment.start,
  105. children: [
  106. Container(
  107. margin: EdgeInsets.only(top: 100, left: 16, right: 16, bottom: 48),
  108. child: kIsWeb?Column(
  109. children: [
  110. Text('noPIDText'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500), textAlign: TextAlign.center),
  111. SizedBox(height: 16),
  112. Text('noPIDText2'.tr(), style: TextStyle(color: Colors.white, fontSize: 16), textAlign: TextAlign.center),
  113. ],
  114. ):Text('scanQr'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w400), textAlign: TextAlign.center),
  115. ),
  116. !kIsWeb?GestureDetector(
  117. onTap: scanDialog,
  118. child: Container(
  119. padding: EdgeInsets.symmetric(vertical: 32, horizontal: 64),
  120. decoration: BoxDecoration(
  121. color: primaryColor.withValues(alpha: 0.50),
  122. border: Border.all(color: Colors.white),
  123. borderRadius: BorderRadius.all(Radius.circular(12))
  124. ),
  125. child: Row(
  126. mainAxisSize: MainAxisSize.min,
  127. children: [
  128. Text('buttonScan'.tr(), style: TextStyle(color: Colors.white, fontSize: 16)),
  129. SizedBox(width: 10),
  130. U.iconsax('scan', color: Colors.white)
  131. ],
  132. ),
  133. ),
  134. ):Container(),
  135. !kIsWeb && U.getAccessCode() != null ? Padding(
  136. padding: EdgeInsets.only(top: 16),
  137. child: GestureDetector(
  138. child: Text('backToLogin'.tr(), style: TextStyle(color: Colors.white, fontSize: 14, decoration: TextDecoration.underline)),
  139. onTap: (){
  140. context.router.removeLast();
  141. context.navigateToPath("/app/${U.getAccessCode()}/login");
  142. },
  143. )
  144. ) : Container(),
  145. ],
  146. ),
  147. ),
  148. companyName.isNotEmpty?Text(companyName, style: TextStyle(fontSize: 16, color: Colors.white), textAlign: TextAlign.center):Container(),
  149. SizedBox(height: 5),
  150. serialNumber.isNotEmpty?Text('${'serialNumber'.tr()} $serialNumber', style: TextStyle(color: Colors.white, fontSize: 14)):Container(),
  151. SizedBox(height: 5),
  152. GestureDetector(
  153. child: Text('policy'.tr(), style: TextStyle(color: Colors.white, fontSize: 14, decoration: TextDecoration.underline)),
  154. onTap: () async {
  155. Uri _url = Uri.parse('https://telmessenger.com/privacy-police/telnow.html');
  156. await canLaunchUrl(_url) ? await launchUrl(_url) : print('Could not launch $_url');
  157. },
  158. ),
  159. SizedBox(height: 5),
  160. Text('${'version'.tr()} ${ApiAuthProvider().displayVersion}', style: TextStyle(color: Colors.white, fontSize: 14)),
  161. SizedBox(height: 5),
  162. Text('Build ${ApiAuthProvider().buildNumber}', style: TextStyle(color: Colors.white, fontSize: 13)),
  163. ],
  164. ),
  165. ),
  166. ),
  167. Container(
  168. margin: EdgeInsets.only(top: kIsWeb?16:50, right: 16),
  169. child: Align(
  170. alignment: Alignment.topRight,
  171. child: lang.isNotEmpty ? GestureDetector(
  172. child: Container(
  173. width: 65, height: 30, padding: EdgeInsets.symmetric(horizontal: 10),
  174. decoration: BoxDecoration(
  175. color: Colors.deepOrange,
  176. borderRadius: BorderRadius.all(Radius.circular(50))
  177. ),
  178. child: Row(
  179. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  180. children: [
  181. U.iconsax('bold/global', color: Colors.white),
  182. Text(context.locale.toString().toUpperCase(), style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold))
  183. ],
  184. ),
  185. ),
  186. onTap: () => changeLangLogin(context, lang),
  187. ) : ToggleSwitch(
  188. minWidth: 40,
  189. minHeight: 30,
  190. cornerRadius: 20,
  191. initialLabelIndex: context.locale.toString() == 'en' ? 0 : 1,
  192. activeBgColor: [Colors.deepOrange],
  193. activeFgColor: Colors.white,
  194. inactiveBgColor: Colors.white54,
  195. inactiveFgColor: Colors.white,
  196. labels: ['EN', 'ID'],
  197. onToggle: (index) {
  198. if (index == 0) {
  199. context.setLocale(Locale('en'));
  200. } else {
  201. context.setLocale(Locale('id'));
  202. }
  203. },
  204. ),
  205. ),
  206. )
  207. ],
  208. ),
  209. );
  210. }
  211. Future scanDialog() async {
  212. try {
  213. final result = await InternetAddress.lookup('google.com');
  214. if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  215. // String barcode = await FlutterBarcodeScanner.scanBarcode('#ff6666', 'Cancel', true, ScanMode.QR);
  216. showModalBottomSheet<void>(
  217. context: context,
  218. backgroundColor: Colors.white,
  219. builder: (BuildContext contextt) {
  220. return Column(
  221. mainAxisSize: MainAxisSize.min,
  222. children: <Widget>[
  223. Padding(
  224. padding: const EdgeInsets.only(top: 15, bottom: 15),
  225. child: Center(
  226. child: Text('buttonScan'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
  227. ),
  228. ),
  229. divider(),
  230. ListTile(
  231. leading: Icon(Icons.image),
  232. title: Text('fromGallery'.tr(), style: TextStyle(color: textColor)),
  233. onTap: () async{
  234. Navigator.of(contextt).pop();
  235. XFile? file = await ImagePicker().pickImage(source: ImageSource.gallery);
  236. if(file != null){
  237. final BarcodeCapture? barcodeCapture = await MobileScannerController().analyzeImage(file.path);
  238. String? str = barcodeCapture?.barcodes.singleOrNull?.displayValue;
  239. if (str != null) {
  240. scan(str);
  241. }
  242. else{
  243. showError(context, 'messageInvalidCode'.tr());
  244. }
  245. }
  246. },
  247. ),
  248. ListTile(
  249. leading: Icon(Icons.camera),
  250. title: Text('fromCamera'.tr(), style: TextStyle(color: textColor)),
  251. onTap: () async{
  252. Navigator.of(contextt).pop();
  253. Navigator.push(context, MaterialPageRoute(builder: (context) => const ScanBarcodePage())).then((barcode){
  254. if(barcode != null){
  255. scan(barcode);
  256. }
  257. });
  258. },
  259. )
  260. ],
  261. );
  262. }
  263. );
  264. }
  265. } on SocketException catch (_) {
  266. handlingError(context, 0); //no internet
  267. } on PlatformException catch (e) {
  268. if (e.code != '') {
  269. showError(context, 'messageCamPermission'.tr());
  270. } else {
  271. showError(context, 'messageInvalidCode'.tr());
  272. }
  273. } catch (e) {
  274. showError(context, 'messageInvalidCode'.tr());
  275. }
  276. }
  277. Future scan(String barcode) async {
  278. // print("called scan()");
  279. try {
  280. var pidString = barcode.split("app/").last;
  281. var pid = Uri.decodeComponent(pidString.split('/').first);
  282. var splitPID = pid.split('#');
  283. // print(splitPID);
  284. // print(U.decodeBase64Url(splitPID[1]));
  285. await _sharedPreferencesManager.clearKey(SharedPreferencesManager.version);
  286. await _sharedPreferencesManager.putString(SharedPreferencesManager.keyBaseUrl, U.rewriteUrl(splitPID[1]));
  287. await _sharedPreferencesManager.putString(SharedPreferencesManager.keyAccessCode, splitPID[0]);
  288. await _sharedPreferencesManager.putString(SharedPreferencesManager.keySerialCode, 'P-${splitPID[0]}');
  289. apiAuthRepository.init();
  290. if (!pidString.contains('loginme')) {
  291. context.router.removeLast();
  292. context.navigateToPath("/app/${Uri.encodeComponent(splitPID[0])}/login");
  293. } else {
  294. context.router.removeLast();
  295. context.navigateToPath("/app/${Uri.encodeComponent(splitPID[0])}/loginme"+pidString.split("/loginme").last);
  296. }
  297. } catch (e) {
  298. print(e);
  299. if(mounted) showError(context, 'messageInvalidCode'.tr());
  300. }
  301. }
  302. }
  303. class ScanBarcodePage extends StatefulWidget {
  304. const ScanBarcodePage({super.key});
  305. @override
  306. State<ScanBarcodePage> createState() => _ScanBarcodePageState();
  307. }
  308. class _ScanBarcodePageState extends State<ScanBarcodePage> {
  309. @override
  310. Widget build(BuildContext context) {
  311. return Scaffold(
  312. body: MobileScanner(
  313. onDetect: (barcodes) {
  314. // print('sini');
  315. // print(barcodes.barcodes.singleOrNull?.displayValue);
  316. Navigator.of(context).pop(barcodes.barcodes.firstOrNull?.displayValue);
  317. },
  318. ),
  319. );
  320. }
  321. }