Check if user is authenticated and manage menu

This commit is contained in:
Thomas 2020-09-30 14:41:17 +02:00
parent d293fc4774
commit 540e92f38e
13 changed files with 198 additions and 113 deletions

View File

@ -6,7 +6,7 @@ android {
defaultConfig {
applicationId "app.fedilab.mobilizon"
minSdkVersion 16
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"

View File

@ -12,16 +12,6 @@ import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@ -33,6 +23,14 @@ import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
@ -51,10 +49,34 @@ import es.dmoral.toasty.Toasty;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public static int PICK_INSTANCE = 5641;
public static boolean isAuthenticated = false;
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull final Location location) {
SharedPreferences sharedpref = getSharedPreferences(Helper.APP_SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpref.edit();
editor.putString(Helper.LAST_LOCATION, location.getLongitude() + "," + location.getLatitude() + "," + location.getAltitude());
editor.apply();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(@NonNull String provider) {
}
@Override
public void onProviderDisabled(@NonNull String provider) {
}
};
private ProgressBar progressBar;
private WebView main_webview;
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
public static int PICK_INSTANCE = 5641;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -80,18 +102,13 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
}
final NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
/*if( Helper.isLoggedIn() ){
MenuItem createEvent = navigationView.getMenu().findItem(R.id.nav_create_event);
}*/
if (Build.VERSION.SDK_INT >= 23) {
permissionsAPI();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
WebView.setWebContentsDebuggingEnabled(true);
drawMenu();
main_webview = findViewById(R.id.main_webview);
progressBar = findViewById(R.id.progressBar);
@ -103,7 +120,7 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
main_webview.setWebChromeClient(mobilizonWebChromeClient);
main_webview.setWebViewClient(new MobilizonWebViewClient(MainActivity.this));
main_webview.loadUrl("https://"+instance);
main_webview.loadUrl("https://" + instance);
}
@ -117,18 +134,10 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
main_webview.loadUrl("https://"+ Helper.getLiveInstance(MainActivity.this)+"/search?term="+ URLEncoder.encode(query, String.valueOf(StandardCharsets.UTF_8)));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
try {
main_webview.loadUrl("https://"+ Helper.getLiveInstance(MainActivity.this)+"/search?term="+ URLEncoder.encode(query, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/search?term=" + URLEncoder.encode(query, String.valueOf(StandardCharsets.UTF_8)));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (!searchView.isIconified()) {
searchView.setIconified(true);
@ -161,27 +170,27 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
return super.onOptionsItemSelected(item);
}
public void showProgressDialog(){
if( progressBar != null){
public void showProgressDialog() {
if (progressBar != null) {
progressBar.setVisibility(View.VISIBLE);
}
}
public void hideProgressDialog(){
if( progressBar != null){
public void hideProgressDialog() {
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
public void setProgressDialog(int progress){
if( progressBar != null){
public void setProgressDialog(int progress) {
if (progressBar != null) {
progressBar.setProgress(progress);
}
}
@Override
public void onBackPressed() {
if( main_webview.canGoBack()){
if (main_webview.canGoBack()) {
main_webview.goBack();
} else {
super.onBackPressed();
@ -193,13 +202,25 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
int id = item.getItemId();
if (id == R.id.nav_explore) {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/search");
}else if( id == R.id.nav_my_event) {
} else if (id == R.id.nav_my_event) {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/events/me");
}else if( id == R.id.nav_my_group) {
} else if (id == R.id.nav_my_group) {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/groups/me");
}else if( id == R.id.nav_create_event) {
} else if (id == R.id.nav_create_event) {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/events/create");
} else if (id == R.id.nav_login) {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/login");
} else if (id == R.id.nav_logout) {
Helper.clearCookies(MainActivity.this);
isAuthenticated = false;
drawMenu();
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this));
} else if (id == R.id.nav_profile) {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/identity/update");
} else if (id == R.id.nav_register) {
main_webview.loadUrl("https://" + Helper.getLiveInstance(MainActivity.this) + "/register/user");
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
@ -230,7 +251,7 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
runOnUiThread(() -> {
dialog.dismiss();
main_webview.clearHistory();
main_webview.loadUrl("https://"+instance);
main_webview.loadUrl("https://" + instance);
});
} else {
runOnUiThread(() -> Toasty.error(MainActivity.this, getString(R.string.not_valide_instance), Toast.LENGTH_LONG).show());
@ -250,32 +271,6 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
alert.show();
}
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull final Location location) {
SharedPreferences sharedpref = getSharedPreferences(Helper.APP_SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpref.edit();
editor.putString(Helper.LAST_LOCATION, location.getLongitude() + "," + location.getLatitude()+","+ location.getAltitude());
editor.apply();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(@NonNull String provider) {
}
@Override
public void onProviderDisabled(@NonNull String provider) {
}
};
@TargetApi(Build.VERSION_CODES.M)
private void permissionsAPI() {
List<String> permissionsNeeded = new ArrayList<>();
@ -319,7 +314,7 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
permissionsList.add(Manifest.permission.ACCESS_FINE_LOCATION);
// Check for Rationale Option
return shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION);
}else{
} else {
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
assert mLocationManager != null;
@ -329,4 +324,22 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
return true;
}
public void drawMenu() {
final NavigationView navigationView = findViewById(R.id.nav_view);
if (isAuthenticated) {
navigationView.getMenu().findItem(R.id.nav_create_event).setVisible(true);
navigationView.getMenu().findItem(R.id.nav_profile).setVisible(true);
navigationView.getMenu().findItem(R.id.nav_login).setVisible(false);
navigationView.getMenu().findItem(R.id.nav_logout).setVisible(true);
navigationView.getMenu().findItem(R.id.nav_register).setVisible(false);
} else {
navigationView.getMenu().findItem(R.id.nav_create_event).setVisible(false);
navigationView.getMenu().findItem(R.id.nav_profile).setVisible(false);
navigationView.getMenu().findItem(R.id.nav_login).setVisible(true);
navigationView.getMenu().findItem(R.id.nav_logout).setVisible(false);
navigationView.getMenu().findItem(R.id.nav_register).setVisible(true);
}
navigationView.invalidate();
}
}

View File

@ -3,7 +3,6 @@ package app.fedilab.mobilizon.client;
import app.fedilab.mobilizon.client.entities.WellKnownNodeinfo;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Path;
interface MobilizonService {

View File

@ -13,6 +13,7 @@ package app.fedilab.mobilizon.client;
*
* You should have received a copy of the GNU General Public License along with Mobilizon app; if not,
* see <http://www.gnu.org/licenses>. */
import android.content.Context;
import java.io.IOException;
@ -33,7 +34,6 @@ public class RetrofitMobilizonAPI {
private String instance;
public RetrofitMobilizonAPI(Context context) {
_context = context;
instance = Helper.getLiveInstance(context);
@ -56,7 +56,6 @@ public class RetrofitMobilizonAPI {
}
/**
* Get NodeInfo
*
@ -69,7 +68,7 @@ public class RetrofitMobilizonAPI {
Response<WellKnownNodeinfo> response = wellKnownNodeinfoCall.execute();
if (response.isSuccessful() && response.body() != null) {
int size = response.body().getLinks().size();
String url = response.body().getLinks().get(size-1).getHref();
String url = response.body().getLinks().get(size - 1).getHref();
if (size > 0 && url != null) {
mobilizonService = init();
String path = new URL(url).getPath();

View File

@ -7,9 +7,10 @@ import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.util.Base64;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import java.io.InputStream;
@ -37,6 +38,7 @@ public class Helper {
public static String LAST_LOCATION = "last_location";
public static int LOCATION_REFRESH_TIME = 60000;
public static int LOCATION_REFRESH_DISTANCE = 100;
/**
* Returns the preferred instance
*
@ -50,6 +52,7 @@ public class Helper {
/**
* Initialize the webview
*
* @param context Context
* @param webView WebView
*/
@ -65,28 +68,16 @@ public class Helper {
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setSupportMultipleWindows(false);
webView.getSettings().setGeolocationDatabasePath(context.getFilesDir().getPath() );
webView.getSettings().setGeolocationDatabasePath(context.getFilesDir().getPath());
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setAppCachePath(context.getCacheDir().getPath());
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
webView.getSettings().setMediaPlaybackRequiresUserGesture(true);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
webView.getSettings().setMediaPlaybackRequiresUserGesture(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webView, true);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
@ -113,4 +104,21 @@ public class Helper {
e.printStackTrace();
}
}
public static void clearCookies(Context context) {
WebStorage.getInstance().deleteAllData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
} else {
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
cookieSyncMngr.startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
}
}
}

View File

@ -48,10 +48,6 @@ public class MobilizonWebChromeClient extends WebChromeClient implements MediaPl
private Activity activity;
public interface ToggledFullscreenCallback {
void toggledFullscreen(boolean fullscreen);
}
public MobilizonWebChromeClient(Activity activity, WebView webView, FrameLayout activityNonVideoView, ViewGroup activityVideoView) {
this.activity = activity;
this.isVideoFullscreen = false;
@ -60,11 +56,6 @@ public class MobilizonWebChromeClient extends WebChromeClient implements MediaPl
this.activityVideoView = activityVideoView;
}
//FULLSCREEN VIDEO
//Code from https://stackoverflow.com/a/16179544/3197259
/**
* Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen)
*
@ -74,6 +65,10 @@ public class MobilizonWebChromeClient extends WebChromeClient implements MediaPl
this.toggledFullscreenCallback = callback;
}
//FULLSCREEN VIDEO
//Code from https://stackoverflow.com/a/16179544/3197259
@Override
public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
@ -83,7 +78,7 @@ public class MobilizonWebChromeClient extends WebChromeClient implements MediaPl
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
((MainActivity)activity).setProgressDialog(newProgress);
((MainActivity) activity).setProgressDialog(newProgress);
}
@Override
@ -194,9 +189,14 @@ public class MobilizonWebChromeClient extends WebChromeClient implements MediaPl
}
// Error while playing video, only called in the case of android.widget.VideoView (typically API level <11)
@Override public boolean onError(MediaPlayer mp, int what, int extra) {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false; // By returning false, onCompletion() will be called
}
public interface ToggledFullscreenCallback {
void toggledFullscreen(boolean fullscreen);
}
}

View File

@ -13,15 +13,16 @@ package app.fedilab.mobilizon.webview;
*
* You should have received a copy of the GNU General Public License along with Mobilizon app; if not,
* see <http://www.gnu.org/licenses>. */
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
@ -33,6 +34,9 @@ import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.snackbar.Snackbar;
import java.util.Iterator;
import java.util.Map;
import app.fedilab.mobilizon.MainActivity;
import app.fedilab.mobilizon.R;
import app.fedilab.mobilizon.helper.Helper;
@ -42,25 +46,37 @@ public class MobilizonWebViewClient extends WebViewClient {
private Activity activity;
private CoordinatorLayout rootView;
public MobilizonWebViewClient(Activity activity){
public MobilizonWebViewClient(Activity activity) {
this.activity = activity;
rootView = activity.findViewById(R.id.main_layout);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
@Override
public WebResourceResponse shouldInterceptRequest(final WebView view, WebResourceRequest request) {
if (request.getUrl().toString().endsWith("api")) {
Map<String, String> headers = request.getRequestHeaders();
Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
if (pair.getKey().compareTo("authorization") == 0 && pair.getValue().startsWith("Bearer")) {
MainActivity.isAuthenticated = true;
}
it.remove();
}
}
return super.shouldInterceptRequest(view, request);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
MainActivity.isAuthenticated = false;
super.onPageStarted(view, url, favicon);
if (activity instanceof MainActivity) {
((MainActivity) activity).showProgressDialog();
@ -125,7 +141,9 @@ public class MobilizonWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
Log.v(Helper.TAG, "onPageFinished: " + url);
Helper.injectCSS(activity, view, "css/style.css");
((MainActivity)activity).hideProgressDialog();
((MainActivity) activity).hideProgressDialog();
((MainActivity) activity).drawMenu();
}
}

View File

@ -0,0 +1,5 @@
<vector android:autoMirrored="true" android:height="24dp"
android:tint="?attr/colorControlNormal" android:viewportHeight="24"
android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,5c1.66,0 3,1.34 3,3s-1.34,3 -3,3 -3,-1.34 -3,-3 1.34,-3 3,-3zM12,19.2c-2.5,0 -4.71,-1.28 -6,-3.22 0.03,-1.99 4,-3.08 6,-3.08 1.99,0 5.97,1.09 6,3.08 -1.29,1.94 -3.5,3.22 -6,3.22z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:autoMirrored="true" android:height="24dp"
android:tint="?attr/colorControlNormal" android:viewportHeight="24"
android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M10.09,15.59L11.5,17l5,-5 -5,-5 -1.41,1.41L12.67,11H3v2h9.67l-2.58,2.59zM19,3H5c-1.11,0 -2,0.9 -2,2v4h2V5h14v14H5v-4H3v4c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2V5c0,-1.1 -0.9,-2 -2,-2z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:autoMirrored="true" android:height="24dp"
android:tint="?attr/colorControlNormal" android:viewportHeight="24"
android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:autoMirrored="true" android:height="24dp"
android:tint="?attr/colorControlNormal" android:viewportHeight="24"
android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M15,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM6,10L6,7L4,7v3L1,10v2h3v3h2v-3h3v-2L6,10zM15,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>

View File

@ -21,5 +21,28 @@
android:icon="@drawable/ic_baseline_schedule_24"
android:title="@string/create" />
</group>
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_account"
android:title="@string/account">
<menu>
<item
android:id="@+id/nav_login"
android:icon="@drawable/ic_baseline_person_24"
android:title="@string/login" />
<item
android:id="@+id/nav_profile"
android:icon="@drawable/ic_baseline_account_circle_24"
android:title="@string/my_account" />
<item
android:id="@+id/nav_logout"
android:icon="@drawable/ic_baseline_exit_to_app_24"
android:title="@string/logout" />
<item
android:id="@+id/nav_register"
android:icon="@drawable/ic_baseline_person_add_24"
android:title="@string/register" />
</menu>
</item>
</group>
</menu>

View File

@ -26,4 +26,9 @@
<string name="create">Create</string>
<string name="mobilizon_banner">Mobilizon banner</string>
<string name="search">Search</string>
<string name="logout">Logout</string>
<string name="login">Login</string>
<string name="my_account">My account</string>
<string name="register">Register</string>
<string name="account">Account</string>
</resources>