v1.0.3 webapi client
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
import 'package:workouttest_util/service/webapi.dart';
|
||||
import 'package:workouttest_util/util/logging.dart';
|
||||
import 'package:workouttest_util/util/common.dart';
|
||||
import 'package:workouttest_util/util/not_found_exception.dart';
|
||||
@@ -19,6 +21,10 @@ class APIClient with Common, Logging {
|
||||
}
|
||||
|
||||
dynamic authenticateUser(String email, String password) async {
|
||||
if ( kIsWeb ) {
|
||||
APIWebClient webClient = APIWebClient();
|
||||
return webClient.authenticateUser(email, password);
|
||||
}
|
||||
var baseUrl = Cache().getBaseUrl();
|
||||
log("Base URL: $baseUrl");
|
||||
var url = "${baseUrl}authenticate";
|
||||
@@ -60,6 +66,10 @@ class APIClient with Common, Logging {
|
||||
}
|
||||
|
||||
Future<String> post(String endPoint, String body) async {
|
||||
if ( kIsWeb ) {
|
||||
APIWebClient webClient = APIWebClient();
|
||||
return webClient.post(endPoint, body);
|
||||
}
|
||||
final url = Cache().getBaseUrl() + endPoint;
|
||||
trace(" ------------ http/post body $body - url: $url ");
|
||||
try {
|
||||
@@ -99,6 +109,10 @@ class APIClient with Common, Logging {
|
||||
}
|
||||
|
||||
Future<String> get(String endPoint, String param) async {
|
||||
if ( kIsWeb ) {
|
||||
APIWebClient webClient = APIWebClient();
|
||||
return webClient.get(endPoint, param);
|
||||
}
|
||||
final url = Cache().getBaseUrl() + endPoint + param;
|
||||
try {
|
||||
trace("-------- API get $url");
|
||||
|
||||
@@ -12,7 +12,7 @@ class CustomerExerciseDeviceApi with Logging {
|
||||
List<CustomerExerciseDevice> devices = [];
|
||||
try {
|
||||
log(" --- get customer_exercise_devices: ");
|
||||
final body = await _client.get("customer_exercise_device/customer/" + customerId.toString(), "");
|
||||
final body = await _client.get("customer_exercise_device/customer/$customerId", "");
|
||||
final Iterable json = jsonDecode(body);
|
||||
devices = json.map((device) => CustomerExerciseDevice.fromJson(device)).toList();
|
||||
} on NotFoundException catch (_) {
|
||||
@@ -25,22 +25,22 @@ class CustomerExerciseDeviceApi with Logging {
|
||||
Future<CustomerExerciseDevice> addDevice(CustomerExerciseDevice device) async {
|
||||
CustomerExerciseDevice savedDevice;
|
||||
try {
|
||||
final String body = JsonEncoder().convert(device.toJson());
|
||||
log(" --- add customer_exercise_device: " + body);
|
||||
final String body = const JsonEncoder().convert(device.toJson());
|
||||
log(" --- add customer_exercise_device: $body");
|
||||
final String responseBody = await _client.post("customer_exercise_device", body);
|
||||
savedDevice = CustomerExerciseDevice.fromJson(jsonDecode(responseBody));
|
||||
} on Exception catch (e) {
|
||||
throw new Exception(e.toString());
|
||||
throw Exception(e.toString());
|
||||
}
|
||||
return savedDevice;
|
||||
}
|
||||
|
||||
Future<void> removeDevice(int id) async {
|
||||
try {
|
||||
log(" --- delete customer_exercise_device: " + id.toString());
|
||||
await _client.post("customer_exercise_device/delete/" + id.toString(), "");
|
||||
log(" --- delete customer_exercise_device: $id");
|
||||
await _client.post("customer_exercise_device/delete/$id", "");
|
||||
} on Exception catch (e) {
|
||||
throw new Exception(e.toString());
|
||||
throw Exception(e.toString());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -7,9 +7,9 @@ class ExerciseApi with Logging {
|
||||
final APIClient _client = APIClient();
|
||||
|
||||
Future<void> saveExercise(Exercise exercise) async {
|
||||
String body = JsonEncoder().convert(exercise.toJson());
|
||||
log(" ===== saving exercise id: " + exercise.exerciseId.toString() + ":" + body);
|
||||
await _client.post("exercises/" + exercise.exerciseId.toString(), body);
|
||||
String body = const JsonEncoder().convert(exercise.toJson());
|
||||
log(" ===== saving exercise id: ${exercise.exerciseId}:$body");
|
||||
await _client.post("exercises/${exercise.exerciseId}", body);
|
||||
}
|
||||
|
||||
Future<List<Exercise>> getExercisesByCustomer(int customerId) async {
|
||||
@@ -25,8 +25,8 @@ class ExerciseApi with Logging {
|
||||
}
|
||||
|
||||
Future<Exercise> addExercise(Exercise exercise) async {
|
||||
String body = JsonEncoder().convert(exercise.toJson());
|
||||
log(" ===== add new exercise: " + body);
|
||||
String body = const JsonEncoder().convert(exercise.toJson());
|
||||
log(" ===== add new exercise: $body");
|
||||
final String response = await _client.post("exercises", body);
|
||||
final Exercise savedExercise = Exercise.fromJson(jsonDecode(response));
|
||||
return savedExercise;
|
||||
@@ -37,8 +37,8 @@ class ExerciseApi with Logging {
|
||||
return;
|
||||
}
|
||||
int exerciseId = exercise.exerciseId!;
|
||||
log(" ===== delete exercise: " + exerciseId.toString());
|
||||
await _client.post("exercises/" + exerciseId.toString(), "");
|
||||
log(" ===== delete exercise: $exerciseId");
|
||||
await _client.post("exercises/$exerciseId", "");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ class ExerciseTreeApi with Logging {
|
||||
exerciseTrees = await getExerciseTreeParents(exerciseTrees);
|
||||
|
||||
await Future.forEach(exerciseTrees, (element) async {
|
||||
ExerciseTree exerciseTree = element as ExerciseTree;
|
||||
ExerciseTree exerciseTree = element;
|
||||
exerciseTree.imageUrl = await buildImage(exerciseTree.imageUrl, exerciseTree.treeId);
|
||||
});
|
||||
exerciseTrees = await getExerciseTreeParents(exerciseTrees);
|
||||
@@ -29,13 +29,13 @@ class ExerciseTreeApi with Logging {
|
||||
}
|
||||
|
||||
Future<String> buildImage(String imageUrl, int treeId) async {
|
||||
String assetImage = 'asset/menu/' + imageUrl.substring(7);
|
||||
print("asset image $assetImage");
|
||||
String assetImage = 'asset/menu/${imageUrl.substring(7)}';
|
||||
log("asset image $assetImage");
|
||||
return await rootBundle.load(assetImage).then((value) {
|
||||
return assetImage;
|
||||
}).catchError((_) {
|
||||
String imagePath = assetImage.substring(10);
|
||||
String url = Cache.mediaUrl + 'images' + imagePath;
|
||||
String url = '${Cache.mediaUrl}images$imagePath';
|
||||
return url;
|
||||
});
|
||||
}
|
||||
@@ -72,10 +72,10 @@ class ExerciseTreeApi with Logging {
|
||||
|
||||
List<ExerciseTree> copyList(List<ExerciseTree> tree) {
|
||||
final List<ExerciseTree> copyList = [];
|
||||
tree.forEach((element) {
|
||||
for (var element in tree) {
|
||||
final ExerciseTree copy = element.copy(-1);
|
||||
copyList.add(copy);
|
||||
});
|
||||
}
|
||||
|
||||
return copyList;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:convert';
|
||||
// ignore: depend_on_referenced_packages
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:workouttest_util/model/cache.dart';
|
||||
import 'package:workouttest_util/util/logging.dart' as logger;
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
// ignore: depend_on_referenced_packages
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:firebase_remote_config/firebase_remote_config.dart';
|
||||
@@ -38,7 +36,7 @@ class FirebaseApi with logger.Logging {
|
||||
// Wait for Firebase to initialize and set `_initialized` state to true
|
||||
await Firebase.initializeApp();
|
||||
|
||||
this.appleSignInAvailable = await SignInWithApple.isAvailable();
|
||||
appleSignInAvailable = await SignInWithApple.isAvailable();
|
||||
|
||||
|
||||
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
|
||||
@@ -46,17 +44,17 @@ class FirebaseApi with logger.Logging {
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
this.firebaseRegToken = await FirebaseMessaging.instance.getToken();
|
||||
firebaseRegToken = await FirebaseMessaging.instance.getToken();
|
||||
Cache().firebaseMessageToken = firebaseRegToken;
|
||||
log("FirebaseMessaging token $firebaseRegToken");
|
||||
|
||||
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
|
||||
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
|
||||
print('Got a message whilst in the foreground!');
|
||||
print('Message data: ${message.data}');
|
||||
log('Got a message whilst in the foreground!');
|
||||
log('Message data: ${message.data}');
|
||||
|
||||
if (message.notification != null) {
|
||||
print('Message also contained a notification: ${message.notification}');
|
||||
log('Message also contained a notification: ${message.notification}');
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -172,7 +170,7 @@ class FirebaseApi with logger.Logging {
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> registerWithApple() async {
|
||||
Map<String, dynamic> userData = Map();
|
||||
Map<String, dynamic> userData = {};
|
||||
|
||||
final rawNonce = generateNonce();
|
||||
final nonce = sha256ofString(rawNonce);
|
||||
@@ -209,7 +207,7 @@ class FirebaseApi with logger.Logging {
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> signInWithGoogle() async {
|
||||
Map<String, dynamic> userData = Map();
|
||||
Map<String, dynamic> userData = {};
|
||||
|
||||
// Trigger the authentication flow
|
||||
GoogleSignIn googleSignIn = GoogleSignIn(
|
||||
@@ -246,7 +244,7 @@ class FirebaseApi with logger.Logging {
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> registerWithGoogle() async {
|
||||
Map<String, dynamic> userData = Map();
|
||||
Map<String, dynamic> userData = {};
|
||||
|
||||
// Trigger the authentication flow
|
||||
GoogleSignIn googleSignIn = GoogleSignIn(
|
||||
@@ -319,7 +317,7 @@ class FirebaseApi with logger.Logging {
|
||||
|
||||
// Once signed in, return the UserCredential
|
||||
final userCredential = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
|
||||
log("Email by FB: " + userData['email'] + " FB credential: " + userCredential.toString());
|
||||
log("Email by FB: ${userData['email']} FB credential: $userCredential");
|
||||
|
||||
Cache().firebaseUid = userCredential.user!.uid;
|
||||
} else {
|
||||
|
||||
@@ -22,7 +22,7 @@ class PurchaseApi with Logging {
|
||||
}
|
||||
|
||||
Future<void> savePurchase(Purchase purchase) async {
|
||||
String body = JsonEncoder().convert(purchase.toJson());
|
||||
String body = const JsonEncoder().convert(purchase.toJson());
|
||||
log(" ===== saving purchase:$body");
|
||||
await _client.post("purchase", body);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
import 'package:workouttest_util/model/cache.dart';
|
||||
import 'package:workouttest_util/util/common.dart';
|
||||
import 'package:workouttest_util/util/logging.dart';
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:workouttest_util/util/not_found_exception.dart';
|
||||
|
||||
class APIWebClient with Common, Logging {
|
||||
static final APIWebClient _singleton = APIWebClient._internal();
|
||||
late bool cert;
|
||||
|
||||
factory APIWebClient() {
|
||||
return _singleton;
|
||||
}
|
||||
|
||||
APIWebClient._internal() {
|
||||
cert = false;
|
||||
}
|
||||
|
||||
dynamic authenticateUser(String email, String password) async {
|
||||
var baseUrl = Cache().getBaseUrl();
|
||||
log("Base URL: $baseUrl");
|
||||
var url = "${baseUrl}authenticate";
|
||||
|
||||
try {
|
||||
final body = jsonEncode(<String, String>{
|
||||
'username': email,
|
||||
'password': password
|
||||
});
|
||||
var uri = Uri.parse(url);
|
||||
var result = await http.post(uri, body: body, headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "1",
|
||||
});
|
||||
|
||||
if (result.statusCode != 200) {
|
||||
log("authentication response: ${result.statusCode} with URL: $url");
|
||||
throw Exception("Authentication error: ${result.statusCode}");
|
||||
}
|
||||
|
||||
String response = result.body;
|
||||
log("Authentication status: ${result.statusCode}, response: $response");
|
||||
final data = jsonDecode(response);
|
||||
return data;
|
||||
} catch (exception) {
|
||||
log(exception.toString());
|
||||
try {
|
||||
await Sentry.captureException(exception);
|
||||
} on Exception catch (e) {
|
||||
log(e.toString());
|
||||
}
|
||||
|
||||
throw Exception("Network error, try again later!");
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> post(String endPoint, String body) async {
|
||||
final url = Cache().getBaseUrl() + endPoint;
|
||||
trace(" ------------ http/post body $body - url: $url ");
|
||||
try {
|
||||
String authToken = Cache().getAuthToken();
|
||||
if (authToken.isEmpty) {
|
||||
var responseJson = await authenticateUser(Cache.username, Cache.password);
|
||||
authToken = responseJson['token'];
|
||||
Cache().authToken = authToken;
|
||||
}
|
||||
var uri = Uri.parse(url);
|
||||
var result = await http.post(uri, body: body, headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": 'Bearer $authToken',
|
||||
});
|
||||
trace(" ------------post response code: ${result.statusCode}");
|
||||
if (result.statusCode == 200) {
|
||||
return result.body;
|
||||
} else if (result.statusCode == 404) {
|
||||
throw const NotFoundException(message: "Not Found");
|
||||
} else {
|
||||
throw Exception("Network Error, please try again later");
|
||||
}
|
||||
} on NotFoundException catch(e) {
|
||||
throw NotFoundException(message: "Not Found ${e.message}");
|
||||
} on Exception catch (e) {
|
||||
log("Post Exception: $e");
|
||||
await Sentry.captureException(e);
|
||||
throw Exception("Network Error, please try again later");
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> get(String endPoint, String param) async {
|
||||
final url = Cache().getBaseUrl() + endPoint + param;
|
||||
try {
|
||||
trace("-------- API get $url");
|
||||
String authToken = Cache().getAuthToken();
|
||||
if (authToken.isEmpty) {
|
||||
var responseJson = await authenticateUser(Cache.username, Cache.password);
|
||||
authToken = responseJson['token'];
|
||||
Cache().authToken = authToken;
|
||||
}
|
||||
var uri = Uri.parse(url);
|
||||
var result = await http.get(uri, headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": 'Bearer $authToken',
|
||||
});
|
||||
|
||||
trace(" ------------get response code: ${result.statusCode}");
|
||||
if (result.statusCode == 200) {
|
||||
return result.body;
|
||||
} else if (result.statusCode == 404) {
|
||||
throw const NotFoundException(message: "Not Found");
|
||||
} else {
|
||||
throw Exception("Network Error, please try again later");
|
||||
}
|
||||
} on NotFoundException catch(e) {
|
||||
throw NotFoundException(message: "Not Found ${e.message}");
|
||||
} on Exception catch (e) {
|
||||
log("Post Exception: $e");
|
||||
await Sentry.captureException(e);
|
||||
throw Exception("Network Error, please try again later");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user