fedilab-Android-App/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java

1527 lines
74 KiB
Java
Raw Normal View History

2017-05-05 16:36:04 +02:00
/* Copyright 2017 Thomas Schneider
*
2017-07-10 10:33:24 +02:00
* This file is a part of Mastalab
2017-05-05 16:36:04 +02:00
*
* 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.
*
2017-07-10 10:33:24 +02:00
* Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
2017-05-05 16:36:04 +02:00
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
2017-08-04 11:11:27 +02:00
* You should have received a copy of the GNU General Public License along with Mastalab; if not,
2017-05-05 16:36:04 +02:00
* see <http://www.gnu.org/licenses>. */
package fr.gouv.etalab.mastodon.activities;
import android.Manifest;
2017-08-26 10:57:08 +02:00
import android.annotation.SuppressLint;
2017-05-05 16:36:04 +02:00
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
2017-09-16 12:20:06 +02:00
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
2017-08-15 18:07:23 +02:00
import android.support.v7.app.AlertDialog;
import android.content.ActivityNotFoundException;
2017-05-05 16:36:04 +02:00
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
2017-05-05 16:36:04 +02:00
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
2017-05-05 16:36:04 +02:00
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
2017-05-05 16:36:04 +02:00
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
2017-05-05 16:36:04 +02:00
import android.text.TextWatcher;
import android.util.Log;
2017-07-16 17:09:35 +02:00
import android.view.LayoutInflater;
import android.view.Menu;
2017-05-05 16:36:04 +02:00
import android.view.MenuItem;
import android.view.MotionEvent;
2017-05-05 16:36:04 +02:00
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
2017-08-02 12:17:43 +02:00
import android.view.inputmethod.InputMethodManager;
import android.webkit.URLUtil;
import android.widget.AdapterView;
2017-05-05 16:36:04 +02:00
import android.widget.ArrayAdapter;
2017-08-02 17:44:36 +02:00
import android.widget.AutoCompleteTextView;
2017-05-05 16:36:04 +02:00
import android.widget.Button;
2017-06-07 15:47:05 +02:00
import android.widget.CheckBox;
import android.widget.CompoundButton;
2017-07-16 17:09:35 +02:00
import android.widget.DatePicker;
2017-05-05 16:36:04 +02:00
import android.widget.EditText;
2017-08-02 17:44:36 +02:00
import android.widget.HorizontalScrollView;
2017-05-05 16:36:04 +02:00
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
2017-05-05 16:36:04 +02:00
import android.widget.TextView;
2017-07-16 17:09:35 +02:00
import android.widget.TimePicker;
2017-05-05 16:36:04 +02:00
import android.widget.Toast;
2017-09-01 19:14:42 +02:00
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
2017-05-05 16:36:04 +02:00
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;
2017-05-05 16:36:04 +02:00
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
2017-05-05 16:36:04 +02:00
2017-09-01 19:14:42 +02:00
import java.io.ByteArrayInputStream;
2017-09-16 12:20:06 +02:00
import java.io.ByteArrayOutputStream;
import java.io.File;
2017-05-05 16:36:04 +02:00
import java.io.FileNotFoundException;
2017-09-01 19:14:42 +02:00
import java.io.FileOutputStream;
import java.io.IOException;
2017-05-05 16:36:04 +02:00
import java.io.InputStream;
2017-09-01 19:14:42 +02:00
import java.io.OutputStream;
2017-05-05 16:36:04 +02:00
import java.util.ArrayList;
2017-07-16 17:09:35 +02:00
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
2017-05-05 16:36:04 +02:00
import java.util.List;
import java.util.Locale;
2017-05-05 16:36:04 +02:00
import java.util.regex.Matcher;
import java.util.regex.Pattern;
2017-09-01 19:14:42 +02:00
import cz.msebera.android.httpclient.Header;
import fr.gouv.etalab.mastodon.asynctasks.PostStatusAsyncTask;
2017-05-26 17:20:36 +02:00
import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAccountsAsyncTask;
2017-10-09 18:35:43 +02:00
import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAsyncTask;
2017-05-05 16:36:04 +02:00
import fr.gouv.etalab.mastodon.asynctasks.UploadActionAsyncTask;
2017-06-03 18:18:27 +02:00
import fr.gouv.etalab.mastodon.client.APIResponse;
2017-05-05 16:36:04 +02:00
import fr.gouv.etalab.mastodon.client.Entities.Account;
import fr.gouv.etalab.mastodon.client.Entities.Attachment;
import fr.gouv.etalab.mastodon.client.Entities.Error;
import fr.gouv.etalab.mastodon.client.Entities.Mention;
2017-10-09 18:35:43 +02:00
import fr.gouv.etalab.mastodon.client.Entities.Results;
2017-05-05 16:36:04 +02:00
import fr.gouv.etalab.mastodon.client.Entities.Status;
2017-07-15 14:59:09 +02:00
import fr.gouv.etalab.mastodon.client.Entities.StoredStatus;
2017-10-09 18:35:43 +02:00
import fr.gouv.etalab.mastodon.client.Entities.Tag;
import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader;
2017-05-05 16:36:04 +02:00
import fr.gouv.etalab.mastodon.drawers.AccountsSearchAdapter;
2017-07-15 14:59:09 +02:00
import fr.gouv.etalab.mastodon.drawers.DraftsListAdapter;
2017-10-09 18:35:43 +02:00
import fr.gouv.etalab.mastodon.drawers.TagsListAdapter;
import fr.gouv.etalab.mastodon.drawers.TagsSearchAdapter;
2017-05-05 16:36:04 +02:00
import fr.gouv.etalab.mastodon.helper.Helper;
import fr.gouv.etalab.mastodon.interfaces.OnPostStatusActionInterface;
2017-05-05 16:36:04 +02:00
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAttachmentInterface;
2017-05-26 17:20:36 +02:00
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearcAccountshInterface;
2017-10-09 18:35:43 +02:00
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearchInterface;
2017-07-16 17:09:35 +02:00
import fr.gouv.etalab.mastodon.jobs.ScheduledTootsSyncJob;
2017-05-05 16:36:04 +02:00
import fr.gouv.etalab.mastodon.sqlite.AccountDAO;
import fr.gouv.etalab.mastodon.sqlite.Sqlite;
2017-08-06 17:58:55 +02:00
import fr.gouv.etalab.mastodon.sqlite.StatusStoredDAO;
2017-05-05 16:36:04 +02:00
import mastodon.etalab.gouv.fr.mastodon.R;
import static fr.gouv.etalab.mastodon.helper.Helper.HOME_TIMELINE_INTENT;
import static fr.gouv.etalab.mastodon.helper.Helper.INTENT_ACTION;
2017-07-01 15:24:28 +02:00
import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor;
2017-05-05 16:36:04 +02:00
/**
* Created by Thomas on 01/05/2017.
* Toot activity class
*/
2017-10-09 18:35:43 +02:00
public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAccountshInterface, OnRetrieveAttachmentInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface {
2017-05-05 16:36:04 +02:00
private String visibility;
private final int PICK_IMAGE = 56556;
private ProgressBar loading_picture;
2017-05-05 16:36:04 +02:00
private ImageButton toot_picture;
private ImageLoader imageLoader;
private DisplayImageOptions options;
private LinearLayout toot_picture_container;
private ArrayList<Attachment> attachments;
2017-06-07 15:47:05 +02:00
private boolean isSensitive = false;
2017-05-05 16:36:04 +02:00
private ImageButton toot_visibility;
private Button toot_it;
2017-08-02 17:44:36 +02:00
private AutoCompleteTextView toot_content;
private EditText toot_cw_content;
private Status tootReply = null;
private String tootMention = null;
private String urlMention = null;
private String fileMention = null;
private String sharedContent, sharedSubject, sharedContentIni;
2017-06-07 15:47:05 +02:00
private CheckBox toot_sensitive;
2017-07-15 14:59:09 +02:00
public long currentToId;
2017-07-16 19:04:53 +02:00
private long restored;
2017-07-21 21:09:32 +02:00
private TextView title;
private ImageView pp_actionBar;
2017-08-02 12:17:43 +02:00
private ProgressBar pp_progress;
private Toast mToast;
2017-08-02 17:44:36 +02:00
private LinearLayout drawer_layout;
private HorizontalScrollView picture_scrollview;
2017-08-09 18:27:03 +02:00
private int currentCursorPosition, searchLength;
2017-08-18 16:54:43 +02:00
private TextView toot_space_left;
private String initialContent;
private final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 754;
private BroadcastReceiver receive_picture;
2017-10-04 15:57:53 +02:00
private Account accountReply;
2017-05-05 16:36:04 +02:00
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
2017-06-30 17:09:07 +02:00
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
2017-06-30 17:09:07 +02:00
if( theme == Helper.THEME_LIGHT){
setTheme(R.style.AppTheme);
}else {
setTheme(R.style.AppThemeDark);
}
2017-05-05 16:36:04 +02:00
setContentView(R.layout.activity_toot);
2017-07-21 21:09:32 +02:00
ActionBar actionBar = getSupportActionBar();
if( actionBar != null ){
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2017-08-26 10:57:08 +02:00
@SuppressLint("InflateParams") View view = inflater.inflate(R.layout.toot_action_bar, null);
2017-07-21 21:09:32 +02:00
actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView close_toot = (ImageView) actionBar.getCustomView().findViewById(R.id.close_toot);
close_toot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
2017-08-02 12:17:43 +02:00
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(toot_content.getWindowToken(), 0);
2017-07-21 21:09:32 +02:00
finish();
}
});
title = (TextView) actionBar.getCustomView().findViewById(R.id.toolbar_title);
pp_actionBar = (ImageView) actionBar.getCustomView().findViewById(R.id.pp_actionBar);
2017-08-02 12:17:43 +02:00
pp_progress = (ProgressBar) actionBar.getCustomView().findViewById(R.id.pp_progress);
2017-07-21 21:09:32 +02:00
}
2017-07-15 14:59:09 +02:00
//By default the toot is not restored so the id -1 is defined
currentToId = -1;
boolean restoredScheduled = false;
imageLoader = ImageLoader.getInstance();
File cacheDir = new File(getCacheDir(), getString(R.string.app_name));
ImageLoaderConfiguration configImg = new ImageLoaderConfiguration.Builder(this)
.imageDownloader(new PatchBaseImageDownloader(getApplicationContext()))
.threadPoolSize(5)
.threadPriority(Thread.MIN_PRIORITY + 3)
.denyCacheImageMultipleSizesInMemory()
.diskCache(new UnlimitedDiskCache(cacheDir))
.build();
imageLoader.init(configImg);
options = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false)
.cacheOnDisk(true).resetViewBeforeLoading(true).build();
toot_it = (Button) findViewById(R.id.toot_it);
Button toot_cw = (Button) findViewById(R.id.toot_cw);
2017-08-18 16:54:43 +02:00
toot_space_left = (TextView) findViewById(R.id.toot_space_left);
toot_visibility = (ImageButton) findViewById(R.id.toot_visibility);
toot_picture = (ImageButton) findViewById(R.id.toot_picture);
loading_picture = (ProgressBar) findViewById(R.id.loading_picture);
toot_picture_container = (LinearLayout) findViewById(R.id.toot_picture_container);
2017-08-02 17:44:36 +02:00
toot_content = (AutoCompleteTextView) findViewById(R.id.toot_content);
int newInputType = toot_content.getInputType() & (toot_content.getInputType() ^ InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
toot_content.setInputType(newInputType);
toot_cw_content = (EditText) findViewById(R.id.toot_cw_content);
2017-08-02 17:44:36 +02:00
picture_scrollview = (HorizontalScrollView) findViewById(R.id.picture_scrollview);
2017-06-07 15:47:05 +02:00
toot_sensitive = (CheckBox) findViewById(R.id.toot_sensitive);
2017-08-02 17:44:36 +02:00
//search_small_container = (LinearLayout) findViewById(R.id.search_small_container);
2017-05-05 16:36:04 +02:00
2017-08-02 17:44:36 +02:00
drawer_layout = (LinearLayout) findViewById(R.id.drawer_layout);
drawer_layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = drawer_layout.getRootView().getHeight() - drawer_layout.getHeight();
if (heightDiff > Helper.convertDpToPixel(200, getApplicationContext())) {
ViewGroup.LayoutParams params = toot_picture_container.getLayoutParams();
params.height = (int) Helper.convertDpToPixel(50, getApplicationContext());
params.width = (int) Helper.convertDpToPixel(50, getApplicationContext());
toot_picture_container.setLayoutParams(params);
}else {
ViewGroup.LayoutParams params = toot_picture_container.getLayoutParams();
params.height = (int) Helper.convertDpToPixel(100, getApplicationContext());
params.width = (int) Helper.convertDpToPixel(100, getApplicationContext());
toot_picture_container.setLayoutParams(params);
}
}
});
2017-05-05 16:36:04 +02:00
Bundle b = getIntent().getExtras();
2017-08-26 10:57:08 +02:00
ArrayList<Uri> sharedUri = new ArrayList<>();
2017-07-16 19:04:53 +02:00
restored = -1;
if(b != null) {
tootReply = b.getParcelable("tootReply");
2017-10-04 15:57:53 +02:00
accountReply = b.getParcelable("accountReply");
tootMention = b.getString("tootMention", null);
urlMention = b.getString("urlMention", null);
fileMention = b.getString("fileMention", null);
sharedContent = b.getString("sharedContent", null);
sharedContentIni = b.getString("sharedContent", null);
sharedSubject = b.getString("sharedSubject", null);
restoredScheduled = b.getBoolean("restoredScheduled", false);
// ACTION_SEND route
2017-08-22 11:59:25 +02:00
if (b.getInt("uriNumber", 0) == 1) {
Uri fileUri = b.getParcelable("sharedUri");
2017-09-16 12:20:06 +02:00
if (fileUri != null) {
sharedUri.add(fileUri);
}
}
// ACTION_SEND_MULTIPLE route
2017-08-22 11:59:25 +02:00
else if( b.getInt("uriNumber", 0) > 1) {
ArrayList<Uri> fileUri = b.getParcelableArrayList("sharedUri");
if (fileUri != null) {
sharedUri.addAll(fileUri);
}
}
2017-07-16 19:04:53 +02:00
restored = b.getLong("restored", -1);
}
initialContent = toot_content.getText().toString();
if(restoredScheduled){
2017-07-16 19:04:53 +02:00
toot_it.setVisibility(View.GONE);
invalidateOptionsMenu();
}
if( tootReply != null) {
tootReply();
2017-05-05 16:36:04 +02:00
}else {
2017-07-21 21:09:32 +02:00
if( title != null)
title.setText(getString(R.string.toot_title));
else
setTitle(R.string.toot_title);
2017-05-05 16:36:04 +02:00
}
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
2017-10-04 15:57:53 +02:00
String userId;
if( accountReply == null)
userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
else
userId = accountReply.getId();
if( tootMention != null && urlMention != null && fileMention != null) {
Bitmap pictureMention = BitmapFactory.decodeFile(getCacheDir() + "/" + fileMention);
if (pictureMention != null) {
2017-09-16 12:20:06 +02:00
ByteArrayOutputStream bos = new ByteArrayOutputStream();
pictureMention.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
toot_picture_container.setVisibility(View.VISIBLE);
2017-09-16 12:20:06 +02:00
loading_picture.setVisibility(View.VISIBLE);
picture_scrollview.setVisibility(View.VISIBLE);
2017-09-16 12:20:06 +02:00
toot_picture.setEnabled(false);
new UploadActionAsyncTask(getApplicationContext(), bs, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
toot_content.setText(String.format("\n\nvia @%s\n\n%s\n\n", tootMention, urlMention));
toot_space_left.setText(String.valueOf(toot_content.length()));
2017-09-16 12:20:06 +02:00
}
2017-10-04 15:57:53 +02:00
Account account;
if( accountReply == null)
account = new AccountDAO(getApplicationContext(),db).getAccountByID(userId);
else
account = accountReply;
2017-09-16 12:20:06 +02:00
String url = account.getAvatar();
if( url.startsWith("/") ){
url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar();
}
imageLoader.loadImage(url, options, new SimpleImageLoadingListener(){
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
2017-07-21 21:09:32 +02:00
BitmapDrawable ppDrawable = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(loadedImage, (int) Helper.convertDpToPixel(25, getApplicationContext()), (int) Helper.convertDpToPixel(25, getApplicationContext()), true));
if( pp_actionBar != null){
pp_actionBar.setImageDrawable(ppDrawable);
} else if( getSupportActionBar() != null){
getSupportActionBar().setIcon(ppDrawable);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
@Override
public void onLoadingFailed(java.lang.String imageUri, android.view.View view, FailReason failReason){
}});
if( sharedContent != null ){ //Shared content
if( sharedSubject != null){
sharedContent = sharedSubject + "\n\n" + sharedContent;
}
receive_picture = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String image = intent.getStringExtra("image");
String title = intent.getStringExtra("title");
String description = intent.getStringExtra("description");
if( description != null && description.length() > 20 ){
if( description.length() > 200 )
description = description.substring(0,199) + "";
if( title != null)
2017-09-02 16:33:30 +02:00
sharedContent = title + "\n\n" + description + "\n\n" + sharedContentIni;
else
2017-09-02 16:33:30 +02:00
sharedContent = description + "\n\n" + sharedContentIni;
toot_content.setText(sharedContent);
toot_space_left.setText(String.valueOf(toot_content.length()));
toot_content.setSelection(toot_content.getText().length());
}
if( image != null){
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedTypes = new String[] { "image/png","image/jpeg" };
client.get(image, new BinaryHttpResponseHandler(allowedTypes) {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
OutputStream f;
try {
f = new FileOutputStream(getCacheDir() + URLUtil.guessFileName(image, null, null));
picture_scrollview.setVisibility(View.VISIBLE);
InputStream bis = new ByteArrayInputStream(binaryData);
toot_picture_container.setVisibility(View.VISIBLE);
loading_picture.setVisibility(View.VISIBLE);
toot_picture.setEnabled(false);
new UploadActionAsyncTask(getApplicationContext(),bis,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
f.write(binaryData);
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2017-09-01 19:14:42 +02:00
@Override
public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
error.printStackTrace();
}
2017-09-01 19:14:42 +02:00
});
2017-09-01 19:14:42 +02:00
}
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(receive_picture, new IntentFilter(Helper.RECEIVE_PICTURE));
toot_content.setText( String.format("\n%s", sharedContent));
toot_space_left.setText(String.valueOf(toot_content.length()));
}
2017-05-05 16:36:04 +02:00
attachments = new ArrayList<>();
2017-08-02 12:17:43 +02:00
int charsInCw = 0;
int charsInToot = 0;
if (!sharedUri.isEmpty()) {
uploadSharedImage(sharedUri);
}
2017-05-05 16:36:04 +02:00
boolean isAccountPrivate = account.isLocked();
if(isAccountPrivate){
if( tootReply == null) {
visibility = "private";
2017-08-29 16:48:28 +02:00
toot_visibility.setImageResource(R.drawable.ic_action_lock_closed);
}else {
if( visibility.equals("direct") ){
toot_visibility.setImageResource(R.drawable.ic_local_post_office);
}else{
visibility = "private";
toot_visibility.setImageResource(R.drawable.ic_action_lock_closed);
}
}
2017-05-05 16:36:04 +02:00
}else {
if( tootReply == null){
visibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), "public");
switch (visibility) {
case "public":
toot_visibility.setImageResource(R.drawable.ic_action_globe);
break;
case "unlisted":
toot_visibility.setImageResource(R.drawable.ic_action_lock_open);
break;
case "private":
toot_visibility.setImageResource(R.drawable.ic_action_lock_closed);
break;
case "direct":
toot_visibility.setImageResource(R.drawable.ic_local_post_office);
break;
}
}
2017-05-05 16:36:04 +02:00
}
2017-06-07 15:47:05 +02:00
toot_sensitive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isSensitive = isChecked;
}
});
2017-05-05 16:36:04 +02:00
2017-08-18 16:54:43 +02:00
toot_space_left.setText(String.valueOf(charsInToot + charsInCw));
2017-05-05 16:36:04 +02:00
toot_cw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toot_cw_content.getVisibility() == View.GONE) {
toot_cw_content.setVisibility(View.VISIBLE);
toot_cw_content.requestFocus();
}else {
toot_cw_content.setVisibility(View.GONE);
toot_cw_content.setText("");
toot_content.requestFocus();
}
}
});
toot_visibility.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tootVisibilityDialog();
}
});
2017-05-05 16:36:04 +02:00
toot_it.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toot_it.setEnabled(false);
if(toot_content.getText().toString().trim().length() == 0){
Toast.makeText(getApplicationContext(),R.string.toot_error_no_content, Toast.LENGTH_LONG).show();
toot_it.setEnabled(true);
return;
}
Status toot = new Status();
2017-06-07 15:47:05 +02:00
toot.setSensitive(isSensitive);
2017-05-05 16:36:04 +02:00
toot.setMedia_attachments(attachments);
if( toot_cw_content.getText().toString().trim().length() > 0)
toot.setSpoiler_text(toot_cw_content.getText().toString().trim());
toot.setVisibility(visibility);
2017-09-22 14:44:00 +02:00
if( tootReply != null)
toot.setIn_reply_to_id(tootReply.getId());
2017-09-20 16:53:46 +02:00
toot.setContent(toot_content.getText().toString().trim());
2017-10-04 15:57:53 +02:00
new PostStatusAsyncTask(getApplicationContext(), accountReply, toot, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
2017-05-05 16:36:04 +02:00
}
});
toot_picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (ContextCompat.checkSelfPermission(TootActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(TootActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
return;
}
}
Intent intent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "video/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(intent, PICK_IMAGE);
}else {
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, getString(R.string.toot_select_image));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
}
2017-05-05 16:36:04 +02:00
}
});
String pattern = "^(.|\\s)*(@([a-zA-Z0-9_]{2,}))$";
final Pattern sPattern = Pattern.compile(pattern);
2017-08-09 18:27:03 +02:00
2017-10-09 18:35:43 +02:00
String patternTag = "^(.|\\s)*(#([\\w-]{2,}))$";
final Pattern tPattern = Pattern.compile(patternTag);
2017-05-05 16:36:04 +02:00
toot_content.addTextChangedListener(new TextWatcher() {
@Override
2017-08-10 09:03:42 +02:00
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
2017-05-05 16:36:04 +02:00
@Override
2017-08-10 09:03:42 +02:00
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
2017-05-05 16:36:04 +02:00
@Override
public void afterTextChanged(Editable s) {
if( toot_content.getSelectionStart() != 0)
currentCursorPosition = toot_content.getSelectionStart();
if( s.toString().length() == 0 )
currentCursorPosition = 0;
//Only check last 15 characters before cursor position to avoid lags
if( currentCursorPosition < 15 ){ //Less than 15 characters are written before the cursor position
searchLength = currentCursorPosition;
}else {
searchLength = 15;
}
int totalChar = toot_cw_content.length() + toot_content.length();
toot_space_left.setText(String.valueOf(totalChar));
2017-08-10 09:03:42 +02:00
if( currentCursorPosition- (searchLength-1) < 0 || currentCursorPosition == 0 || currentCursorPosition > s.toString().length())
return;
2017-10-09 18:35:43 +02:00
Matcher m, mt;
if( s.toString().charAt(0) == '@')
m = sPattern.matcher(s.toString().substring(currentCursorPosition- searchLength, currentCursorPosition));
else
m = sPattern.matcher(s.toString().substring(currentCursorPosition- (searchLength-1), currentCursorPosition));
2017-05-05 16:36:04 +02:00
if(m.matches()) {
2017-08-09 18:27:03 +02:00
String search = m.group(3);
if (pp_progress != null && pp_actionBar != null) {
2017-08-02 12:17:43 +02:00
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
2017-05-26 17:20:36 +02:00
new RetrieveSearchAccountsAsyncTask(getApplicationContext(),search,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
2017-08-02 17:44:36 +02:00
}else{toot_content.dismissDropDown();}
2017-10-09 18:35:43 +02:00
if( s.toString().charAt(0) == '#')
mt = tPattern.matcher(s.toString().substring(currentCursorPosition- searchLength, currentCursorPosition));
else
mt = tPattern.matcher(s.toString().substring(currentCursorPosition- (searchLength-1), currentCursorPosition));
if(mt.matches()) {
String search = mt.group(3);
if (pp_progress != null && pp_actionBar != null) {
pp_progress.setVisibility(View.VISIBLE);
pp_actionBar.setVisibility(View.GONE);
}
new RetrieveSearchAsyncTask(getApplicationContext(),search,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else{toot_content.dismissDropDown();}
totalChar = toot_cw_content.length() + toot_content.length();
2017-08-18 16:54:43 +02:00
toot_space_left.setText(String.valueOf(totalChar));
2017-05-05 16:36:04 +02:00
}
});
//Allow scroll of the EditText though it's embedded in a scrollview
toot_content.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.toot_content) {
v.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
}
return false;
}
});
2017-05-05 16:36:04 +02:00
toot_cw_content.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) {
int totalChar = toot_cw_content.length() + toot_content.length();
2017-08-18 16:54:43 +02:00
toot_space_left.setText(String.valueOf(totalChar));
2017-05-05 16:36:04 +02:00
}
});
2017-07-16 19:04:53 +02:00
if( restored != -1 ){
restoreToot(restored);
}
changeColor();
if( theme == Helper.THEME_LIGHT) {
toot_it.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
}
2017-05-05 16:36:04 +02:00
}
@Override
public void onDestroy(){
super.onDestroy();
if( receive_picture != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(receive_picture);
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// We have the permission.
toot_picture.callOnClick();
}
break;
}
}
}
public void showAToast (String message){
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
mToast.show();
}
2017-05-05 16:36:04 +02:00
// Handles uploading shared images
public void uploadSharedImage(ArrayList<Uri> uri)
{
if (!uri.isEmpty()) {
int count = 0;
for(Uri fileUri: uri) {
if (fileUri != null) {
if (count == 4)
{
break;
}
picture_scrollview.setVisibility(View.VISIBLE);
try {
InputStream inputStream = getContentResolver().openInputStream(fileUri);
toot_picture_container.setVisibility(View.VISIBLE);
loading_picture.setVisibility(View.VISIBLE);
picture_scrollview.setVisibility(View.VISIBLE);
toot_picture.setEnabled(false);
new UploadActionAsyncTask(getApplicationContext(), inputStream, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
count++;
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), R.string.toot_select_image_error, Toast.LENGTH_LONG).show();
loading_picture.setVisibility(View.GONE);
toot_picture.setEnabled(true);
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), R.string.toot_select_image_error, Toast.LENGTH_LONG).show();
}
}
}
}
2017-05-05 16:36:04 +02:00
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
2017-08-02 17:44:36 +02:00
picture_scrollview.setVisibility(View.VISIBLE);
2017-05-05 16:36:04 +02:00
if (data == null) {
Toast.makeText(getApplicationContext(),R.string.toot_select_image_error,Toast.LENGTH_LONG).show();
return;
}
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
toot_picture_container.setVisibility(View.VISIBLE);
2017-05-05 16:36:04 +02:00
loading_picture.setVisibility(View.VISIBLE);
toot_picture.setEnabled(false);
new UploadActionAsyncTask(getApplicationContext(),inputStream,TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),R.string.toot_select_image_error,Toast.LENGTH_LONG).show();
loading_picture.setVisibility(View.GONE);
toot_picture.setEnabled(true);
e.printStackTrace();
}
}else if(requestCode == Helper.REQ_CODE_SPEECH_INPUT && resultCode == Activity.RESULT_OK){
if (null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
toot_content.setText(result.get(0));
toot_content.setSelection(toot_content.getText().length());
}
2017-05-05 16:36:04 +02:00
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
2017-07-15 14:59:09 +02:00
final SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
2017-05-05 16:36:04 +02:00
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_view_reply:
AlertDialog.Builder alert = new AlertDialog.Builder(TootActivity.this);
alert.setTitle(R.string.toot_reply_content_title);
final TextView input = new TextView(TootActivity.this);
//Set the padding
input.setPadding(30, 30, 30, 30);
alert.setView(input);
String content = tootReply.getContent();
if(tootReply.getReblog() != null)
content = tootReply.getReblog().getContent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
input.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY));
else
//noinspection deprecation
input.setText(Html.fromHtml(content));
alert.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
return true;
case R.id.action_microphone:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, Helper.REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
return true;
2017-07-15 14:59:09 +02:00
case R.id.action_store:
2017-07-16 17:09:35 +02:00
storeToot(true);
2017-07-15 14:59:09 +02:00
return true;
case R.id.action_restore:
try{
final List<StoredStatus> drafts = new StatusStoredDAO(TootActivity.this, db).getAllDrafts();
if( drafts == null || drafts.size() == 0){
Toast.makeText(getApplicationContext(), R.string.no_draft, Toast.LENGTH_LONG).show();
return true;
}
2017-08-15 18:07:23 +02:00
AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this);
2017-07-15 14:59:09 +02:00
builderSingle.setTitle(getString(R.string.choose_toot));
final DraftsListAdapter draftsListAdapter = new DraftsListAdapter(TootActivity.this, drafts);
final int[] ids = new int[drafts.size()];
int i = 0;
for(StoredStatus draft: drafts){
ids[i] = draft.getId();
i++;
}
builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setPositiveButton(R.string.delete_all, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, int which) {
2017-08-15 18:07:23 +02:00
AlertDialog.Builder builder = new AlertDialog.Builder(TootActivity.this);
2017-07-15 14:59:09 +02:00
builder.setTitle(R.string.delete_all);
builder.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogConfirm, int which) {
new StatusStoredDAO(getApplicationContext(), db).removeAllDrafts();
dialogConfirm.dismiss();
dialog.dismiss();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogConfirm, int which) {
dialogConfirm.dismiss();
}
})
.show();
}
});
builderSingle.setAdapter(draftsListAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int id = ids[which];
2017-07-16 19:04:53 +02:00
restoreToot(id);
2017-07-15 14:59:09 +02:00
dialog.dismiss();
}
});
builderSingle.show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), R.string.toast_error, Toast.LENGTH_LONG).show();
}
return true;
2017-07-16 17:09:35 +02:00
case R.id.action_schedule:
2017-07-15 14:59:09 +02:00
if(toot_content.getText().toString().trim().length() == 0 ){
Toast.makeText(getApplicationContext(),R.string.toot_error_no_content, Toast.LENGTH_LONG).show();
return true;
}
2017-08-15 18:07:23 +02:00
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(TootActivity.this);
2017-07-16 17:09:35 +02:00
LayoutInflater inflater = this.getLayoutInflater();
2017-08-26 10:57:08 +02:00
@SuppressLint("InflateParams") View dialogView = inflater.inflate(R.layout.datetime_picker, null);
2017-07-16 17:09:35 +02:00
dialogBuilder.setView(dialogView);
final AlertDialog alertDialog = dialogBuilder.create();
final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
final TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker);
timePicker.setIs24HourView(true);
2017-07-16 17:09:35 +02:00
Button date_time_cancel = (Button) dialogView.findViewById(R.id.date_time_cancel);
2017-07-16 19:04:53 +02:00
final ImageButton date_time_previous = (ImageButton) dialogView.findViewById(R.id.date_time_previous);
final ImageButton date_time_next = (ImageButton) dialogView.findViewById(R.id.date_time_next);
final ImageButton date_time_set = (ImageButton) dialogView.findViewById(R.id.date_time_set);
2017-07-16 17:09:35 +02:00
//Buttons management
date_time_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
date_time_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
datePicker.setVisibility(View.GONE);
timePicker.setVisibility(View.VISIBLE);
date_time_previous.setVisibility(View.VISIBLE);
date_time_next.setVisibility(View.GONE);
date_time_set.setVisibility(View.VISIBLE);
}
});
date_time_previous.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
datePicker.setVisibility(View.VISIBLE);
timePicker.setVisibility(View.GONE);
date_time_previous.setVisibility(View.GONE);
date_time_next.setVisibility(View.VISIBLE);
date_time_set.setVisibility(View.GONE);
}
});
date_time_set.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour, minute;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
hour = timePicker.getHour();
minute = timePicker.getMinute();
}else {
//noinspection deprecation
hour = timePicker.getCurrentHour();
//noinspection deprecation
minute = timePicker.getCurrentMinute();
}
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
hour,
minute);
long time = calendar.getTimeInMillis();
if( (time - new Date().getTime()) < 60000 ){
Toast.makeText(getApplicationContext(), R.string.toot_scheduled_date, Toast.LENGTH_LONG).show();
}else {
//Store the toot as draft first
storeToot(false);
//Schedules the toot
2017-07-17 18:53:12 +02:00
ScheduledTootsSyncJob.schedule(getApplicationContext(), currentToId, time);
2017-07-16 17:09:35 +02:00
//Clear content
toot_content.setText("");
toot_cw_content.setText("");
toot_space_left.setText(0);
2017-07-16 17:09:35 +02:00
if( attachments != null) {
for (Attachment attachment : attachments) {
View namebar = findViewById(Integer.parseInt(attachment.getId()));
if (namebar != null && namebar.getParent() != null)
((ViewGroup) namebar.getParent()).removeView(namebar);
}
List<Attachment> tmp_attachment = new ArrayList<>();
tmp_attachment.addAll(attachments);
attachments.removeAll(tmp_attachment);
tmp_attachment.clear();
}
isSensitive = false;
toot_sensitive.setVisibility(View.GONE);
currentToId = -1;
Toast.makeText(TootActivity.this,R.string.toot_scheduled, Toast.LENGTH_LONG).show();
alertDialog.dismiss();
}
}
});
changeColor();
2017-07-16 17:09:35 +02:00
alertDialog.show();
return true;
2017-05-05 16:36:04 +02:00
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_toot, menu);
2017-07-16 19:04:53 +02:00
if( restored != -1 ){
MenuItem itemRestore = menu.findItem(R.id.action_restore);
if( itemRestore != null)
itemRestore.setVisible(false);
MenuItem itemSchedule = menu.findItem(R.id.action_schedule);
if( itemSchedule != null)
itemSchedule.setVisible(false);
}
MenuItem itemViewReply = menu.findItem(R.id.action_view_reply);
if( tootReply == null){
if( itemViewReply != null)
itemViewReply.setVisible(false);
}
if( accountReply != null){
MenuItem itemRestore = menu.findItem(R.id.action_restore);
if( itemRestore != null)
itemRestore.setVisible(false);
MenuItem itemSchedule = menu.findItem(R.id.action_schedule);
if( itemSchedule != null)
itemSchedule.setVisible(false);
MenuItem itemStore= menu.findItem(R.id.action_store);
if( itemStore != null)
itemStore.setVisible(false);
}
return true;
}
2017-05-05 16:36:04 +02:00
@Override
public void onRetrieveAttachment(final Attachment attachment, Error error) {
2017-05-05 16:36:04 +02:00
loading_picture.setVisibility(View.GONE);
if( error != null){
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean show_error_messages = sharedpreferences.getBoolean(Helper.SET_SHOW_ERROR_MESSAGES, true);
if( show_error_messages)
Toast.makeText(getApplicationContext(), error.getError(),Toast.LENGTH_LONG).show();
2017-08-02 17:44:36 +02:00
if( attachments.size() == 0 )
toot_picture_container.setVisibility(View.GONE);
toot_picture.setEnabled(true);
return;
}
2017-08-02 17:44:36 +02:00
toot_picture_container.setVisibility(View.VISIBLE);
2017-05-05 16:36:04 +02:00
if( attachment != null ){
String url = attachment.getPreview_url();
if( url == null || url.trim().equals(""))
url = attachment.getUrl();
final ImageView imageView = new ImageView(getApplicationContext());
imageView.setId(Integer.parseInt(attachment.getId()));
imageLoader.displayImage(url, imageView, options);
LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
imParams.setMargins(20, 5, 20, 5);
imParams.height = (int) Helper.convertDpToPixel(100, getApplicationContext());
2017-05-05 16:36:04 +02:00
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, true);
if( show_media_urls) {
//Adds the shorter text_url of attachment at the end of the toot
int selectionBefore = toot_content.getSelectionStart();
toot_content.setText(toot_content.getText().toString() + "\n" + attachment.getText_url());
toot_space_left.setText(String.valueOf(toot_content.length()));
//Moves the cursor
if (selectionBefore >= 0)
toot_content.setSelection(selectionBefore);
}
toot_picture_container.addView(imageView, attachments.size(), imParams);
2017-05-05 16:36:04 +02:00
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showRemove(imageView.getId());
}
});
attachments.add(attachment);
if( attachments.size() < 4)
toot_picture.setEnabled(true);
2017-06-07 15:47:05 +02:00
toot_sensitive.setVisibility(View.VISIBLE);
2017-08-02 17:44:36 +02:00
picture_scrollview.setVisibility(View.VISIBLE);
2017-05-05 16:36:04 +02:00
}
}
/**
* Removes a media
* @param viewId String
*/
private void showRemove(final int viewId){
2017-08-15 18:07:23 +02:00
AlertDialog.Builder dialog = new AlertDialog.Builder(TootActivity.this);
2017-05-05 16:36:04 +02:00
dialog.setMessage(R.string.toot_delete_media);
dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
dialog.dismiss();
}
});
dialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
View namebar = findViewById(viewId);
for(Attachment attachment: attachments){
if( Integer.valueOf(attachment.getId()) == viewId){
attachments.remove(attachment);
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, true);
if( show_media_urls) {
//Clears the text_url at the end of the toot for this attachment
int selectionBefore = toot_content.getSelectionStart();
toot_content.setText(toot_content.getText().toString().replace(attachment.getText_url(), ""));
toot_space_left.setText(String.valueOf(toot_content.length()));
//Moves the cursor
if (selectionBefore >= 0)
toot_content.setSelection(selectionBefore);
}
((ViewGroup) namebar.getParent()).removeView(namebar);
break;
}
}
2017-05-05 16:36:04 +02:00
dialog.dismiss();
2017-06-07 15:47:05 +02:00
if( attachments.size() == 0 ) {
toot_sensitive.setVisibility(View.GONE);
isSensitive = false;
toot_sensitive.setChecked(false);
2017-08-02 17:44:36 +02:00
picture_scrollview.setVisibility(View.GONE);
2017-06-07 15:47:05 +02:00
}
toot_picture.setEnabled(true);
2017-05-05 16:36:04 +02:00
}
});
dialog.show();
}
private void tootVisibilityDialog(){
2017-08-15 18:07:23 +02:00
AlertDialog.Builder dialog = new AlertDialog.Builder(TootActivity.this);
2017-05-05 16:36:04 +02:00
dialog.setTitle(R.string.toot_visibility_tilte);
final String[] stringArray = getResources().getStringArray(R.array.toot_visibility);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(TootActivity.this, android.R.layout.simple_list_item_1, stringArray);
dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
dialog.dismiss();
}
});
dialog.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
switch (position){
case 0:
visibility = "public";
toot_visibility.setImageResource(R.drawable.ic_action_globe);
break;
case 1:
visibility = "unlisted";
toot_visibility.setImageResource(R.drawable.ic_action_lock_open);
break;
case 2:
visibility = "private";
toot_visibility.setImageResource(R.drawable.ic_action_lock_closed);
break;
case 3:
visibility = "direct";
toot_visibility.setImageResource(R.drawable.ic_local_post_office);
break;
}
changeColor();
2017-05-05 16:36:04 +02:00
dialog.dismiss();
}
});
dialog.show();
}
2017-07-15 14:59:09 +02:00
@Override
public void onPause(){
super.onPause();
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean storeToot = sharedpreferences.getBoolean(Helper.SET_AUTO_STORE, true);
if( storeToot && accountReply == null)
2017-07-16 17:09:35 +02:00
storeToot(true);
2017-07-15 14:59:09 +02:00
}
2017-05-05 16:36:04 +02:00
@Override
public void onPostStatusAction(APIResponse apiResponse) {
if( apiResponse.getError() != null){
2017-08-18 16:54:43 +02:00
toot_it.setEnabled(true);
if( apiResponse.getError().getError().contains("422")){
showAToast(getString(R.string.toast_error_char_limit));
}else {
showAToast(apiResponse.getError().getError());
}
return;
}
if(restored != -1){
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new StatusStoredDAO(getApplicationContext(), db).remove(restored);
}
//Clear the toot
toot_content.setText("");
toot_cw_content.setText("");
toot_space_left.setText("0");
if( attachments != null) {
for (Attachment attachment : attachments) {
View namebar = findViewById(Integer.parseInt(attachment.getId()));
if (namebar != null && namebar.getParent() != null)
((ViewGroup) namebar.getParent()).removeView(namebar);
}
List<Attachment> tmp_attachment = new ArrayList<>();
tmp_attachment.addAll(attachments);
attachments.removeAll(tmp_attachment);
tmp_attachment.clear();
}
isSensitive = false;
toot_sensitive.setVisibility(View.GONE);
currentToId = -1;
Toast.makeText(TootActivity.this,R.string.toot_sent, Toast.LENGTH_LONG).show();
toot_it.setEnabled(true);
//It's a reply, so the user will be redirect to its answer
if( tootReply != null){
List<Status> statuses = apiResponse.getStatuses();
if( statuses != null && statuses.size() > 0 ){
Status status = statuses.get(0);
if( status != null ) {
Intent intent = new Intent(getApplicationContext(), ShowConversationActivity.class);
Bundle b = new Bundle();
b.putString("statusId", status.getId());
intent.putExtras(b);
startActivity(intent);
finish();
2017-05-05 16:36:04 +02:00
}
}
}else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra(INTENT_ACTION, HOME_TIMELINE_INTENT);
startActivity(intent);
finish();
2017-05-05 16:36:04 +02:00
}
}
2017-05-05 16:36:04 +02:00
@Override
2017-06-03 18:18:27 +02:00
public void onRetrieveSearchAccounts(APIResponse apiResponse) {
2017-08-02 12:17:43 +02:00
if( pp_progress != null && pp_actionBar != null) {
pp_progress.setVisibility(View.GONE);
pp_actionBar.setVisibility(View.VISIBLE);
}
2017-06-03 18:18:27 +02:00
if( apiResponse.getError() != null){
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean show_error_messages = sharedpreferences.getBoolean(Helper.SET_SHOW_ERROR_MESSAGES, true);
if( show_error_messages)
2017-06-03 18:18:27 +02:00
Toast.makeText(getApplicationContext(), apiResponse.getError().getError(),Toast.LENGTH_LONG).show();
return;
}
final List<Account> accounts = apiResponse.getAccounts();
2017-05-26 17:20:36 +02:00
if( accounts != null && accounts.size() > 0){
AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(TootActivity.this, accounts);
toot_content.setThreshold(1);
2017-08-02 17:44:36 +02:00
toot_content.setAdapter(accountsListAdapter);
2017-08-09 18:27:03 +02:00
final String oldContent = toot_content.getText().toString();
String[] searchA = oldContent.substring(0,currentCursorPosition).split("@");
2017-08-10 09:03:42 +02:00
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());
}
2017-08-10 09:03:42 +02:00
if( !search.equals(""))
deltaSearch = deltaSearch.replace("@"+search,"");
2017-08-09 18:27:03 +02:00
String newContent = oldContent.substring(0,currentCursorPosition-searchLength);
newContent += deltaSearch;
newContent += "@" + account.getAcct() + " ";
2017-08-10 09:03:42 +02:00
int newPosition = newContent.length();
2017-08-09 18:27:03 +02:00
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()));
2017-08-09 18:27:03 +02:00
toot_content.setSelection(newPosition);
AccountsSearchAdapter accountsListAdapter = new AccountsSearchAdapter(TootActivity.this, new ArrayList<Account>());
toot_content.setThreshold(1);
toot_content.setAdapter(accountsListAdapter);
}
});
2017-05-05 16:36:04 +02:00
}
2017-10-09 18:35:43 +02:00
}
@Override
public void onRetrieveSearch(Results results, Error error) {
if( pp_progress != null && pp_actionBar != null) {
pp_progress.setVisibility(View.GONE);
pp_actionBar.setVisibility(View.VISIBLE);
}
if( results == null){
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean show_error_messages = sharedpreferences.getBoolean(Helper.SET_SHOW_ERROR_MESSAGES, true);
if( show_error_messages)
Toast.makeText(getApplicationContext(), R.string.toast_error, Toast.LENGTH_LONG).show();
return;
}
2017-10-09 18:35:43 +02:00
final List<String> tags = results.getHashtags();
if( tags != null && tags.size() > 0){
TagsSearchAdapter tagsSearchAdapter = new TagsSearchAdapter(TootActivity.this, tags);
toot_content.setThreshold(1);
toot_content.setAdapter(tagsSearchAdapter);
final String oldContent = toot_content.getText().toString();
String[] searchA = oldContent.substring(0,currentCursorPosition).split("@");
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) {
String tag = tags.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 += "#" + tag + " ";
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);
TagsSearchAdapter tagsSearchAdapter = new TagsSearchAdapter(TootActivity.this, new ArrayList<String>());
toot_content.setThreshold(1);
toot_content.setAdapter(tagsSearchAdapter);
}
});
}
2017-05-05 16:36:04 +02:00
}
2017-07-16 19:04:53 +02:00
private void restoreToot(long id){
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
StoredStatus draft = new StatusStoredDAO(TootActivity.this, db).getStatus(id);
Status status = draft.getStatus();
//Retrieves attachments
restored = id;
2017-07-16 19:04:53 +02:00
attachments = status.getMedia_attachments();
2017-08-06 17:03:15 +02:00
int childCount = toot_picture_container.getChildCount();
ArrayList<ImageView> toRemove = new ArrayList<>();
if( childCount > 0 ){
for(int i = 0 ; i < childCount ; i++){
if( toot_picture_container.getChildAt(i) instanceof ImageView)
toRemove.add((ImageView) toot_picture_container.getChildAt(i));
}
if( toRemove.size() > 0){
for(ImageView imageView: toRemove)
toot_picture_container.removeView(imageView);
}
toRemove.clear();
}
2017-07-16 19:04:53 +02:00
loading_picture.setVisibility(View.GONE);
if( attachments != null && attachments.size() > 0){
toot_picture_container.setVisibility(View.VISIBLE);
2017-08-02 17:44:36 +02:00
picture_scrollview.setVisibility(View.VISIBLE);
2017-07-16 19:04:53 +02:00
int i = 0 ;
for(Attachment attachment: attachments){
String url = attachment.getPreview_url();
if( url == null || url.trim().equals(""))
url = attachment.getUrl();
final ImageView imageView = new ImageView(getApplicationContext());
imageView.setId(Integer.parseInt(attachment.getId()));
imageLoader.displayImage(url, imageView, options);
LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
imParams.setMargins(20, 5, 20, 5);
imParams.height = (int) Helper.convertDpToPixel(100, getApplicationContext());
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
toot_picture_container.addView(imageView, i, imParams);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showRemove(imageView.getId());
}
});
if( attachments.size() < 4)
toot_picture.setEnabled(true);
toot_sensitive.setVisibility(View.VISIBLE);
i++;
}
}else {
toot_picture_container.setVisibility(View.GONE);
}
//Sensitive content
toot_sensitive.setChecked(status.isSensitive());
if( status.getSpoiler_text() != null && status.getSpoiler_text().length() > 0 ){
toot_cw_content.setText(status.getSpoiler_text());
toot_cw_content.setVisibility(View.VISIBLE);
}else {
toot_cw_content.setText("");
toot_cw_content.setVisibility(View.GONE);
}
String content = status.getContent();
toot_content.setText(content);
toot_space_left.setText(String.valueOf(toot_content.length()));
2017-07-16 19:04:53 +02:00
toot_content.setSelection(toot_content.getText().length());
switch (status.getVisibility()){
case "public":
visibility = "public";
toot_visibility.setImageResource(R.drawable.ic_action_globe);
break;
case "unlisted":
visibility = "unlisted";
toot_visibility.setImageResource(R.drawable.ic_action_lock_open);
break;
case "private":
visibility = "private";
toot_visibility.setImageResource(R.drawable.ic_action_lock_closed);
break;
case "direct":
visibility = "direct";
toot_visibility.setImageResource(R.drawable.ic_local_post_office);
break;
}
changeColor();
2017-07-16 19:04:53 +02:00
//The current id is set to the draft
currentToId = draft.getId();
tootReply = draft.getStatusReply();
if( tootReply != null) {
tootReply();
2017-10-01 19:01:15 +02:00
}else {
2017-07-21 21:09:32 +02:00
if( title != null)
title.setText(getString(R.string.toot_title));
else
setTitle(R.string.toot_title);
}
2017-10-01 19:01:15 +02:00
invalidateOptionsMenu();
initialContent = toot_content.getText().toString();
2017-08-18 16:54:43 +02:00
toot_space_left.setText(String.valueOf(toot_content.getText().length() + toot_cw_content.getText().length()));
2017-07-16 19:04:53 +02:00
}
2017-08-02 17:44:36 +02:00
private void tootReply(){
SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
2017-07-21 21:09:32 +02:00
if( title != null)
title.setText(getString(R.string.toot_title_reply));
else
setTitle(R.string.toot_title_reply);
2017-10-04 15:57:53 +02:00
String userId;
if( accountReply == null)
userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
else
userId = accountReply.getId();
2017-08-08 18:15:37 +02:00
switch (tootReply.getVisibility()){
case "public":
visibility = "public";
toot_visibility.setImageResource(R.drawable.ic_action_globe);
break;
case "unlisted":
visibility = "unlisted";
toot_visibility.setImageResource(R.drawable.ic_action_lock_open);
break;
case "private":
visibility = "private";
toot_visibility.setImageResource(R.drawable.ic_action_lock_closed);
break;
case "direct":
visibility = "direct";
toot_visibility.setImageResource(R.drawable.ic_local_post_office);
break;
}
changeColor();
//If toot is not restored
if( restored == -1 ){
//Retrieves mentioned accounts + OP and adds them at the beginin of the toot
ArrayList<String> mentionedAccountsAdded = new ArrayList<>();
if( tootReply.getAccount() != null && tootReply.getAccount().getAcct() != null && !tootReply.getAccount().getId().equals(userId)) {
toot_content.setText(String.format("@%s ", tootReply.getAccount().getAcct()));
mentionedAccountsAdded.add(tootReply.getAccount().getAcct());
}
if( tootReply.getMentions() != null ){
for(Mention mention : tootReply.getMentions()){
if( mention.getAcct() != null && !mention.getId().equals(userId) && !mentionedAccountsAdded.contains(mention.getAcct())) {
mentionedAccountsAdded.add(mention.getAcct());
String tootTemp = String.format("@%s ", mention.getAcct());
toot_content.setText(String.format("%s ", (toot_content.getText().toString() + " " + tootTemp)));
}
}
}
2017-09-20 16:53:46 +02:00
toot_content.setText(toot_content.getText().toString().trim());
if (toot_content.getText().toString().startsWith("@")) {
2017-09-20 16:53:46 +02:00
//Put a "<trim>dot<space>" at the end of all mentioned account to force capitalization
2017-09-24 10:02:56 +02:00
toot_content.append("\n");
}
toot_space_left.setText(String.valueOf(toot_content.length()));
toot_content.setSelection(toot_content.getText().length()); //Put cursor at the end
}
initialContent = toot_content.getText().toString();
}
2017-07-16 17:09:35 +02:00
private void storeToot(boolean message){
2017-07-15 14:59:09 +02:00
//Nothing to store here....
if(toot_content.getText().toString().trim().length() == 0 && (attachments == null || attachments.size() <1) && toot_cw_content.getText().toString().trim().length() == 0)
return;
if( initialContent.equals(toot_content.getText().toString()))
return;
2017-07-15 14:59:09 +02:00
Status toot = new Status();
toot.setSensitive(isSensitive);
toot.setMedia_attachments(attachments);
if( toot_cw_content.getText().toString().trim().length() > 0)
toot.setSpoiler_text(toot_cw_content.getText().toString().trim());
toot.setVisibility(visibility);
toot.setContent(toot_content.getText().toString().trim());
2017-09-22 14:44:00 +02:00
2017-07-15 14:59:09 +02:00
if( tootReply != null)
toot.setIn_reply_to_id(tootReply.getId());
SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
try{
if( currentToId == -1 ) {
currentToId = new StatusStoredDAO(TootActivity.this, db).insertStatus(toot, tootReply);
2017-07-15 14:59:09 +02:00
}else{
StoredStatus storedStatus = new StatusStoredDAO(TootActivity.this, db).getStatus(currentToId);
if( storedStatus != null ){
new StatusStoredDAO(TootActivity.this, db).updateStatus(currentToId, toot);
}else { //Might have been deleted, so it needs insertion
new StatusStoredDAO(TootActivity.this, db).insertStatus(toot, tootReply);
2017-07-15 14:59:09 +02:00
}
}
2017-07-16 17:09:35 +02:00
if( message )
Toast.makeText(getApplicationContext(), R.string.toast_toot_saved, Toast.LENGTH_LONG).show();
2017-07-15 14:59:09 +02:00
}catch (Exception e){
2017-07-16 17:09:35 +02:00
if( message)
Toast.makeText(getApplicationContext(), R.string.toast_error, Toast.LENGTH_LONG).show();
2017-07-15 14:59:09 +02:00
}
}
private void changeColor(){
2017-08-13 18:31:44 +02:00
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
2017-08-13 18:31:44 +02:00
if( theme == Helper.THEME_DARK) {
changeDrawableColor(TootActivity.this, R.drawable.ic_action_globe, R.color.dark_text);
changeDrawableColor(TootActivity.this, R.drawable.ic_action_lock_open, R.color.dark_text);
changeDrawableColor(TootActivity.this, R.drawable.ic_action_lock_closed, R.color.dark_text);
changeDrawableColor(TootActivity.this, R.drawable.ic_local_post_office, R.color.dark_text);
changeDrawableColor(TootActivity.this, R.drawable.ic_action_camera, R.color.dark_text);
changeDrawableColor(TootActivity.this, R.drawable.ic_skip_previous, R.color.dark_text);
changeDrawableColor(TootActivity.this, R.drawable.ic_skip_next, R.color.dark_text);
changeDrawableColor(TootActivity.this, R.drawable.ic_check, R.color.dark_text);
}else {
2017-08-13 18:31:44 +02:00
changeDrawableColor(TootActivity.this, R.drawable.ic_action_globe, R.color.white);
changeDrawableColor(TootActivity.this, R.drawable.ic_action_lock_open, R.color.white);
changeDrawableColor(TootActivity.this, R.drawable.ic_action_lock_closed, R.color.white);
changeDrawableColor(TootActivity.this, R.drawable.ic_local_post_office, R.color.white);
changeDrawableColor(TootActivity.this, R.drawable.ic_action_camera, R.color.white);
changeDrawableColor(TootActivity.this, R.drawable.ic_skip_previous, R.color.white);
changeDrawableColor(TootActivity.this, R.drawable.ic_skip_next, R.color.white);
changeDrawableColor(TootActivity.this, R.drawable.ic_check, R.color.white);
}
}
2017-10-09 18:35:43 +02:00
2017-05-05 16:36:04 +02:00
}