Merged in develop (pull request #145)

Release 1.5.4
This commit is contained in:
tom79 2017-10-22 16:07:21 +00:00
commit ee75d58349
39 changed files with 2733 additions and 3624 deletions

View File

@ -79,7 +79,7 @@ The number of libraries is minimized and it does not use tracking tools. The sou
* Disable the built-in browser in settings
Developer: [@tschneider](https://mastodon.etalab.gouv.fr/@tschneider)
Developer: [@tom79](https://mastodon.social/@tom79)

View File

@ -7,8 +7,8 @@ android {
applicationId "fr.gouv.etalab.mastodon"
minSdkVersion 15
targetSdkVersion 26
versionCode 63
versionName "1.5.3"
versionCode 64
versionName "1.5.4"
}
buildTypes {
release {
@ -37,7 +37,7 @@ dependencies {
compile 'com.android.support:cardview-v7:26.0.2'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.evernote:android-job:1.1.11'
compile 'com.evernote:android-job:1.2.0'
compile 'com.github.chrisbanes:PhotoView:2.0.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'org.jsoup:jsoup:1.10.3'

View File

@ -14,312 +14,14 @@
* see <http://www.gnu.org/licenses>. */
package fr.gouv.etalab.mastodon.activities;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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.KinrarClient;
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;
import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor;
/**
* Created by Thomas on 23/04/2017.
* Login activity class which handles the connection
*/
public class LoginActivity extends AppCompatActivity {
private String client_id;
private String client_secret;
private TextView login_two_step;
private static boolean client_id_for_webview = false;
private String instance;
private AutoCompleteTextView login_instance;
boolean isLoadingInstance = false;
public class LoginActivity extends BaseLoginActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
if( theme == Helper.THEME_LIGHT){
setTheme(R.style.AppTheme);
}else {
setTheme(R.style.AppThemeDark);
}
setContentView(R.layout.activity_login);
if( theme == Helper.THEME_DARK) {
changeDrawableColor(getApplicationContext(), R.drawable.mastodon_icon, R.color.mastodonC2);
}else {
changeDrawableColor(getApplicationContext(), R.drawable.mastodon_icon, R.color.mastodonC3);
}
final Button connectionButton = (Button) findViewById(R.id.login_button);
login_instance = (AutoCompleteTextView) findViewById(R.id.login_instance);
if( theme == Helper.THEME_LIGHT) {
connectionButton.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
}
login_instance.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if( s.length() > 2 && !isLoadingInstance){
String action = "/instances/search";
RequestParams parameters = new RequestParams();
parameters.add("q", s.toString().trim());
parameters.add("count", String.valueOf(5));
parameters.add("name", String.valueOf(true));
isLoadingInstance = true;
new KinrarClient().get(action, parameters, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
isLoadingInstance = false;
String response = new String(responseBody);
String[] instances;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("instances");
if( jsonArray != null){
instances = new String[jsonArray.length()];
for(int i = 0 ; i < jsonArray.length() ; i++){
instances[i] = jsonArray.getJSONObject(i).get("name").toString();
}
}else {
instances = new String[]{};
}
login_instance.setAdapter(null);
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_list_item_1, instances);
login_instance.setAdapter(adapter);
if( login_instance.hasFocus() && !LoginActivity.this.isFinishing())
login_instance.showDropDown();
} catch (JSONException ignored) {isLoadingInstance = false;}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
isLoadingInstance = false;
}
});
}
}
});
connectionButton.setEnabled(false);
login_two_step = (TextView) findViewById(R.id.login_two_step);
login_two_step.setVisibility(View.GONE);
login_two_step.setPaintFlags(login_two_step.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
login_two_step.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
client_id_for_webview = true;
retrievesClientId();
}
});
login_instance.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
connectionButton.setEnabled(false);
login_two_step.setVisibility(View.INVISIBLE);
if (!hasFocus) {
retrievesClientId();
}
}
});
protected void installProviders() {
// do nothing
}
@Override
protected void onResume(){
super.onResume();
Button connectionButton = (Button) findViewById(R.id.login_button);
if (login_instance.getText() != null && login_instance.getText().toString().length() > 0 && client_id_for_webview) {
connectionButton.setEnabled(false);
client_id_for_webview = false;
retrievesClientId();
}
}
private void retrievesClientId(){
final Button connectionButton = (Button) findViewById(R.id.login_button);
try {
instance = URLEncoder.encode(login_instance.getText().toString().trim(), "utf-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(LoginActivity.this,R.string.client_error, Toast.LENGTH_LONG).show();
}
String action = "/api/v1/apps";
RequestParams parameters = new RequestParams();
parameters.add(Helper.CLIENT_NAME, Helper.CLIENT_NAME_VALUE);
parameters.add(Helper.REDIRECT_URIS, client_id_for_webview?Helper.REDIRECT_CONTENT_WEB:Helper.REDIRECT_CONTENT);
parameters.add(Helper.SCOPES, Helper.OAUTH_SCOPES);
parameters.add(Helper.WEBSITE, Helper.WEBSITE_VALUE);
new OauthClient(instance).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);
client_id = resobj.get(Helper.CLIENT_ID).toString();
client_secret = resobj.get(Helper.CLIENT_SECRET).toString();
String id = resobj.get(Helper.ID).toString();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.CLIENT_ID, client_id);
editor.putString(Helper.CLIENT_SECRET, client_secret);
editor.putString(Helper.ID, id);
editor.apply();
connectionButton.setEnabled(true);
login_two_step.setVisibility(View.VISIBLE);
if( client_id_for_webview){
Intent i = new Intent(LoginActivity.this, WebviewConnectActivity.class);
i.putExtra("instance", instance);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace();
Toast.makeText(LoginActivity.this,R.string.client_error, Toast.LENGTH_LONG).show();
}
});
connectionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connectionButton.setEnabled(false);
if( client_id_for_webview ){
client_id_for_webview = false;
retrievesClientId();
return;
}
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 {
MastalabSSLSocketFactory mastalabSSLSocketFactory = new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore());
mastalabSSLSocketFactory.setHostnameVerifier(MastalabSSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
client.setSSLSocketFactory(mastalabSSLSocketFactory);
client.post("https://" + 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, instance).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);
error.printStackTrace();
Toast.makeText(getApplicationContext(),R.string.toast_error_login,Toast.LENGTH_LONG).show();
}
});
} catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_about) {
Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(intent);
}else if(id == R.id.action_privacy){
Intent intent = new Intent(getApplicationContext(), PrivacyActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}

View File

@ -153,7 +153,7 @@ public class AboutActivity extends AppCompatActivity implements OnRetrieveRemote
accountSearchWebAdapterDeveloper = new AccountSearchDevAdapter(AboutActivity.this, developers);
lv_developers.setAdapter(accountSearchWebAdapterDeveloper);
new RetrieveRemoteAccountsAsyncTask(getApplicationContext(), "tschneider", "mastodon.etalab.gouv.fr", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteAccountsAsyncTask(getApplicationContext(), "tom79", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteAccountsAsyncTask(getApplicationContext(), "daycode", "mastodon.social", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteAccountsAsyncTask(getApplicationContext(), "PhotonQyv", "mastodon.xyz", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new RetrieveRemoteAccountsAsyncTask(getApplicationContext(), "angrytux", "social.tchncs.de", AboutActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
@ -187,7 +187,7 @@ public class AboutActivity extends AppCompatActivity implements OnRetrieveRemote
account = accounts.get(0);
account.setFollowing(true);
switch (account.getUsername()) {
case "tschneider":
case "tom79":
developers.add(account);
accountSearchWebAdapterDeveloper.notifyDataSetChanged();
break;

View File

@ -0,0 +1,331 @@
/* Copyright 2017 Thomas Schneider
*
* This file is a part of Mastalab
*
* 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.
*
* Mastalab 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 Mastalab; if not,
* see <http://www.gnu.org/licenses>. */
package fr.gouv.etalab.mastodon.activities;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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.KinrarClient;
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;
import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor;
/**
* Created by Thomas on 23/04/2017.
* Login activity class which handles the connection
*/
public abstract class BaseLoginActivity extends AppCompatActivity {
private String client_id;
private String client_secret;
private TextView login_two_step;
private static boolean client_id_for_webview = false;
private String instance;
private AutoCompleteTextView login_instance;
private EditText login_uid;
private EditText login_passwd;
boolean isLoadingInstance = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
installProviders();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
if( theme == Helper.THEME_LIGHT){
setTheme(R.style.AppTheme);
}else {
setTheme(R.style.AppThemeDark);
}
setContentView(R.layout.activity_login);
if( theme == Helper.THEME_DARK) {
changeDrawableColor(getApplicationContext(), R.drawable.mastodon_icon, R.color.mastodonC2);
}else {
changeDrawableColor(getApplicationContext(), R.drawable.mastodon_icon, R.color.mastodonC3);
}
final Button connectionButton = findViewById(R.id.login_button);
login_instance = findViewById(R.id.login_instance);
login_uid = findViewById(R.id.login_uid);
login_passwd = findViewById(R.id.login_passwd);
if( theme == Helper.THEME_LIGHT) {
connectionButton.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
}
login_instance.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if( s.length() > 2 && !isLoadingInstance){
String action = "/instances/search";
RequestParams parameters = new RequestParams();
parameters.add("q", s.toString().trim());
parameters.add("count", String.valueOf(5));
parameters.add("name", String.valueOf(true));
isLoadingInstance = true;
new KinrarClient().get(action, parameters, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
isLoadingInstance = false;
String response = new String(responseBody);
String[] instances;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("instances");
if( jsonArray != null){
instances = new String[jsonArray.length()];
for(int i = 0 ; i < jsonArray.length() ; i++){
instances[i] = jsonArray.getJSONObject(i).get("name").toString();
}
}else {
instances = new String[]{};
}
login_instance.setAdapter(null);
ArrayAdapter<String> adapter =
new ArrayAdapter<>(BaseLoginActivity.this, android.R.layout.simple_list_item_1, instances);
login_instance.setAdapter(adapter);
if( login_instance.hasFocus() && !BaseLoginActivity.this.isFinishing())
login_instance.showDropDown();
} catch (JSONException ignored) {isLoadingInstance = false;}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
isLoadingInstance = false;
}
});
}
}
});
connectionButton.setEnabled(false);
login_two_step = findViewById(R.id.login_two_step);
login_two_step.setVisibility(View.GONE);
login_two_step.setPaintFlags(login_two_step.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
login_two_step.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
client_id_for_webview = true;
retrievesClientId();
}
});
login_instance.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
connectionButton.setEnabled(false);
login_two_step.setVisibility(View.INVISIBLE);
if (!hasFocus) {
retrievesClientId();
}
}
});
}
protected abstract void installProviders();
@Override
protected void onResume(){
super.onResume();
Button connectionButton = findViewById(R.id.login_button);
if (login_instance.getText() != null && login_instance.getText().toString().length() > 0 && client_id_for_webview) {
connectionButton.setEnabled(false);
client_id_for_webview = false;
retrievesClientId();
}
}
private void retrievesClientId(){
final Button connectionButton = findViewById(R.id.login_button);
try {
instance = URLEncoder.encode(login_instance.getText().toString().trim(), "utf-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(BaseLoginActivity.this,R.string.client_error, Toast.LENGTH_LONG).show();
}
String action = "/api/v1/apps";
RequestParams parameters = new RequestParams();
parameters.add(Helper.CLIENT_NAME, Helper.CLIENT_NAME_VALUE);
parameters.add(Helper.REDIRECT_URIS, client_id_for_webview?Helper.REDIRECT_CONTENT_WEB:Helper.REDIRECT_CONTENT);
parameters.add(Helper.SCOPES, Helper.OAUTH_SCOPES);
parameters.add(Helper.WEBSITE, Helper.WEBSITE_VALUE);
new OauthClient(instance).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);
client_id = resobj.get(Helper.CLIENT_ID).toString();
client_secret = resobj.get(Helper.CLIENT_SECRET).toString();
String id = resobj.get(Helper.ID).toString();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.CLIENT_ID, client_id);
editor.putString(Helper.CLIENT_SECRET, client_secret);
editor.putString(Helper.ID, id);
editor.apply();
connectionButton.setEnabled(true);
login_two_step.setVisibility(View.VISIBLE);
if( client_id_for_webview){
Intent i = new Intent(BaseLoginActivity.this, WebviewConnectActivity.class);
i.putExtra("instance", instance);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace();
Toast.makeText(BaseLoginActivity.this,R.string.client_error, Toast.LENGTH_LONG).show();
}
});
connectionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connectionButton.setEnabled(false);
if( client_id_for_webview ){
client_id_for_webview = false;
retrievesClientId();
return;
}
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");
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 {
MastalabSSLSocketFactory mastalabSSLSocketFactory = new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore());
mastalabSSLSocketFactory.setHostnameVerifier(MastalabSSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
client.setSSLSocketFactory(mastalabSSLSocketFactory);
client.post("https://" + 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(BaseLoginActivity.this, token, instance).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);
error.printStackTrace();
Toast.makeText(getApplicationContext(),R.string.toast_error_login,Toast.LENGTH_LONG).show();
}
});
} catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_about) {
Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(intent);
}else if(id == R.id.action_privacy){
Intent intent = new Intent(getApplicationContext(), PrivacyActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,6 @@ public class MainApplication extends Application{
public void onCreate() {
super.onCreate();
JobManager.create(this).addJobCreator(new ApplicationJob());
JobManager.instance().getConfig().setVerbose(false);
NotificationsSyncJob.schedule(false);
HomeTimelineSyncJob.schedule(false);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();

View File

@ -271,7 +271,7 @@ public class MediaActivity extends AppCompatActivity {
currentAction = action;
final Attachment attachment = attachments.get(mediaPosition-1);
String type = attachment.getType();
final String url = attachment.getUrl();
String url = attachment.getUrl();
finalUrlDownload = url;
videoView.setVisibility(View.GONE);
if( videoView.isPlaying()) {
@ -279,8 +279,19 @@ public class MediaActivity extends AppCompatActivity {
}
imageView.setVisibility(View.GONE);
preview_url = attachment.getPreview_url();
if( type.equals("unknown")){
preview_url = attachment.getRemote_url();
if( preview_url.endsWith(".png") || preview_url.endsWith(".jpg")|| preview_url.endsWith(".jpeg")) {
type = "image";
}else if( preview_url.endsWith(".mp4")) {
type = "video";
}
url = attachment.getRemote_url();
attachment.setType(type);
}
switch (type){
case "image":
final String finalUrl = url;
imageLoader.displayImage(url, imageView, options, new SimpleImageLoadingListener(){
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
@ -292,7 +303,7 @@ public class MediaActivity extends AppCompatActivity {
}
@Override
public void onLoadingFailed(java.lang.String imageUri, android.view.View view, FailReason failReason){
imageLoader.displayImage(url, imageView, options);
imageLoader.displayImage(finalUrl, imageView, options);
loader.setVisibility(View.GONE);
}
});
@ -329,6 +340,7 @@ public class MediaActivity extends AppCompatActivity {
client.setSSLSocketFactory(mastalabSSLSocketFactory);
client.setUserAgent(USER_AGENT);
client.setConnectTimeout(120000); //120s timeout
final String finalUrl1 = url;
client.get(url, null, new FileAsyncHttpResponseHandler(MediaActivity.this) {
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
@ -345,7 +357,7 @@ public class MediaActivity extends AppCompatActivity {
public void onSuccess(int statusCode, Header[] headers, File response) {
File dir = getCacheDir();
File from = new File(dir, response.getName());
File to = new File(dir, Helper.md5(url) + ".mp4");
File to = new File(dir, Helper.md5(finalUrl1) + ".mp4");
if (from.exists())
//noinspection ResultOfMethodCallIgnored
from.renameTo(to);

View File

@ -33,20 +33,16 @@ import android.support.annotation.RequiresApi;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.transition.Visibility;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@ -116,7 +112,6 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
private TabLayout tabLayout;
private TextView account_note, account_follow_request;
private String userId;
private static int instanceValue = 0;
private Relationship relationship;
private boolean showMediaOnly, showPinned;
private ImageView pp_actionBar;
@ -126,6 +121,9 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
private int maxScrollSize;
private boolean avatarShown = true;
private DisplayStatusFragment displayStatusFragment;
private CircleImageView account_pp;
private TextView account_dn;
private TextView account_un;
public enum action{
FOLLOW,
@ -149,13 +147,15 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
}
setContentView(R.layout.activity_show_account);
setTitle("");
instanceValue += 1;
pins = new ArrayList<>();
Bundle b = getIntent().getExtras();
account_follow = (FloatingActionButton) findViewById(R.id.account_follow);
account_follow_request = (TextView) findViewById(R.id.account_follow_request);
header_edit_profile = (ImageView) findViewById(R.id.header_edit_profile);
account_follow = findViewById(R.id.account_follow);
account_follow_request = findViewById(R.id.account_follow_request);
header_edit_profile = findViewById(R.id.header_edit_profile);
account_follow.setEnabled(false);
account_pp = findViewById(R.id.account_pp);
account_dn = findViewById(R.id.account_dn);
account_un = findViewById(R.id.account_un);
if(b != null){
accountId = b.getString("accountId");
new RetrieveRelationshipAsyncTask(getApplicationContext(), accountId,ShowAccountActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
@ -189,12 +189,12 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
tabLayout = (TabLayout) findViewById(R.id.account_tabLayout);
tabLayout = findViewById(R.id.account_tabLayout);
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.toots)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.following)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.followers)));
mPager = (ViewPager) findViewById(R.id.account_viewpager);
mPager = findViewById(R.id.account_viewpager);
PagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
@ -246,7 +246,7 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
}
});
account_note = (TextView) findViewById(R.id.account_note);
account_note = findViewById(R.id.account_note);
//Follow button
account_follow.setOnClickListener(new View.OnClickListener() {
@ -279,7 +279,7 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
final ImageButton account_menu = (ImageButton) findViewById(R.id.account_menu);
final ImageButton account_menu = findViewById(R.id.account_menu);
account_menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
@ -356,9 +356,6 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
}
accountUrl = account.getUrl();
final CircleImageView account_pp = (CircleImageView) findViewById(R.id.account_pp);
TextView account_dn = (TextView) findViewById(R.id.account_dn);
TextView account_un = (TextView) findViewById(R.id.account_un);
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
if( theme == Helper.THEME_DARK){
@ -380,7 +377,7 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
ImageView banner_pp = (ImageView) findViewById(R.id.banner_pp);
ImageView banner_pp = findViewById(R.id.banner_pp);
Bitmap workingBitmap = Bitmap.createBitmap(loadedImage);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
@ -411,10 +408,10 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
if( account != null){
TextView actionbar_title = (TextView) findViewById(R.id.show_account_title);
TextView actionbar_title = findViewById(R.id.show_account_title);
if( account.getAcct() != null)
actionbar_title.setText(account.getAcct());
pp_actionBar = (ImageView) findViewById(R.id.pp_actionBar);
pp_actionBar = findViewById(R.id.pp_actionBar);
String url = account.getAvatar();
if( url.startsWith("/") ){
url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar();
@ -434,7 +431,7 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
public void onLoadingFailed(java.lang.String imageUri, android.view.View view, FailReason failReason){
}});
final AppBarLayout appBar = (AppBarLayout) findViewById(R.id.appBar);
final AppBarLayout appBar = findViewById(R.id.appBar);
maxScrollSize = appBar.getTotalScrollRange();
@ -619,7 +616,7 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
//The authenticated account is followed by the account
if( relationship.isFollowed_by()){
TextView account_followed_by = (TextView) findViewById(R.id.account_followed_by);
TextView account_followed_by = findViewById(R.id.account_followed_by);
account_followed_by.setVisibility(View.VISIBLE);
}
@ -674,7 +671,6 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
bundle.putBoolean("hideHeader",true);
bundle.putBoolean("showMediaOnly",showMediaOnly);
bundle.putBoolean("showPinned",showPinned);
bundle.putString("hideHeaderValue",String.valueOf(instanceValue));
displayStatusFragment.setArguments(bundle);
return displayStatusFragment;
case 1:
@ -682,7 +678,6 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
bundle.putSerializable("type", RetrieveAccountsAsyncTask.Type.FOLLOWING);
bundle.putString("targetedId", accountId);
bundle.putBoolean("hideHeader",true);
bundle.putString("hideHeaderValue",String.valueOf(instanceValue));
displayAccountsFragment.setArguments(bundle);
return displayAccountsFragment;
case 2:
@ -690,7 +685,6 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi
bundle.putSerializable("type", RetrieveAccountsAsyncTask.Type.FOLLOWERS);
bundle.putString("targetedId", accountId);
bundle.putBoolean("hideHeader",true);
bundle.putString("hideHeaderValue",String.valueOf(instanceValue));
displayAccountsFragment.setArguments(bundle);
return displayAccountsFragment;
}

View File

@ -75,7 +75,6 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet
private String statusId;
private Status initialStatus;
public static int position;
private SwipeRefreshLayout swipeRefreshLayout;
private ListView lv_status;
private boolean isRefreshed;
@ -100,10 +99,10 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet
View view = inflater.inflate(R.layout.conversation_action_bar, null);
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
TextView title = (TextView) actionBar.getCustomView().findViewById(R.id.toolbar_title);
pp_actionBar = (ImageView) actionBar.getCustomView().findViewById(R.id.pp_actionBar);
TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar);
title.setText(R.string.conversation);
ImageView close_conversation = (ImageView) actionBar.getCustomView().findViewById(R.id.close_conversation);
ImageView close_conversation = actionBar.getCustomView().findViewById(R.id.close_conversation);
if( close_conversation != null){
close_conversation.setOnClickListener(new View.OnClickListener() {
@Override
@ -159,7 +158,7 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet
finish();
isRefreshed = false;
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
swipeRefreshLayout = findViewById(R.id.swipeContainer);
new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.ONESTATUS, statusId,null, false,false, ShowConversationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
swipeRefreshLayout.setColorSchemeResources(R.color.mastodonC4,
@ -172,7 +171,7 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet
new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.ONESTATUS, statusId,null, false,false, ShowConversationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
lv_status = (ListView) findViewById(R.id.lv_status);
lv_status = findViewById(R.id.lv_status);
lv_status.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
@ -225,7 +224,7 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet
}
@Override
public void onRetrieveFeeds(Context context, Error error) {
public void onRetrieveContext(Context context, Status statusFirst, Error error) {
swipeRefreshLayout.setRefreshing(false);
if( error != null){
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
@ -238,22 +237,36 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS);
int positionSpinnerTrans = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX);
position = 0;
int position = 0;
boolean positionFound = false;
List<Status> statuses = new ArrayList<>();
if( statusFirst != null)
statuses.add(0, statusFirst);
if( context.getAncestors() != null && context.getAncestors().size() > 0){
for(Status status: context.getAncestors()){
statuses.add(status);
position++;
if( !positionFound)
position++;
if( status.getId().equals(initialStatus.getId()))
positionFound = true;
}
}else if( statusFirst == null){
statuses.add(0, initialStatus);
positionFound = true;
}
statuses.add(initialStatus);
if( context.getDescendants() != null && context.getDescendants().size() > 0){
for(Status status: context.getDescendants()){
statuses.add(status);
if( !positionFound)
position++;
if( status.getId().equals(initialStatus.getId()))
positionFound = true;
}
}
RelativeLayout loader = (RelativeLayout) findViewById(R.id.loader);
StatusListAdapter statusListAdapter = new StatusListAdapter(ShowConversationActivity.this, RetrieveFeedsAsyncTask.Type.CONTEXT, null, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, statuses);
RelativeLayout loader = findViewById(R.id.loader);
StatusListAdapter statusListAdapter = new StatusListAdapter(ShowConversationActivity.this, position, null, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, statuses);
lv_status.setAdapter(statusListAdapter);
statusListAdapter.notifyDataSetChanged();
loader.setVisibility(View.GONE);

View File

@ -921,7 +921,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc
//Clear content
toot_content.setText("");
toot_cw_content.setText("");
toot_space_left.setText(0);
toot_space_left.setText("0");
if( attachments != null) {
for (Attachment attachment : attachments) {
View namebar = findViewById(Integer.parseInt(attachment.getId()));
@ -1213,37 +1213,39 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc
toot_content.setThreshold(1);
toot_content.setAdapter(accountsListAdapter);
final String oldContent = toot_content.getText().toString();
String[] searchA = oldContent.substring(0,currentCursorPosition).split("@");
if( searchA.length > 0 ) {
final String search = searchA[searchA.length - 1];
toot_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Account account = accounts.get(position);
String deltaSearch = "";
if (currentCursorPosition - searchLength > 0 && currentCursorPosition < oldContent.length())
deltaSearch = oldContent.substring(currentCursorPosition - searchLength, currentCursorPosition);
else {
if (currentCursorPosition >= oldContent.length())
deltaSearch = oldContent.substring(currentCursorPosition - searchLength, oldContent.length());
}
if( oldContent.length() >= currentCursorPosition) {
String[] searchA = oldContent.substring(0, currentCursorPosition).split("@");
if (searchA.length > 0) {
final String search = searchA[searchA.length - 1];
toot_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Account account = accounts.get(position);
String deltaSearch = "";
if (currentCursorPosition - searchLength > 0 && currentCursorPosition < oldContent.length())
deltaSearch = oldContent.substring(currentCursorPosition - searchLength, currentCursorPosition);
else {
if (currentCursorPosition >= oldContent.length())
deltaSearch = oldContent.substring(currentCursorPosition - searchLength, oldContent.length());
}
if (!search.equals(""))
deltaSearch = deltaSearch.replace("@" + search, "");
String newContent = oldContent.substring(0, currentCursorPosition - searchLength);
newContent += deltaSearch;
newContent += "@" + account.getAcct() + " ";
int newPosition = newContent.length();
if (currentCursorPosition < oldContent.length() - 1)
newContent += oldContent.substring(currentCursorPosition, oldContent.length() - 1);
toot_content.setText(newContent);
toot_space_left.setText(String.valueOf(toot_content.length()));
toot_content.setSelection(newPosition);
AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(TootActivity.this, new ArrayList<Account>());
toot_content.setThreshold(1);
toot_content.setAdapter(accountsListAdapter);
}
});
if (!search.equals(""))
deltaSearch = deltaSearch.replace("@" + search, "");
String newContent = oldContent.substring(0, currentCursorPosition - searchLength);
newContent += deltaSearch;
newContent += "@" + account.getAcct() + " ";
int newPosition = newContent.length();
if (currentCursorPosition < oldContent.length() - 1)
newContent += oldContent.substring(currentCursorPosition, oldContent.length() - 1);
toot_content.setText(newContent);
toot_space_left.setText(String.valueOf(toot_content.length()));
toot_content.setSelection(newPosition);
AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(TootActivity.this, new ArrayList<Account>());
toot_content.setThreshold(1);
toot_content.setAdapter(accountsListAdapter);
}
});
}
}
}
}

View File

@ -30,6 +30,7 @@ public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> {
private Context context;
private String statusId;
private fr.gouv.etalab.mastodon.client.Entities.Status statusFirst;
private fr.gouv.etalab.mastodon.client.Entities.Context statusContext;
private OnRetrieveContextInterface listener;
private API api;
@ -44,12 +45,17 @@ public class RetrieveContextAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
api = new API(context);
statusContext = api.getStatusContext(statusId);
//Retrieves the first toot
if( statusContext.getAncestors().size() > 0 ) {
statusFirst = statusContext.getAncestors().get(0);
statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
listener.onRetrieveFeeds(statusContext, api.getError());
listener.onRetrieveContext(statusContext, statusFirst, api.getError());
}
}

View File

@ -45,7 +45,7 @@ public class RetrieveDeveloperAccountsAsyncTask extends AsyncTask<Void, Void, Vo
protected Void doInBackground(Void... params) {
API api = new API(context);
accounts = new ArrayList<>();
APIResponse apiResponse = api.searchAccounts("@tschneider@mastodon.etalab.gouv.fr", 1);
APIResponse apiResponse = api.searchAccounts("@tom79@mastodon.social", 1);
if( apiResponse.getAccounts() != null && apiResponse.getAccounts().size() > 0)
accounts.add(apiResponse.getAccounts().get(0));
apiResponse = api.searchAccounts("@daycode@mastodon.social",1);

View File

@ -1500,6 +1500,26 @@ public class API {
}
status.setTags(tags);
//Retrieves emjis
List<Emojis> emojiList = new ArrayList<>();
try {
JSONArray emojisTag = resobj.getJSONArray("emojis");
if( arrayTag != null){
for(int j = 0 ; j < emojisTag.length() ; j++){
JSONObject emojisObj = emojisTag.getJSONObject(j);
Emojis emojis = new Emojis();
emojis.setShortcode(emojisObj.get("shortcode").toString());
emojis.setStatic_url(emojisObj.get("static_url").toString());
emojis.setUrl(emojisObj.get("url").toString());
emojiList.add(emojis);
}
}
status.setEmojis(emojiList);
}catch (Exception e){
status.setEmojis(new ArrayList<Emojis>());
}
status.setAccount(parseAccountResponse(context, resobj.getJSONObject("account")));
status.setContent(resobj.get("content").toString());
status.setFavourites_count(Integer.valueOf(resobj.get("favourites_count").toString()));

View File

@ -0,0 +1,50 @@
/* Copyright 2017 Thomas Schneider
*
* This file is a part of Mastalab
*
* 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.
*
* Mastalab 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 Mastalab; if not,
* see <http://www.gnu.org/licenses>. */
package fr.gouv.etalab.mastodon.client.Entities;
/**
* Created by Thomas on 20/10/2017.
*/
public class Emojis {
private String shortcode;
private String static_url;
private String url;
public String getShortcode() {
return shortcode;
}
public void setShortcode(String shortcode) {
this.shortcode = shortcode;
}
public String getStatic_url() {
return static_url;
}
public void setStatic_url(String static_url) {
this.static_url = static_url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

View File

@ -17,6 +17,8 @@ package fr.gouv.etalab.mastodon.client.Entities;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.SpannableString;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -37,6 +39,8 @@ public class Status implements Parcelable {
private Status reblog;
private String content;
private String content_translated;
private SpannableString contents;
private SpannableString content_translateds;
private Date created_at;
private int reblogs_count;
private int favourites_count;
@ -51,10 +55,12 @@ public class Status implements Parcelable {
private ArrayList<Attachment> media_attachments;
private List<Status> replies;
private List<Mention> mentions;
private List<Emojis> emojis;
private List<Tag> tags;
private Application application;
private String language;
private boolean isTranslated = false;
private boolean isEmojiFound = false;
private boolean isTranslationShown = false;
private boolean isNew = false;
private boolean isTakingScreenShot = false;
@ -379,4 +385,36 @@ public class Status implements Parcelable {
public void setVisible(boolean visible) {
isVisible = visible;
}
public List<Emojis> getEmojis() {
return emojis;
}
public void setEmojis(List<Emojis> emojis) {
this.emojis = emojis;
}
public SpannableString getContents() {
return contents;
}
public void setContents(SpannableString contents) {
this.contents = contents;
}
public SpannableString getContent_translateds() {
return content_translateds;
}
public void setContent_translateds(SpannableString content_translateds) {
this.content_translateds = content_translateds;
}
public boolean isEmojiFound() {
return isEmojiFound;
}
public void setEmojiFound(boolean emojiFound) {
isEmojiFound = emojiFound;
}
}

View File

@ -71,6 +71,7 @@ import fr.gouv.etalab.mastodon.client.Entities.Error;
import fr.gouv.etalab.mastodon.helper.CrossActions;
import fr.gouv.etalab.mastodon.interfaces.OnPostActionInterface;
import fr.gouv.etalab.mastodon.interfaces.OnPostNotificationsActionInterface;
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveEmojiInterface;
import mastodon.etalab.gouv.fr.mastodon.R;
import fr.gouv.etalab.mastodon.client.Entities.Notification;
import fr.gouv.etalab.mastodon.client.Entities.Status;
@ -84,7 +85,7 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor;
* Created by Thomas on 24/04/2017.
* Adapter for Status
*/
public class NotificationsListAdapter extends BaseAdapter implements OnPostActionInterface, OnPostNotificationsActionInterface {
public class NotificationsListAdapter extends BaseAdapter implements OnPostActionInterface, OnPostNotificationsActionInterface, OnRetrieveEmojiInterface {
private Context context;
private List<Notification> notifications;
@ -288,13 +289,19 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio
holder.status_document_container.setVisibility(View.VISIBLE);
String content = status.getContent();
content = content.replaceAll("</p>","<br/><br/>");
content = content.replaceAll("<p>","");
if( content.endsWith("<br/><br/>") )
content = content.substring(0,content.length() -10);
if( content != null) {
content = content.replaceAll("</p>", "<br/><br/>");
content = content.replaceAll("<p>", "");
if (content.endsWith("<br/><br/>"))
content = content.substring(0, content.length() - 10);
}
SpannableString spannableString = Helper.clickableElements(context, status.getContent(),
status.getReblog() != null?status.getReblog().getMentions():status.getMentions(),
status.getReblog() != null?status.getReblog().getEmojis():status.getEmojis(),
position,
true, NotificationsListAdapter.this);
SpannableString spannableString = Helper.clickableElements(context, content,
status.getReblog() != null?status.getReblog().getMentions():status.getMentions(), true);
Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans-Regular.ttf");
holder.notification_status_content.setTypeface(tf);
holder.notification_status_content.setText(spannableString, TextView.BufferType.SPANNABLE);
@ -765,40 +772,42 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio
notifications.removeAll(notificationsToRemove);
notificationsListAdapter.notifyDataSetChanged();
}
if (statusAction == API.StatusAction.REBLOG) {
for (Notification notification : notifications) {
if (notification.getStatus().getId().equals(targetedId)) {
notification.getStatus().setReblogs_count(notification.getStatus().getReblogs_count() + 1);
break;
if( targetedId != null ) {
if (statusAction == API.StatusAction.REBLOG) {
for (Notification notification : notifications) {
if (notification.getStatus() != null && notification.getStatus().getId().equals(targetedId)) {
notification.getStatus().setReblogs_count(notification.getStatus().getReblogs_count() + 1);
break;
}
}
}
notificationsListAdapter.notifyDataSetChanged();
} else if (statusAction == API.StatusAction.UNREBLOG) {
for (Notification notification : notifications) {
if (notification.getStatus().getId().equals(targetedId)) {
if (notification.getStatus().getReblogs_count() - 1 >= 0)
notification.getStatus().setReblogs_count(notification.getStatus().getReblogs_count() - 1);
break;
notificationsListAdapter.notifyDataSetChanged();
} else if (statusAction == API.StatusAction.UNREBLOG) {
for (Notification notification : notifications) {
if (notification.getStatus() != null && notification.getStatus().getId().equals(targetedId)) {
if (notification.getStatus().getReblogs_count() - 1 >= 0)
notification.getStatus().setReblogs_count(notification.getStatus().getReblogs_count() - 1);
break;
}
}
}
notificationsListAdapter.notifyDataSetChanged();
} else if (statusAction == API.StatusAction.FAVOURITE) {
for (Notification notification : notifications) {
if (notification.getStatus().getId().equals(targetedId)) {
notification.getStatus().setFavourites_count(notification.getStatus().getFavourites_count() + 1);
break;
notificationsListAdapter.notifyDataSetChanged();
} else if (statusAction == API.StatusAction.FAVOURITE) {
for (Notification notification : notifications) {
if (notification.getStatus() != null && notification.getStatus().getId().equals(targetedId)) {
notification.getStatus().setFavourites_count(notification.getStatus().getFavourites_count() + 1);
break;
}
}
}
notificationsListAdapter.notifyDataSetChanged();
} else if (statusAction == API.StatusAction.UNFAVOURITE) {
for (Notification notification : notifications) {
if (notification.getStatus().getId().equals(targetedId)) {
if (notification.getStatus().getFavourites_count() - 1 >= 0)
notification.getStatus().setFavourites_count(notification.getStatus().getFavourites_count() - 1);
break;
notificationsListAdapter.notifyDataSetChanged();
} else if (statusAction == API.StatusAction.UNFAVOURITE) {
for (Notification notification : notifications) {
if (notification.getStatus() != null && notification.getStatus().getId().equals(targetedId)) {
if (notification.getStatus().getFavourites_count() - 1 >= 0)
notification.getStatus().setFavourites_count(notification.getStatus().getFavourites_count() - 1);
break;
}
}
notificationsListAdapter.notifyDataSetChanged();
}
notificationsListAdapter.notifyDataSetChanged();
}
}
@ -904,6 +913,15 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio
holder.status_show_more.setVisibility(View.GONE);
}
@Override
public void onRetrieveEmoji(int position, SpannableString spannableString, Boolean error) {
notifications.get(position).getStatus().setContents(spannableString);
if( !notifications.get(position).getStatus().isEmojiFound()) {
notifications.get(position).getStatus().setEmojiFound(true);
notificationsListAdapter.notifyDataSetChanged();
}
}
private class ViewHolder {
CardView card_status_container;

View File

@ -15,7 +15,6 @@ package fr.gouv.etalab.mastodon.drawers;
* see <http://www.gnu.org/licenses>. */
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
@ -39,11 +38,8 @@ import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.Patterns;
import android.util.TypedValue;
import android.view.LayoutInflater;
@ -83,7 +79,6 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import fr.gouv.etalab.mastodon.activities.HashTagActivity;
import fr.gouv.etalab.mastodon.activities.MediaActivity;
import fr.gouv.etalab.mastodon.activities.ShowAccountActivity;
import fr.gouv.etalab.mastodon.activities.ShowConversationActivity;
@ -99,6 +94,7 @@ import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader;
import fr.gouv.etalab.mastodon.helper.CrossActions;
import fr.gouv.etalab.mastodon.helper.Helper;
import fr.gouv.etalab.mastodon.interfaces.OnPostActionInterface;
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveEmojiInterface;
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveFeedsInterface;
import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface;
import fr.gouv.etalab.mastodon.translation.GoogleTranslateQuery;
@ -114,13 +110,13 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor;
* Created by Thomas on 24/04/2017.
* Adapter for Status
*/
public class StatusListAdapter extends BaseAdapter implements OnPostActionInterface, OnTranslatedInterface, OnRetrieveFeedsInterface {
public class StatusListAdapter extends BaseAdapter implements OnPostActionInterface, OnTranslatedInterface, OnRetrieveFeedsInterface, OnRetrieveEmojiInterface {
private Context context;
private List<Status> statuses;
private LayoutInflater layoutInflater;
private ImageLoader imageLoader;
private DisplayImageOptions options, optionsAttachment;
private DisplayImageOptions optionsAttachment;
private ViewHolder holder;
private boolean isOnWifi;
private int translator;
@ -133,6 +129,7 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
private final int HIDDEN_STATUS = 0;
private final int DISPLAYED_STATUS = 1;
private List<Status> pins;
private int conversationPosition;
public StatusListAdapter(Context context, RetrieveFeedsAsyncTask.Type type, String targetedId, boolean isOnWifi, int behaviorWithAttachments, int translator, List<Status> statuses){
this.context = context;
@ -147,7 +144,19 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
pins = new ArrayList<>();
}
public StatusListAdapter(Context context, int position, String targetedId, boolean isOnWifi, int behaviorWithAttachments, int translator, List<Status> statuses){
this.context = context;
this.statuses = statuses;
this.isOnWifi = isOnWifi;
this.behaviorWithAttachments = behaviorWithAttachments;
layoutInflater = LayoutInflater.from(this.context);
statusListAdapter = this;
this.type = RetrieveFeedsAsyncTask.Type.CONTEXT;
this.conversationPosition = position;
this.targetedId = targetedId;
this.translator = translator;
pins = new ArrayList<>();
}
@Override
public int getCount() {
@ -190,7 +199,7 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
if( getItemViewType(position) == HIDDEN_STATUS){
return new View(context);
}else {
}else if( getItemViewType(position) == DISPLAYED_STATUS){
final Status status = statuses.get(position);
imageLoader = ImageLoader.getInstance();
File cacheDir = new File(context.getCacheDir(), context.getString(R.string.app_name));
@ -203,56 +212,56 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
.build();
if( !imageLoader.isInited())
imageLoader.init(configImg);
options = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(10)).cacheInMemory(false)
DisplayImageOptions options = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(10)).cacheInMemory(false)
.cacheOnDisk(true).resetViewBeforeLoading(true).build();
optionsAttachment = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false)
.cacheOnDisk(true).resetViewBeforeLoading(true).build();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.drawer_status, parent, false);
holder = new ViewHolder();
holder.loader_replies = (LinearLayout) convertView.findViewById(R.id.loader_replies);
holder.card_status_container = (CardView) convertView.findViewById(R.id.card_status_container);
holder.status_document_container = (LinearLayout) convertView.findViewById(R.id.status_document_container);
holder.status_content = (TextView) convertView.findViewById(R.id.status_content);
holder.status_content_translated = (TextView) convertView.findViewById(R.id.status_content_translated);
holder.status_account_username = (TextView) convertView.findViewById(R.id.status_account_username);
holder.status_account_displayname = (TextView) convertView.findViewById(R.id.status_account_displayname);
holder.status_account_profile = (ImageView) convertView.findViewById(R.id.status_account_profile);
holder.status_account_profile_boost = (ImageView) convertView.findViewById(R.id.status_account_profile_boost);
holder.status_account_profile_boost_by = (ImageView) convertView.findViewById(R.id.status_account_profile_boost_by);
holder.status_favorite_count = (TextView) convertView.findViewById(R.id.status_favorite_count);
holder.status_reblog_count = (TextView) convertView.findViewById(R.id.status_reblog_count);
holder.status_pin = (ImageView) convertView.findViewById(R.id.status_pin);
holder.status_toot_date = (TextView) convertView.findViewById(R.id.status_toot_date);
holder.status_show_more = (Button) convertView.findViewById(R.id.status_show_more);
holder.status_more = (ImageView) convertView.findViewById(R.id.status_more);
holder.status_prev1 = (ImageView) convertView.findViewById(R.id.status_prev1);
holder.status_prev2 = (ImageView) convertView.findViewById(R.id.status_prev2);
holder.status_prev3 = (ImageView) convertView.findViewById(R.id.status_prev3);
holder.status_prev4 = (ImageView) convertView.findViewById(R.id.status_prev4);
holder.status_prev1_play = (ImageView) convertView.findViewById(R.id.status_prev1_play);
holder.status_prev2_play = (ImageView) convertView.findViewById(R.id.status_prev2_play);
holder.status_prev3_play = (ImageView) convertView.findViewById(R.id.status_prev3_play);
holder.status_prev4_play = (ImageView) convertView.findViewById(R.id.status_prev4_play);
holder.status_container2 = (LinearLayout) convertView.findViewById(R.id.status_container2);
holder.status_container3 = (LinearLayout) convertView.findViewById(R.id.status_container3);
holder.status_prev4_container = (RelativeLayout) convertView.findViewById(R.id.status_prev4_container);
holder.status_reply = (ImageView) convertView.findViewById(R.id.status_reply);
holder.status_privacy = (ImageView) convertView.findViewById(R.id.status_privacy);
holder.status_translate = (FloatingActionButton) convertView.findViewById(R.id.status_translate);
holder.status_content_translated_container = (LinearLayout) convertView.findViewById(R.id.status_content_translated_container);
holder.main_container = (LinearLayout) convertView.findViewById(R.id.main_container);
holder.status_spoiler_container = (LinearLayout) convertView.findViewById(R.id.status_spoiler_container);
holder.status_content_container = (LinearLayout) convertView.findViewById(R.id.status_content_container);
holder.status_spoiler = (TextView) convertView.findViewById(R.id.status_spoiler);
holder.status_spoiler_button = (Button) convertView.findViewById(R.id.status_spoiler_button);
holder.yandex_translate = (TextView) convertView.findViewById(R.id.yandex_translate);
holder.google_translate = (TextView) convertView.findViewById(R.id.google_translate);
holder.status_replies = (LinearLayout) convertView.findViewById(R.id.status_replies);
holder.status_replies_profile_pictures = (LinearLayout) convertView.findViewById(R.id.status_replies_profile_pictures);
holder.status_replies_text = (TextView) convertView.findViewById(R.id.status_replies_text);
holder.new_element = (ImageView) convertView.findViewById(R.id.new_element);
holder.status_action_container = (LinearLayout) convertView.findViewById(R.id.status_action_container);
holder.loader_replies = convertView.findViewById(R.id.loader_replies);
holder.card_status_container = convertView.findViewById(R.id.card_status_container);
holder.status_document_container = convertView.findViewById(R.id.status_document_container);
holder.status_content = convertView.findViewById(R.id.status_content);
holder.status_content_translated = convertView.findViewById(R.id.status_content_translated);
holder.status_account_username = convertView.findViewById(R.id.status_account_username);
holder.status_account_displayname = convertView.findViewById(R.id.status_account_displayname);
holder.status_account_profile = convertView.findViewById(R.id.status_account_profile);
holder.status_account_profile_boost = convertView.findViewById(R.id.status_account_profile_boost);
holder.status_account_profile_boost_by = convertView.findViewById(R.id.status_account_profile_boost_by);
holder.status_favorite_count = convertView.findViewById(R.id.status_favorite_count);
holder.status_reblog_count = convertView.findViewById(R.id.status_reblog_count);
holder.status_pin = convertView.findViewById(R.id.status_pin);
holder.status_toot_date = convertView.findViewById(R.id.status_toot_date);
holder.status_show_more = convertView.findViewById(R.id.status_show_more);
holder.status_more = convertView.findViewById(R.id.status_more);
holder.status_prev1 = convertView.findViewById(R.id.status_prev1);
holder.status_prev2 = convertView.findViewById(R.id.status_prev2);
holder.status_prev3 = convertView.findViewById(R.id.status_prev3);
holder.status_prev4 = convertView.findViewById(R.id.status_prev4);
holder.status_prev1_play = convertView.findViewById(R.id.status_prev1_play);
holder.status_prev2_play = convertView.findViewById(R.id.status_prev2_play);
holder.status_prev3_play = convertView.findViewById(R.id.status_prev3_play);
holder.status_prev4_play = convertView.findViewById(R.id.status_prev4_play);
holder.status_container2 = convertView.findViewById(R.id.status_container2);
holder.status_container3 = convertView.findViewById(R.id.status_container3);
holder.status_prev4_container = convertView.findViewById(R.id.status_prev4_container);
holder.status_reply = convertView.findViewById(R.id.status_reply);
holder.status_privacy = convertView.findViewById(R.id.status_privacy);
holder.status_translate = convertView.findViewById(R.id.status_translate);
holder.status_content_translated_container = convertView.findViewById(R.id.status_content_translated_container);
holder.main_container = convertView.findViewById(R.id.main_container);
holder.status_spoiler_container = convertView.findViewById(R.id.status_spoiler_container);
holder.status_content_container = convertView.findViewById(R.id.status_content_container);
holder.status_spoiler = convertView.findViewById(R.id.status_spoiler);
holder.status_spoiler_button = convertView.findViewById(R.id.status_spoiler_button);
holder.yandex_translate = convertView.findViewById(R.id.yandex_translate);
holder.google_translate = convertView.findViewById(R.id.google_translate);
holder.status_replies = convertView.findViewById(R.id.status_replies);
holder.status_replies_profile_pictures = convertView.findViewById(R.id.status_replies_profile_pictures);
holder.status_replies_text = convertView.findViewById(R.id.status_replies_text);
holder.new_element = convertView.findViewById(R.id.new_element);
holder.status_action_container = convertView.findViewById(R.id.status_action_container);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
@ -444,8 +453,11 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
if( status.getContent_translated() != null && status.getContent_translated().length() > 0){
holder.status_content_translated.setMovementMethod(null);
SpannableString spannableStringTrans = Helper.clickableElements(context, status.getContent_translated(),
status.getReblog() != null?status.getReblog().getMentions():status.getMentions(), false);
SpannableString spannableStringTrans = Helper.clickableElements(context,status.getContent_translated(),
status.getReblog() != null?status.getReblog().getMentions():status.getMentions(),
status.getReblog() != null?status.getReblog().getEmojis():status.getEmojis(),
position,
true, StatusListAdapter.this);
holder.status_content_translated.setText(spannableStringTrans, TextView.BufferType.SPANNABLE);
holder.status_content_translated.setOnLongClickListener(new View.OnLongClickListener() {
@Override
@ -466,14 +478,22 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
});
holder.status_content_translated.setMovementMethod(LinkMovementMethod.getInstance());
}
content = content.replaceAll("</p>","<br/><br/>");
content = content.replaceAll("<p>","");
if( content.endsWith("<br/><br/>") )
content = content.substring(0,content.length() -10);
holder.status_content.setMovementMethod(null);
final SpannableString spannableString = Helper.clickableElements(context,content,
status.getReblog() != null?status.getReblog().getMentions():status.getMentions(), true);
holder.status_content.setText(spannableString, TextView.BufferType.SPANNABLE);
if( status.getContents() != null){
holder.status_content.setText(status.getContents(), TextView.BufferType.SPANNABLE);
}else{
content = content.replaceAll("</p>","<br/><br/>");
content = content.replaceAll("<p>","");
if( content.endsWith("<br/><br/>") )
content = content.substring(0,content.length() -10);
holder.status_content.setMovementMethod(null);
final SpannableString spannableString = Helper.clickableElements(context,content,
status.getReblog() != null?status.getReblog().getMentions():status.getMentions(),
status.getReblog() != null?status.getReblog().getEmojis():status.getEmojis(),
position,
true, StatusListAdapter.this);
holder.status_content.setText(spannableString, TextView.BufferType.SPANNABLE);
}
holder.status_content.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
@ -481,6 +501,7 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
return false;
}
});
holder.status_content.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
@ -727,13 +748,13 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
});
}else {
if( theme == Helper.THEME_LIGHT){
if( position == ShowConversationActivity.position){
if( position == conversationPosition){
holder.main_container.setBackgroundResource(R.color.mastodonC3_);
}else {
holder.main_container.setBackgroundResource(R.color.mastodonC3__);
}
}else {
if( position == ShowConversationActivity.position){
if( position == conversationPosition){
holder.main_container.setBackgroundResource(R.color.mastodonC1___);
}else {
holder.main_container.setBackgroundResource(R.color.mastodonC1_);
@ -1115,7 +1136,7 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
});
return convertView;
}
return convertView;
}
@ -1154,32 +1175,34 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
ImageView imageView;
if( i == 0) {
imageView = holder.status_prev1;
if( attachment.getType().equals("image"))
if( attachment.getType().equals("image") || attachment.getType().equals("unknown"))
holder.status_prev1_play.setVisibility(View.GONE);
else
holder.status_prev1_play.setVisibility(View.VISIBLE);
}else if( i == 1) {
imageView = holder.status_prev2;
if( attachment.getType().equals("image"))
if( attachment.getType().equals("image") || attachment.getType().equals("unknown"))
holder.status_prev2_play.setVisibility(View.GONE);
else
holder.status_prev2_play.setVisibility(View.VISIBLE);
}else if(i == 2) {
imageView = holder.status_prev3;
if( attachment.getType().equals("image"))
if( attachment.getType().equals("image") || attachment.getType().equals("unknown"))
holder.status_prev3_play.setVisibility(View.GONE);
else
holder.status_prev3_play.setVisibility(View.VISIBLE);
}else {
imageView = holder.status_prev4;
if( attachment.getType().equals("image"))
if( attachment.getType().equals("image") || attachment.getType().equals("unknown"))
holder.status_prev4_play.setVisibility(View.GONE);
else
holder.status_prev4_play.setVisibility(View.VISIBLE);
}
String url = attachment.getPreview_url();
if( url == null || url.trim().equals(""))
if( url == null || url.trim().equals("") )
url = attachment.getUrl();
else if( attachment.getType().equals("unknown"))
url = attachment.getRemote_url();
if( !url.trim().contains("missing.png"))
imageLoader.displayImage(url, imageView, optionsAttachment);
final int finalPosition = position;
@ -1315,6 +1338,16 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
}
}
@Override
public void onRetrieveEmoji(int position, SpannableString spannableString, Boolean error) {
statuses.get(position).setContents(spannableString);
if( !statuses.get(position).isEmojiFound()) {
statuses.get(position).setEmojiFound(true);
statusListAdapter.notifyDataSetChanged();
}
}
@Override
public void onTranslatedTextview(int position, String translatedResult, Boolean error) {
if( error){
@ -1406,6 +1439,8 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf
}
private class ViewHolder {
LinearLayout status_content_container;
LinearLayout status_spoiler_container;

View File

@ -14,14 +14,12 @@ package fr.gouv.etalab.mastodon.fragments;
* You should have received a copy of the GNU General Public License along with Mastalab; if not,
* see <http://www.gnu.org/licenses>. */
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
@ -66,7 +64,6 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou
private String targetedId;
private boolean swiped;
private ListView lv_accounts;
private String instanceValue;
boolean hideHeader;
@Override
@ -83,7 +80,6 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou
type = (RetrieveAccountsAsyncTask.Type) bundle.get("type");
targetedId = bundle.getString("targetedId", null);
hideHeader = bundle.getBoolean("hideHeader", false);
instanceValue = bundle.getString("hideHeaderValue", null);
if( bundle.containsKey("accounts")){
ArrayList<Parcelable> accountsReceived = bundle.getParcelableArrayList("accounts");
assert accountsReceived != null;
@ -98,13 +94,12 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou
flag_loading = true;
swiped = false;
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
lv_accounts = (ListView) rootView.findViewById(R.id.lv_accounts);
swipeRefreshLayout = rootView.findViewById(R.id.swipeContainer);
lv_accounts = rootView.findViewById(R.id.lv_accounts);
mainLoader = (RelativeLayout) rootView.findViewById(R.id.loader);
nextElementLoader = (RelativeLayout) rootView.findViewById(R.id.loading_next_accounts);
textviewNoAction = (RelativeLayout) rootView.findViewById(R.id.no_action);
mainLoader = rootView.findViewById(R.id.loader);
nextElementLoader = rootView.findViewById(R.id.loading_next_accounts);
textviewNoAction = rootView.findViewById(R.id.no_action);
mainLoader.setVisibility(View.VISIBLE);
nextElementLoader.setVisibility(View.GONE);
accountsListAdapter = new AccountsListAdapter(context, type, targetedId, this.accounts);
@ -115,31 +110,11 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou
if (hideHeader && Build.VERSION.SDK_INT >= 21)
ViewCompat.setNestedScrollingEnabled(lv_accounts, true);
lv_accounts.setOnScrollListener(new AbsListView.OnScrollListener() {
int lastFirstVisibleItem = 0;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (hideHeader && Build.VERSION.SDK_INT < 21) {
if(firstVisibleItem == 0 && Helper.listIsAtTop(lv_accounts)){
Intent intent = new Intent(Helper.HEADER_ACCOUNT+instanceValue);
intent.putExtra("hide", false);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}else if (view.getId() == lv_accounts.getId() && totalItemCount > visibleItemCount) {
final int currentFirstVisibleItem = lv_accounts.getFirstVisiblePosition();
if (currentFirstVisibleItem > lastFirstVisibleItem) {
Intent intent = new Intent(Helper.HEADER_ACCOUNT + instanceValue);
intent.putExtra("hide", true);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else if (currentFirstVisibleItem < lastFirstVisibleItem) {
Intent intent = new Intent(Helper.HEADER_ACCOUNT + instanceValue);
intent.putExtra("hide", false);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
lastFirstVisibleItem = currentFirstVisibleItem;
}
}
if (firstVisibleItem + visibleItemCount == totalItemCount) {
if (!flag_loading) {
flag_loading = true;

View File

@ -61,6 +61,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
private StatusListAdapter statusListAdapter;
private String max_id;
private List<Status> statuses;
private ArrayList<String> knownId;
private RetrieveFeedsAsyncTask.Type type;
private RelativeLayout mainLoader, nextElementLoader, textviewNoAction;
private boolean firstLoad;
@ -73,8 +74,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
private int behaviorWithAttachments;
private boolean showMediaOnly, showPinned;
private int positionSpinnerTrans;
private boolean hideHeader;
private String instanceValue;
private String lastReadStatus;
private Intent streamingFederatedIntent, streamingLocalIntent;
@ -85,17 +84,17 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_status, container, false);
statuses = new ArrayList<>();
knownId = new ArrayList<>();
context = getContext();
Bundle bundle = this.getArguments();
boolean comesFromSearch = false;
hideHeader = false;
boolean hideHeader = false;
showMediaOnly = false;
showPinned = false;
if (bundle != null) {
type = (RetrieveFeedsAsyncTask.Type) bundle.get("type");
targetedId = bundle.getString("targetedId", null);
tag = bundle.getString("tag", null);
instanceValue = bundle.getString("hideHeaderValue", null);
hideHeader = bundle.getBoolean("hideHeader", false);
showMediaOnly = bundle.getBoolean("showMediaOnly",false);
showPinned = bundle.getBoolean("showPinned",false);
@ -104,6 +103,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
assert statusesReceived != null;
for(Parcelable status: statusesReceived){
statuses.add((Status) status);
knownId.add(((Status) status).getId());
}
comesFromSearch = true;
}
@ -116,15 +116,15 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
isOnWifi = Helper.isOnWIFI(context);
positionSpinnerTrans = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
swipeRefreshLayout = rootView.findViewById(R.id.swipeContainer);
behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
if( type == RetrieveFeedsAsyncTask.Type.HOME)
lastReadStatus = sharedpreferences.getString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, null);
lv_status = (ListView) rootView.findViewById(R.id.lv_status);
mainLoader = (RelativeLayout) rootView.findViewById(R.id.loader);
nextElementLoader = (RelativeLayout) rootView.findViewById(R.id.loading_next_status);
textviewNoAction = (RelativeLayout) rootView.findViewById(R.id.no_action);
lv_status = rootView.findViewById(R.id.lv_status);
mainLoader = rootView.findViewById(R.id.loader);
nextElementLoader = rootView.findViewById(R.id.loading_next_status);
textviewNoAction = rootView.findViewById(R.id.no_action);
mainLoader.setVisibility(View.VISIBLE);
nextElementLoader.setVisibility(View.GONE);
statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, this.statuses);
@ -132,11 +132,10 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
if( !comesFromSearch){
//Hide account header when scrolling for ShowAccountActivity
if (hideHeader )
if (hideHeader)
ViewCompat.setNestedScrollingEnabled(lv_status, true);
lv_status.setOnScrollListener(new AbsListView.OnScrollListener() {
int lastFirstVisibleItem = 0;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
@ -166,6 +165,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
public void onRefresh() {
max_id = null;
statuses = new ArrayList<>();
knownId = new ArrayList<>();
firstLoad = true;
flag_loading = true;
swiped = true;
@ -229,9 +229,9 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
nextElementLoader.setVisibility(View.GONE);
//Discards 404 - error which can often happen due to toots which have been deleted
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
if( apiResponse.getError() != null && !apiResponse.getError().getError().startsWith("404 -")){
if( apiResponse.getError() != null ){
boolean show_error_messages = sharedpreferences.getBoolean(Helper.SET_SHOW_ERROR_MESSAGES, true);
if( show_error_messages)
if( show_error_messages && !apiResponse.getError().getError().startsWith("404 -"))
Toast.makeText(context, apiResponse.getError().getError(),Toast.LENGTH_LONG).show();
swipeRefreshLayout.setRefreshing(false);
swiped = false;
@ -253,10 +253,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
}
if( statuses != null && statuses.size() > 0) {
ArrayList<String> knownId = new ArrayList<>();
for(Status st: this.statuses){
knownId.add(st.getId());
}
for(Status tmpStatus: statuses){
if( !knownId.contains(tmpStatus.getId())) {
if( type == RetrieveFeedsAsyncTask.Type.HOME && firstLoad && lastReadStatus != null && Long.parseLong(tmpStatus.getId()) > Long.parseLong(lastReadStatus)){
@ -266,6 +262,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
tmpStatus.setNew(false);
}
this.statuses.add(tmpStatus);
knownId.add(tmpStatus.getId());
}
}
@ -307,7 +304,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
if( type == RetrieveFeedsAsyncTask.Type.HOME) {
if (context == null)
return;
if (status != null) {
if (status != null && !knownId.contains(status.getId())) {
//Update the id of the last toot retrieved
MainActivity.lastHomeId = status.getId();
int index = lv_status.getFirstVisiblePosition() + 1;
@ -315,6 +312,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
int top = (v == null) ? 0 : v.getTop();
status.setReplies(new ArrayList<Status>());
statuses.add(0,status);
knownId.add(0,status.getId());
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
if( !status.getAccount().getId().equals(userId))
@ -327,17 +325,21 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
}else if(type == RetrieveFeedsAsyncTask.Type.PUBLIC || type == RetrieveFeedsAsyncTask.Type.LOCAL){
if (context == null)
return;
//Avoids the array to be too big...
if (status != null) {
if (status != null && !knownId.contains(status.getId())) {
status.setReplies(new ArrayList<Status>());
status.setNew(false);
if (lv_status.getFirstVisiblePosition() == 0) {
status.setReplies(new ArrayList<Status>());
status.setNew(false);
statuses.add(0, status);
statusListAdapter.notifyDataSetChanged();
} else {
status.setReplies(new ArrayList<Status>());
int index = lv_status.getFirstVisiblePosition() + 1;
View v = lv_status.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
statuses.add(0, status);
statusListAdapter.notifyDataSetChanged();
lv_status.setSelectionFromTop(index, top);
}
knownId.add(0, status.getId());
if (textviewNoAction.getVisibility() == View.VISIBLE)
textviewNoAction.setVisibility(View.GONE);
}
@ -518,10 +520,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
@Override
public void onRetrieveMissingFeeds(List<Status> statuses) {
if( statuses != null && statuses.size() > 0) {
ArrayList<String> knownId = new ArrayList<>();
for (Status st : this.statuses) {
knownId.add(st.getId());
}
if( lv_status.getFirstVisiblePosition() > 1 ) {
int index = lv_status.getFirstVisiblePosition() + statuses.size();
View v = lv_status.getChildAt(0);
@ -530,6 +528,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
if (!knownId.contains(statuses.get(i).getId())) {
if (type == RetrieveFeedsAsyncTask.Type.HOME)
statuses.get(i).setNew(true);
knownId.add(0, statuses.get(i).getId());
statuses.get(i).setReplies(new ArrayList<Status>());
this.statuses.add(0, statuses.get(i));
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
@ -545,6 +544,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn
if (!knownId.contains(statuses.get(i).getId())) {
if (type == RetrieveFeedsAsyncTask.Type.HOME)
statuses.get(i).setNew(true);
knownId.add(0,statuses.get(i).getId());
statuses.get(i).setReplies(new ArrayList<Status>());
this.statuses.add(0, statuses.get(i));
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);

View File

@ -49,13 +49,16 @@ import mastodon.etalab.gouv.fr.mastodon.R;
*/
public class CrossActions {
public static void doCrossAction(final Context context, final Status status, final API.StatusAction doAction, final BaseAdapter baseAdapter, final OnPostActionInterface onPostActionInterface, boolean limitedToOwner){
private static API.StatusAction doAction;
public static void doCrossAction(final Context context, final Status status, API.StatusAction makeAction, final BaseAdapter baseAdapter, final OnPostActionInterface onPostActionInterface, boolean limitedToOwner){
List<Account> accounts = connectedAccounts(context, status, limitedToOwner);
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
doAction = makeAction;
boolean undoAction = (doAction == API.StatusAction.UNPIN || doAction == API.StatusAction.UNREBLOG || doAction == API.StatusAction.UNFAVOURITE );
//Undo actions won't ask for choosing a user
if( accounts.size() == 1 || undoAction ) {
if( accounts.size() == 1 || (undoAction && limitedToOwner) ) {
boolean confirmation = false;
if( doAction == API.StatusAction.UNFAVOURITE || doAction == API.StatusAction.FAVOURITE)
@ -82,6 +85,7 @@ public class CrossActions {
accountArray[i] = account;
i++;
}
builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
@ -91,10 +95,17 @@ public class CrossActions {
builderSingle.setAdapter(accountsSearchAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Account selectedAccount = accountArray[which];
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account loggedAccount = new AccountDAO(context, db).getAccountByID(userId);
//Cross action can only be create elements (boost/fav)
if( doAction == API.StatusAction.UNREBLOG)
doAction = API.StatusAction.REBLOG;
else if( doAction == API.StatusAction.UNFAVOURITE)
doAction = API.StatusAction.FAVOURITE;
if(loggedAccount.getInstance().equals(selectedAccount.getInstance())){
new PostActionAsyncTask(context, selectedAccount, doAction, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else{ //Account is from another instance

View File

@ -18,12 +18,13 @@ package fr.gouv.etalab.mastodon.helper;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.Color;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.RequiresApi;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.app.DownloadManager;
import android.app.PendingIntent;
@ -57,20 +58,20 @@ import android.support.design.widget.NavigationView;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Patterns;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.MimeTypeMap;
@ -90,7 +91,10 @@ import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.ViewScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.NonViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
@ -108,7 +112,6 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
@ -125,16 +128,15 @@ import fr.gouv.etalab.mastodon.activities.HashTagActivity;
import fr.gouv.etalab.mastodon.activities.LoginActivity;
import fr.gouv.etalab.mastodon.activities.MainActivity;
import fr.gouv.etalab.mastodon.activities.ShowAccountActivity;
import fr.gouv.etalab.mastodon.activities.TootActivity;
import fr.gouv.etalab.mastodon.activities.WebviewActivity;
import fr.gouv.etalab.mastodon.asynctasks.RemoveAccountAsyncTask;
import fr.gouv.etalab.mastodon.client.API;
import fr.gouv.etalab.mastodon.client.Entities.Account;
import fr.gouv.etalab.mastodon.client.Entities.Emojis;
import fr.gouv.etalab.mastodon.client.Entities.Mention;
import fr.gouv.etalab.mastodon.client.Entities.Status;
import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader;
import fr.gouv.etalab.mastodon.fragments.DisplayNotificationsFragment;
import fr.gouv.etalab.mastodon.fragments.DisplayStatusFragment;
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveEmojiInterface;
import fr.gouv.etalab.mastodon.sqlite.AccountDAO;
import fr.gouv.etalab.mastodon.sqlite.Sqlite;
import mastodon.etalab.gouv.fr.mastodon.R;
@ -612,7 +614,14 @@ public class Helper {
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP);
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// build notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
String channelId = "channel_"+ String.valueOf(notificationId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, title, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.notification_icon)
.setTicker(message)
.setWhen(System.currentTimeMillis())
@ -1124,6 +1133,7 @@ public class Helper {
}
/**
* Check if the status contents mentions & tags and fills the content with ClickableSpan
* Click on account => ShowAccountActivity
@ -1133,8 +1143,9 @@ public class Helper {
* @param mentions List<Mention>
* @return TextView
*/
public static SpannableString clickableElements(final Context context, String fullContent, List<Mention> mentions, boolean useHTML) {
SpannableString spannableString;
public static SpannableString clickableElements(final Context context, String fullContent, List<Mention> mentions, final List<Emojis> emojis, final int position, boolean useHTML, final OnRetrieveEmojiInterface listener) {
final SpannableString spannableString;
if( useHTML) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
spannableString = new SpannableString(Html.fromHtml(fullContent, Html.FROM_HTML_MODE_LEGACY));
@ -1179,6 +1190,53 @@ public class Helper {
}
}
if( emojis != null && emojis.size() > 0 ) {
final int[] i = {0};
int emojiToSearch = 0;
for (final Emojis emoji : emojis) {
final String targetedEmoji = ":" + emoji.getShortcode() + ":";
for(int startPosition = -1 ; (startPosition = spannableString.toString().indexOf(targetedEmoji, startPosition + 1)) != -1 ; startPosition++){
emojiToSearch++;
}
}
ImageLoader imageLoader;
DisplayImageOptions options = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false)
.cacheOnDisk(true).resetViewBeforeLoading(true).build();
imageLoader = ImageLoader.getInstance();
for (final Emojis emoji : emojis) {
final String targetedEmoji = ":" + emoji.getShortcode() + ":";
if (spannableString.toString().contains(targetedEmoji)) {
//emojis can be used several times so we have to loop
for(int startPosition = -1 ; (startPosition = spannableString.toString().indexOf(targetedEmoji, startPosition + 1)) != -1 ; startPosition++){
final int endPosition = startPosition + targetedEmoji.length();
final int finalStartPosition = startPosition;
NonViewAware imageAware = new NonViewAware(new ImageSize(50, 50), ViewScaleType.CROP);
final int finalEmojiToSearch = emojiToSearch;
imageLoader.displayImage(emoji.getUrl(), imageAware, options, new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
spannableString.setSpan(
new ImageSpan(context,
Bitmap.createScaledBitmap(loadedImage, (int)Helper.convertDpToPixel(20, context),
(int)Helper.convertDpToPixel(20, context), false)), finalStartPosition,
endPosition, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
i[0]++;
if( i[0] == finalEmojiToSearch)
listener.onRetrieveEmoji(position, spannableString, false);
}
@Override
public void onLoadingFailed(java.lang.String imageUri, android.view.View view, FailReason failReason) {
i[0]++;
}
});
}
}
}
}
//Deals with mention to make them clickable
if( mentions != null && mentions.size() > 0 ) {
//Looping through accounts which are mentioned
@ -1230,6 +1288,7 @@ public class Helper {
}
}, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
return spannableString;
}

View File

@ -17,11 +17,12 @@ package fr.gouv.etalab.mastodon.interfaces;
import fr.gouv.etalab.mastodon.client.Entities.Context;
import fr.gouv.etalab.mastodon.client.Entities.Error;
import fr.gouv.etalab.mastodon.client.Entities.Status;
/**
* Created by Thomas on 04/05/2017.
* Interface when a context for a status has been retrieved
*/
public interface OnRetrieveContextInterface {
void onRetrieveFeeds(Context context, Error error);
void onRetrieveContext(Context context, Status statusFirst, Error error);
}

View File

@ -0,0 +1,26 @@
/* Copyright 2017 Thomas Schneider
*
* This file is a part of Mastalab
*
* 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.
*
* Mastalab 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 Mastalab; if not,
* see <http://www.gnu.org/licenses>. */
package fr.gouv.etalab.mastodon.interfaces;
import android.text.SpannableString;
/**
* Created by Thomas on 19/10/2017.
* Interface when retrieving emojis
*/
public interface OnRetrieveEmojiInterface {
void onRetrieveEmoji(int position, SpannableString spannableString, Boolean error);
}

View File

@ -84,9 +84,9 @@ public class HomeTimelineSyncJob extends Job implements OnRetrieveHomeTimelineSe
}
return new JobRequest.Builder(HomeTimelineSyncJob.HOME_TIMELINE)
.setPeriodic(TimeUnit.MINUTES.toMillis(Helper.MINUTES_BETWEEN_HOME_TIMELINE), TimeUnit.MINUTES.toMillis(5))
.setPersisted(true)
.setUpdateCurrent(updateCurrent)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequiredNetworkType(JobRequest.NetworkType.METERED)
.setRequiresBatteryNotLow(true)
.setRequirementsEnforced(false)
.build()
.schedule();

View File

@ -85,9 +85,9 @@ public class NotificationsSyncJob extends Job implements OnRetrieveNotifications
return new JobRequest.Builder(NotificationsSyncJob.NOTIFICATION_REFRESH)
.setPeriodic(TimeUnit.MINUTES.toMillis(Helper.MINUTES_BETWEEN_NOTIFICATIONS_REFRESH), TimeUnit.MINUTES.toMillis(5))
.setPersisted(true)
.setUpdateCurrent(updateCurrent)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequiredNetworkType(JobRequest.NetworkType.METERED)
.setRequiresBatteryNotLow(true)
.setRequirementsEnforced(false)
.build()
.schedule();

View File

@ -79,9 +79,8 @@ public class ScheduledTootsSyncJob extends Job {
int jobId = new JobRequest.Builder(ScheduledTootsSyncJob.SCHEDULED_TOOT)
.setExecutionWindow(startMs, endMs)
.setPersisted(true)
.setUpdateCurrent(false)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequiredNetworkType(JobRequest.NetworkType.METERED)
.setRequirementsEnforced(false)
.build()
.schedule();

View File

@ -44,12 +44,15 @@
android:id="@+id/login_instance"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:maxLines="1"
android:inputType="textWebEmailAddress"
android:hint="@string/instance_example"
/>
<EditText
android:id="@+id/login_uid"
android:layout_width="300dp"
android:maxLines="1"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="@string/email"
@ -57,6 +60,7 @@
<EditText
android:id = "@+id/login_passwd"
android:inputType="textPassword"
android:maxLines="1"
android:hint="@string/password"
android:layout_width="300dp"
android:layout_height="wrap_content"

View File

@ -44,13 +44,16 @@
android:id="@+id/login_instance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:inputType="textWebEmailAddress"
android:maxLines="1"
android:hint="@string/instance_example"
/>
<EditText
android:id="@+id/login_uid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:inputType="textEmailAddress"
android:hint="@string/email"
/>
@ -58,6 +61,7 @@
android:id = "@+id/login_passwd"
android:inputType="textPassword"
android:hint="@string/password"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

View File

@ -33,13 +33,13 @@
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UseCompoundDrawables">
<ImageView
android:layout_gravity="center_horizontal"
android:id="@+id/account_pp"
android:layout_margin="10dp"
android:layout_width="60dp"
android:layout_height="60dp"
tools:ignore="ContentDescription" />
android:layout_margin="10dp"
tools:ignore="ContentDescription"/>
<LinearLayout
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"

View File

@ -84,6 +84,7 @@
android:layout_marginLeft="10dp"
android:focusableInTouchMode="false"
android:id="@+id/scheduled_toot_date"
style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

View File

@ -193,7 +193,6 @@
<!-- About -->
<string name="about_vesrion">Version %1$s</string>
<string name="about_developer">Entwickler:</string>
<string name="about_developer_action">\\@tschneider</string>
<string name="about_license">Lizenz:</string>
<string name="about_license_action">GNU GPL V3</string>
<string name="about_code">Quellcode:</string>

View File

@ -189,7 +189,6 @@
<!-- About -->
<string name="about_vesrion">Version %1$s</string>
<string name="about_developer">Développeur :</string>
<string name="about_developer_action">\@tschneider</string>
<string name="about_license">Licence : </string>
<string name="about_license_action">GNU GPL V3</string>
<string name="about_code">Code source : </string>

View File

@ -0,0 +1,436 @@
<resources>
<string name="navigation_drawer_open">Menu openen</string>
<string name="navigation_drawer_close">Menu sluiten</string>
<string name="action_about">Over</string>
<string name="action_about_instance">Over deze Mastodon-server</string>
<string name="action_privacy">Privacy</string>
<string name="action_cache">Buffer</string>
<string name="action_logout">Uitloggen</string>
<string name="login">Inloggen</string>
<!-- common -->
<string name="close">Sluiten</string>
<string name="yes">Ja</string>
<string name="no">Nee</string>
<string name="cancel">Annuleren</string>
<string name="download">Downloaden</string>
<string name="download_file">%1$s downloaden</string>
<string name="download_over">Downloaden voltooid</string>
<string name="save_file">%1$s opslaan</string>
<string name="save_over">Media opgeslagen</string>
<string name="download_from">Bestand: %1$s</string>
<string name="password">Wachtwoord</string>
<string name="email">E-mail</string>
<string name="accounts">Accounts</string>
<string name="toots">Toots</string>
<string name="tags">Tags</string>
<string name="token">Aanmeldcode</string>
<string name="save">Opslaan</string>
<string name="restore">Herstellen</string>
<string name="two_factor_authentification">Tweestapsverificatie?</string>
<string name="other_instance">Andere Mastodon-server dan mastodon.social?</string>
<string name="no_result">Geen resultaten!</string>
<string name="instance">Mastodon-server</string>
<string name="instance_example">Server: bv. mastodon.social</string>
<string name="toast_account_changed">Werkt nu met account %1$s</string>
<string name="add_account">Account toevoegen</string>
<string name="clipboard">De inhoud van deze toot is naar het klembord gekopieerd</string>
<string name="change">Veranderen</string>
<string name="choose_picture">Kies een afbeelding…</string>
<string name="clear">Leegmaken</string>
<string name="microphone">Microfoon</string>
<string name="speech_prompt">Zeg naar iets</string>
<string name="speech_not_supported">Sorry! Jouw apparaat ondersteund geen geluidsinvoer!</string>
<string name="delete_all">Alles verwijderen</string>
<string name="translate_toot">Deze toot vertalen.</string>
<string name="schedule">Inplannen</string>
<string name="text_size">Tekst- en pictogramgrootte</string>
<string name="text_size_change">De huidige tekstgrootte veranderen:</string>
<string name="icon_size_change">De huidige pictogramgrootte veranderen:</string>
<string name="next">Volgende</string>
<string name="previous">Vorige</string>
<string name="open_with">Open met</string>
<string name="validate">Bevestigen</string>
<string name="media">Media</string>
<string name="share_with">Delen met</string>
<string name="shared_via">Gedeeld via Mastalab</string>
<string name="replies">Reacties</string>
<string name="username">Gebruikersnaam</string>
<string name="drafts">Concepten</string>
<string name="new_data">Nieuwe gegevens beschikbaar! Wil je deze tonen?</string>
<string name="favourite">Favorieten</string>
<string name="follow">Nieuwe volgers</string>
<string name="mention">Meldingen</string>
<string name="reblog">Boosts</string>
<string name="show_boosts">Boosts tonen</string>
<string name="show_replies">Reacties tonen</string>
<string name="action_open_in_web">Open in webbrowser</string>
<!--- Menu -->
<string name="home_menu">Start</string>
<string name="local_menu">Lokale tijdlijn</string>
<string name="global_menu">Globale tijdlijn</string>
<string name="neutral_menu_title">Opties</string>
<string name="favorites_menu">Favorieten</string>
<string name="communication_menu_title">Communicatie</string>
<string name="muted_menu">Genegeerde gebruikers</string>
<string name="blocked_menu">Geblokkeerde gebruikers</string>
<string name="remote_follow_menu">Extern volgen</string>
<string name="notifications">Meldingen</string>
<string name="follow_request">Volgverzoeken</string>
<string name="optimization">Optimalisatie</string>
<string name="settings">Instellingen</string>
<string name="profile">Profiel</string>
<string name="make_a_choice">Wat wil je doen?</string>
<string name="delete_account_title">Account verwijderen</string>
<string name="delete_account_message">Account %1$s uit deze app verwijderen?</string>
<string name="send_email">E-mail verzenden</string>
<string name="choose_file">Kies een bestand</string>
<string name="choose_file_error">Geen bestandsbeheerder gevonden!</string>
<string name="click_to_change">Op het pad klikken om het te veranderen</string>
<string name="failed">Mislukt!</string>
<string name="scheduled_toots">Ingeplande toots</string>
<!-- Status -->
<string name="no_status">Geen toot om weer te geven</string>
<string name="fav_added">De toot is aan jouw favorieten toegevoegd</string>
<string name="fav_removed">De toot is uit jouw favorieten verwijderd!</string>
<string name="reblog_added">De toot is geboost!</string>
<string name="reblog_removed">De toot is niet meer geboost!</string>
<string name="reblog_by">Gedeeld via %1$s</string>
<string name="favourite_add">Deze toot aan jouw favorieten toevoegen?</string>
<string name="favourite_remove">Deze toot uit jouw favorieten verwijderen?</string>
<string name="reblog_add">Deze toot boosten?</string>
<string name="reblog_remove">Deze toot niet meer boosten?</string>
<string name="pin_add">Deze toot aan jouw profielpagina vastmaken?</string>
<string name="pin_remove">Deze toot van profielpagina losmaken?</string>
<string name="more_action_1">Negeren</string>
<string name="more_action_2">Blokkeren</string>
<string name="more_action_3">Rapporteren</string>
<string name="more_action_4">Verwijderen</string>
<string name="more_action_5">Kopiëren</string>
<string name="more_action_6">Delen</string>
<string name="more_action_7">Vermelden</string>
<string-array name="more_action_confirm">
<item>Account negeren?</item>
<item>Account blokkeren?</item>
<item>Toot rapporteren?</item>
</string-array>
<string-array name="more_action_owner_confirm">
<item>Toot verwijderen?</item>
</string-array>
<plurals name="preview_replies">
<item quantity="one">%d reactie</item>
<item quantity="other">%d reacties</item>
</plurals>
<!-- Date -->
<plurals name="date_seconds">
<item quantity="one">%d seconde geleden</item>
<item quantity="other">%d seconden geleden</item>
</plurals>
<plurals name="date_minutes">
<item quantity="one">%d minuut geleden</item>
<item quantity="other">%d minuten geleden</item>
</plurals>
<plurals name="date_hours">
<item quantity="one">%d uur geleden</item>
<item quantity="other">%d uur geleden</item>
</plurals>
<string name="date_yesterday">Gisteren</string>
<string name="date_day_before_yesterday">Eergisteren</string>
<string name="date_day">%d dagen geleden</string>
<plurals name="date_month">
<item quantity="one">%d maand geleden</item>
<item quantity="other">%d maanden geleden</item>
</plurals>
<plurals name="date_year">
<item quantity="one">Een jaar geleden</item>
<item quantity="other">%d jaar geleden</item>
</plurals>
<!-- TOOT -->
<string name="toot_cw_placeholder">Waarschuwing</string>
<string name="toot_placeholder">Wat wil je kwijt?</string>
<string name="toot_it">TOOT!</string>
<string name="cw">cw</string>
<string name="toot_title">Schrijf een toot</string>
<string name="toot_title_reply">Reageer op een toot</string>
<string name="toot_no_space">Je hebt de limiet van 500 tekens bereikt!</string>
<string name="toot_select_image">Kies een afbeelding of video</string>
<string name="toot_select_image_error">Tijdens het kiezen van een afbeelding of video heeft zich een fout voorgedaan!</string>
<string name="toot_delete_media">Media verwijderen?</string>
<string name="toot_error_no_content">Jouw toot is leeg!</string>
<string name="toot_visibility_tilte">Zichtbaarheid van toot</string>
<string name="toots_visibility_tilte">Standaard zichtbaarheid van toot: </string>
<string name="toot_sent">De toot is verzonden!</string>
<string name="toot_reply_content_title">Je reageert op deze toot:</string>
<string name="toot_sensitive">Gevoelige inhoud?</string>
<string-array name="toot_visibility">
<item>Op openbare tijdlijnen tonen</item>
<item>Niet op openbare tijdlijnen tonen</item>
<item>Alleen aan volgers tonen</item>
<item>Alleen aan vermelde gebruikers tonen</item>
</string-array>
<string name="no_draft">Geen concepten!</string>
<string name="choose_toot">Kies een toot</string>
<string name="choose_accounts">Kies een account</string>
<string name="remove_draft">Concept verwijderen?</string>
<string name="show_reply">Klik om de oorspronkelijke toot te tonen</string>
<!-- Instance -->
<string name="instance_no_description">Geen beschrijving beschikbaar!</string>
<!-- About -->
<string name="about_vesrion">Release %1$s</string>
<string name="about_developer">Ontwikkelaar:</string>
<string name="about_license">Licentie: </string>
<string name="about_license_action">GNU GPL V3</string>
<string name="about_code">Broncode: </string>
<string name="about_code_action">Bitbucket</string>
<string name="about_yandex">Vertaling van toots:</string>
<string name="about_thekinrar">Servers zoeken:</string>
<string name="about_thekinrar_action">instances.social</string>
<string name="thanks_text_logo">Ontwerper pictogram:</string>
<!-- Conversation -->
<string name="conversation">Conversatie</string>
<!-- Accounts -->
<string name="no_accounts">Geen account om weer te geven</string>
<string name="no_follow_request">Geen volgverzoeken</string>
<string name="status_cnt">Toots \n %d</string>
<string name="following_cnt">Volgt \n %d</string>
<string name="followers_cnt">Volgers \n %d</string>
<string name="pins_cnt">Vastgezet \n %d</string>
<string name="authorize">Goedkeuren</string>
<string name="reject">Afkeuren</string>
<!-- Scheduled toots -->
<string name="no_scheduled_toots">Geen ingeplande toots!</string>
<string name="no_scheduled_toots_indications">Schrijf een toot en kies dan <b>Inplannen</b> in het menu rechtsboven.</string>
<string name="remove_scheduled">Ingeplande toot verwijderent?</string>
<string name="media_count">Media: %d</string>
<string name="toot_scheduled">De toot is ingepland!</string>
<string name="toot_scheduled_date">De toot moet wel in de toekomst ingepland worden!</string>
<string name="warning_battery">Energiebesparing is ingeschakeld! Het inplannen werkt mogelijk niet zoals verwacht.</string>
<!-- Notifications -->
<string name="no_notifications">Je hebt nog geen meldingen</string>
<string name="notif_mention">vermeldde jou</string>
<string name="notif_reblog">boostte jouw toot</string>
<string name="notif_favourite">markeerde jouw toot als favoriet</string>
<string name="notif_follow">volgt jou nu</string>
<string name="notif_pouet">Nieuwe toot van %1$s</string>
<plurals name="other_notifications">
<item quantity="one">en één andere melding</item>
<item quantity="other">en %d andere meldingen</item>
</plurals>
<plurals name="other_notif_hometimeline">
<item quantity="one">en één andere toot</item>
<item quantity="other">en %d andere toots</item>
</plurals>
<string name="delete_notification_ask">Deze melding verwijderen?</string>
<string name="delete_notification_ask_all">Alle meldingen verwijderen?</string>
<string name="delete_notification">De melding is verwijderd!</string>
<string name="delete_notification_all">Alle meldingen zijn verwijderd!</string>
<!-- HEADER -->
<string name="following">Volgt</string>
<string name="followers">Volgers</string>
<string name="pinned_toots">Vastgezet</string>
<!-- TOAST -->
<string name="client_error">Niet in staat om client-id te verkrijgen!</string>
<string name="no_internet">Geen internetverbinding!</string>
<string name="toast_block">Account is geblokkeerd!</string>
<string name="toast_unblock">Account is gedeblokkeerd!</string>
<string name="toast_mute">Account wordt nu genegeerd!</string>
<string name="toast_unmute">Account wordt niet meer genegeerd!</string>
<string name="toast_follow">Account wordt nu gevolgd!</string>
<string name="toast_unfollow">Account wordt niet meer gevolgd!</string>
<string name="toast_reblog">Toot is geboost!</string>
<string name="toast_unreblog">Toot wordt niet meer geboost!</string>
<string name="toast_favourite">Toot is als favoriet gemarkeerd!</string>
<string name="toast_unfavourite">Toot is niet meer als favoriet gemarkeerd!</string>
<string name="toast_report">Toot is gerapporteerd!</string>
<string name="toast_unstatus">Toot is verwijderd!</string>
<string name="toast_pin">Toot is vastgezet!</string>
<string name="toast_unpin">Toot is losgemaakt!</string>
<string name="toast_error">Oeps! Er ging wat mis!</string>
<string name="toast_code_error">Er ging wat mis! De Mastodon-server gaf geen autorisatiecode terug!</string>
<string name="toast_error_instance">De domeinnaam van de Mastodon-server is onjuist!</string>
<string name="toast_error_loading_account">Er ging wat mis tijdens het omschakelen van accounts!</string>
<string name="toast_error_search">Er ging wat mis tijdens het zoeken!</string>
<string name="toast_error_login">Kan niet inloggen!</string>
<string name="toast_update_credential_ok">De profielgegevens zijn opgeslagen!</string>
<string name="nothing_to_do">Er valt niets te doen</string>
<string name="toast_saved">Media is opgeslagen!</string>
<string name="toast_error_translate">Er ging wat mis tijdens het vertalen!</string>
<string name="toast_toot_saved">Concept opgeslagen!</string>
<string name="toast_error_char_limit">Weet je zeker dat je op deze Mastodon-server zoveel karakters mag gebruiken? Standaard is er een limiet van 500 karakters.</string>
<string name="toast_visibility_changed">Zichtbaarheid toots van account %1$s is veranderd</string>
<string name="toast_empty_search">Server- en gebruikersnaam kunnen niet leeg blijven!</string>
<!-- Settings -->
<string name="settings_title_optimisation">Optimalisatie laden van gegevens</string>
<string name="set_toots_page">Aantal toots per keer</string>
<string name="set_accounts_page">Aantal accounts per keer</string>
<string name="set_notifications_page">Aantal meldingen per keer</string>
<string name="set_attachment_always">Altijd</string>
<string name="set_attachment_wifi">Wifi</string>
<string name="set_attachment_ask">Vragen</string>
<string name="set_attachment_action">Media laden</string>
<string name="load_attachment">Laad de afbeeldingen of video</string>
<string name="load_attachment_spoiler">Meer tonen</string>
<string name="load_sensitive_attachment">Gevoelige inhoud</string>
<string name="set_display_reply">Vorig bericht in reacties tonen</string>
<string name="set_display_local">Lokale tijdlijn tonen</string>
<string name="set_display_global">Globale tijdlijn tonen</string>
<string name="set_folder_title">Downloadlocatie: </string>
<string name="set_auto_store_toot">Concepten automatisch opslaan</string>
<string name="set_bubble_counter">Aantal nieuwe toots bovenaan tijdlijn tonen</string>
<string name="set_auto_add_media_url">URL van afbeelding of video aan toot toevoegen</string>
<string name="settings_title_notifications">Meldingen beheren</string>
<string name="set_notif_follow">Geef een melding wanneer iemand jou volgt</string>
<string name="set_notif_follow_ask">Geef een melding van een volgverzoek</string>
<string name="set_notif_follow_share">Geef een melding wanneer jouw toot is geboost</string>
<string name="set_notif_follow_add">Geef een melding wanneer jouw toot als favoriet is gemarkeerd</string>
<string name="set_notif_follow_mention">Geef een melding wanneer iemand jou vermeldt</string>
<string name="set_share_validation">Vraag voor het boosten een bevestiging</string>
<string name="set_share_validation_fav">Vraag voor het markeren als favoriet een bevestiging</string>
<string name="settings_title_more_options">Geavanceerde instellingen</string>
<string name="set_wifi_only">Alleen met Wifi meldingen tonen</string>
<string name="set_notify">Meldingen?</string>
<string name="set_notif_silent">Stille meldingen</string>
<string name="set_night_mode">Donker thema</string>
<string name="set_nsfw_timeout">Hoe lang gevoelige inhoud blijven tonen (in seconden, 0 is onbeperkt)</string>
<string name="settings_title_profile">Profiel bewerken</string>
<string name="set_profile_description">Bio…</string>
<string name="set_save_changes">Wijzigingen opslaan</string>
<string name="set_header_picture_overlay">Omslagfoto kiezen</string>
<string name="set_preview_reply">Aantal reacties per toot op jouw start-tijdlijn tonen</string>
<string name="set_preview_reply_pp">Avatars bij aantal reacties tonen?</string>
<string name="set_multiaccount_actions">Interactie tussen ingestelde accounts toestaan?</string>
<string name="note_no_space">Je hebt het limiet van 160 karakters bereikt!</string>
<string name="username_no_space">Je hebt het limiet van 30 karakters bereikt!</string>
<string name="settings_title_hour">Op welk moment van de dag zijn meldingen toegestaan:</string>
<string name="settings_time_from">Tussen</string>
<string name="settings_time_to">en</string>
<string name="settings_time_greater">Dit tijdstip moet na %1$s zijn</string>
<string name="settings_time_lower">Dit tijdstip moet voor %1$s zijn</string>
<string name="settings_hour_init">Begintijd</string>
<string name="settings_hour_end">Eindtijd</string>
<string name="embedded_browser">Gebruik de ingebouwde webbrowser</string>
<string name="use_javascript">Javascript toegestaan</string>
<string name="use_cookies">Cookies van derden accepteren</string>
<string name="settings_ui_layout">Lay-out voor tijdlijnen: </string>
<string-array name="settings_menu_tabs">
<item>Tabs</item>
<item>Menu</item>
<item>Tabs en menu</item>
</string-array>
<string-array name="settings_translation">
<item>Yandex</item>
<item>Google</item>
<item>Nee</item>
</string-array>
<string name="set_led_colour">LED-kleur instellen:</string>
<string-array name="led_colours">
<item>Blaauw</item>
<item>Cyaan</item>
<item>Magenta</item>
<item>Groen</item>
<item>Rood</item>
<item>Geel</item>
<item>Wit</item>
</string-array>
<string name="set_title_news">Nieuwe toots</string>
<string name="set_notification_news">Geef een melding van nieuwe toots op jouw start-tijdlijn</string>
<string name="set_show_error_messages">Toon foutmeldingen</string>
<string name="action_follow">Volgen</string>
<string name="action_unfollow">Ontvolgen</string>
<string name="action_block">Blokkeren</string>
<string name="action_unblock">Deblokkeren</string>
<string name="action_mute">Negeren</string>
<string name="action_no_action">Geen actie</string>
<string name="action_unmute">Niet meer negeren</string>
<string name="request_sent">Verzoek verzonden</string>
<string name="followed_by">Volgt jou</string>
<string name="action_search">Zoeken</string>
<!-- Quick settings for notifications -->
<string name="settings_popup_title">Pushmeldingen</string>
<string name="settings_popup_message">
Bevestig de pushmeldingen die jij wilt ontvangen.
Je kan deze later in- en uitschakelen in jouw instellingen (onder meldingen).
</string>
<string name="settings_popup_timeline">Voor ongelezen toots in jouw start-tijdlijn?</string>
<string name="settings_popup_notification">Voor ongelezen meldingen?</string>
<!-- CACHE -->
<string name="cache_title">Buffer leegmaken</string>
<string name="cache_message">De buffer bevat %1$s aan gegevens.\n\nWil je dit verwijderen?</string>
<string name="cache_units">Mb</string>
<string name="toast_cache_clear">De buffer is leeggemaakt! Er is %1$s vrijgekomen</string>
<!-- PRIVACY -->
<string name="privacy_data_title">Recorded data:</string>
<string name="privacy_data">
Only basic information from accounts are stored on the device.
These data are strictly confidential and can only be used by the application.
Deleting the application immediately removes these data.\n
&#9888; Login and passwords are never stored. They are only used during a secure authentication (SSL) with an instance.
</string>
<string name="privacy_authorizations_title">Permissions:</string>
<string name="privacy_authorizations">
- <b>ACCESS_NETWORK_STATE</b>: Used to detect if the device is connected to a WIFI network.\n
- <b>INTERNET</b>: Used for queries to an instance.\n
- <b>WRITE_EXTERNAL_STORAGE</b>: Used to store media or to move the app on a SD card.\n
- <b>READ_EXTERNAL_STORAGE</b>: Used to add media to toots.\n
- <b>BOOT_COMPLETED</b>: Used to start the notification service.\n
- <b>WAKE_LOCK</b>: Used during the notification service.
</string>
<string name="privacy_API_authorizations_title">API permissions:</string>
<string name="privacy_API_authorizations">
- <b>Read</b>: Read data.\n
- <b>Write</b>: Post statuses and upload media for statuses.\n
- <b>Follow</b>: Follow, unfollow, block, unblock.\n\n
<b>&#9888; These actions are carried out only when user requests them.</b>
</string>
<string name="privacy_API_title">Tracking and Libraries:</string>
<string name="privacy_API">
The application <b>does not use tracking tools</b> (audience measurement, error reporting, etc.) and does not contain any advertising.\n\n
The use of libraries is minimized: \n
- <b>Android Asynchronous Http Client</b>: To manage queries\n
- <b>Universal Image Loader</b>: To manage media\n
- <b>Android-Job</b>: To manage services\n
- <b>PhotoView</b>: To manage images\n
- <b>Gson</b> : To save drafts
</string>
<string name="privacy_API_yandex_title">Translation of toots</string>
<string name="privacy_API_yandex_authorizations">
The application offers the ability to translate toots using the locale of the device and the Yandex API.\n
Yandex has its proper privacy-policy which can be found here: https://yandex.ru/legal/confidential/?lang=en
</string>
<string name="thanks_text">
Met dank aan Stéphane voor het logo.
</string>
<string name="thanks_text_dev">
Met dank aan:
</string>
</resources>

View File

@ -189,7 +189,6 @@
<!-- About -->
<string name="about_vesrion">Versão %1$s</string>
<string name="about_developer">Desenvolvedor:</string>
<string name="about_developer_action">\@tschneider</string>
<string name="about_license">Licença: </string>
<string name="about_license_action">GNU GPL V3</string>
<string name="about_code">Código-fonte: </string>
@ -232,7 +231,7 @@
<item quantity="other">e outras %d notificações</item>
</plurals>
<plurals name="other_notif_hometimeline">
<item quantity="one">e outro % toot para descobrir</item>
<item quantity="one">e outro %d toot para descobrir</item>
<item quantity="other">e outros %d toots para descobrir</item>
</plurals>
<string name="delete_notification_ask">Excluir notificação?</string>

View File

@ -190,7 +190,7 @@
<!-- About -->
<string name="about_vesrion">Release %1$s</string>
<string name="about_developer">Developer:</string>
<string name="about_developer_action">\@tschneider</string>
<string name="about_developer_action" translatable="false">\@tom79</string>
<string name="about_license">License: </string>
<string name="about_license_action">GNU GPL V3</string>
<string name="about_code">Source code: </string>

View File

@ -14,54 +14,11 @@
* see <http://www.gnu.org/licenses>. */
package fr.gouv.etalab.mastodon.activities;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.security.ProviderInstaller;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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.KinrarClient;
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;
import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor;
/**
@ -69,265 +26,15 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor;
* Login activity class which handles the connection
*/
public class LoginActivity extends AppCompatActivity implements ProviderInstaller.ProviderInstallListener {
public class LoginActivity extends BaseLoginActivity implements ProviderInstaller.ProviderInstallListener {
private String client_id;
private String client_secret;
private TextView login_two_step;
private static boolean client_id_for_webview = false;
private String instance;
private AutoCompleteTextView login_instance;
boolean isLoadingInstance = false;
private static final int ERROR_DIALOG_REQUEST_CODE = 97;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
protected void installProviders() {
ProviderInstaller.installIfNeededAsync(this, this);
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
if( theme == Helper.THEME_LIGHT){
setTheme(R.style.AppTheme);
}else {
setTheme(R.style.AppThemeDark);
}
setContentView(R.layout.activity_login);
if( theme == Helper.THEME_DARK) {
changeDrawableColor(getApplicationContext(), R.drawable.mastodon_icon, R.color.mastodonC2);
}else {
changeDrawableColor(getApplicationContext(), R.drawable.mastodon_icon, R.color.mastodonC3);
}
final Button connectionButton = (Button) findViewById(R.id.login_button);
login_instance = (AutoCompleteTextView) findViewById(R.id.login_instance);
if( theme == Helper.THEME_LIGHT) {
connectionButton.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
}
login_instance.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if( s.length() > 2 && !isLoadingInstance){
String action = "/instances/search";
RequestParams parameters = new RequestParams();
parameters.add("q", s.toString().trim());
parameters.add("count", String.valueOf(5));
parameters.add("name", String.valueOf(true));
isLoadingInstance = true;
new KinrarClient().get(action, parameters, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
isLoadingInstance = false;
String response = new String(responseBody);
String[] instances;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("instances");
if( jsonArray != null){
instances = new String[jsonArray.length()];
for(int i = 0 ; i < jsonArray.length() ; i++){
instances[i] = jsonArray.getJSONObject(i).get("name").toString();
}
}else {
instances = new String[]{};
}
login_instance.setAdapter(null);
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_list_item_1, instances);
login_instance.setAdapter(adapter);
if( login_instance.hasFocus() && !LoginActivity.this.isFinishing())
login_instance.showDropDown();
} catch (JSONException ignored) {isLoadingInstance = false;}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
isLoadingInstance = false;
}
});
}
}
});
connectionButton.setEnabled(false);
login_two_step = (TextView) findViewById(R.id.login_two_step);
login_two_step.setVisibility(View.GONE);
login_two_step.setPaintFlags(login_two_step.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
login_two_step.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
client_id_for_webview = true;
retrievesClientId();
}
});
login_instance.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
connectionButton.setEnabled(false);
login_two_step.setVisibility(View.INVISIBLE);
if (!hasFocus) {
retrievesClientId();
}
}
});
}
@Override
protected void onResume(){
super.onResume();
Button connectionButton = (Button) findViewById(R.id.login_button);
if (login_instance.getText() != null && login_instance.getText().toString().length() > 0 && client_id_for_webview) {
connectionButton.setEnabled(false);
client_id_for_webview = false;
retrievesClientId();
}
}
private void retrievesClientId(){
final Button connectionButton = (Button) findViewById(R.id.login_button);
try {
instance = URLEncoder.encode(login_instance.getText().toString().trim(), "utf-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(LoginActivity.this,R.string.client_error, Toast.LENGTH_LONG).show();
}
String action = "/api/v1/apps";
RequestParams parameters = new RequestParams();
parameters.add(Helper.CLIENT_NAME, Helper.CLIENT_NAME_VALUE);
parameters.add(Helper.REDIRECT_URIS, client_id_for_webview?Helper.REDIRECT_CONTENT_WEB:Helper.REDIRECT_CONTENT);
parameters.add(Helper.SCOPES, Helper.OAUTH_SCOPES);
parameters.add(Helper.WEBSITE, Helper.WEBSITE_VALUE);
new OauthClient(instance).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);
client_id = resobj.get(Helper.CLIENT_ID).toString();
client_secret = resobj.get(Helper.CLIENT_SECRET).toString();
String id = resobj.get(Helper.ID).toString();
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.CLIENT_ID, client_id);
editor.putString(Helper.CLIENT_SECRET, client_secret);
editor.putString(Helper.ID, id);
editor.apply();
connectionButton.setEnabled(true);
login_two_step.setVisibility(View.VISIBLE);
if( client_id_for_webview){
Intent i = new Intent(LoginActivity.this, WebviewConnectActivity.class);
i.putExtra("instance", instance);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace();
Toast.makeText(LoginActivity.this,R.string.client_error, Toast.LENGTH_LONG).show();
}
});
connectionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connectionButton.setEnabled(false);
if( client_id_for_webview ){
client_id_for_webview = false;
retrievesClientId();
return;
}
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 {
MastalabSSLSocketFactory mastalabSSLSocketFactory = new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore());
mastalabSSLSocketFactory.setHostnameVerifier(MastalabSSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
client.setSSLSocketFactory(mastalabSSLSocketFactory);
client.post("https://" + 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, instance).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);
error.printStackTrace();
Toast.makeText(getApplicationContext(),R.string.toast_error_login,Toast.LENGTH_LONG).show();
}
});
} catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_about) {
Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(intent);
}else if(id == R.id.action_privacy){
Intent intent = new Intent(getApplicationContext(), PrivacyActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onProviderInstalled() {
}
@ -366,10 +73,10 @@ public class LoginActivity extends AppCompatActivity implements ProviderInstalle
onProviderInstallerNotAvailable();
}
}
private void onProviderInstallerNotAvailable() {
// This is reached if the provider cannot be updated for some reason.
// App should consider all HTTP communication to be vulnerable, and take
// appropriate action.
}
}