Progressing with making app compatible with either osdapi or firebase backend - still crashing sometimes, so need to fix that...and reported IDs of events look wrong for the osdapi backend.

This commit is contained in:
Graham Jones
2022-04-09 21:58:26 +01:00
parent c0cfdbf8f7
commit c0fdc10dcd
7 changed files with 222 additions and 68 deletions

View File

@@ -24,6 +24,9 @@ import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays; import java.util.Arrays;
public class AuthenticateActivity extends AppCompatActivity { public class AuthenticateActivity extends AppCompatActivity {
@@ -35,6 +38,7 @@ public class AuthenticateActivity extends AppCompatActivity {
final Handler serverStatusHandler = new Handler(); final Handler serverStatusHandler = new Handler();
private WebApiConnection mWac; private WebApiConnection mWac;
private LogManager mLm; private LogManager mLm;
private static final String TOKEN_ID = "webApiAuthToken";
@Override @Override
@@ -146,6 +150,7 @@ public class AuthenticateActivity extends AppCompatActivity {
} }
private void initialiseServiceConnection() { private void initialiseServiceConnection() {
Log.v(TAG,"initialiseServiceConnection()");
mLm = mConnection.mSdServer.mLm; mLm = mConnection.mSdServer.mLm;
mWac = mConnection.mSdServer.mLm.mWac; mWac = mConnection.mSdServer.mLm.mWac;
updateUi(); updateUi();
@@ -165,25 +170,45 @@ public class AuthenticateActivity extends AppCompatActivity {
private void updateUi() { private void updateUi() {
Log.v(TAG,"updateUi()");
LinearLayout loginLl = (LinearLayout) findViewById(R.id.login_ui); LinearLayout loginLl = (LinearLayout) findViewById(R.id.login_ui);
LinearLayout osdApiLoginLl = (LinearLayout) findViewById(R.id.login_osdapi_ui);
LinearLayout logoutLl = (LinearLayout) findViewById(R.id.logout_ui); LinearLayout logoutLl = (LinearLayout) findViewById(R.id.logout_ui);
// Check if we are already logged in if (mWac == null) {
FirebaseAuth auth = FirebaseAuth.getInstance(); Log.i(TAG,"mWac is null - not updating UI");
if (auth.getCurrentUser() == null) { return;
Log.i(TAG, "Not Logged in - showing log in UI");
loginLl.setVisibility(View.VISIBLE);
logoutLl.setVisibility(View.GONE);
} else {
Log.i(TAG, "Already Logged in - showing Log Out prompt - " + auth.getCurrentUser().toString());
loginLl.setVisibility(View.GONE);
logoutLl.setVisibility(View.VISIBLE);
TextView tv2 = (TextView) findViewById(R.id.userIdTv);
tv2.setText(auth.getCurrentUser().getDisplayName());
tv2 = (TextView) findViewById(R.id.usernameTv);
tv2.setText(auth.getCurrentUser().getEmail());
} }
if (mWac.isLoggedIn()) {
Log.v(TAG, "Already Logged in - showing Log Out prompt");
loginLl.setVisibility(View.GONE);
logoutLl.setVisibility(View.VISIBLE);
if (!LogManager.USE_FIREBASE_BACKEND) {
osdApiLoginLl.setVisibility(View.GONE);
}
mWac.getUserProfile((JSONObject profileObj) -> {
try {
String userId = profileObj.getString("id");
String userName = profileObj.getString("username");
TextView tv2 = (TextView) findViewById(R.id.userIdTv);
tv2.setText(userId);
tv2 = (TextView) findViewById(R.id.usernameTv);
tv2.setText(userName);
} catch (JSONException e) {
Log.e(TAG, "Error Parsing profileObj: " + e.getMessage());
mUtil.showToast("Error Parsing profileObj - this should not happen!!!");
}
});
} else {
Log.v(TAG,"updateUi() - not logged in..");
loginLl.setVisibility(View.VISIBLE);
logoutLl.setVisibility(View.GONE);
if (!LogManager.USE_FIREBASE_BACKEND) {
osdApiLoginLl.setVisibility(View.VISIBLE);
}
}
} }
View.OnClickListener onCancel = View.OnClickListener onCancel =
@@ -201,23 +226,46 @@ public class AuthenticateActivity extends AppCompatActivity {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
//m_status=true; //m_status=true;
Log.v(TAG, "onLogin() - using Firebase Login"); if (LogManager.USE_FIREBASE_BACKEND) {
Intent signInIntent = AuthUI.getInstance() Log.v(TAG, "onLogin() - using Firebase Login");
.createSignInIntentBuilder() Intent signInIntent = AuthUI.getInstance()
.setAvailableProviders(Arrays.asList( .createSignInIntentBuilder()
new AuthUI.IdpConfig.GoogleBuilder().build(), .setAvailableProviders(Arrays.asList(
//new AuthUI.IdpConfig.FacebookBuilder().build(), new AuthUI.IdpConfig.GoogleBuilder().build(),
//new AuthUI.IdpConfig.TwitterBuilder().build(), //new AuthUI.IdpConfig.FacebookBuilder().build(),
//new AuthUI.IdpConfig.MicrosoftBuilder().build(), //new AuthUI.IdpConfig.TwitterBuilder().build(),
//new AuthUI.IdpConfig.YahooBuilder().build(), //new AuthUI.IdpConfig.MicrosoftBuilder().build(),
//new AuthUI.IdpConfig.AppleBuilder().build(), //new AuthUI.IdpConfig.YahooBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build() //new AuthUI.IdpConfig.AppleBuilder().build(),
//new AuthUI.IdpConfig.PhoneBuilder().build() new AuthUI.IdpConfig.EmailBuilder().build()
//new AuthUI.IdpConfig.AnonymousBuilder().build())) //new AuthUI.IdpConfig.PhoneBuilder().build()
)) //new AuthUI.IdpConfig.AnonymousBuilder().build()))
// ... options ... ))
.build(); // ... options ...
signInLauncher.launch(signInIntent); .build();
signInLauncher.launch(signInIntent);
} else {
// Use Username and password authentication for OSDAPI.
// FIXME - make this work with Google Authentication like we do for Firebase.
String uname = mUnameEt.getText().toString();
String passwd = mPasswdEt.getText().toString();
Log.v(TAG,"onOK() - uname="+uname+", passwd="+passwd);
mWac.authenticate(uname, passwd, new WebApiConnection.StringCallback() {
@Override
public void accept(String retVal) {
if (retVal != null) {
Log.d(TAG,"Authentication Success - token is "+retVal);
mUtil.showToast("Login Successful");
saveAuthToken(retVal);
updateUi();
} else {
Log.e(TAG,"onOk: Authentication failure for "+uname+", "+passwd);
mUtil.showToast("ERROR: Authentication Failed - Please Try Again");
mUtil.writeToSysLogFile("AuthActivity - Authorisation failed for "+uname+", "+passwd);
}
}
});
}
} }
}; };
@@ -225,14 +273,24 @@ public class AuthenticateActivity extends AppCompatActivity {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Log.v(TAG, "onLogout"); Log.v(TAG, "onLogout");
AuthUI.getInstance() if (LogManager.USE_FIREBASE_BACKEND) {
.signOut(getApplicationContext()) AuthUI.getInstance()
.addOnCompleteListener(new OnCompleteListener<Void>() { .signOut(getApplicationContext())
public void onComplete(@NonNull Task<Void> task) { .addOnCompleteListener(new OnCompleteListener<Void>() {
// user is now signed out public void onComplete(@NonNull Task<Void> task) {
updateUi(); // user is now signed out
} updateUi();
}); }
});
} else {
if (mWac != null) {
mWac.logout();
saveAuthToken(null);
} else {
Log.e(TAG,"logout() - mWac is null - not doing anything");
}
}
updateUi();
} }
}; };

View File

@@ -130,7 +130,7 @@ public class LogManager {
mWac = new WebApiConnection_osdapi(mContext); mWac = new WebApiConnection_osdapi(mContext);
} }
//mWac.setStoredToken(mAuthToken); mWac.setStoredToken(mAuthToken);
if (mLogRemote) { if (mLogRemote) {
Log.i(TAG, "Starting Remote Log Timer"); Log.i(TAG, "Starting Remote Log Timer");

View File

@@ -624,24 +624,27 @@ public class LogManagerControlActivity extends AppCompatActivity {
// Convert date format to something more readable. // Convert date format to something more readable.
TextView tv = (TextView) v.findViewById(R.id.event_date_remote_tv); TextView tv = (TextView) v.findViewById(R.id.event_date_remote_tv);
Date dataTime = null;
try { try {
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//Date dataTime = dateFormat.parse(dataItem.get("dataTime").toString());
Long tstamp = Long.parseLong((String) dataItem.get("dataTime")); Long tstamp = Long.parseLong((String) dataItem.get("dataTime"));
Date dataTime = new Date(tstamp); dataTime = new Date(tstamp);
} catch (NumberFormatException e) {
Log.v(TAG, "remoteEventsAdapter.getView: Error Parsing dataDate as Long: " + e.getLocalizedMessage()+" trying as string");
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dataTime = dateFormat.parse(dataItem.get("dataTime").toString());
} catch (ParseException e2) {
Log.e(TAG, "remoteEventsAdapter.getView: Error Parsing dataDate " + e2.getLocalizedMessage());
}
}
if (dataTime != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
tv.setText(dateFormat.format(dataTime)); tv.setText(dateFormat.format(dataTime));
} catch (NumberFormatException e) { } else {
Log.e(TAG, "remoteEventsAdapter.getView: Error Parsing dataDate " + e.getLocalizedMessage());
tv.setText("---"); tv.setText("---");
} }
return (v); return (v);
} }
} }
;
} }

View File

@@ -46,6 +46,8 @@ public abstract class WebApiConnection {
private Context mContext; private Context mContext;
private OsdUtil mUtil; private OsdUtil mUtil;
private String TAG = "WebApiConnection"; private String TAG = "WebApiConnection";
private String mAuthToken;
public interface JSONObjectCallback { public interface JSONObjectCallback {
@@ -109,4 +111,26 @@ public abstract class WebApiConnection {
*/ */
public abstract boolean checkServerConnection(); public abstract boolean checkServerConnection();
public abstract boolean getUserProfile(JSONObjectCallback callback);
public boolean authenticate(final String uname, final String passwd, StringCallback callback) {
Log.e(TAG,"WebApiConnection.authenticate(username, password, callback) Not Implemented");
return false;
}
// Remove the stored token so future calls are not authenticated.
public void logout() {
Log.v(TAG, "logout()");
setStoredToken(null);
}
protected void setStoredToken(String authToken) {
mAuthToken = authToken;
}
protected String getStoredToken() {
return (mAuthToken);
}
} }

View File

@@ -3,6 +3,7 @@ package uk.org.openseizuredetector;
import android.content.Context; import android.content.Context;
import android.os.Handler; import android.os.Handler;
import android.util.Log; import android.util.Log;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@@ -31,7 +32,7 @@ import java.util.Map;
// This class is intended to handle all interactions with the OSD WebAPI // This class is intended to handle all interactions with the OSD WebAPI
public class WebApiConnection_firebase extends WebApiConnection{ public class WebApiConnection_firebase extends WebApiConnection {
public String retVal; public String retVal;
public int retCode; public int retCode;
public boolean mServerConnectionOk = false; public boolean mServerConnectionOk = false;
@@ -42,7 +43,7 @@ public class WebApiConnection_firebase extends WebApiConnection{
FirebaseFirestore mDb; FirebaseFirestore mDb;
RequestQueue mQueue; RequestQueue mQueue;
public WebApiConnection_firebase(Context context) { public WebApiConnection_firebase(Context context) {
super(context); super(context);
@@ -85,6 +86,28 @@ public class WebApiConnection_firebase extends WebApiConnection{
} }
} }
public boolean getUserProfile(JSONObjectCallback callback) {
Log.v(TAG, "getUserProfile()");
FirebaseAuth auth = FirebaseAuth.getInstance();
if (!isLoggedIn()) {
Log.v(TAG, "not logged in - doing nothing");
return (false);
} else {
try {
JSONObject retObj = new JSONObject();
retObj.put("id",auth.getCurrentUser().getUid());
retObj.put("username", auth.getCurrentUser().getDisplayName());
retObj.put("email", auth.getCurrentUser().getEmail());
callback.accept(retObj);
} catch (JSONException e) {
Log.e(TAG, "Error Creating retObjObj: " + e.getMessage());
mUtil.showToast("Error Creating retObj - this should not happen!!!");
return (false);
}
}
return (true);
}
public String getStoredToken() { public String getStoredToken() {
return null; return null;
} }

View File

@@ -32,7 +32,6 @@ public class WebApiConnection_osdapi extends WebApiConnection {
public boolean mServerConnectionOk = false; public boolean mServerConnectionOk = false;
private String mUrlBase = "https://osdApi.ddns.net"; private String mUrlBase = "https://osdApi.ddns.net";
private String TAG = "WebApiConnection_osdapi"; private String TAG = "WebApiConnection_osdapi";
private String mAuthToken;
private Context mContext; private Context mContext;
private OsdUtil mUtil; private OsdUtil mUtil;
RequestQueue mQueue; RequestQueue mQueue;
@@ -57,6 +56,7 @@ public class WebApiConnection_osdapi extends WebApiConnection {
* @param callback - call back function callback(String retVal) * @param callback - call back function callback(String retVal)
* @return true if request sent, or false if failed to send request. * @return true if request sent, or false if failed to send request.
*/ */
@Override
public boolean authenticate(final String uname, final String passwd, StringCallback callback) { public boolean authenticate(final String uname, final String passwd, StringCallback callback) {
// NOTE: the 'final' keyword is necessary for uname and passwd to be accessible to getParams below - I don't know why! // NOTE: the 'final' keyword is necessary for uname and passwd to be accessible to getParams below - I don't know why!
// We know that this command works, so we just need the Java equivalent: // We know that this command works, so we just need the Java equivalent:
@@ -111,28 +111,17 @@ public class WebApiConnection_osdapi extends WebApiConnection {
return (true); return (true);
} }
// Remove the stored token so future calls are not authenticated.
public void logout() {
Log.v(TAG, "logout()");
setStoredToken(null);
//saveStoredToken(null);
}
public void setStoredToken(String authToken) {
mAuthToken = authToken;
}
private String getStoredToken() {
return (mAuthToken);
}
public boolean isLoggedIn() { public boolean isLoggedIn() {
String authToken = getStoredToken(); String authToken = getStoredToken();
//Log.v(TAG, "isLoggedIn(): token=" + authToken); Log.v(TAG, "isLoggedIn(): token=" + authToken);
if (authToken == null || authToken.length() == 0) { if (authToken == null || authToken.length() == 0) {
//Log.v(TAG, "isLogged in - not logged in"); Log.v(TAG, "isLogged in - not logged in");
return (false); return (false);
} else { } else {
Log.v(TAG,"isLoggedIn - logged in ok");
return (true); return (true);
} }
@@ -543,7 +532,7 @@ public class WebApiConnection_osdapi extends WebApiConnection {
JSONObject retObj = new JSONObject(response); JSONObject retObj = new JSONObject(response);
callback.accept(retObj); callback.accept(retObj);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "getUserProfile.onRespons(): Error: " + e.getMessage() + "," + e.toString()); Log.e(TAG, "getUserProfile.onResponse(): Error: " + e.getMessage() + "," + e.toString());
callback.accept(null); callback.accept(null);
} }
mServerConnectionOk = true; mServerConnectionOk = true;

View File

@@ -55,6 +55,59 @@
</LinearLayout> </LinearLayout>
<LinearLayout
android:id="@+id/login_osdapi_ui"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginTop="16dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="username" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginTop="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="password"
android:inputType="textPassword" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="@+id/RegisterBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/register" />
<Button
android:id="@+id/ResetPasswordBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/reset_password" />
</LinearLayout>
</LinearLayout>
<LinearLayout <LinearLayout
android:id="@+id/logout_ui" android:id="@+id/logout_ui"
android:layout_width="fill_parent" android:layout_width="fill_parent"
@@ -146,4 +199,8 @@
android:text="@string/privacy_policy" /> android:text="@string/privacy_policy" />
</LinearLayout> </LinearLayout>
</LinearLayout> </LinearLayout>