diff --git a/app/build.gradle b/app/build.gradle index e0c5f69e8..6dd18c435 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -7,8 +7,8 @@ android { applicationId "fr.gouv.etalab.mastodon" minSdkVersion 15 targetSdkVersion 25 - versionCode 8 - versionName "1.1.1" + versionCode 9 + versionName "1.1.2" } buildTypes { release { @@ -20,7 +20,6 @@ android { dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.google.android.gms:play-services-safetynet:10.2.4' compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:design:25.3.1' compile 'com.android.support:support-v4:25.3.1' diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 63e864d70..a6b2329f3 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -70,11 +70,6 @@ android:configChanges="orientation|screenSize" android:label="@string/app_name" /> - diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java index c01474789..71f05f0fc 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java @@ -55,7 +55,7 @@ public class AboutActivity extends AppCompatActivity { about_code.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://bitbucket.org/tom79/mastodon_etalab")); + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://bitbucket.org/tom79/mastodon_etalab/src")); startActivity(browserIntent); } }); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java index 4d09b1006..d63e6f018 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java @@ -15,27 +15,36 @@ package fr.gouv.etalab.mastodon.activities; import android.content.Context; -import android.content.Intent; import android.content.SharedPreferences; +import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; +import android.widget.EditText; import android.widget.Toast; +import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONException; import org.json.JSONObject; -import java.util.HashMap; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; import cz.msebera.android.httpclient.Header; +import fr.gouv.etalab.mastodon.asynctasks.UpdateAccountInfoAsyncTask; +import fr.gouv.etalab.mastodon.client.MastalabSSLSocketFactory; import fr.gouv.etalab.mastodon.client.OauthClient; import fr.gouv.etalab.mastodon.helper.Helper; import mastodon.etalab.gouv.fr.mastodon.R; +import static fr.gouv.etalab.mastodon.helper.Helper.USER_AGENT; + /** * Created by Thomas on 23/04/2017. @@ -65,13 +74,12 @@ public class LoginActivity extends AppCompatActivity { private void retrievesClientId(){ final Button connectionButton = (Button) findViewById(R.id.login_button); - final Intent webviewIntent = new Intent(this, WebviewActivity.class); String action = "/api/v1/apps"; RequestParams parameters = new RequestParams(); - parameters.put(Helper.CLIENT_NAME, Helper.OAUTH_REDIRECT_HOST); - parameters.put(Helper.REDIRECT_URIS,"https://" + Helper.INSTANCE + Helper.REDIRECT_CONTENT); - parameters.put(Helper.SCOPES, Helper.OAUTH_SCOPES); - parameters.put(Helper.WEBSITE,"https://" + Helper.INSTANCE); + parameters.add(Helper.CLIENT_NAME, Helper.OAUTH_REDIRECT_HOST); + parameters.add(Helper.REDIRECT_URIS, Helper.REDIRECT_CONTENT); + parameters.add(Helper.SCOPES, Helper.OAUTH_SCOPES); + parameters.add(Helper.WEBSITE,"https://" + Helper.INSTANCE); new OauthClient().post(action, parameters, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { @@ -106,12 +114,53 @@ public class LoginActivity extends AppCompatActivity { connectionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - startActivity(webviewIntent); - finish(); + connectionButton.setEnabled(false); + AsyncHttpClient client = new AsyncHttpClient(); + RequestParams requestParams = new RequestParams(); + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + requestParams.add(Helper.CLIENT_ID, sharedpreferences.getString(Helper.CLIENT_ID, null)); + requestParams.add(Helper.CLIENT_SECRET, sharedpreferences.getString(Helper.CLIENT_SECRET, null)); + requestParams.add("grant_type", "password"); + EditText login_uid = (EditText) findViewById(R.id.login_uid); + EditText login_passwd = (EditText) findViewById(R.id.login_passwd); + requestParams.add("username",login_uid.getText().toString().trim()); + requestParams.add("password",login_passwd.getText().toString().trim()); + requestParams.add("scope"," read write follow"); + client.setUserAgent(USER_AGENT); + try { + client.setSSLSocketFactory(new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore())); + client.post("https://" + Helper.INSTANCE + "/oauth/token", requestParams, new AsyncHttpResponseHandler() { + @Override + public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { + String response = new String(responseBody); + JSONObject resobj; + try { + resobj = new JSONObject(response); + String token = resobj.get("access_token").toString(); + SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token); + editor.apply(); + //Update the account with the token; + new UpdateAccountInfoAsyncTask(LoginActivity.this, token).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { + connectionButton.setEnabled(true); + Toast.makeText(getApplicationContext(),R.string.toast_error_login,Toast.LENGTH_LONG).show(); + } + }); + + } catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException e) { + e.printStackTrace(); + } + } }); } - - } \ No newline at end of file diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/MainActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/MainActivity.java index fdd2a249d..d619b795d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/MainActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/MainActivity.java @@ -39,9 +39,6 @@ import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; -import com.google.android.gms.common.GooglePlayServicesNotAvailableException; -import com.google.android.gms.common.GooglePlayServicesRepairableException; -import com.google.android.gms.security.ProviderInstaller; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; @@ -53,6 +50,7 @@ import java.util.HashMap; import fr.gouv.etalab.mastodon.asynctasks.UpdateAccountInfoByIDAsyncTask; import fr.gouv.etalab.mastodon.client.Entities.Account; +import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.fragments.DisplayAccountsFragment; import fr.gouv.etalab.mastodon.fragments.DisplayNotificationsFragment; import fr.gouv.etalab.mastodon.helper.Helper; @@ -86,9 +84,6 @@ public class MainActivity extends AppCompatActivity super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); - try { - ProviderInstaller.installIfNeeded(this); - } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException ignored) {} //Test if user is still log in if( ! Helper.isLoggedIn(getApplicationContext())) { //It is not, the user is redirected to the login page @@ -124,6 +119,7 @@ public class MainActivity extends AppCompatActivity imageLoader = ImageLoader.getInstance(); File cacheDir = new File(getCacheDir(), getString(R.string.app_name)); ImageLoaderConfiguration configImg = new ImageLoaderConfiguration.Builder(this) + .imageDownloader(new PatchBaseImageDownloader(getApplicationContext())) .threadPoolSize(5) .threadPriority(Thread.MIN_PRIORITY + 3) .denyCacheImageMultipleSizesInMemory() diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java index ceacccd0b..317da269c 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java @@ -246,7 +246,7 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi setTitle(account.getAcct()); account_dn.setText(account.getDisplay_name()); account_un.setText(account.getUsername()); - if( account.getAcct().equals(account.getUsername())) + if( account.getAcct() != null && account.getAcct().equals(account.getUsername())) account_ac.setVisibility(View.GONE); else account_ac.setText(account.getAcct()); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewActivity.java deleted file mode 100644 index ef97ad591..000000000 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewActivity.java +++ /dev/null @@ -1,212 +0,0 @@ -/* Copyright 2017 Thomas Schneider - * - * This file is a part of Mastodon Etalab for mastodon.etalab.gouv.fr - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Mastodon Etalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Thomas Schneider; if not, - * see . */ - -package fr.gouv.etalab.mastodon.activities; - - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.SharedPreferences; -import android.net.Uri; -import android.net.http.SslError; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Bundle; -import android.support.v7.app.AlertDialog; -import android.support.v7.app.AppCompatActivity; -import android.util.Log; -import android.webkit.CookieManager; -import android.webkit.CookieSyncManager; -import android.webkit.HttpAuthHandler; -import android.webkit.SslErrorHandler; -import android.webkit.WebChromeClient; -import android.webkit.WebResourceResponse; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.webkit.WebViewClient; -import android.widget.ProgressBar; - -import com.loopj.android.http.AsyncHttpResponseHandler; -import com.loopj.android.http.RequestHandle; -import com.loopj.android.http.RequestParams; -import com.loopj.android.http.SyncHttpClient; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import java.net.MalformedURLException; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; - -import cz.msebera.android.httpclient.Header; -import mastodon.etalab.gouv.fr.mastodon.R; -import fr.gouv.etalab.mastodon.asynctasks.UpdateAccountInfoAsyncTask; -import fr.gouv.etalab.mastodon.client.OauthClient; -import fr.gouv.etalab.mastodon.helper.Helper; - -/** - * Created by Thomas on 24/04/2017. - * Webview to connect accounts - */ -public class WebviewActivity extends AppCompatActivity { - - - private WebView webView; - private AlertDialog alert; - private String clientId, clientSecret; - private WebResourceResponse webResourceResponse; - - public void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_webview); - SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - clientId = sharedpreferences.getString(Helper.CLIENT_ID, null); - clientSecret = sharedpreferences.getString(Helper.CLIENT_SECRET, null); - - webView = (WebView) findViewById(R.id.webviewConnect); - clearCookies(getApplicationContext()); - final ProgressBar pbar = (ProgressBar) findViewById(R.id.progress_bar); - WebSettings settings = webView.getSettings(); - settings.setJavaScriptEnabled(true); - settings.setDomStorageEnabled(true); - webView.setWebChromeClient(new WebChromeClient() { - @Override - public void onProgressChanged(WebView view, int progress) { - if (progress < 100 && pbar.getVisibility() == ProgressBar.GONE) { - pbar.setVisibility(ProgressBar.VISIBLE); - } - pbar.setProgress(progress); - if (progress == 100) { - pbar.setVisibility(ProgressBar.GONE); - } - } - }); - - - webView.setWebViewClient(new WebViewClient() { - @SuppressWarnings("deprecation") - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url){ - super.shouldOverrideUrlLoading(view,url); - if( url.contains(Helper.REDIRECT_CONTENT)){ - String val[] = url.split("code="); - String code = val[1]; - - String action = "/oauth/token"; - RequestParams parameters = new RequestParams(); - parameters.add(Helper.CLIENT_ID, clientId); - parameters.add(Helper.CLIENT_SECRET, clientSecret); - parameters.add(Helper.REDIRECT_URI,"https://" + Helper.INSTANCE + Helper.REDIRECT_CONTENT); - parameters.add("grant_type", "authorization_code"); - parameters.add("code",code); - new OauthClient().post(action, parameters, new AsyncHttpResponseHandler() { - @Override - public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { - String response = new String(responseBody); - JSONObject resobj; - try { - resobj = new JSONObject(response); - String token = resobj.get("access_token").toString(); - SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sharedpreferences.edit(); - editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token); - editor.apply(); - //Update the account with the token; - new UpdateAccountInfoAsyncTask(WebviewActivity.this, true, token).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } catch (JSONException e) { - e.printStackTrace(); - } - - } - - - - @Override - public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { - error.printStackTrace(); - } - }); - - - return true; - } - return false; - } - - }); - webView.loadUrl(redirectUserToAuthorizeAndLogin()); - } - - - @Override - public void onBackPressed() { - if (webView != null && webView.canGoBack()) { - webView.goBack(); - } else { - super.onBackPressed(); - } - } - - - - private String redirectUserToAuthorizeAndLogin() { - - String queryString = Helper.CLIENT_ID + "="+ clientId; - queryString += "&" + Helper.REDIRECT_URI + "="+ Uri.encode("https://" + Helper.INSTANCE + "/redirect_mastodon_api"); - queryString += "&" + Helper.RESPONSE_TYPE +"=code"; - queryString += "&" + Helper.SCOPE +"=" + Helper.OAUTH_SCOPES; - /*try { - queryString = URLEncoder.encode(queryString, "utf-8"); - } catch (UnsupportedEncodingException ignored) {}*/ - return "https://" + Helper.INSTANCE + Helper.EP_AUTHORIZE + "?" + queryString; - } - - - @Override - public void onDestroy() { - super.onDestroy(); - if (alert != null) { - alert.dismiss(); - alert = null; - } - } - - @SuppressWarnings("deprecation") - public static void clearCookies(Context context) - { - - 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(); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java index a6f509279..fa8c5154a 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java @@ -20,13 +20,11 @@ import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; -import android.util.Log; import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.helper.Helper; -import fr.gouv.etalab.mastodon.interfaces.OnUpdateAccountInfoInterface; import fr.gouv.etalab.mastodon.sqlite.Sqlite; import fr.gouv.etalab.mastodon.sqlite.AccountDAO; @@ -39,22 +37,11 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { private Context context; private String token; - private boolean fromWebview; - private boolean error; - private OnUpdateAccountInfoInterface listener; - public UpdateAccountInfoAsyncTask(Context context, String token, OnUpdateAccountInfoInterface onUpdateAccountInfoInterface){ + + public UpdateAccountInfoAsyncTask(Context context, String token){ this.context = context; this.token = token; - this.fromWebview = false; - this.error = false; - this.listener = onUpdateAccountInfoInterface; - } - - public UpdateAccountInfoAsyncTask(Context context, boolean fromWebview, String token){ - this.context = context; - this.token = token; - this.fromWebview = fromWebview; } @@ -78,8 +65,6 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { else { if( account.getUsername() != null && account.getCreated_at() != null) new AccountDAO(context, db).insertAccount(account); - else //Here the user credential in db doesn't match the remote one (it will be disconnected) - error = true; } return null; } @@ -87,14 +72,10 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { @Override protected void onPostExecute(Void result) { - if( fromWebview){ - Intent mainActivity = new Intent(context, MainActivity.class); - mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(mainActivity); - ((Activity) context).finish(); - }else{ - listener.onUpdateAccountInfo(error); - } + Intent mainActivity = new Intent(context, MainActivity.class); + mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(mainActivity); + ((Activity) context).finish(); } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java index 3cf904bd2..2e3da2279 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java @@ -16,6 +16,7 @@ package fr.gouv.etalab.mastodon.client; import android.content.Context; import android.content.SharedPreferences; +import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; @@ -44,6 +45,7 @@ import fr.gouv.etalab.mastodon.client.Entities.Attachment; import fr.gouv.etalab.mastodon.client.Entities.Notification; import fr.gouv.etalab.mastodon.client.Entities.Relationship; import fr.gouv.etalab.mastodon.client.Entities.Status; +import mastodon.etalab.gouv.fr.mastodon.R; import static fr.gouv.etalab.mastodon.helper.Helper.USER_AGENT; @@ -1156,28 +1158,49 @@ public class API { private void get(String action, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.setTimeout(10000); - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - client.addHeader("Authorization", "Bearer "+prefKeyOauthTokenT); - client.setUserAgent(USER_AGENT); - client.get(getAbsoluteUrl(action), params, responseHandler); + try { + client.setConnectTimeout(10000); //10s timeout + client.setUserAgent(USER_AGENT); + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); + client.addHeader("Authorization", "Bearer "+prefKeyOauthTokenT); + client.setSSLSocketFactory(new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore())); + client.get(getAbsoluteUrl(action), params, responseHandler); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) { + Toast.makeText(context, R.string.toast_error,Toast.LENGTH_LONG).show(); + e.printStackTrace(); + } } private void post(String action, RequestParams params, AsyncHttpResponseHandler responseHandler) { - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - client.addHeader("Authorization", "Bearer "+prefKeyOauthTokenT); - client.setUserAgent(USER_AGENT); - client.post(getAbsoluteUrl(action), params, responseHandler); + + try { + client.setConnectTimeout(10000); //10s timeout + client.setUserAgent(USER_AGENT); + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); + client.addHeader("Authorization", "Bearer "+prefKeyOauthTokenT); + client.setSSLSocketFactory(new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore())); + client.post(getAbsoluteUrl(action), params, responseHandler); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) { + Toast.makeText(context, R.string.toast_error,Toast.LENGTH_LONG).show(); + e.printStackTrace(); + } } private void delete(String action, RequestParams params, AsyncHttpResponseHandler responseHandler){ - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - client.addHeader("Authorization", "Bearer "+prefKeyOauthTokenT); - client.setUserAgent(USER_AGENT); - client.delete(getAbsoluteUrl(action), params, responseHandler); + try { + client.setConnectTimeout(10000); //10s timeout + client.setUserAgent(USER_AGENT); + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String prefKeyOauthTokenT = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); + client.addHeader("Authorization", "Bearer "+prefKeyOauthTokenT); + client.setSSLSocketFactory(new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore())); + client.delete(getAbsoluteUrl(action), params, responseHandler); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) { + Toast.makeText(context, R.string.toast_error,Toast.LENGTH_LONG).show(); + e.printStackTrace(); + } } private String getAbsoluteUrl(String action) { diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/OauthClient.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/OauthClient.java index 5417e784a..77275279e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/OauthClient.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/OauthClient.java @@ -18,9 +18,11 @@ package fr.gouv.etalab.mastodon.client; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; + +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; import fr.gouv.etalab.mastodon.helper.Helper; @@ -38,16 +40,26 @@ public class OauthClient { private static AsyncHttpClient client = new AsyncHttpClient(); public void get(String action, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.setTimeout(5000); - client.setUserAgent(USER_AGENT); - client.post(getAbsoluteUrl(action), params, responseHandler); - client.get(getAbsoluteUrl(action), params, responseHandler); + try { + client.setConnectTimeout(10000); //10s timeout + client.setUserAgent(USER_AGENT); + client.setSSLSocketFactory(new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore())); + client.get(getAbsoluteUrl(action), params, responseHandler); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) { + e.printStackTrace(); + } } public void post(String action, RequestParams params, AsyncHttpResponseHandler responseHandler) { - client.setConnectTimeout(30000); //30s timeout - client.setUserAgent(USER_AGENT); - client.post(getAbsoluteUrl(action), params, responseHandler); + try { + client.setConnectTimeout(10000); //10s timeout + client.setUserAgent(USER_AGENT); + client.setSSLSocketFactory(new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore())); + client.post(getAbsoluteUrl(action), params, responseHandler); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) { + e.printStackTrace(); + } + } private String getAbsoluteUrl(String action) { diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/PatchBaseImageDownloader.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/PatchBaseImageDownloader.java new file mode 100644 index 000000000..a80527c1d --- /dev/null +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/PatchBaseImageDownloader.java @@ -0,0 +1,127 @@ +package fr.gouv.etalab.mastodon.client; + +import android.content.Context; + +import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream; +import com.nostra13.universalimageloader.core.download.BaseImageDownloader; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.Socket; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +/** + * Created by Thomas on 21/05/2017. + * Patch for universal image loader to support TLS 1.1+ + */ + +public class PatchBaseImageDownloader extends BaseImageDownloader { + + private SSLSocketFactory sf; + + public PatchBaseImageDownloader(Context context) { + super(context); + + initSSLSocketFactory(); + } + + private void initSSLSocketFactory() { + sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); + try { + sf = new MySSLSocketFactory(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException { + HttpURLConnection conn = createConnection(imageUri, extra); + if (conn instanceof HttpsURLConnection) { + ((HttpsURLConnection) conn).setSSLSocketFactory(sf); + } + return new ContentLengthInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_SIZE), conn.getContentLength()); + } + + private static class MySSLSocketFactory extends SSLSocketFactory { + SSLContext sslContext = SSLContext.getInstance("TLS"); + + MySSLSocketFactory() throws Exception { + super(); + TrustManager tm = new X509TrustManager() { + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[]{tm}, null); + } + + @Override + public String[] getDefaultCipherSuites() { + return new String[0]; + } + + @Override + public String[] getSupportedCipherSuites() { + return new String[0]; + } + + + @Override + public Socket createSocket(String host, int port) throws IOException { + return enableTLSOnSocket(sslContext.getSocketFactory().createSocket(host, port)); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { + return enableTLSOnSocket(sslContext.getSocketFactory().createSocket(host, port, localHost, localPort)); + } + + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + return enableTLSOnSocket(sslContext.getSocketFactory().createSocket(host, port)); + } + + @Override + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { + return enableTLSOnSocket(sslContext.getSocketFactory().createSocket(address, port, localAddress, localPort)); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return enableTLSOnSocket(sslContext.getSocketFactory().createSocket(socket, host, port, autoClose)); + } + + @Override + public Socket createSocket() throws IOException { + return enableTLSOnSocket(sslContext.getSocketFactory().createSocket()); + } + + private Socket enableTLSOnSocket(Socket socket) { + if(socket != null && (socket instanceof SSLSocket)) { + ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"}); + } + return socket; + } + + } + +} \ No newline at end of file diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java index 77297226a..0b144a899 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java @@ -212,9 +212,6 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou } swipeRefreshLayout.setRefreshing(false); firstLoad = false; - if( accounts != null && accounts.size() < accountPerPage ) - flag_loading = true; - else - flag_loading = false; + flag_loading = accounts != null && accounts.size() < accountPerPage; } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java index c194cead3..677d6324e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java @@ -15,6 +15,7 @@ package fr.gouv.etalab.mastodon.fragments; * see . */ import android.content.Context; import android.content.SharedPreferences; +import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -29,8 +30,11 @@ import android.widget.RelativeLayout; import java.util.ArrayList; import java.util.List; +import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.drawers.NotificationsListAdapter; import fr.gouv.etalab.mastodon.helper.Helper; +import fr.gouv.etalab.mastodon.sqlite.AccountDAO; +import fr.gouv.etalab.mastodon.sqlite.Sqlite; import mastodon.etalab.gouv.fr.mastodon.R; import fr.gouv.etalab.mastodon.asynctasks.RetrieveNotificationsAsyncTask; import fr.gouv.etalab.mastodon.client.Entities.Notification; @@ -162,9 +166,19 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve } swipeRefreshLayout.setRefreshing(false); firstLoad = false; - if( notifications != null && notifications.size() < notificationPerPage ) - flag_loading = true; - else - flag_loading = false; + flag_loading = notifications != null && notifications.size() < notificationPerPage; + //Store last notification id to avoid to notify for those that have been already seen + if( notifications != null && notifications.size() > 0) { + final SharedPreferences sharedpreferences = getContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + //acct is null when used in Fragment, data need to be retrieved via shared preferences and db + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + Account currentAccount = new AccountDAO(context, db).getAccountByID(userId); + if( currentAccount != null){ + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(Helper.LAST_NOTIFICATION_MAX_ID + currentAccount.getAcct(), notifications.get(0).getId()); + editor.apply(); + } + } } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index ded4620ad..84466e8fe 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -16,11 +16,13 @@ package fr.gouv.etalab.mastodon.fragments; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; +import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -33,8 +35,11 @@ import java.util.ArrayList; import java.util.List; +import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.drawers.StatusListAdapter; import fr.gouv.etalab.mastodon.helper.Helper; +import fr.gouv.etalab.mastodon.sqlite.AccountDAO; +import fr.gouv.etalab.mastodon.sqlite.Sqlite; import mastodon.etalab.gouv.fr.mastodon.R; import fr.gouv.etalab.mastodon.asynctasks.RetrieveFeedsAsyncTask; import fr.gouv.etalab.mastodon.client.Entities.Status; @@ -61,6 +66,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn private String targetedId; private String tag; private boolean hideHeader = false; + private int tootsPerPage; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -85,7 +91,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); final ListView lv_status = (ListView) rootView.findViewById(R.id.lv_status); - + tootsPerPage = sharedpreferences.getInt(Helper.SET_TOOTS_PER_PAGE, 40); mainLoader = (RelativeLayout) rootView.findViewById(R.id.loader); nextElementLoader = (RelativeLayout) rootView.findViewById(R.id.loading_next_status); textviewNoAction = (RelativeLayout) rootView.findViewById(R.id.no_action); @@ -99,13 +105,12 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if(firstVisibleItem + visibleItemCount == totalItemCount ) { if(!flag_loading ) { flag_loading = true; if( type == RetrieveFeedsAsyncTask.Type.USER) asyncTask = new RetrieveFeedsAsyncTask(context, type, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( type == RetrieveFeedsAsyncTask.Type.TAG) + else if( type == RetrieveFeedsAsyncTask.Type.TAG) asyncTask = new RetrieveFeedsAsyncTask(context, type, tag, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -156,7 +161,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn flag_loading = true; if( type == RetrieveFeedsAsyncTask.Type.USER) asyncTask = new RetrieveFeedsAsyncTask(context, type, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( type == RetrieveFeedsAsyncTask.Type.TAG) + else if( type == RetrieveFeedsAsyncTask.Type.TAG) asyncTask = new RetrieveFeedsAsyncTask(context, type, tag, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -169,7 +174,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if( type == RetrieveFeedsAsyncTask.Type.USER) asyncTask = new RetrieveFeedsAsyncTask(context, type, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - if( type == RetrieveFeedsAsyncTask.Type.TAG) + else if( type == RetrieveFeedsAsyncTask.Type.TAG) asyncTask = new RetrieveFeedsAsyncTask(context, type, tag, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -203,7 +208,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override public void onRetrieveFeeds(List statuses) { - if( firstLoad && (statuses == null || statuses.size() == 0)) textviewNoAction.setVisibility(View.VISIBLE); else @@ -223,7 +227,20 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } swipeRefreshLayout.setRefreshing(false); firstLoad = false; - flag_loading = false; + flag_loading = statuses != null && statuses.size() < tootsPerPage; + //Store last toot id for home timeline to avoid to notify for those that have been already seen + if(statuses != null && statuses.size() > 0 && type == RetrieveFeedsAsyncTask.Type.HOME ){ + final SharedPreferences sharedpreferences = getContext().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + //acct is null when used in Fragment, data need to be retrieved via shared preferences and db + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + Account currentAccount = new AccountDAO(context, db).getAccountByID(userId); + if( currentAccount != null){ + SharedPreferences.Editor editor = sharedpreferences.edit(); + editor.putString(Helper.LAST_HOMETIMELINE_MAX_ID + currentAccount.getAcct(), statuses.get(0).getId()); + editor.apply(); + } + } } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java index 796252fa5..a0fb5f826 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java @@ -72,7 +72,7 @@ public class Helper { public static final String OAUTH_SCOPES = "read write follow"; public static final String PREF_KEY_OAUTH_TOKEN = "oauth_token"; public static final String PREF_KEY_ID = "userID"; - public static final String REDIRECT_CONTENT = "/redirect_mastodon_api"; + public static final String REDIRECT_CONTENT = "urn:ietf:wg:oauth:2.0:oob"; public static final int EXTERNAL_STORAGE_REQUEST_CODE = 84; //Some definitions diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/jobs/HomeTimelineSyncJob.java b/app/src/main/java/fr/gouv/etalab/mastodon/jobs/HomeTimelineSyncJob.java index 2d187e900..743371932 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/jobs/HomeTimelineSyncJob.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/jobs/HomeTimelineSyncJob.java @@ -37,6 +37,7 @@ import java.util.concurrent.TimeUnit; import fr.gouv.etalab.mastodon.asynctasks.RetrieveHomeTimelineServiceAsyncTask; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Status; +import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveHomeTimelineServiceInterface; import fr.gouv.etalab.mastodon.sqlite.AccountDAO; @@ -124,7 +125,8 @@ public class HomeTimelineSyncJob extends Job implements OnRetrieveHomeTimelineSe String title = null; for(Status status: statuses){ //The notification associated to max_id is discarded as it is supposed to have already been sent - if( status.getId().equals(max_id)) + //Also, if the toot comes from the owner, we will avoid to warn him/her... + if( status.getId().equals(max_id) || status.getAccount().getAcct().trim().equals(acct.trim())) continue; String notificationUrl = status.getAccount().getAvatar(); if( notificationUrl != null && icon_notification == null){ @@ -132,6 +134,7 @@ public class HomeTimelineSyncJob extends Job implements OnRetrieveHomeTimelineSe ImageLoader imageLoaderNoty = ImageLoader.getInstance(); File cacheDir = new File(getContext().getCacheDir(), getContext().getString(R.string.app_name)); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()) + .imageDownloader(new PatchBaseImageDownloader(getContext())) .threadPoolSize(5) .threadPriority(Thread.MIN_PRIORITY + 3) .denyCacheImageMultipleSizesInMemory() diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/jobs/NotificationsSyncJob.java b/app/src/main/java/fr/gouv/etalab/mastodon/jobs/NotificationsSyncJob.java index a116e1b2f..84510a7e1 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/jobs/NotificationsSyncJob.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/jobs/NotificationsSyncJob.java @@ -36,6 +36,7 @@ import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; +import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.helper.Helper; import mastodon.etalab.gouv.fr.mastodon.R; import fr.gouv.etalab.mastodon.asynctasks.RetrieveNotificationsAsyncTask; @@ -190,6 +191,7 @@ public class NotificationsSyncJob extends Job implements OnRetrieveNotifications ImageLoader imageLoaderNoty = ImageLoader.getInstance(); File cacheDir = new File(getContext().getCacheDir(), getContext().getString(R.string.app_name)); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()) + .imageDownloader(new PatchBaseImageDownloader(getContext())) .threadPoolSize(5) .threadPriority(Thread.MIN_PRIORITY + 3) .denyCacheImageMultipleSizesInMemory() diff --git a/app/src/main/res/layout/activity_about.xml b/app/src/main/res/layout/activity_about.xml index 6990bbf42..9310ef771 100644 --- a/app/src/main/res/layout/activity_about.xml +++ b/app/src/main/res/layout/activity_about.xml @@ -50,14 +50,14 @@ android:layout_gravity="center" android:gravity="center" android:clickable="true" - android:layout_weight="3" + android:layout_weight="2" android:layout_width="0dp" android:text="@string/about_developer" android:layout_height="wrap_content" />