feat(wip): Update entities and adopt a proper repository workflow for trip "obtention"
This commit is contained in:
@@ -1,119 +1,89 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:anyway/domain/entities/landmark.dart';
|
||||
import 'package:anyway/domain/entities/preferences.dart';
|
||||
import 'package:anyway/domain/entities/trip.dart';
|
||||
import 'package:anyway/domain/repositories/trip_repository.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:anyway/data/datasources/trip_remote_datasource.dart';
|
||||
|
||||
// We can request a new trip from our backend API by passing it user preferences (which contain all the necessary data)
|
||||
class BackendTripRepository implements TripRepository {
|
||||
final Dio dio;
|
||||
|
||||
BackendTripRepository({required this.dio});
|
||||
final TripRemoteDataSource remote;
|
||||
|
||||
BackendTripRepository({required this.remote});
|
||||
|
||||
@override
|
||||
Future<Trip> getTrip({Preferences? preferences, String? tripUUID}) async {
|
||||
Map<String, dynamic> data = {
|
||||
"preferences": preferences!.toJson(),
|
||||
// "start": preferences!.startPoint.location,
|
||||
Future<Trip> getTrip({Preferences? preferences, String? tripUUID, List<Landmark>? landmarks}) async {
|
||||
try {
|
||||
Map<String, dynamic> json;
|
||||
|
||||
if (tripUUID != null) {
|
||||
json = await remote.fetchTrip(tripUUID);
|
||||
} else {
|
||||
if (preferences == null) {
|
||||
throw ArgumentError('Either preferences or tripUUID must be provided');
|
||||
}
|
||||
|
||||
final Map<String, dynamic> prefsPayload = _buildPreferencesPayload(preferences);
|
||||
List<Map<String, dynamic>> landmarkBodies = landmarks != null
|
||||
? landmarks.map((lm) => lm.toJson()).toList()
|
||||
: await _fetchLandmarkPayloads(prefsPayload, preferences.startLocation);
|
||||
|
||||
// TODO: remove
|
||||
// restrict the landmark list to 30 to iterate quickly
|
||||
landmarkBodies = landmarkBodies.take(30).toList();
|
||||
// change the json key because of backend inconsistency
|
||||
for (var lm in landmarkBodies) {
|
||||
if (lm.containsKey('type')) {
|
||||
lm['type'] = "sightseeing";
|
||||
}
|
||||
lm['osm_type'] = 'node';
|
||||
lm['osm_id'] = 1;
|
||||
}
|
||||
|
||||
final Map<String, dynamic> body = {
|
||||
'preferences': prefsPayload,
|
||||
'landmarks': landmarkBodies,
|
||||
'start': preferences.startLocation,
|
||||
};
|
||||
if (preferences.endLocation != null) {
|
||||
body['end'] = preferences.endLocation;
|
||||
}
|
||||
if (preferences.detourToleranceMinutes != null) {
|
||||
body['detour_tolerance_minute'] = preferences.detourToleranceMinutes;
|
||||
}
|
||||
|
||||
json = await remote.createTrip(body);
|
||||
}
|
||||
|
||||
return Trip.fromJson(json);
|
||||
} catch (e) {
|
||||
throw Exception('Failed to fetch trip: ${e.toString()}');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// TODO - maybe shorten this
|
||||
@override
|
||||
Future<List<Landmark>> searchLandmarks(Preferences preferences) async {
|
||||
final Map<String, dynamic> prefsPayload = _buildPreferencesPayload(preferences);
|
||||
final List<Map<String, dynamic>> rawLandmarks = await _fetchLandmarkPayloads(prefsPayload, preferences.startLocation);
|
||||
return rawLandmarks.map((lmJson) => Landmark.fromJson(lmJson)).toList();
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _fetchLandmarkPayloads(
|
||||
Map<String, dynamic> prefsPayload, List<double> startLocation) async {
|
||||
final Map<String, dynamic> landmarkRequest = {
|
||||
'preferences': prefsPayload,
|
||||
'start': startLocation,
|
||||
};
|
||||
|
||||
return await remote.fetchLandmarks(landmarkRequest);
|
||||
}
|
||||
|
||||
late Response response;
|
||||
try {
|
||||
response = await dio.post(
|
||||
"/trip/new",
|
||||
data: data
|
||||
);
|
||||
} catch (e) {
|
||||
trip.updateUUID("error");
|
||||
|
||||
// Format the error message to be more user friendly
|
||||
String errorDescription;
|
||||
if (e is DioException) {
|
||||
errorDescription = e.message ?? "Unknown error";
|
||||
} else if (e is SocketException) {
|
||||
errorDescription = "No internet connection";
|
||||
} else if (e is TimeoutException) {
|
||||
errorDescription = "Request timed out";
|
||||
} else {
|
||||
errorDescription = "Unknown error";
|
||||
}
|
||||
|
||||
String errorMessage = """
|
||||
We're sorry, the following error was generated:
|
||||
|
||||
${errorDescription.trim()}
|
||||
""".trim();
|
||||
|
||||
trip.updateError(errorMessage);
|
||||
log(e.toString());
|
||||
log(errorMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
// handle more specific errors
|
||||
if (response.statusCode != 200) {
|
||||
trip.updateUUID("error");
|
||||
String errorDescription;
|
||||
if (response.data.runtimeType == String) {
|
||||
errorDescription = response.data;
|
||||
} else if (response.data.runtimeType == Map<String, dynamic>) {
|
||||
errorDescription = response.data["detail"] ?? "Unknown error";
|
||||
} else {
|
||||
errorDescription = "Unknown error";
|
||||
}
|
||||
|
||||
String errorMessage = """
|
||||
We're sorry, our servers generated the following error:
|
||||
|
||||
${errorDescription.trim()}
|
||||
Please try again.
|
||||
""".trim();
|
||||
trip.updateError(errorMessage);
|
||||
log(errorMessage);
|
||||
// Actualy no need to throw an exception, we can just log the error and let the user retry
|
||||
// throw Exception(errorDetail);
|
||||
} else {
|
||||
|
||||
// if the response data is not json, throw an error
|
||||
if (response.data is! Map<String, dynamic>) {
|
||||
log("${response.data.runtimeType}");
|
||||
trip.updateUUID("error");
|
||||
String errorMessage = """
|
||||
We're sorry, our servers generated the following error:
|
||||
|
||||
${response.data.trim()}
|
||||
Please try again.
|
||||
""".trim();
|
||||
trip.updateError(errorMessage);
|
||||
log(errorMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, dynamic> json = response.data;
|
||||
|
||||
// only fill in the trip "meta" data for now
|
||||
trip.loadFromJson(json);
|
||||
|
||||
// now fill the trip with landmarks
|
||||
// we are going to recreate ALL the landmarks from the information given by the api
|
||||
trip.landmarks.remove(trip.landmarks.first);
|
||||
String? nextUUID = json["first_landmark_uuid"];
|
||||
while (nextUUID != null) {
|
||||
var (landmark, newUUID) = await fetchLandmark(nextUUID);
|
||||
trip.addLandmark(landmark);
|
||||
nextUUID = newUUID;
|
||||
}
|
||||
|
||||
log(response.data.toString());
|
||||
// // Also save the trip for the user's convenience
|
||||
// savedTrips.addTrip(trip);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Map<String, dynamic> _buildPreferencesPayload(Preferences preferences) {
|
||||
final Map<String, dynamic> prefsPayload = {};
|
||||
preferences.scores.forEach((type, score) {
|
||||
prefsPayload[type] = {'type': type, 'score': score};
|
||||
});
|
||||
prefsPayload['max_time_minute'] = preferences.maxTimeMinutes;
|
||||
return prefsPayload;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:anyway/domain/repositories/onboarding_repository.dart';
|
||||
|
||||
class LocalOnboardingRepository implements OnboardingRepository {
|
||||
static const _key = 'onboardingCompleted';
|
||||
|
||||
@override
|
||||
Future<bool> isOnboarded() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_key) ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setOnboarded(bool value) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_key, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:anyway/domain/entities/preferences.dart';
|
||||
import 'package:anyway/domain/repositories/preferences_repository.dart';
|
||||
|
||||
class PreferencesRepositoryImpl implements PreferencesRepository {
|
||||
static const _key = 'userPreferences';
|
||||
|
||||
@override
|
||||
Future<Preferences> getPreferences() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_key);
|
||||
if (raw == null) {
|
||||
// TODO - rethink this
|
||||
// return a sensible default
|
||||
return Preferences(
|
||||
scores: {
|
||||
'sightseeing': 0,
|
||||
'shopping': 0,
|
||||
'nature': 0,
|
||||
},
|
||||
maxTimeMinutes: 120,
|
||||
startLocation: const [48.8575, 2.3514],
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
final map = json.decode(raw) as Map<String, dynamic>;
|
||||
return Preferences.fromJson(map);
|
||||
} catch (_) {
|
||||
return Preferences(
|
||||
scores: {
|
||||
'sightseeing': 0,
|
||||
'shopping': 0,
|
||||
'nature': 0,
|
||||
},
|
||||
maxTimeMinutes: 120,
|
||||
startLocation: const [48.8575, 2.3514],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> savePreferences(Preferences preferences) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = json.encode(preferences.toJson());
|
||||
await prefs.setString(_key, raw);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user