Business Login Flutter Apps
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

382 rindas
13 KiB

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:flutter/services.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:another_flushbar/flushbar.dart';
  7. import 'package:http/io_client.dart';
  8. import 'package:in_app_update/in_app_update.dart';
  9. import 'package:url_launcher/url_launcher.dart';
  10. import 'package:location/location.dart';
  11. import 'package:permission_handler/permission_handler.dart' as pHandler;
  12. import 'keys.dart';
  13. import 'package:oauth2/oauth2.dart' as oauth2;
  14. import '../main.dart';
  15. class Util{
  16. bool tokenValidity = true;
  17. bool useLocal = false;
  18. showLoading(context,{dissmissable=false,onwillpop}){
  19. showDialog(
  20. context: context,
  21. builder: (BuildContext context) {
  22. return WillPopScope(
  23. onWillPop: onwillpop??()async{return true;},
  24. child: const Center(
  25. child: CircularProgressIndicator(),
  26. ),
  27. );
  28. },
  29. barrierDismissible: dissmissable,
  30. );
  31. }
  32. checkinternet()async{
  33. try {
  34. var result = await InternetAddress.lookup('google.com').timeout(const Duration(seconds: 3));
  35. if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  36. return true;
  37. }
  38. return false;
  39. }
  40. on TimeoutException catch(_){
  41. return false;
  42. }
  43. on SocketException catch (_) {
  44. return false;
  45. }
  46. }
  47. getMinAppVer()async{
  48. var req = await JsonDataGetRaw({},'${prefs.getString(Keys.hostAddress)}/app/min_ver/');
  49. return req;
  50. }
  51. launchURL(String url) async {
  52. if (await canLaunch(url)) {
  53. await launch(url);
  54. } else {
  55. throw 'Could not launch $url';
  56. }
  57. }
  58. updateDialog(context)async{
  59. WidgetsBinding.instance!.addPostFrameCallback((_) async {
  60. await showDialog(
  61. context: context,
  62. builder: (BuildContext context) {
  63. return WillPopScope(
  64. onWillPop: ()async{
  65. return false;
  66. },
  67. child: AlertDialog(
  68. title: const Text('App version is too old'),
  69. content: const Text('Please update the application'),
  70. actions: <Widget>[
  71. TextButton(
  72. child: const Text('Update',style: TextStyle(color: Colors.blue),),
  73. onPressed: ()async{
  74. try{
  75. AppUpdateInfo _updateInfo;
  76. _updateInfo = await InAppUpdate.checkForUpdate();
  77. if(_updateInfo.updateAvailability == 2){
  78. await InAppUpdate.performImmediateUpdate();
  79. }
  80. else throw {"message":"manual Update"};
  81. }
  82. catch(e){
  83. await Future.delayed(const Duration(milliseconds: 500));
  84. await launchURL('https://play.google.com/store/apps/details?id=com.thamringroup.unitstocks');
  85. }
  86. },
  87. ),
  88. ],
  89. ),
  90. );
  91. },
  92. barrierDismissible: false,
  93. );
  94. });
  95. }
  96. getOauth2Client() async {
  97. bool resetClient = false;
  98. oauth2.Credentials? restData = (prefs.getString(Keys.restData)!=null&&prefs.getString(Keys.restData).contains("accessToken"))?oauth2.Credentials.fromJson(prefs.getString(Keys.restData)):null;
  99. if(restData == null)resetClient = true;
  100. else{
  101. if(DateTime.now().isAfter(restData.expiration??DateTime.now().subtract(const Duration(hours:1))))resetClient = true;
  102. }
  103. oauth2.Client client;
  104. if(resetClient||!tokenValidity){
  105. final tokenEndpoint = Uri.parse(prefs.getString(Keys.restTokenAddress));
  106. if(prefs.getString(Keys.clientCredential)==null){
  107. client = await initRest();
  108. }
  109. else{
  110. var clients = const JsonDecoder().convert(prefs.getString(Keys.clientCredential));
  111. client = await oauth2.clientCredentialsGrant(tokenEndpoint, clients["id"], clients["secret"],httpClient: http);
  112. prefs.setString(Keys.restData, client.credentials.toJson());
  113. }
  114. }
  115. else {
  116. if (prefs.getString(Keys.clientCredential) == null) {
  117. client = await initRest();
  118. }
  119. else {
  120. var clients = const JsonDecoder().convert(prefs.getString(Keys.clientCredential));
  121. client = oauth2.Client(restData!, identifier: clients["id"],
  122. secret: clients["secret"],
  123. httpClient: http);
  124. }
  125. }
  126. return client;
  127. }
  128. JsonDataPostRaw(Map jsonData, String url,{secure:true,timeout:false}) async{
  129. var httpClient;
  130. const JsonDecoder decoder = const JsonDecoder();
  131. var headers = {'Content-type': 'application/json'};
  132. try {
  133. var response;
  134. if(secure) {
  135. httpClient = await getOauth2Client();
  136. oauth2.Credentials tokenRestData = oauth2.Credentials.fromJson(prefs.getString(Keys.restData));
  137. headers["Authorization"] =
  138. "bearer ${tokenRestData.accessToken}";
  139. }
  140. else {
  141. httpClient = http;
  142. }
  143. if (timeout)
  144. response = await httpClient.post(
  145. Uri.parse(url), headers: headers,
  146. body: json.encode(jsonData)).timeout(
  147. const Duration(seconds: 8));
  148. else
  149. response = await httpClient.post(
  150. Uri.parse(url), headers: {'Content-type': 'application/json'},
  151. body: json.encode(jsonData));
  152. if(response.statusCode == 403) tokenValidity = false;
  153. if(htmlErrorTitle(response.body.toString())!=""){
  154. return {"STATUS":(response.statusCode != 200)?0:1,"DATA":htmlErrorTitle(response.body.toString())};
  155. }
  156. final Map data = decoder.convert(response.body);
  157. try{data["DATA"] = decoder.convert(data["DATA"]);}catch(e){}
  158. return data;
  159. } on TimeoutException catch(e){
  160. return {"STATUS":0,"DATA":"Request Timeout"};
  161. }
  162. on HandshakeException catch(e){
  163. if(useLocal){
  164. return {"STATUS":0,"DATA":"Not Connected to Server. $e"};
  165. }
  166. else{
  167. useLocal = true;
  168. http = IOClient(HttpClient(context: clientContext));
  169. return await JsonDataPostRaw(jsonData, url,timeout:timeout,secure: secure);
  170. }
  171. }
  172. on Exception catch(exception){
  173. print(url);
  174. // Toast("Not Connected to Server", Colors.red);
  175. return {"STATUS":0,"DATA":"Not Connected to Server. $exception"};
  176. }
  177. }
  178. JsonDataGetRaw(Map jsonData, String url,{secure:true,timeout:false}) async{
  179. var httpClient;
  180. const JsonDecoder decoder = const JsonDecoder();
  181. var headers = {'Content-type': 'application/json'};
  182. try {
  183. var response;
  184. if(secure) {
  185. httpClient = await getOauth2Client();
  186. oauth2.Credentials tokenRestData = oauth2.Credentials.fromJson(prefs.getString(Keys.restData));
  187. headers["Authorization"] =
  188. "bearer ${tokenRestData.accessToken}";
  189. }
  190. else {
  191. httpClient = http;
  192. }
  193. if(jsonData!= null&&jsonData.length!=0) {
  194. url = url + '?';
  195. for (var i in jsonData.keys) {
  196. url = url + i + '=' + jsonData[i] + '&';
  197. }
  198. url = url.substring(0, url.length - 1);
  199. }
  200. if (timeout)
  201. response = await httpClient.get(
  202. Uri.parse(url), headers: headers,
  203. ).timeout(const Duration(seconds: 10));
  204. else
  205. response = await httpClient.get(
  206. Uri.parse(url), headers: {'Content-type': 'application/json'},
  207. );
  208. if(response.statusCode == 403) tokenValidity = false;
  209. if(htmlErrorTitle(response.body.toString())!=""){
  210. return {"STATUS":(response.statusCode != 200)?0:1,"DATA":htmlErrorTitle(response.body.toString())};
  211. }
  212. final Map data = decoder.convert(response.body);
  213. try{data["DATA"] = decoder.convert(data["DATA"]);}catch(e){}
  214. return data;
  215. } on TimeoutException catch(e){
  216. return {"STATUS":0,"DATA":"Request Timeout"};
  217. }
  218. on HandshakeException catch(e){
  219. if(useLocal){
  220. return {"STATUS":0,"DATA":"Not Connected to Server. $e"};
  221. }
  222. else{
  223. useLocal = true;
  224. http = IOClient(HttpClient(context: clientContext));
  225. return await JsonDataPostRaw(jsonData, url,timeout:timeout,secure: secure);
  226. }
  227. }
  228. on Exception catch(exception){
  229. print(url);
  230. // Toast("Not Connected to Server", Colors.red);
  231. return {"STATUS":0,"DATA":"Not Connected to Server. $exception"};
  232. }
  233. }
  234. JsonDataPutRaw(Map jsonData, String url,{secure:true,timeout:false}) async{
  235. var httpClient;
  236. const JsonDecoder decoder = const JsonDecoder();
  237. var headers = {'Content-type': 'application/json'};
  238. try {
  239. var response;
  240. if(secure) {
  241. httpClient = await getOauth2Client();
  242. oauth2.Credentials tokenRestData = oauth2.Credentials.fromJson(prefs.getString(Keys.restData));
  243. headers["Authorization"] =
  244. "bearer ${tokenRestData.accessToken}";
  245. }
  246. else {
  247. httpClient = http;
  248. }
  249. if (timeout)
  250. response = await httpClient.put(
  251. Uri.parse(url), headers: headers,
  252. body: json.encode(jsonData)).timeout(
  253. const Duration(seconds: 10));
  254. else
  255. response = await httpClient.put(
  256. Uri.parse(url), headers: {'Content-type': 'application/json'},
  257. body: json.encode(jsonData));
  258. if(response.statusCode == 403) tokenValidity = false;
  259. if(htmlErrorTitle(response.body.toString())!=""){
  260. return {"STATUS":(response.statusCode != 200)?0:1,"DATA":htmlErrorTitle(response.body.toString())};
  261. }
  262. final Map data = decoder.convert(response.body);
  263. try{data["DATA"] = decoder.convert(data["DATA"]);}catch(e){}
  264. return data;
  265. } on TimeoutException catch(e){
  266. return {"STATUS":0,"DATA":"Request Timeout"};
  267. }
  268. on HandshakeException catch(e){
  269. if(useLocal){
  270. return {"STATUS":0,"DATA":"Not Connected to Server. $e"};
  271. }
  272. else{
  273. useLocal = true;
  274. http = IOClient(HttpClient(context: clientContext));
  275. return await JsonDataPostRaw(jsonData, url,timeout:timeout,secure: secure);
  276. }
  277. }
  278. on Exception catch(exception){
  279. print(url);
  280. // Toast("Not Connected to Server", Colors.red);
  281. return {"STATUS":0,"DATA":"Not Connected to Server. $exception"};
  282. }
  283. }
  284. htmlErrorTitle(String html){
  285. // FlutterLogs.logInfo("TAG", "subTag", html);
  286. try{
  287. if(html.contains('<title>')) {
  288. String titleElement = html.substring(html.indexOf("<title>")+7,html.indexOf("<\/title>"));
  289. return titleElement;
  290. }
  291. return '';
  292. }
  293. catch(e){
  294. return '';
  295. }
  296. }
  297. initRest()async{
  298. try{
  299. if(prefs.getString(Keys.clientCredential)==null){
  300. prefs.setString(Keys.clientCredential, json.encode({
  301. "id": "IZ4W8u8YZmLtUV0p1zd-_A..",
  302. "secret" : "AQ16v4bzGWm9AsWHvUcu2Q.."
  303. }).toString());
  304. }
  305. return await getOauth2Client();
  306. }
  307. catch(e){
  308. print(e);
  309. print("error fetching Rest token");
  310. }
  311. }
  312. permissionCheck(context,pHandler.Permission permissionType,ifGranted,{customMessage=''})async{
  313. pHandler.PermissionStatus permission = await permissionType.status;
  314. if(permission!= pHandler.PermissionStatus.granted){
  315. if(permission== pHandler.PermissionStatus.denied || permission== pHandler.PermissionStatus.restricted){
  316. showFlushbar(context,'${permissionType.toString().substring(permissionType.toString().lastIndexOf('.')+1)} permission is needed$customMessage. Please grant the permission!');
  317. await Future.delayed(const Duration(seconds: 3));
  318. permission = await permissionType.request();
  319. }
  320. if(permission== pHandler.PermissionStatus.permanentlyDenied) {
  321. showFlushbar(context,'It seems, your system security explicitly denied access to your ${permissionType.toString().substring(permissionType.toString().lastIndexOf('.')+1)} permission. Please MANUALLY enable it in setings!');
  322. await Future.delayed(const Duration(seconds: 3));
  323. pHandler.openAppSettings();
  324. SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  325. }
  326. if(permission== pHandler.PermissionStatus.denied || permission== pHandler.PermissionStatus.restricted){
  327. showFlushbar(context,'${permissionType.toString().substring(permissionType.toString().lastIndexOf('.')+1)} permission is needed$customMessage. Please grant the permission!');
  328. await Future.delayed(const Duration(seconds: 3));
  329. permission = await permissionType.request();
  330. }
  331. await permissionCheck(context,permissionType,ifGranted);
  332. }
  333. else{
  334. await ifGranted();
  335. }
  336. }
  337. showFlushbar(context,text,{color:Colors.grey}){
  338. Flushbar(
  339. message: "$text",
  340. backgroundColor: color,
  341. duration: const Duration(seconds: 5),
  342. ).show(context);
  343. }
  344. streamLocation(context)async{
  345. // print('checking location');
  346. await permissionCheck(context,pHandler.Permission.locationWhenInUse,()async{
  347. location.changeSettings(accuracy: LocationAccuracy.high);
  348. bool gpsEnabled = false;
  349. if(await location.serviceEnabled()){
  350. gpsEnabled = await location.serviceEnabled();
  351. }
  352. else{
  353. // print('requesting gps');
  354. gpsEnabled = await location.requestService();
  355. await streamLocation(context);
  356. }
  357. // print([gpsEnabled,permissionEnabled]);
  358. if(gpsEnabled){
  359. locationStream ??= location.onLocationChanged.listen((LocationData event) {
  360. currentPosisiton = event;
  361. });
  362. }
  363. },customMessage: " to locate your REAL location");
  364. }
  365. }