More redux work. User creation/retrieve

This commit is contained in:
vjrj 2018-06-27 19:46:02 +02:00
parent 2c67b68512
commit 2dfa745c6a
16 changed files with 212 additions and 110 deletions

View file

@ -1,26 +1,26 @@
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'dart:async'; import 'package:redux/src/store.dart';
import 'models/appState.dart';
import 'redux/actions.dart';
import 'globals.dart' as globals;
import 'models/firesApi.dart';
final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging(); final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();
// https://pub.dartlang.org/packages/firebase_messaging#-example-tab- // https://pub.dartlang.org/packages/firebase_messaging#-example-tab-
void firebaseConfig() { void firebaseConfig(Store<AppState> store) {
_firebaseMessaging.configure( _firebaseMessaging.configure(onLaunch: (Map<String, dynamic> message) {
onLaunch: (Map<String, dynamic> message) { print('On firebase launch');
print('On firebase launch'); }, onMessage: (Map<String, dynamic> message) {
}, print('On firebase message');
onMessage: (Map<String, dynamic> message) { }, onResume: (Map<String, dynamic> message) {
print('On firebase message'); print('On firebase resume');
}, });
onResume: (Map<String, dynamic> message) { getToken(store);
print('On firebase resume');
}
);
getToken();
} }
getToken() async { getToken(Store<AppState> store) async {
String token = await _firebaseMessaging.onTokenRefresh.first; String token = await _firebaseMessaging.onTokenRefresh.first;
// print(token); store.dispatch(new OnUserTokenAction(token));
// await _firebaseMessaging.getToken();
} }

View file

@ -1,16 +1,17 @@
import 'package:comunes_flutter/comunes_flutter.dart'; import 'package:comunes_flutter/comunes_flutter.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'activeFires.dart'; import 'activeFires.dart';
import 'generated/i18n.dart'; import 'generated/i18n.dart';
import 'homePage.dart'; import 'homePage.dart';
import 'introPage.dart'; import 'introPage.dart';
import 'models/appState.dart';
import 'redux/actions.dart';
import 'sandbox.dart'; import 'sandbox.dart';
import 'theme.dart'; import 'theme.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'models/appState.dart';
class FiresApp extends StatelessWidget { class FiresApp extends StatelessWidget {
static final WidgetBuilder introWidget = (context) => new IntroPage(); static final WidgetBuilder introWidget = (context) => new IntroPage();
@ -30,20 +31,25 @@ class FiresApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return new StoreProvider(store: this.store, child: return new StoreProvider(
new MaterialApp( store: this.store,
localizationsDelegates: [ child: new MaterialApp(
S.delegate, localizationsDelegates: [
GlobalMaterialLocalizations.delegate, S.delegate,
GlobalWidgetsLocalizations.delegate, GlobalMaterialLocalizations.delegate,
], GlobalWidgetsLocalizations.delegate,
supportedLocales: S.delegate.supportedLocales, ],
localeResolutionCallback: supportedLocales: S.delegate.supportedLocales,
S.delegate.resolution(fallback: new Locale("en", "")), localeResolutionCallback:
home: new MaterialAppWithIntroHome( S.delegate.resolution(fallback: new Locale("en", "")),
introWidget, continueWidget, 'showInitialWizard-2018-06-27-01'), home: new MaterialAppWithIntroHome(
onGenerateTitle: (context) => S.of(context).appName, introWidget, continueWidget, 'showInitialWizard-2018-06-27-01'),
theme: firesTheme, onGenerateTitle: (context) {
routes: routes)); String lang = Localizations.localeOf(context).languageCode;
this.store.dispatch(new OnUserLangAction(lang));
return S.of(context).appName;
},
theme: firesTheme,
routes: routes));
} }
} }

View file

@ -7,6 +7,7 @@ import 'dart:async';
import 'package:fires_flutter/models/yourLocation.dart'; import 'package:fires_flutter/models/yourLocation.dart';
// FIXME remove this later
String gmapKey; String gmapKey;
String firesApiKey; String firesApiKey;
String firesApiUrl; String firesApiUrl;

View file

@ -8,32 +8,34 @@ import 'firebaseMessagingConf.dart';
import 'firesApp.dart'; import 'firesApp.dart';
import 'globals.dart' as globals; import 'globals.dart' as globals;
import 'models/appState.dart'; import 'models/appState.dart';
import 'models/firesApi.dart';
import 'redux/fetchDataMiddleware.dart';
import 'redux/reducers.dart'; import 'redux/reducers.dart';
import 'yourLocationPersist.dart'; import 'yourLocationPersist.dart';
import 'models/firesApi.dart'; import 'package:redux_logging/redux_logging.dart';
import 'package:get_it/get_it.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();
} }
void mainCommon(List<Middleware<AppState>> otherMiddleware) { void mainCommon(List<Middleware<AppState>> otherMiddleware) {
final store = new Store<AppState>(
appStateReducer,
initialState: new AppState(),
middleware: otherMiddleware,
);
globals.getIt.registerSingleton<FiresApi>(new FiresApi()); globals.getIt.registerSingleton<FiresApi>(new FiresApi());
loadSecrets().then((secrets) { loadSecrets().then((secrets) {
globals.gmapKey = secrets['gmapKey'];
globals.firesApiKey = secrets['firesApiKey']; final store = new Store<AppState>(appStateReducer,
globals.firesApiUrl = secrets['firesApiUrl'] + "api/v1/"; initialState: new AppState(
gmapKey: secrets['gmapKey'],
firesApiKey: secrets['firesApiKey'],
firesApiUrl: secrets['firesApiUrl'] + "api/v1/"),
middleware: List.from(otherMiddleware)..add(fetchYourLocationsMiddleware));
// FIXME remove this later
globals.firesApiKey = store.state.firesApiKey;
globals.firesApiUrl = store.state.firesApiUrl;
globals.gmapKey = store.state.gmapKey;
globals.prefs.then((prefs) { globals.prefs.then((prefs) {
loadYourLocationsWithPrefs(prefs); loadYourLocationsWithPrefs(prefs);
firebaseConfig(); firebaseConfig(store);
// Run baby run! // Run baby run!
runApp(new FiresApp(store)); runApp(new FiresApp(store));

View file

@ -2,12 +2,13 @@ import 'package:redux_logging/redux_logging.dart';
import 'globals.dart' as globals; import 'globals.dart' as globals;
import 'mainCommon.dart'; import 'mainCommon.dart';
import 'package:redux/redux.dart';
void main() { void main() {
globals.isDevelopment = true; globals.isDevelopment = true;
List devMiddlewares = [ List<Middleware> devMiddlewares = [
new LoggingMiddleware(formatter: LoggingMiddleware.multiLineFormatter) LoggingMiddleware.printer(formatter: LoggingMiddleware.multiLineFormatter)
]; ];
mainCommon(devMiddlewares); mainCommon(devMiddlewares);

View file

@ -1,9 +1,9 @@
import 'package:json_annotation/json_annotation.dart'; import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:comunes_flutter/comunes_flutter.dart';
import 'fireMapState.dart'; import 'fireMapState.dart';
import 'yourLocation.dart'; import 'yourLocation.dart';
import 'user.dart';
part 'appState.g.dart'; part 'appState.g.dart';
@immutable @immutable
@ -15,8 +15,14 @@ class AppState extends Object with _$AppStateSerializerMixin {
final bool isLoaded; final bool isLoaded;
@JsonKey(ignore: true) @JsonKey(ignore: true)
final String error; final String error;
final String userId; @JsonKey(ignore: true)
final String token; final User user;
@JsonKey(ignore: true)
final String gmapKey;
@JsonKey(ignore: true)
final String firesApiKey;
@JsonKey(ignore: true)
final String firesApiUrl;
final List<YourLocation> yourLocations; final List<YourLocation> yourLocations;
@JsonKey(ignore: true) @JsonKey(ignore: true)
final FireMapState fireMapState; final FireMapState fireMapState;
@ -26,34 +32,40 @@ class AppState extends Object with _$AppStateSerializerMixin {
_$AppStateFromJson(json); _$AppStateFromJson(json);
AppState( AppState(
{this.yourLocations = const [], {this.yourLocations : const <YourLocation>[],
this.userId, this.user: const User.initial(),
this.token,
this.isLoading: false, this.isLoading: false,
this.isLoaded: false, this.isLoaded: false,
this.error: null, this.error: null,
this.gmapKey,
this.firesApiKey,
this.firesApiUrl,
this.fireMapState: const FireMapState.initial()}); this.fireMapState: const FireMapState.initial()});
AppState copyWith( AppState copyWith(
{bool isLoading, {bool isLoading,
bool isLoaded, bool isLoaded,
String userId, String user,
String token,
String error, String error,
String gmapKey,
String firesApiKey,
String firesApiUrl,
List<YourLocation> yourLocations, List<YourLocation> yourLocations,
FireMapState fireMapState}) { FireMapState fireMapState}) {
return new AppState( return new AppState(
isLoading: isLoading ?? this.isLoading, isLoading: isLoading ?? this.isLoading,
isLoaded: isLoaded ?? this.isLoaded, isLoaded: isLoaded ?? this.isLoaded,
userId: userId ?? this.userId, user: user ?? this.user,
token: token ?? this.token,
error: error ?? this.error, error: error ?? this.error,
gmapKey: gmapKey ?? this.gmapKey,
firesApiKey: firesApiKey ?? this.firesApiKey,
firesApiUrl: firesApiUrl ?? this.firesApiUrl,
yourLocations: yourLocations ?? this.yourLocations, yourLocations: yourLocations ?? this.yourLocations,
fireMapState: fireMapState ?? this.fireMapState); fireMapState: fireMapState ?? this.fireMapState);
} }
@override @override
String toString() { String toString() {
return 'AppState{\nuserId: $userId\ntoken: $token\nisLoading: $isLoading\nisLoaded: $isLoaded\nYourLocations: $yourLocations}'; return 'AppState{\nuser: ${user}\nisLoading: $isLoading\nisLoaded: $isLoaded\napiKey: ${ellipse(firesApiKey, 8)}\napiUrl: ${ellipse(firesApiUrl, 8)}';
} }
} }

View file

@ -11,13 +11,9 @@ part of 'appState.dart';
AppState _$AppStateFromJson(Map<String, dynamic> json) => new AppState( AppState _$AppStateFromJson(Map<String, dynamic> json) => new AppState(
yourLocations: (json['yourLocations'] as List) yourLocations: (json['yourLocations'] as List)
.map((e) => new YourLocation.fromJson(e as Map<String, dynamic>)) .map((e) => new YourLocation.fromJson(e as Map<String, dynamic>))
.toList(), .toList());
userId: json['userId'] as String,
token: json['token'] as String);
abstract class _$AppStateSerializerMixin { abstract class _$AppStateSerializerMixin {
String get userId;
String get token;
List<YourLocation> get yourLocations; List<YourLocation> get yourLocations;
Map<String, dynamic> toJson() => new _$AppStateJsonMapWrapper(this); Map<String, dynamic> toJson() => new _$AppStateJsonMapWrapper(this);
} }
@ -27,16 +23,12 @@ class _$AppStateJsonMapWrapper extends $JsonMapWrapper {
_$AppStateJsonMapWrapper(this._v); _$AppStateJsonMapWrapper(this._v);
@override @override
Iterable<String> get keys => const ['userId', 'token', 'yourLocations']; Iterable<String> get keys => const ['yourLocations'];
@override @override
dynamic operator [](Object key) { dynamic operator [](Object key) {
if (key is String) { if (key is String) {
switch (key) { switch (key) {
case 'userId':
return _v.userId;
case 'token':
return _v.token;
case 'yourLocations': case 'yourLocations':
return _v.yourLocations; return _v.yourLocations;
} }

View file

@ -1,14 +1,39 @@
import 'yourLocation.dart';
import 'dart:async'; import 'dart:async';
import 'dart:convert';
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 'appState.dart';
import 'yourLocation.dart';
class FiresApi { class FiresApi {
FiresApi() {
Future<String> createUser(String token) async { resty.globalClient = new ht.IOClient();
} }
Future<List<YourLocation>> fetchYourLocations() async { Future<String> createUser(AppState state, String token, String lang) async {
assert(state.firesApiUrl != null);
assert(state.firesApiKey != null);
assert(token != null);
assert(lang != null);
final params = {
"token": state.firesApiKey,
"mobileToken": token,
"lang": lang
};
final url = '${state.firesApiUrl}mobile/users';
/* print(url);
print(params); */
String resp = await resty.post(url).json(params).go().then((response) {
if (response.statusCode == 200) {
// print(response.body);
return json.decode(response.body)['data']['userId'];
}
});
return resp;
} }
Future<List<YourLocation>> fetchYourLocations() async {}
} }

29
lib/models/user.dart Normal file
View file

@ -0,0 +1,29 @@
import 'package:meta/meta.dart';
import 'package:comunes_flutter/comunes_flutter.dart';
@immutable
class User {
final String userId;
final String lang;
final String token;
const User.initial()
: this.userId = null,
lang = null,
token = null;
User({this.userId, this.lang, this.token});
User copyWith({String userId, String lang, String token}) {
return new User(
userId: userId ?? this.userId,
token: token ?? this.token,
lang: lang ?? this.lang);
}
@override
String toString() {
return 'User {userId: $userId, lang: $lang, token: ${ellipse(token)}';
}
}

View file

@ -27,3 +27,9 @@ class OnUserCreatedAction extends AppActions {
OnUserCreatedAction(this.userId); OnUserCreatedAction(this.userId);
} }
class OnUserLangAction extends AppActions {
final String lang;
OnUserLangAction(this.lang);
}

View file

@ -1,9 +1,10 @@
import 'package:redux/redux.dart'; import 'package:redux/redux.dart';
import 'actions.dart';
import '../models/yourLocation.dart';
import '../models/appState.dart';
import '../globals.dart' as globals; import '../globals.dart' as globals;
import '../models/appState.dart';
import '../models/firesApi.dart'; import '../models/firesApi.dart';
import '../models/yourLocation.dart';
import 'actions.dart';
// A middleware takes in 3 parameters: your Store, which you can use to // A middleware takes in 3 parameters: your Store, which you can use to
// read state or dispatch new actions, the action that was dispatched, // read state or dispatch new actions, the action that was dispatched,
@ -13,10 +14,26 @@ import '../models/firesApi.dart';
// //
// Middleware do not return any values themselves. They simply forward // Middleware do not return any values themselves. They simply forward
// actions on to the Reducer or swallow actions in some special cases. // actions on to the Reducer or swallow actions in some special cases.
void fetchYourLocationsMiddleware(Store<AppState> store, action, NextDispatcher next) {
// If our Middleware encounters a `FetchYourLocationAction`
if (action is FetchYourLocationsAction) {
FiresApi api = globals.getIt.get<FiresApi>();
void fetchYourLocationsMiddleware(
Store<AppState> store, action, NextDispatcher next) {
// If our Middleware encounters a `FetchYourLocationAction`
if (action is OnUserLangAction) {
// I can create the user with the lang and the token
if (store.state.user.token != null)
createUser(store, action.lang, store.state.user.token);
}
if (action is OnUserTokenAction) {
// I can create the user with the lang and the token
if (store.state.user.lang != null)
createUser(store, store.state.user.lang, action.token);
}
if (action is FetchYourLocationsAction) {
final api = globals.getIt.get<FiresApi>(); final api = globals.getIt.get<FiresApi>();
// Use the api to fetch the YourLocations // Use the api to fetch the YourLocations
@ -34,3 +51,11 @@ void fetchYourLocationsMiddleware(Store<AppState> store, action, NextDispatcher
// Make sure our actions continue on to the reducer. // Make sure our actions continue on to the reducer.
next(action); next(action);
} }
void createUser(store, lang, token) {
assert(token != null, "User lang is null");
assert(token != null, "User mobile token is null");
api
.createUser(store.state, token, lang)
.then((userId) => store.dispatch(new OnUserCreatedAction(userId)));
}

View file

@ -1,22 +1,22 @@
import '../models/appState.dart'; import '../models/appState.dart';
import 'yourLocationsReducer.dart'; import 'errorReducer.dart';
import 'fireMapReducer.dart';
import 'loadedReducer.dart'; import 'loadedReducer.dart';
import 'loadingReducer.dart'; import 'loadingReducer.dart';
import 'errorReducer.dart'; import 'userReducer.dart';
import 'userIdReducer.dart'; import 'yourLocationsReducer.dart';
import 'userTokenReducer.dart';
import 'fireMapReducer.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 state, action) {
return AppState(
return AppState(
yourLocations: yourLocationsReducer(state.yourLocations, action), yourLocations: yourLocationsReducer(state.yourLocations, action),
userId: userReducer(state.userId, action), user: userReducer(state.user, action),
token: userTokenReducer(state.token, action),
isLoading: loadingReducer(state.isLoading, action), isLoading: loadingReducer(state.isLoading, action),
isLoaded: loadedReducer(state.isLoaded, action), isLoaded: loadedReducer(state.isLoaded, action),
error: errorReducer(state.error, action), error: errorReducer(state.error, action),
fireMapState: fireMapReducer(state.fireMapState, action) fireMapState: fireMapReducer(state.fireMapState, action),
); firesApiKey: state.firesApiKey,
firesApiUrl: state.firesApiUrl,
gmapKey: state.gmapKey
);
} }

View file

@ -1,3 +0,0 @@
String userReducer(String userId, action) {
return userId;
}

View file

@ -0,0 +1,9 @@
import 'actions.dart';
import '../models/user.dart';
User userReducer(User user, action) {
if (action is OnUserCreatedAction) return user.copyWith(userId: action.userId);
if (action is OnUserTokenAction) return user.copyWith(token: action.token);
if (action is OnUserLangAction) return user.copyWith(lang: action.lang);
return user;
}

View file

@ -1,3 +0,0 @@
String userTokenReducer(String userToken, action) {
return userToken;
}

View file

@ -25,7 +25,7 @@ dependencies:
bson_objectid: "^0.1.0" bson_objectid: "^0.1.0"
comunes_flutter: comunes_flutter:
path: /home/vjrj/dev/comunes_flutter path: /home/vjrj/dev/comunes_flutter
version: "^0.0.10" version: "^0.0.12"
# redux # redux
redux: "^3.0.0" redux: "^3.0.0"