createOrUpdateUserProfile method
Creates or updates the user profile following the ontology structure.
Implementation
Future<bool> createOrUpdateUserProfile({
String? apiKey,
String? dobString,
String? genderString,
List<String>? movieListIds,
}) async {
try {
final loggedIn = await isLoggedIn();
if (!loggedIn) {
debugPrint('❌ User not logged in, cannot create profile');
return false;
}
final webId = await getCurrentUserWebId();
if (webId == null) {
debugPrint('❌ Could not get Web ID for user');
return false;
}
// First, try to load existing profile data to reuse existing resources.
final existingProfileData = await _loadExistingProfile();
// Get API key from secure storage if not provided.
String? actualApiKey = apiKey;
if (actualApiKey == null) {
final apiKeyService = ApiKeyService();
actualApiKey = await apiKeyService.getApiKey();
}
// Use existing API key ID if available, otherwise create new one.
String? apiKeyFileId = existingProfileData?['apiKeyId'];
if (apiKeyFileId == null &&
actualApiKey != null &&
actualApiKey.isNotEmpty) {
apiKeyFileId = await _createApiKeyFile(actualApiKey);
}
// Merge existing MovieList IDs with any new ones provided.
final existingMovieListIds =
existingProfileData?['movieListIds'] as List<String>? ?? [];
final providedMovieListIds = movieListIds ?? [];
// Combine and deduplicate MovieList IDs.
final allMovieListIds = <String>{};
allMovieListIds.addAll(existingMovieListIds);
allMovieListIds.addAll(providedMovieListIds);
final finalMovieListIds = allMovieListIds.toList();
// Create the profile TTL content.
final profileTtl = TurtleSerializer.createUserProfile(
webId,
apiKey: apiKeyFileId,
dobString: dobString,
genderString: genderString,
movieListIds: finalMovieListIds,
);
// Write to POD profile.
if (!_context.mounted) return false;
final result = await writePod(
'profile/profile.ttl',
profileTtl,
_context,
_child,
encrypted: false,
);
if (result == SolidFunctionCallStatus.success) {
// Update cache.
_cachedProfile = {
'webId': webId,
'apiKey': actualApiKey,
'apiKeyId': apiKeyFileId,
'dob': dobString,
'gender': genderString,
'movieListIds': finalMovieListIds,
};
return true;
}
debugPrint('❌ Failed to write profile to POD');
return false;
} catch (e) {
debugPrint('❌ Exception in create/update user profile: $e');
return false;
}
}