Skip to content

Commit

Permalink
Fix map and home screen issues (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-radhika-s authored Dec 20, 2024
1 parent 1bd2f9f commit 24058e2
Show file tree
Hide file tree
Showing 19 changed files with 561 additions and 395 deletions.
8 changes: 5 additions & 3 deletions app/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ void main() async {

if (Platform.isAndroid) _configureService();

if (await Permission.location.isGranted) {
await locationMethodChannel.invokeMethod('startTracking');
if (await Permission.location.isGranted && Platform.isIOS) {
await locationMethodChannel.invokeMethod('startTracking');
}

locationMethodChannel.setMethodCallHandler(_handleLocationUpdates);
Expand Down Expand Up @@ -111,7 +111,9 @@ Future<void> _handleLocationUpdates(MethodCall call) async {
locationData['timestamp'].toInt()),
);

await LocationManager.instance.updateUserLocation(locationPosition);
if (locationPosition.latitude != 0 && locationPosition.longitude != 0) {
await LocationManager.instance.updateUserLocation(locationPosition);
}
}
}

Expand Down
6 changes: 3 additions & 3 deletions app/lib/ui/components/user_battery_status.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import 'package:style/text/app_text_dart.dart';
import '../../gen/assets.gen.dart';

class UserBatteryStatus extends StatelessWidget {
final ApiUserInfo userInfo;
final ApiUser user;

const UserBatteryStatus({super.key, required this.userInfo});
const UserBatteryStatus({super.key, required this.user});

@override
Widget build(BuildContext context) {
final batteryPct = userInfo.user.battery_pct ?? 0;
final batteryPct = user.battery_pct ?? 0;
String icon;
Color color;

Expand Down
16 changes: 2 additions & 14 deletions app/lib/ui/flow/home/home_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ class _HomeScreenState extends ConsumerState<HomeScreen> {

notifier = ref.watch(homeViewStateProvider.notifier);

geofenceRepository = ref.read(geofenceRepositoryProvider);
geofenceRepository.init();
GeofenceService.setGeofenceCallback(
onEnter: (id) => geofenceRepository.makeHttpCall(id, GEOFENCE_ENTER),
onExit: (id) => geofenceRepository.makeHttpCall(id, GEOFENCE_EXIT),
Expand All @@ -71,7 +69,6 @@ class _HomeScreenState extends ConsumerState<HomeScreen> {
final state = ref.watch(homeViewStateProvider);
_observeNavigation(state);
_observeError();
_observeSelectedSpace();
if (Platform.isAndroid) _observeShowBatteryDialog(context);
_observeSessionExpiredAlertPopup(context);
_observeSessionExpired();
Expand All @@ -93,7 +90,7 @@ class _HomeScreenState extends ConsumerState<HomeScreen> {
Widget _body(BuildContext context, HomeViewState state) {
if (state.isNetworkOff) {
return NoInternetScreen(onPressed: () {
notifier.setDate();
notifier.fetchData();
});
}

Expand Down Expand Up @@ -143,15 +140,6 @@ class _HomeScreenState extends ConsumerState<HomeScreen> {
});
}

void _observeSelectedSpace() {
ref.listen(homeViewStateProvider.select((state) => state.selectedSpace),
(previous, next) {
if (previous?.space.id != next?.space.id) {
mapNotifier.loadData(next?.space.id);
}
});
}

void _observeShowBatteryDialog(BuildContext context) {
ref.listen(homeViewStateProvider.select((state) => state.showBatteryDialog),
(_, next) {
Expand Down Expand Up @@ -198,7 +186,7 @@ class _HomeScreenState extends ConsumerState<HomeScreen> {
ref.listen(homeViewStateProvider.select((state) => state.popToSignIn),
(_, next) {
if (next != null) {
AppRoute.signInMethod.push(context);
AppRoute.signInMethod.go(context);
}
});
}
Expand Down
136 changes: 95 additions & 41 deletions app/lib/ui/flow/home/home_screen_viewmodel.dart
Original file line number Diff line number Diff line change
@@ -1,44 +1,51 @@
import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:data/api/auth/api_user_service.dart';
import 'package:data/api/auth/auth_models.dart';
import 'package:data/api/location/location.dart';
import 'package:data/api/place/api_place.dart';
import 'package:data/api/space/space_models.dart';
import 'package:data/log/logger.dart';
import 'package:data/service/geofence_service.dart';
import 'package:data/service/permission_service.dart';
import 'package:data/service/space_service.dart';
import 'package:data/storage/app_preferences.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:geolocator/geolocator.dart';

import '../../components/no_internet_screen.dart';

part 'home_screen_viewmodel.freezed.dart';

final homeViewStateProvider =
StateNotifierProvider.autoDispose<HomeViewNotifier, HomeViewState>(
(ref) => HomeViewNotifier(
StateNotifierProvider.autoDispose<HomeViewNotifier, HomeViewState>((ref) {
final notifier = HomeViewNotifier(
ref.read(spaceServiceProvider),
ref.read(currentSpaceId.notifier),
ref.read(permissionServiceProvider),
ref.read(lastBatteryDialogPod.notifier),
ref.read(currentUserPod),
ref.read(apiUserServiceProvider),
ref.read(currentUserSessionPod),
),
);
);
ref.listen(currentUserPod, (prev, user) {
notifier._onUpdateUser(prevUser: prev, currentUser: user);
});

ref.listen(currentSpaceId, (prev, newSpaceId) {
notifier._onUpdateSpace(prev: prev, current: newSpaceId);
});

return notifier;
});

class HomeViewNotifier extends StateNotifier<HomeViewState> {
final SpaceService spaceService;
final PermissionService permissionService;
final StateController<String?> _currentSpaceIdController;
final StateController<String?> _lastBatteryDialogDate;
final ApiUser? _currentUser;
ApiUser? _currentUser;
final ApiUserService userService;
final ApiSession? _userSession;

Expand All @@ -51,48 +58,87 @@ class HomeViewNotifier extends StateNotifier<HomeViewState> {
this.userService,
this._userSession,
) : super(const HomeViewState()) {
setDate();
fetchData();
_listenPlaces();
}

StreamSubscription<List<SpaceInfo>>? _spacesSubscription;
StreamSubscription<ApiSession?>? _userSessionSubscription;
StreamSubscription<List<ApiPlace>?>? _spacePlacesSubscription;

String? get currentSpaceId => _currentSpaceIdController.state;

void setDate() async {
void fetchData() async {
final isNetworkOff = await _checkUserInternet();
if (isNetworkOff) return;

listenSpaceMember();
updateCurrentUserNetworkState();

if (_currentUser == null && _userSession == null) return;
listenUserSession(_currentUser!.id, _userSession!.id);
listenUserSession();
}

Future<LocationData> currentUserLocation() async {
if (Platform.isIOS) {
const platform = MethodChannel('com.grouptrack/current_location');
final locationFromIOS = await platform.invokeMethod('getCurrentLocation');
return LocationData(
latitude: locationFromIOS['latitude'],
longitude: locationFromIOS['longitude'],
timestamp: DateTime.fromMillisecondsSinceEpoch(
locationFromIOS['timestamp'].toInt()),
);
} else {
var location = await Geolocator.getCurrentPosition();
return LocationData(
latitude: location.latitude,
longitude: location.longitude,
timestamp: DateTime.now());
void _listenPlaces() async {
if (_currentUser == null) return;
try {
_spacePlacesSubscription?.cancel();
_spacePlacesSubscription = spaceService
.getStreamPlacesByUserId(_currentUser!.id)
.listen((places) {
if (places.isEmpty) {
logger.e('No places found for spaces.');
return;
}

GeofenceService.startMonitoring(places);
});
} catch (error) {
logger.e('GeofenceRepository: error while get user space $error');
}
}

void _onUpdateSpace({String? prev, String? current}) {
if (current == null) {
_cancelSubscriptions();
state = state.copyWith(selectedSpace: null);
fetchData();
} else if (prev != current) {
state = state.copyWith(
selectedSpace:
state.spaceList.where((e) => e.space.id == current).firstOrNull);
}
}

void _onUpdateUser({ApiUser? prevUser, ApiUser? currentUser}) {
_currentUser = currentUser;
if (currentUser == null) {
_cancelSubscriptions();
state = state.copyWith(spaceList: [], selectedSpace: null);
} else if (prevUser?.id != currentUser.id) {
fetchData();
_listenPlaces();
}
}

void _cancelSubscriptions() {
_spacePlacesSubscription?.cancel();
_spacesSubscription?.cancel();
_userSessionSubscription?.cancel();
}

void listenSpaceMember() async {
if (state.loading) return;
final userId = _currentUser?.id;
if (state.loading || userId == null) return;
try {
_spacesSubscription?.cancel();
state = state.copyWith(loading: true);
_spacesSubscription = spaceService.streamAllSpace().listen((spaces) {

_spacesSubscription =
spaceService.streamAllSpace(userId).listen((spaces) {
if ((currentSpaceId?.isEmpty ?? true) && spaces.isNotEmpty) {
spaceService.currentSpaceId = spaces.firstOrNull?.space.id;
}

if (spaces.isNotEmpty) {
if (state.spaceList.length != spaces.length) {
reorderSpaces(spaces);
Expand All @@ -119,7 +165,7 @@ class HomeViewNotifier extends StateNotifier<HomeViewState> {
try {
var connectivityResult = await Connectivity().checkConnectivity();
final userState = await checkUserState(connectivityResult.first);
await userService.updateUserState(_currentUser.id, userState);
await userService.updateUserState(_currentUser!.id, userState);
} catch (error, stack) {
logger.e(
'HomeViewNotifier: error while update current user state',
Expand Down Expand Up @@ -176,11 +222,6 @@ class HomeViewNotifier extends StateNotifier<HomeViewState> {
state = state.copyWith(selectedSpace: selectedSpace);
}
}
if (currentSpaceId == null && sortedSpaces.isNotEmpty) {
_currentSpaceIdController.state = sortedSpaces.first.space.id;
updateSelectedSpace(sortedSpaces.first);
state = state.copyWith(selectedSpace: sortedSpaces.first);
}
state = state.copyWith(
selectedSpace: sortedSpaces.first, spaceList: sortedSpaces);
}
Expand All @@ -196,7 +237,8 @@ class HomeViewNotifier extends StateNotifier<HomeViewState> {
? _currentUser?.location_enabled ?? true
: members.first.isLocationEnabled,
);
_currentSpaceIdController.state = space.space.id;

spaceService.currentSpaceId = space.space.id;
}
}

Expand Down Expand Up @@ -241,7 +283,7 @@ class HomeViewNotifier extends StateNotifier<HomeViewState> {
state = state.copyWith(enablingLocation: true);
await spaceService.enableLocation(
currentSpaceId!,
_currentUser.id,
_currentUser!.id,
isEnabled,
);
state = state.copyWith(
Expand All @@ -256,9 +298,15 @@ class HomeViewNotifier extends StateNotifier<HomeViewState> {
}
}

void listenUserSession(String userId, String sessionId) async {
void listenUserSession() async {
if (_currentUser == null && _userSession == null) return;
try {
userService.getUserSessionByIdStream(userId, sessionId).listen((session) {
final userId = _currentUser!.id;
final sessionId = _userSession!.id;
_userSessionSubscription?.cancel();
_userSessionSubscription = userService
.getUserSessionByIdStream(userId, sessionId)
.listen((session) {
if (session != null && !session.session_active) {
state = state.copyWith(isSessionExpired: true, error: null);
}
Expand All @@ -285,6 +333,12 @@ class HomeViewNotifier extends StateNotifier<HomeViewState> {
if (isNetworkOff) _spacesSubscription?.cancel();
return isNetworkOff;
}

@override
void dispose() {
_cancelSubscriptions();
super.dispose();
}
}

@freezed
Expand Down
Loading

0 comments on commit 24058e2

Please sign in to comment.