From 82c0605b95cb1fff03c50ca70d692148c7f39b5d Mon Sep 17 00:00:00 2001 From: Apostolof Date: Wed, 16 Nov 2016 16:12:49 +0200 Subject: [PATCH] Added shared preferences, main activity -> launcher & main, login activity called when needed, logout tweaks --- app/build.gradle | 9 +- app/src/main/AndroidManifest.xml | 7 +- .../thmmy/mthmmy/activities/BaseActivity.java | 7 ++ .../mthmmy/activities/LoginActivity.java | 43 +++++---- .../thmmy/mthmmy/activities/MainActivity.java | 80 ++++++++-------- .../java/gr/thmmy/mthmmy/utils/Thmmy.java | 91 ++++++------------- app/src/main/res/drawable/page_first.xml | 8 -- app/src/main/res/drawable/page_last.xml | 8 -- app/src/main/res/drawable/page_next.xml | 8 -- app/src/main/res/drawable/page_previous.xml | 8 -- 10 files changed, 106 insertions(+), 163 deletions(-) delete mode 100644 app/src/main/res/drawable/page_first.xml delete mode 100644 app/src/main/res/drawable/page_last.xml delete mode 100644 app/src/main/res/drawable/page_next.xml delete mode 100644 app/src/main/res/drawable/page_previous.xml diff --git a/app/build.gradle b/app/build.gradle index e3f337ea..7e901287 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -21,9 +21,10 @@ android { dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.android.support:appcompat-v7:25.0.1' - compile 'com.android.support:design:25.0.1' - compile 'com.squareup.okhttp3:okhttp:3.4.1' + compile 'com.android.support:appcompat-v7:25.0.0' + compile 'com.android.support:design:25.0.0' + compile 'com.squareup.okhttp3:okhttp:3.4.0' + compile 'com.jakewharton:butterknife:7.0.1' compile 'org.jsoup:jsoup:1.10.1' compile 'com.android.support:support-v4:25.0.1' compile 'com.android.support:cardview-v7:25.0.1' @@ -33,6 +34,4 @@ dependencies { compile('com.mikepenz:materialdrawer:5.7.0@aar') { transitive = true } - - } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7611e6f0..ec83d38a 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -12,9 +12,11 @@ android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> + @@ -23,9 +25,8 @@ diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/BaseActivity.java b/app/src/main/java/gr/thmmy/mthmmy/activities/BaseActivity.java index fb0afd67..e2428346 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/BaseActivity.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/BaseActivity.java @@ -1,5 +1,6 @@ package gr.thmmy.mthmmy.activities; +import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; @@ -19,6 +20,12 @@ public class BaseActivity extends AppCompatActivity { protected static Thmmy.LoginData loginData; private static boolean init =false; //To initialize stuff only once per app start + //Shared preferences + public static final String SHARED_PREFS_NAME = "thmmySharedPrefs"; + public static final String USER_NAME = "userNameKey"; + public static final String GUEST_PREF_USERNAME = "GUEST"; + public static final String IS_LOGGED_IN = "isLogedIn"; + public static CookieJar getCookieJar() { return cookieJar; diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/LoginActivity.java b/app/src/main/java/gr/thmmy/mthmmy/activities/LoginActivity.java index d62c9334..5e1173b3 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/LoginActivity.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/LoginActivity.java @@ -2,6 +2,7 @@ package gr.thmmy.mthmmy.activities; import android.app.ProgressDialog; import android.content.Intent; +import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; @@ -22,20 +23,15 @@ import static gr.thmmy.mthmmy.utils.Thmmy.login; public class LoginActivity extends BaseActivity { private static final String TAG = "LoginActivity"; - private static boolean passed=false; //becomes true after (guest) login - to redirect to Main Button btnLogin; Button btnGuest; private EditText inputUsername; private EditText inputPassword; + private String username; + private String password; @Override public void onCreate(Bundle savedInstanceState) { - /*if(passed) //redirect to MainActivity if user passed this one at least once - { - Intent intent = new Intent(LoginActivity.this, MainActivity.class); - startActivity(intent); - finish(); - }*/ super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); @@ -50,27 +46,31 @@ public class LoginActivity extends BaseActivity { public void onClick(View view) { Log.d(TAG, "Login"); + username = inputUsername.getText().toString().trim(); + password = inputPassword.getText().toString().trim(); + // Check for empty data in the form if (!validate()) { onLoginFailed(); return; } - String username = inputUsername.getText().toString().trim(); - String password = inputPassword.getText().toString().trim(); - // login user - new LoginTask().execute(username,password); + new LoginTask().execute(username, password); } }); - // Link to Register Screen + // Guest Button Action btnGuest.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { + SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE).edit(); + editor.putString(USER_NAME, GUEST_PREF_USERNAME); + editor.putBoolean(IS_LOGGED_IN, true); + editor.apply(); + Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); - passed=true; finish(); overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } @@ -92,10 +92,7 @@ public class LoginActivity extends BaseActivity { public boolean validate() { boolean valid = true; - String email = inputUsername.getText().toString(); - String password = inputPassword.getText().toString(); - - if (email.isEmpty()) { + if (username.isEmpty()) { inputUsername.setError("Enter a valid username"); valid = false; } else { @@ -112,13 +109,12 @@ public class LoginActivity extends BaseActivity { return valid; } - private class LoginTask extends AsyncTask - { + private class LoginTask extends AsyncTask { ProgressDialog progressDialog; @Override protected Integer doInBackground(String... params) { - setLoginData(login(params[0], params[1],"-1")); + setLoginData(login(params[0], params[1], "-1")); return loginData.getStatus(); } @@ -162,13 +158,16 @@ public class LoginActivity extends BaseActivity { .show(); break; case LOGGED_IN: - //progressDialog.dismiss(); + SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE).edit(); + editor.putString(USER_NAME, username); + editor.putBoolean(IS_LOGGED_IN, true); + editor.apply(); + Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG) .show(); Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); - passed=true; finish(); overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); break; diff --git a/app/src/main/java/gr/thmmy/mthmmy/activities/MainActivity.java b/app/src/main/java/gr/thmmy/mthmmy/activities/MainActivity.java index aea722cb..9f8138cf 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/activities/MainActivity.java +++ b/app/src/main/java/gr/thmmy/mthmmy/activities/MainActivity.java @@ -1,6 +1,7 @@ package gr.thmmy.mthmmy.activities; import android.content.Intent; +import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.TabLayout; @@ -11,18 +12,17 @@ import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; - -import org.jsoup.nodes.Document; +import android.widget.Toast; import gr.thmmy.mthmmy.R; import gr.thmmy.mthmmy.data.TopicSummary; import gr.thmmy.mthmmy.sections.recent.RecentFragment; import gr.thmmy.mthmmy.utils.Thmmy; -public class MainActivity extends BaseActivity implements RecentFragment.OnListFragmentInteractionListener -{ - private SectionsPagerAdapter mSectionsPagerAdapter; - private ViewPager mViewPager; /** The {@link ViewPager} that will host the section contents.*/ +public class MainActivity extends BaseActivity implements RecentFragment.OnListFragmentInteractionListener { + /** + * The {@link ViewPager} that will host the section contents. + */ private Menu menu; @@ -31,14 +31,22 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); + SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); + if (!prefs.getBoolean(IS_LOGGED_IN, false)) { + Intent intent = new Intent(MainActivity.this, LoginActivity.class); + startActivity(intent); + finish(); + overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out); + } + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Create the adapter that will return a fragment for each section of the activity - mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); + SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. - mViewPager = (ViewPager) findViewById(R.id.container); + ViewPager mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); @@ -55,10 +63,11 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. - this.menu=menu; + this.menu = menu; getMenuInflater().inflate(R.menu.menu_main, menu); - - if(loginData.getStatus()== Thmmy.LOGGED_IN) + SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); + if (prefs.getBoolean(IS_LOGGED_IN, false) + && prefs.getString(USER_NAME, null) != GUEST_PREF_USERNAME) hideLogin(); else hideLogout(); @@ -67,20 +76,17 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF } @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); - if (id == R.id.action_about) - { + if (id == R.id.action_about) { Intent i = new Intent(MainActivity.this, AboutActivity.class); startActivity(i); return true; - } - else if (id == R.id.action_logout) + } else if (id == R.id.action_logout) new LogoutTask().execute(); - else{ - Intent intent = new Intent(MainActivity.this,LoginActivity.class); + else { + Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); finish(); overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out); @@ -89,26 +95,22 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF return super.onOptionsItemSelected(item); } - private void hideLogin() - { + private void hideLogin() { MenuItem login = menu.findItem(R.id.action_login); MenuItem logout = menu.findItem(R.id.action_logout); login.setVisible(false); logout.setVisible(true); } - private void hideLogout() - { + private void hideLogout() { MenuItem login = menu.findItem(R.id.action_login); MenuItem logout = menu.findItem(R.id.action_logout); login.setVisible(true); logout.setVisible(false); } - @Override - public void onFragmentInteraction(TopicSummary topicSummary) - { + public void onFragmentInteraction(TopicSummary topicSummary) { Intent i = new Intent(MainActivity.this, TopicActivity.class); i.putExtra("TOPIC_URL", topicSummary.getTopicUrl()); i.putExtra("TOPIC_TITLE", topicSummary.getTitle()); @@ -116,6 +118,7 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF } //---------------------------------FragmentPagerAdapter--------------------------------------------- + /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. If it becomes too memory intensive, @@ -154,29 +157,26 @@ public class MainActivity extends BaseActivity implements RecentFragment.OnListF } } - - private class LogoutTask extends AsyncTask - { - protected Integer doInBackground(Void... voids) - { + private class LogoutTask extends AsyncTask { + protected Integer doInBackground(Void... voids) { return Thmmy.logout(loginData); } - protected void onPreExecute() { //TODO: a progressbar maybe? } - protected void onPostExecute(Integer result) - { - if(result==Thmmy.LOGGED_OUT) + protected void onPostExecute(Integer result) { + if (result == Thmmy.LOGGED_OUT) { + SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE).edit(); + editor.putString(USER_NAME, null); + editor.putBoolean(IS_LOGGED_IN, false); + editor.apply(); + Toast.makeText(getBaseContext(), "Logged out successfully!", Toast.LENGTH_LONG).show(); + hideLogout(); - else + } else hideLogin(); } - - - - } } diff --git a/app/src/main/java/gr/thmmy/mthmmy/utils/Thmmy.java b/app/src/main/java/gr/thmmy/mthmmy/utils/Thmmy.java index c00d94aa..2c3b592c 100644 --- a/app/src/main/java/gr/thmmy/mthmmy/utils/Thmmy.java +++ b/app/src/main/java/gr/thmmy/mthmmy/utils/Thmmy.java @@ -27,32 +27,27 @@ import okhttp3.RequestBody; import okhttp3.Response; -public class Thmmy -{ +public class Thmmy { private static final HttpUrl loginUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php?action=login2"); private static final HttpUrl indexUrl = HttpUrl.parse("https://www.thmmy.gr/smf/index.php"); public static final int LOGGED_OUT = 0; public static final int LOGGED_IN = 1; - public static final int WRONG_USER= 2; - public static final int WRONG_PASSWORD= 3; - public static final int FAILED= 4; + public static final int WRONG_USER = 2; + public static final int WRONG_PASSWORD = 3; + public static final int FAILED = 4; public static final int CERTIFICATE_ERROR = 5; public static final int OTHER_ERROR = 6; - - //-------------------------------------------LOGIN-------------------------------------------------- //Two options: (username, password, duration) or nothing - cookies - public static LoginData login(String... strings) - { - Log.d("Login","Logging in..."); + public static LoginData login(String... strings) { + Log.d("Login", "Logging in..."); LoginData loginData = new LoginData(); Request request; - if(strings.length==3) - { + if (strings.length == 3) { String loginName = strings[0]; String password = strings[1]; String duration = strings[2]; @@ -68,9 +63,7 @@ public class Thmmy .url(loginUrl) .post(formBody) .build(); - } - else - { + } else { request = new Request.Builder() .url(loginUrl) .build(); @@ -78,39 +71,33 @@ public class Thmmy OkHttpClient client = BaseActivity.getClient(); - try - { + try { Response response = client.newCall(request).execute(); Document document = Jsoup.parse(response.body().string()); Element logout = document.getElementById("logoutbtn"); - if (logout != null) - { + if (logout != null) { Log.i("Login", "Login successful"); setPersistentCookieSession(); loginData.setUsername(extractUserName(document)); loginData.setLogoutLink(HttpUrl.parse(logout.attr("href"))); loginData.setStatus(LOGGED_IN); - } - else - { + } else { Log.w("Login", "Login failed"); loginData.setStatus(FAILED); //Making error more specific Elements error = document.select("b:contains(That username does not exist.)"); - if (error.size()==1) - { + if (error.size() == 1) { loginData.setStatus(WRONG_USER); - Log.d("Login","Wrong Username"); + Log.d("Login", "Wrong Username"); } error = document.select("body:contains(Password incorrect)"); - if (error.size()==1) - { - Log.d("Login","Wrong Password"); + if (error.size() == 1) { + Log.d("Login", "Wrong Password"); loginData.setStatus(WRONG_PASSWORD); } @@ -126,21 +113,17 @@ public class Thmmy loginData.setStatus(OTHER_ERROR); } - - return loginData; - - } //To maintain data between activities/ between activity state change (possibly temporary solution) - public static class LoginData implements Parcelable - { + public static class LoginData implements Parcelable { private int status; private String username; private HttpUrl logoutLink; - public LoginData() {} + public LoginData() { + } public String getUsername() { return username; @@ -192,18 +175,16 @@ public class Thmmy private LoginData(Parcel in) { status = in.readInt(); - username=in.readString(); - logoutLink=HttpUrl.parse(in.readString()); + username = in.readString(); + logoutLink = HttpUrl.parse(in.readString()); } } - private static boolean setPersistentCookieSession() - { + private static boolean setPersistentCookieSession() { List cookieList = BaseActivity.getCookieJar().loadForRequest(HttpUrl.parse("https://www.thmmy.gr")); if (cookieList.size() == 2) { - if ((cookieList.get(0).name().equals("THMMYgrC00ki3")) && (cookieList.get(1).name().equals("PHPSESSID"))) - { + if ((cookieList.get(0).name().equals("THMMYgrC00ki3")) && (cookieList.get(1).name().equals("PHPSESSID"))) { Cookie.Builder builder = new Cookie.Builder(); builder.name(cookieList.get(1).name()) .value(cookieList.get(1).value()) @@ -221,10 +202,8 @@ public class Thmmy //-------------------------------------LOGIN ENDS----------------------------------------------- - //--------------------------------------LOGOUT-------------------------------------------------- - public static int logout(LoginData loginData) - { + public static int logout(LoginData loginData) { OkHttpClient client = BaseActivity.getClient(); Request request = new Request.Builder() .url(loginData.getLogoutLink()) @@ -234,16 +213,13 @@ public class Thmmy Response response = client.newCall(request).execute(); Document document = Jsoup.parse(response.body().string()); - Elements login = document.select("[value=Login]"); + Elements login = document.select("[value=Login]"); ((PersistentCookieJar) BaseActivity.getCookieJar()).clear(); - if(!login.isEmpty()) - { + if (!login.isEmpty()) { Log.i("Logout", "Logout successful"); loginData.setStatus(LOGGED_OUT); return LOGGED_OUT; - } - else - { + } else { Log.w("Logout", "Logout failed"); return FAILED; } @@ -260,22 +236,15 @@ public class Thmmy } - - //----------------------------------------LOGOUT ENDS----------------------------------------------- - - -//-------------------------------------------MISC--------------------------------------------------- - public static String extractUserName(Document doc) - { - if(doc!=null) - { + //-------------------------------------------MISC--------------------------------------------------- + public static String extractUserName(Document doc) { + if (doc != null) { Elements user = doc.select("div[id=myuser] > h3"); - if (user.size()==1) - { + if (user.size() == 1) { String txt = user.first().ownText(); Pattern pattern = Pattern.compile(", (.*?),"); diff --git a/app/src/main/res/drawable/page_first.xml b/app/src/main/res/drawable/page_first.xml deleted file mode 100644 index 258658e2..00000000 --- a/app/src/main/res/drawable/page_first.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/page_last.xml b/app/src/main/res/drawable/page_last.xml deleted file mode 100644 index 9e9d9915..00000000 --- a/app/src/main/res/drawable/page_last.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/page_next.xml b/app/src/main/res/drawable/page_next.xml deleted file mode 100644 index 7692c3ef..00000000 --- a/app/src/main/res/drawable/page_next.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable/page_previous.xml b/app/src/main/res/drawable/page_previous.xml deleted file mode 100644 index 58c22797..00000000 --- a/app/src/main/res/drawable/page_previous.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - -