Untitled
unknown
dart
a year ago
21 kB
1
Indexable
Never
import 'dart:convert'; import 'package:anas/app/models/booking_history.dart'; import 'package:anas/app/models/classes_details_model.dart'; import 'package:anas/app/models/classes_gallery_model.dart'; import 'package:anas/app/models/classes_model.dart'; import 'package:anas/app/models/personal_details_model.dart'; import 'package:anas/app/models/personal_model.dart'; import 'package:anas/app/models/product_history_model.dart'; import 'package:anas/app/models/product_model.dart'; import 'package:anas/app/models/static_pages_model.dart'; import 'package:anas/app/models/subscription_model.dart'; import 'package:anas/app/services/auth_service.dart'; import 'package:dio/dio.dart'; import 'package:dio_http_cache/dio_http_cache.dart'; import '../models/user_model.dart'; import 'api_provider.dart'; import 'package:get/get.dart'; class ServerApiClient extends GetxService with ApiClient { late Dio _httpClient; late Options _optionsNetwork; late Options _optionsCache; static RxBool hasMore = true.obs; late Rx<User> currentUser = Get.find<AuthService>().user; late RxBool refresh = false.obs; ServerApiClient() {} Future<ServerApiClient> init() async { baseUrl = globalService.global.value.laravelBaseUrl; _httpClient = Dio(); var token = currentUser.value.token ?? ''; _optionsNetwork = buildCacheOptions(const Duration(days: 0), forceRefresh: false); _optionsCache = buildCacheOptions(const Duration(minutes: 0), forceRefresh: false); _httpClient.interceptors.add( DioCacheManager(CacheConfig(baseUrl: getApiBaseUrl(""))).interceptor); _httpClient.options.headers['Authorization'] = 'Bearer ' + token; _httpClient.options.headers['Content-Type'] = 'application/json'; _httpClient.options.headers['language'] = Get.locale.toString() == 'en_GB' ? 'en' : 'ar'; return this; } Future<User> login(User user) async { Uri _uri = getApiBaseUri("Authenticate/Login"); try { var response = await _httpClient.postUri( _uri, data: {'username': user.uid, 'password': user.password}, options: _optionsNetwork, ); if (response.data['jwt'] != '') { user.token = response.data['jwt']['accessToken']; user.refreshToken = response.data['jwt']['refreshToken']; _httpClient.options.headers['Authorization'] = 'Bearer ' + response.data['jwt']['accessToken']; user.auth = true; } } on DioError catch (e) { print('catch= ' + e.toString()); Get.defaultDialog( middleText: 'ID Number or password is incorrect', title: 'Error'); } await account(); return user; } Future forgetPassword(id, mobile) async { Uri _uri = getApiBaseUri("Authenticate/ResetInitiate"); var response = await _httpClient.postUri( _uri, options: _optionsNetwork, ); _httpClient.options.headers['Authorization'] = 'Bearer ' + response.data['jwt']['accessToken']; _uri = getApiBaseUri("Authenticate/VerifyAccount"); try { response = await _httpClient.postUri( _uri, data: {'userName': id, 'mobile': mobile}, options: _optionsNetwork, ); } on DioError catch (e) { print('catch= ' + e.toString()); Get.defaultDialog( middleText: 'ID Number or mobile is incorrect', title: 'Error'); } return response.data; } Future resetPassword(arguments, id, mobile) async { Uri _uri = getApiBaseUri("Authenticate/ResetPassword"); var response; try { response = await _httpClient.postUri( _uri, data: { 'userName': arguments[0], 'mobile': arguments[1], 'newPassword': id, 'confirmPassword': mobile }, options: _optionsNetwork, ); } on DioError catch (e) { print('catch= ' + e.toString()); Get.defaultDialog( middleText: 'ID Number or mobile is incorrect', title: 'Error'); } return response.data; } Future otp(arguments, code) async { Uri _uri = getApiBaseUri("Authenticate/VerifyOTP"); var response; try { response = await _httpClient.postUri( _uri, data: { 'userName': arguments[0], 'mobile': arguments[1], 'otp': code, }, options: _optionsNetwork, ); } on DioError catch (e) { print('catch= ' + e.toString()); Get.defaultDialog(middleText: 'otp number is incorrect', title: 'Error'); } return response.data; } Future<void> account() async { Uri _uri = getApiBaseUri("Membership/MyAccount"); var response; if (_httpClient.options.headers['Authorization'] != "Bearer ") { try { response = await _httpClient.postUri( _uri, options: _optionsNetwork, ); currentUser.value.name = response.data['result']['memberFullName']; currentUser.value.image = response.data['result']['url']; currentUser.value.phone = response.data['result']['mobile']; currentUser.value.email = response.data['result']['email']; currentUser.value.dob = response.data['result']['dateOfBirth']; currentUser.value.gender = response.data['result']['genderID']; currentUser.value.creditBalance = response.data['result']['creditBalanceString']; } on DioError catch (e) { if (e.response != null && e.response!.statusCode == 401) { // Token expired, attempt token refresh bool refreshTokenSuccess = await refreshtoken(account()); if (refreshTokenSuccess) { // Token refresh successful, retry account API call await account(); } else { // Token refresh failed or user not authenticated, redirect to login AuthService().removeCurrentUser(); Get.toNamed('/login'); } } else { // Handle other DioError cases here } } } } Future refreshtoken(function) async { Uri _uri = getApiBaseUri("Authenticate/RefreshToken"); var response; try { print('refresh Tokenn'); response = await _httpClient.postUri( _uri, data: { 'accessToken': currentUser.value.token, 'refreshToken': currentUser.value.refreshToken }, options: _optionsNetwork, ); print('refresh Tokenn'); if (response.data != '') { currentUser.value.token = response.data['jwt']['accessToken']; currentUser.value.refreshToken = response.data['jwt']['refreshToken']; _httpClient.options.headers['Authorization'] = 'Bearer ' + response.data['jwt']['accessToken']; function; } else { AuthService().removeCurrentUser(); Get.toNamed('/login'); } } on DioError catch (e) { // print('catch =' + e.toString()); AuthService().removeCurrentUser(); Get.toNamed('/login'); } } Future<List<Subscriptions>> subscriptions() async { Uri _uri = getApiBaseUri("Membership/MemberSubscription"); var response; print(_httpClient.options.headers); try { response = await _httpClient.postUri( _uri, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result'] .map<Subscriptions>((obj) => Subscriptions.fromJson(obj)) .toList(); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(subscriptions()); } } } return response; } Future<List<Classes>> classes() async { Uri _uri = getApiBaseUri("Calendar/Classes"); var response; print(_httpClient.options.headers); try { response = await _httpClient.postUri( _uri, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result'] .map<Classes>((obj) => Classes.fromJson(obj)) .toList(); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(classes()); } } } return response; } Future<ClassesDetails> classesInfo(arguments) async { Uri _uri = getApiBaseUri("Calendar/ClassDetails"); var response; print(_httpClient.options.headers); try { response = await _httpClient.postUri( _uri, data: {'DailyEventID': arguments[0]}, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = ClassesDetails.fromJson(response.data['result']); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(classesInfo(arguments)); } } } return response; } Future<PersonalDetails> personalInfo(arguments) async { Uri _uri = getApiBaseUri("Calendar/PersonalTrainingDetails"); var response; print(_httpClient.options.headers); try { response = await _httpClient.postUri( _uri, data: {'trainerID': arguments[0], 'memberActivityID': arguments[1]}, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = PersonalDetails.fromJson(response.data['result']); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(classesInfo(arguments)); } } } return response; } Future<List<ClassesGallery>> classesImage(arguments) async { Uri _uri = getApiBaseUri("Calendar/ClassDetails"); var response; print(_httpClient.options.headers); try { response = await _httpClient.postUri( _uri, data: {'DailyEventID': arguments[0]}, options: _optionsNetwork, ); print('response =' + response.data['galleryUrl'].toString()); response = response.data['galleryUrl']['urls'] .map<ClassesGallery>((obj) => ClassesGallery.fromJson(obj)) .toList(); ; } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(classesImage(arguments)); } } } return response; } Future<List<ClassesGallery>> personalImage(arguments) async { Uri _uri = getApiBaseUri("Calendar/PersonalTrainingDetails"); var response; print(_httpClient.options.headers); try { response = await _httpClient.postUri( _uri, data: {'trainerID': arguments[0], 'memberActivityID': arguments[1]}, options: _optionsNetwork, ); print('response =' + response.data['galleryUrl'].toString()); response = response.data['galleryUrl']['urls'] .map<ClassesGallery>((obj) => ClassesGallery.fromJson(obj)) .toList(); ; } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(classesImage(arguments)); } } } return response; } Future<List<Personal>> personals() async { Uri _uri = getApiBaseUri("Calendar/PersonalTraining"); var response; try { response = await _httpClient.postUri( _uri, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result'] .map<Personal>((obj) => Personal.fromJson(obj)) .toList(); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(personals()); } } } return response; } Future<List<Product>> products() async { Uri _uri = getApiBaseUri("/POS/Products"); var response; try { response = await _httpClient.postUri( _uri, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result'] .map<Product>((obj) => Product.fromJson(obj)) .toList(); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(products()); } } } return response; } Future<List<ProductHistory>> purchaseHistory() async { Uri _uri = getApiBaseUri("/POS/PurchaseHistory"); var response; try { response = await _httpClient.postUri( _uri, data: {"year": 0}, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result'] .map<ProductHistory>((obj) => ProductHistory.fromJson(obj)) .toList(); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(purchaseHistory()); } } } return response; } Future<List> purchaseHistoryYears(year) async { Uri _uri = getApiBaseUri("/POS/PurchaseHistoryYears"); var response; try { response = await _httpClient.postUri( _uri, data: {"year": year}, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result']; } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(purchaseHistory()); } } } return response; } Future buyNow(id, qty) async { Uri _uri = getApiBaseUri("/POS/ProductPurchase"); var response; try { response = await _httpClient.postUri( _uri, data: {'productID': id, 'qty': qty}, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result']; account(); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(buyNow(id, qty)); } } } return response; } Future book(id) async { Uri _uri = getApiBaseUri("/Calendar/EventBook"); var response; try { response = await _httpClient.postUri( _uri, data: {'dailyEventID': id}, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result']; } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(book(id)); } } } return response; } Future cancel(id) async { Uri _uri = getApiBaseUri("/Calendar/EventCancel"); var response; try { response = await _httpClient.postUri( _uri, data: {'dailyEventID': id}, options: _optionsNetwork, ); print('response =' + response.data.toString()); response = response.data['result']; } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(cancel(id)); } } } return response; } Future<StaticPages> terms() async { Uri _uri = getApiBaseUri("General/TermsAndConditions"); var response; try { response = await _httpClient.getUri( _uri, options: _optionsNetwork, ); // print(response); response = StaticPages.fromJson(response.data['result']); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(terms()); } } } return response; } Future<BookingHistoryResponse> bookingHistory(int year) async { Uri _uri = getApiBaseUri("Calendar/BookingHistory"); var response; try { response = await _httpClient.postUri( _uri, data: { 'year': year, }, options: _optionsNetwork.copyWith(headers: {'Authorization': 'Bearer ${currentUser.value.token}'}), ); print(response); response = BookingHistoryResponse.fromJson(response.data); } on DioError catch (e) { if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(terms()); } } } return response; } Future<StaticPages> privacy() async { Uri _uri = getApiBaseUri("General/PrivacyPolicy"); var response; try { response = await _httpClient.getUri( _uri, options: _optionsNetwork, ); // print(response); response = StaticPages.fromJson(response.data['result']); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(privacy()); } } } return response; } Future<StaticPages> about() async { Uri _uri = getApiBaseUri("General/About"); var response; try { response = await _httpClient.getUri( _uri, options: _optionsNetwork, ); // print(response); response = StaticPages.fromJson(response.data['result']); } on DioError catch (e) { print('catch =' + e.toString()); if (e.response!.statusCode == 401) { if (refresh.value) { refresh = false.obs; AuthService().removeCurrentUser(); Get.toNamed('/login'); } else { refresh = true.obs; refreshtoken(about()); } } } return response; } }