More redux work in fires page

This commit is contained in:
vjrj 2018-06-28 10:42:59 +02:00
parent 5d947f9577
commit 7dddf03e32
13 changed files with 210 additions and 54 deletions

View file

@ -91,7 +91,7 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
: Icons.notifications_off), : Icons.notifications_off),
onPressed: () { onPressed: () {
loc.subscribed = !loc.subscribed; loc.subscribed = !loc.subscribed;
onToggle(loc.id); onToggle(loc);
/* FIXME int i = globals.yourLocations.indexOf(loc); /* FIXME int i = globals.yourLocations.indexOf(loc);
globals.yourLocations.removeAt(i); globals.yourLocations.removeAt(i);
globals.yourLocations.insert(i, loc); globals.yourLocations.insert(i, loc);
@ -189,8 +189,8 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
onDelete: (id) { onDelete: (id) {
store.dispatch(new DeleteYourLocationAction(id)); store.dispatch(new DeleteYourLocationAction(id));
}, },
onToggleSubs: (id) { onToggleSubs: (loc) {
store.dispatch(new ToggleSubscriptionAction(id)); store.dispatch(new ToggleSubscriptionAction(loc));
}, },
yourLocations: store.state.yourLocations); yourLocations: store.state.yourLocations);
}, },

View file

@ -12,6 +12,7 @@ import 'models/firesApi.dart';
import 'redux/fetchDataMiddleware.dart'; import 'redux/fetchDataMiddleware.dart';
import 'redux/reducers.dart'; import 'redux/reducers.dart';
import 'package:fires_flutter/models/yourLocationPersist.dart'; import 'package:fires_flutter/models/yourLocationPersist.dart';
import 'package:fires_flutter/models/yourLocation.dart';
Future<Map<String, dynamic>> loadSecrets() async { Future<Map<String, dynamic>> loadSecrets() async {
return await SecretLoader(secretPath: 'assets/private-settings.json').load(); return await SecretLoader(secretPath: 'assets/private-settings.json').load();
@ -40,8 +41,11 @@ void mainCommon(List<Middleware<AppState>> otherMiddleware) {
// Run baby run! // Run baby run!
runApp(new FiresApp(store)); runApp(new FiresApp(store));
}); });
// Listen to store changes, and re-render when the state is updated
// store.onChange.listen((state) {
// });
}); });
// Listen to store changes, and re-render when the state is updated
// store.onChange.listen(render);
} }

View file

@ -6,10 +6,11 @@ import 'package:redux/redux.dart';
void main() { void main() {
globals.isDevelopment = true; globals.isDevelopment = true;
var logRedux = false;
List<Middleware> devMiddlewares = [ List<Middleware> devMiddlewares = logRedux ? [
LoggingMiddleware.printer(formatter: LoggingMiddleware.multiLineFormatter) LoggingMiddleware.printer(formatter: LoggingMiddleware.multiLineFormatter)
]; ] : [];
mainCommon(devMiddlewares); mainCommon(devMiddlewares);
} }

View file

@ -79,6 +79,6 @@ class AppState extends Object with _$AppStateSerializerMixin {
typedef void AddYourLocationFunction(YourLocation loc); typedef void AddYourLocationFunction(YourLocation loc);
typedef void DeleteYourLocationFunction(ObjectId id); typedef void DeleteYourLocationFunction(ObjectId id);
typedef void UpdateYourLocationFunction(ObjectId id, YourLocation loc); typedef void UpdateYourLocationFunction(ObjectId id, YourLocation loc);
typedef void ToggleSubscriptionFunction(ObjectId id); typedef void ToggleSubscriptionFunction(YourLocation loc);
typedef void SubscribeFunction(ObjectId id); typedef void SubscribeFunction(ObjectId id);
typedef void UnSubscribeFunction(ObjectId id); typedef void UnSubscribeFunction(ObjectId id);

View file

@ -1,12 +1,11 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:bson_objectid/bson_objectid.dart';
import 'package:fires_flutter/models/yourLocation.dart';
import 'package:http/http.dart' as ht; import 'package:http/http.dart' as ht;
import 'package:jaguar_resty/jaguar_resty.dart' as resty; import 'package:jaguar_resty/jaguar_resty.dart' as resty;
import 'package:fires_flutter/models/yourLocation.dart';
import 'appState.dart'; import 'appState.dart';
class FiresApi { class FiresApi {
@ -14,7 +13,8 @@ class FiresApi {
resty.globalClient = new ht.IOClient(); resty.globalClient = new ht.IOClient();
} }
Future<String> createUser(AppState state, String mobileToken, String lang) async { Future<String> createUser(
AppState state, String mobileToken, String lang) async {
assert(state.firesApiUrl != null); assert(state.firesApiUrl != null);
assert(state.firesApiKey != null); assert(state.firesApiKey != null);
assert(mobileToken != null); assert(mobileToken != null);
@ -28,25 +28,87 @@ class FiresApi {
final String url = '${state.firesApiUrl}mobile/users'; final String url = '${state.firesApiUrl}mobile/users';
/* print(url); /* print(url);
print(params); */ print(params); */
String resp = await resty.post(url).json(params).go().then((response) { return await resty.post(url).json(params).go().then((response) {
if (response.statusCode == 200) { if (response.statusCode == 200) {
// print(response.body); // print(response.body);
return json.decode(response.body)['data']['userId']; return json.decode(response.body)['data']['userId'];
} }
}); });
return resp;
} }
Future<List<YourLocation>> fetchYourLocations(AppState state) async { Future<List<YourLocation>> fetchYourLocations(AppState state) async {
final apiKey = state.firesApiKey; final apiKey = state.firesApiKey;
final mobileToken = state.user.token; final mobileToken = state.user.token;
final String url = '${state.firesApiUrl}mobile/subscriptions/all/$apiKey/$mobileToken'; final String url = '${state
List<YourLocation> resp = await resty.get(url).go().then((response) { .firesApiUrl}mobile/subscriptions/all/$apiKey/$mobileToken';
return await resty.get(url).go().then((response) {
if (response.statusCode == 200) { if (response.statusCode == 200) {
// print(response.body); // print(response.body);
print(json.decode(response.body)['data']['subscriptions']); return []; final dataSubscriptions =
json.decode(response.body)['data']['subscriptions'];
List<YourLocation> subscribed = [];
for (int i = 0; i < dataSubscriptions.length; i++) {
var el = dataSubscriptions[i];
var lat = el['location']['lat'];
var lon = el['location']['lon'];
var id = el['_id']['_str'];
subscribed.add(new YourLocation(
id: ObjectId.fromHexString(el['_id']['_str']),
lat: lat,
lon: lon,
subscribed: true,
distance: el['distance']));
}
return subscribed;
}
});
}
Future<String> subscribe(AppState state, YourLocation loc) async {
assert(state.firesApiUrl != null);
assert(state.firesApiKey != null);
assert(state.user.token != null);
assert(loc != null);
assert(loc.lat != null);
assert(loc.lon != null);
assert(loc.id != null);
assert(loc.distance != null);
final params = {
"token": state.firesApiKey,
"mobileToken": state.user.token,
"id": loc.id.toHexString(),
"lat": loc.lat,
"lon": loc.lon,
"distance": loc.distance
};
final String url = '${state
.firesApiUrl}mobile/subscriptions';
return await resty.post(url).json(params).go().then((response) {
if (response.statusCode == 200) {
// print(response.body);
return json.decode(response.body)['data']['subsId'];
} else {
// take care of? "Unexpected error in REST call: Error: The user is already subscribed to this area [on-already-subscribed]"
print(response.body);
}
});
}
Future<bool> unsubscribe(AppState state, String subsId) async {
assert(state.firesApiUrl != null);
assert(state.firesApiKey != null);
assert(state.user.token != null);
final apiKey = state.firesApiKey;
final mobileToken = state.user.token;
assert(subsId != null);
final String url = '${state
.firesApiUrl}mobile/subscriptions/$apiKey/$mobileToken/$subsId';
return await resty.delete(url).go().then((response) {
if (response.statusCode == 200) {
// print(response.body);
return true;
} }
}); });
return resp;
} }
} }

View file

@ -20,6 +20,7 @@ class YourLocation extends Object with _$YourLocationSerializerMixin {
final double lon; final double lon;
String description; String description;
bool subscribed; bool subscribed;
int distance;
factory YourLocation.fromJson(Map<String, dynamic> json) => factory YourLocation.fromJson(Map<String, dynamic> json) =>
_$YourLocationFromJson(json); _$YourLocationFromJson(json);
@ -31,14 +32,13 @@ class YourLocation extends Object with _$YourLocationSerializerMixin {
@required this.lat, @required this.lat,
@required this.lon, @required this.lon,
this.description, this.description,
this.distance: 10,
this.subscribed: false}) { this.subscribed: false}) {
if (this.description == null) if (this.description == null)
this.description = 'Position: ${this.lat}, ${this.lon}'; this.description = 'Position: ${this.lat}, ${this.lon}';
if (this.id == null) this.id = new ObjectId(); if (this.id == null) this.id = new ObjectId();
} }
@override @override
bool operator ==(Object other) => bool operator ==(Object other) =>
identical(this, other) || identical(this, other) ||
@ -48,7 +48,8 @@ class YourLocation extends Object with _$YourLocationSerializerMixin {
lat == other.lat && lat == other.lat &&
lon == other.lon && lon == other.lon &&
description == other.description && description == other.description &&
subscribed == other.subscribed; subscribed == other.subscribed &&
distance == other.distance;
@override @override
int get hashCode => int get hashCode =>
@ -56,11 +57,11 @@ class YourLocation extends Object with _$YourLocationSerializerMixin {
lat.hashCode ^ lat.hashCode ^
lon.hashCode ^ lon.hashCode ^
description.hashCode ^ description.hashCode ^
subscribed.hashCode; subscribed.hashCode ^
distance.hashCode;
@override @override
String toString() { String toString() {
return 'YourLocation {id: $id, lat: $lat, lon: $lon, description: $description, subscribed: $subscribed}'; return 'YourLocation {id: $id, lat: $lat, lon: $lon, description: $description, subscribed: $subscribed, distance: $distance}';
} }
} }

View file

@ -14,24 +14,33 @@ YourLocation _$YourLocationFromJson(Map<String, dynamic> json) =>
lat: (json['lat'] as num).toDouble(), lat: (json['lat'] as num).toDouble(),
lon: (json['lon'] as num).toDouble(), lon: (json['lon'] as num).toDouble(),
description: json['description'] as String, description: json['description'] as String,
distance: json['distance'] as int,
subscribed: json['subscribed'] as bool); subscribed: json['subscribed'] as bool);
abstract class _$YourLocationSerializerMixin { abstract class _$YourLocationSerializerMixin {
ObjectId get id; ObjectId get id;
double get lat; double get lat;
double get lon; double get lon;
String get description; String get description;
bool get subscribed; bool get subscribed;
int get distance;
Map<String, dynamic> toJson() => new _$YourLocationJsonMapWrapper(this); Map<String, dynamic> toJson() => new _$YourLocationJsonMapWrapper(this);
} }
class _$YourLocationJsonMapWrapper extends $JsonMapWrapper { class _$YourLocationJsonMapWrapper extends $JsonMapWrapper {
final _$YourLocationSerializerMixin _v; final _$YourLocationSerializerMixin _v;
_$YourLocationJsonMapWrapper(this._v); _$YourLocationJsonMapWrapper(this._v);
@override @override
Iterable<String> get keys => Iterable<String> get keys =>
const ['id', 'lat', 'lon', 'description', 'subscribed']; const ['id', 'lat', 'lon', 'description', 'subscribed', 'distance'];
@override @override
dynamic operator [](Object key) { dynamic operator [](Object key) {
@ -47,6 +56,8 @@ class _$YourLocationJsonMapWrapper extends $JsonMapWrapper {
return _v.description; return _v.description;
case 'subscribed': case 'subscribed':
return _v.subscribed; return _v.subscribed;
case 'distance':
return _v.distance;
} }
} }
return null; return null;

View file

@ -4,6 +4,8 @@ abstract class AppActions {}
class FetchYourLocationsAction extends AppActions {} class FetchYourLocationsAction extends AppActions {}
class PersistAppStateAction extends AppActions {}
class FetchYourLocationsSucceededAction extends AppActions { class FetchYourLocationsSucceededAction extends AppActions {
final List<YourLocation> fetchedYourLocations; final List<YourLocation> fetchedYourLocations;

10
lib/redux/appReducer.dart Normal file
View file

@ -0,0 +1,10 @@
import 'actions.dart';
import '../models/user.dart';
import '../models/appState.dart';
AppState appReducer(AppState state, action) {
if (action is FetchYourLocationsSucceededAction) {
return state.copyWith(yourLocations: action.fetchedYourLocations);
}
return state;
}

View file

@ -1,11 +1,10 @@
import 'package:bson_objectid/bson_objectid.dart';
import 'package:fires_flutter/models/yourLocation.dart';
import 'package:redux/redux.dart'; import 'package:redux/redux.dart';
import '../globals.dart' as globals; import '../globals.dart' as globals;
import '../models/appState.dart'; import '../models/appState.dart';
import '../models/firesApi.dart'; import '../models/firesApi.dart';
import 'package:fires_flutter/models/yourLocation.dart';
import '../models/yourLocationPersist.dart'; import '../models/yourLocationPersist.dart';
import 'actions.dart'; import 'actions.dart';
@ -36,28 +35,52 @@ void fetchYourLocationsMiddleware(
createUser(store, store.state.user.lang, action.token); createUser(store, store.state.user.lang, action.token);
} }
if (action is FetchYourLocationsAction) { if (action is AddYourLocationAction) {
final api = globals.getIt.get<FiresApi>(); if (action.loc.subscribed) {
subscribeViaApi(store, action.loc,
(sub) => store.dispatch(new AddedYourLocationAction(sub)));
} else {
// No subscribed (only local)
store.dispatch(new AddedYourLocationAction(action.loc));
persistYourLocations(store.state.yourLocations);
}
}
if (action is DeleteYourLocationAction) {
unsubsViaApi(store, action.id,
() => store.dispatch(new DeletedYourLocationAction(action.id)));
}
if (action is ToggleSubscriptionAction) {
if (action.loc.subscribed) {
subscribeViaApi(store, action.loc,
(sub) => store.dispatch(new ToggledSubscriptionAction(sub)));
} else {
unsubsViaApi(store, action.loc.id,
() => store.dispatch(new ToggledSubscriptionAction(action.loc)));
}
}
if (action is FetchYourLocationsAction) {
// Use the api to fetch the YourLocations // Use the api to fetch the YourLocations
api.fetchYourLocations(store.state).then((List<YourLocation> yourSubs) { api
.fetchYourLocations(store.state)
.then((List<YourLocation> subscribedLocations) {
// If it succeeds, dispatch a success action with the YourLocations. // If it succeeds, dispatch a success action with the YourLocations.
// Our reducer will then update the State using these YourLocations. // Our reducer will then update the State using these YourLocations.
// print('Subscribed to: ${subscribedLocations.length}');
loadYourLocations().then((localLocations) { loadYourLocations().then((localLocations) {
// unsubscribe all locally to sync the subs state // unsubscribe all locally to sync the subs state
localLocations.forEach((location) => location.subscribed = false); localLocations.forEach((location) => location.subscribed = false);
// print('Local persisted: ${localLocations.length}');
yourSubs.forEach((loc) { subscribedLocations.forEach((subsLoc) {
localLocations.firstWhere( localLocations.firstWhere(
(localLocation) => localLocation.id == loc.id, orElse: () { (localLocation) => localLocation.id == subsLoc.id, orElse: () {
localLocations.add(loc); localLocations.add(subsLoc);
}).subscribed = true; }).subscribed = true;
}); });
persistYourLocations(localLocations);
store.dispatch(new FetchYourLocationsSucceededAction(localLocations)); store.dispatch(new FetchYourLocationsSucceededAction(localLocations));
persistYourLocations(localLocations);
}); });
}).catchError((Exception error) { }).catchError((Exception error) {
// If it fails, dispatch a failure action. The reducer will // If it fails, dispatch a failure action. The reducer will
@ -65,11 +88,28 @@ void fetchYourLocationsMiddleware(
store.dispatch(new FetchYourLocationsFailedAction(error)); store.dispatch(new FetchYourLocationsFailedAction(error));
}); });
} }
// Make sure our actions continue on to the reducer. // Make sure our actions continue on to the reducer.
next(action); next(action);
} }
void unsubsViaApi(Store<AppState> store, ObjectId id, onUnsubs) {
api.unsubscribe(store.state, id.toHexString()).then((res) {
onUnsubs();
persistYourLocations(store.state.yourLocations);
});
}
void subscribeViaApi(Store<AppState> store, YourLocation loc, onSubs) {
api.subscribe(store.state, loc).then((subsId) {
YourLocation sub = loc;
if (loc.id != subsId) {
sub.id = new ObjectId.fromHexString(subsId);
}
onSubs(sub);
persistYourLocations(store.state.yourLocations);
});
}
void createUser(store, lang, token) { void createUser(store, lang, token) {
assert(token != null, "User lang is null"); assert(token != null, "User lang is null");
assert(token != null, "User mobile token is null"); assert(token != null, "User mobile token is null");

View file

@ -5,9 +5,14 @@ import 'loadedReducer.dart';
import 'loadingReducer.dart'; import 'loadingReducer.dart';
import 'userReducer.dart'; import 'userReducer.dart';
import 'yourLocationsReducer.dart'; import 'yourLocationsReducer.dart';
import 'actions.dart';
import 'appReducer.dart';
// We create the State reducer by combining many smaller reducers into one! // We create the State reducer by combining many smaller reducers into one!
AppState appStateReducer(AppState state, action) { AppState appStateReducer(AppState prevState, action) {
var state = prevState;
if (action is AppActions)
state = appReducer(prevState, action);
return AppState( return AppState(
yourLocations: yourLocationsReducer(state.yourLocations, action), yourLocations: yourLocationsReducer(state.yourLocations, action),
user: userReducer(state.user, action), user: userReducer(state.user, action),

View file

@ -11,12 +11,25 @@ class AddYourLocationAction extends YourLocationActions {
AddYourLocationAction(this.loc); AddYourLocationAction(this.loc);
} }
class AddedYourLocationAction extends YourLocationActions {
YourLocation loc;
AddedYourLocationAction(this.loc);
}
class DeleteYourLocationAction extends YourLocationActions { class DeleteYourLocationAction extends YourLocationActions {
ObjectId id; ObjectId id;
DeleteYourLocationAction(this.id); DeleteYourLocationAction(this.id);
} }
class DeletedYourLocationAction extends YourLocationActions {
ObjectId id;
DeletedYourLocationAction(this.id);
}
class UpdateYourLocationAction extends YourLocationActions { class UpdateYourLocationAction extends YourLocationActions {
ObjectId id; ObjectId id;
YourLocation loc; YourLocation loc;
@ -25,9 +38,15 @@ class UpdateYourLocationAction extends YourLocationActions {
} }
class ToggleSubscriptionAction extends YourLocationActions { class ToggleSubscriptionAction extends YourLocationActions {
ObjectId id; YourLocation loc;
ToggleSubscriptionAction(this.id); ToggleSubscriptionAction(this.loc);
}
class ToggledSubscriptionAction extends YourLocationActions {
YourLocation loc;
ToggledSubscriptionAction(this.loc);
} }
class SubscribeAction extends YourLocationActions { class SubscribeAction extends YourLocationActions {

View file

@ -4,24 +4,25 @@ import 'package:redux/redux.dart';
import 'actions.dart'; import 'actions.dart';
final yourLocationsReducer = combineReducers<List<YourLocation>>([ final yourLocationsReducer = combineReducers<List<YourLocation>>([
new TypedReducer<List<YourLocation>, AddYourLocationAction>(_addYourLocation), new TypedReducer<List<YourLocation>, AddedYourLocationAction>(_addedYourLocation),
new TypedReducer<List<YourLocation>, DeleteYourLocationAction>( new TypedReducer<List<YourLocation>, DeletedYourLocationAction>(
_deleteYourLocation), _deletedYourLocation),
new TypedReducer<List<YourLocation>, UpdateYourLocationAction>( new TypedReducer<List<YourLocation>, UpdateYourLocationAction>(
_updateYourLocation), _updateYourLocation),
new TypedReducer<List<YourLocation>, ToggledSubscriptionAction>(_toggledSubscriptionAction)
/* new TypedReducer<List<YourLocation>, ToggleSubscriptionAction>(_toggleSubscriptionAction), /* new TypedReducer<List<YourLocation>, ToggleSubscriptionAction>(_toggleSubscriptionAction),
new TypedReducer<List<YourLocation>, SubscribeAction>(_setLoadedYourLocations), new TypedReducer<List<YourLocation>, SubscribeAction>(_setLoadedYourLocations),
new TypedReducer<List<YourLocation>, UnSubscribeAction>(_setNoYourLocations), */ new TypedReducer<List<YourLocation>, UnSubscribeAction>(_setNoYourLocations), */
]); ]);
List<YourLocation> _addYourLocation( List<YourLocation> _addedYourLocation(
List<YourLocation> yourLocations, AddYourLocationAction action) { List<YourLocation> yourLocations, AddedYourLocationAction action) {
return new List.from(yourLocations)..add(action.loc); return new List.from(yourLocations)..add(action.loc);
} }
List<YourLocation> _deleteYourLocation( List<YourLocation> _deletedYourLocation(
List<YourLocation> yourLocations, DeleteYourLocationAction action) { List<YourLocation> yourLocations, DeletedYourLocationAction action) {
return yourLocations return yourLocations
.where((yourLocation) => yourLocation.id != action.id) .where((yourLocation) => yourLocation.id != action.id)
.toList(); .toList();
@ -34,13 +35,13 @@ List<YourLocation> _updateYourLocation(
yourLocation.id == action.id ? action.loc : yourLocation) yourLocation.id == action.id ? action.loc : yourLocation)
.toList(); .toList();
} }
/*
List<YourLocation> _toggleSubscriptionAction(List<YourLocation> yourLocations, UpdateYourLocationAction action) { List<YourLocation> _toggledSubscriptionAction(List<YourLocation> yourLocations, ToggledSubscriptionAction action) {
return yourLocations return yourLocations
.map((yourLocation) => yourLocation.id == action.id ? action.loc : yourLocation) .map((yourLocation) => yourLocation.id == action.loc.id ? action.loc : yourLocation)
.toList(); .toList();
} }
/*
List<YourLocation> _setLoadedYourLocations(List<YourLocation> yourLocations, YourLocationsLoadedAction action) { List<YourLocation> _setLoadedYourLocations(List<YourLocation> yourLocations, YourLocationsLoadedAction action) {
return action.yourLocations; return action.yourLocations;
} }