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 '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();
// https://pub.dartlang.org/packages/firebase_messaging#-example-tab-
void firebaseConfig() {
_firebaseMessaging.configure(
onLaunch: (Map<String, dynamic> message) {
print('On firebase launch');
},
onMessage: (Map<String, dynamic> message) {
print('On firebase message');
},
onResume: (Map<String, dynamic> message) {
print('On firebase resume');
}
);
getToken();
void firebaseConfig(Store<AppState> store) {
_firebaseMessaging.configure(onLaunch: (Map<String, dynamic> message) {
print('On firebase launch');
}, onMessage: (Map<String, dynamic> message) {
print('On firebase message');
}, onResume: (Map<String, dynamic> message) {
print('On firebase resume');
});
getToken(store);
}
getToken() async {
getToken(Store<AppState> store) async {
String token = await _firebaseMessaging.onTokenRefresh.first;
// print(token);
// await _firebaseMessaging.getToken();
store.dispatch(new OnUserTokenAction(token));
}

View file

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

View file

@ -8,32 +8,34 @@ import 'firebaseMessagingConf.dart';
import 'firesApp.dart';
import 'globals.dart' as globals;
import 'models/appState.dart';
import 'models/firesApi.dart';
import 'redux/fetchDataMiddleware.dart';
import 'redux/reducers.dart';
import 'yourLocationPersist.dart';
import 'models/firesApi.dart';
import 'package:get_it/get_it.dart';
import 'package:redux_logging/redux_logging.dart';
Future<Map<String, dynamic>> loadSecrets() async {
return await SecretLoader(secretPath: 'assets/private-settings.json').load();
}
void mainCommon(List<Middleware<AppState>> otherMiddleware) {
final store = new Store<AppState>(
appStateReducer,
initialState: new AppState(),
middleware: otherMiddleware,
);
globals.getIt.registerSingleton<FiresApi>(new FiresApi());
loadSecrets().then((secrets) {
globals.gmapKey = secrets['gmapKey'];
globals.firesApiKey = secrets['firesApiKey'];
globals.firesApiUrl = secrets['firesApiUrl'] + "api/v1/";
final store = new Store<AppState>(appStateReducer,
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) {
loadYourLocationsWithPrefs(prefs);
firebaseConfig();
firebaseConfig(store);
// Run baby run!
runApp(new FiresApp(store));

View file

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

View file

@ -1,9 +1,9 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
import 'package:comunes_flutter/comunes_flutter.dart';
import 'fireMapState.dart';
import 'yourLocation.dart';
import 'user.dart';
part 'appState.g.dart';
@immutable
@ -15,8 +15,14 @@ class AppState extends Object with _$AppStateSerializerMixin {
final bool isLoaded;
@JsonKey(ignore: true)
final String error;
final String userId;
final String token;
@JsonKey(ignore: true)
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;
@JsonKey(ignore: true)
final FireMapState fireMapState;
@ -26,34 +32,40 @@ class AppState extends Object with _$AppStateSerializerMixin {
_$AppStateFromJson(json);
AppState(
{this.yourLocations = const [],
this.userId,
this.token,
{this.yourLocations : const <YourLocation>[],
this.user: const User.initial(),
this.isLoading: false,
this.isLoaded: false,
this.error: null,
this.gmapKey,
this.firesApiKey,
this.firesApiUrl,
this.fireMapState: const FireMapState.initial()});
AppState copyWith(
{bool isLoading,
bool isLoaded,
String userId,
String token,
String user,
String error,
String gmapKey,
String firesApiKey,
String firesApiUrl,
List<YourLocation> yourLocations,
FireMapState fireMapState}) {
return new AppState(
isLoading: isLoading ?? this.isLoading,
isLoaded: isLoaded ?? this.isLoaded,
userId: userId ?? this.userId,
token: token ?? this.token,
user: user ?? this.user,
error: error ?? this.error,
gmapKey: gmapKey ?? this.gmapKey,
firesApiKey: firesApiKey ?? this.firesApiKey,
firesApiUrl: firesApiUrl ?? this.firesApiUrl,
yourLocations: yourLocations ?? this.yourLocations,
fireMapState: fireMapState ?? this.fireMapState);
}
@override
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(
yourLocations: (json['yourLocations'] as List)
.map((e) => new YourLocation.fromJson(e as Map<String, dynamic>))
.toList(),
userId: json['userId'] as String,
token: json['token'] as String);
.toList());
abstract class _$AppStateSerializerMixin {
String get userId;
String get token;
List<YourLocation> get yourLocations;
Map<String, dynamic> toJson() => new _$AppStateJsonMapWrapper(this);
}
@ -27,16 +23,12 @@ class _$AppStateJsonMapWrapper extends $JsonMapWrapper {
_$AppStateJsonMapWrapper(this._v);
@override
Iterable<String> get keys => const ['userId', 'token', 'yourLocations'];
Iterable<String> get keys => const ['yourLocations'];
@override
dynamic operator [](Object key) {
if (key is String) {
switch (key) {
case 'userId':
return _v.userId;
case 'token':
return _v.token;
case 'yourLocations':
return _v.yourLocations;
}

View file

@ -1,14 +1,39 @@
import 'yourLocation.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as ht;
import 'package:jaguar_resty/jaguar_resty.dart' as resty;
import 'appState.dart';
import 'yourLocation.dart';
class FiresApi {
Future<String> createUser(String token) async {
FiresApi() {
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);
}
class OnUserLangAction extends AppActions {
final String lang;
OnUserLangAction(this.lang);
}

View file

@ -1,9 +1,10 @@
import 'package:redux/redux.dart';
import 'actions.dart';
import '../models/yourLocation.dart';
import '../models/appState.dart';
import '../globals.dart' as globals;
import '../models/appState.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
// 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
// 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>();
// 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.
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 'yourLocationsReducer.dart';
import 'errorReducer.dart';
import 'fireMapReducer.dart';
import 'loadedReducer.dart';
import 'loadingReducer.dart';
import 'errorReducer.dart';
import 'userIdReducer.dart';
import 'userTokenReducer.dart';
import 'fireMapReducer.dart';
import 'userReducer.dart';
import 'yourLocationsReducer.dart';
// We create the State reducer by combining many smaller reducers into one!
AppState appStateReducer(AppState state, action) {
return AppState(
return AppState(
yourLocations: yourLocationsReducer(state.yourLocations, action),
userId: userReducer(state.userId, action),
token: userTokenReducer(state.token, action),
user: userReducer(state.user, action),
isLoading: loadingReducer(state.isLoading, action),
isLoaded: loadedReducer(state.isLoaded, 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"
comunes_flutter:
path: /home/vjrj/dev/comunes_flutter
version: "^0.0.10"
version: "^0.0.12"
# redux
redux: "^3.0.0"