This commit is contained in:
tom79 2019-06-05 18:23:44 +02:00
parent 1cb3e414b6
commit 896c40490a
5 changed files with 232 additions and 531 deletions

View File

@ -30,7 +30,6 @@ import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
@ -92,13 +91,21 @@ import com.github.stom79.mytransl.client.HttpsConnectionException;
import com.github.stom79.mytransl.translate.Translate;
import com.vanniktech.emoji.EmojiPopup;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.ServerResponse;
import net.gotev.uploadservice.UploadInfo;
import net.gotev.uploadservice.UploadNotificationConfig;
import net.gotev.uploadservice.UploadStatusDelegate;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
@ -112,7 +119,6 @@ import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import app.fedilab.android.BuildConfig;
import app.fedilab.android.client.API;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
@ -128,6 +134,7 @@ import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.StoredStatus;
import app.fedilab.android.client.Entities.Tag;
import app.fedilab.android.client.Entities.Version;
import app.fedilab.android.client.GNUAPI;
import app.fedilab.android.client.HttpsConnection;
import app.fedilab.android.drawers.AccountsReplyAdapter;
import app.fedilab.android.drawers.AccountsSearchAdapter;
@ -135,6 +142,7 @@ import app.fedilab.android.drawers.CustomEmojiAdapter;
import app.fedilab.android.drawers.DraftsListAdapter;
import app.fedilab.android.drawers.EmojisSearchAdapter;
import app.fedilab.android.drawers.TagsSearchAdapter;
import app.fedilab.android.helper.FileNameCleaner;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.helper.MastalabAutoCompleteTextView;
import app.fedilab.android.jobs.ScheduledTootsSyncJob;
@ -169,7 +177,7 @@ import static app.fedilab.android.helper.Helper.countWithEmoji;
* Toot activity class
*/
public class TootActivity extends BaseActivity implements OnPostActionInterface, OnRetrieveSearcAccountshInterface, OnRetrieveAttachmentInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveAccountsReplyInterface, OnRetrieveEmojiInterface, OnDownloadInterface {
public class TootActivity extends BaseActivity implements OnPostActionInterface, OnRetrieveSearcAccountshInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveAccountsReplyInterface, OnRetrieveEmojiInterface, OnDownloadInterface, OnRetrieveAttachmentInterface {
private String visibility;
@ -466,29 +474,6 @@ public class TootActivity extends BaseActivity implements OnPostActionInterface,
toot_space_left.setText(String.valueOf(countLength()));
}
if (tootMention != null && urlMention != null) {
if (fileMention != null) {
Bitmap pictureMention = BitmapFactory.decodeFile(getCacheDir() + "/" + fileMention);
AsyncTask.execute(new Runnable() {
@Override
public void run() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
pictureMention.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
runOnUiThread(new Runnable() {
@Override
public void run() {
toot_picture_container.setVisibility(View.VISIBLE);
picture_scrollview.setVisibility(View.VISIBLE);
toot_picture.setEnabled(false);
toot_it.setEnabled(false);
new HttpsConnection(TootActivity.this, instance).upload(bs, fileMention, account, TootActivity.this);
}
});
}
});
}
toot_content.setText(String.format("\n\nvia @%s\n\n%s\n\n", tootMention, urlMention));
toot_space_left.setText(String.valueOf(countLength()));
}
@ -960,30 +945,23 @@ public class TootActivity extends BaseActivity implements OnPostActionInterface,
}
uploadSharedImage(mArrayUri);
} else {
try {
String filename = Helper.getFileName(TootActivity.this, data.getData());
ContentResolver cr = getContentResolver();
String mime = cr.getType(data.getData());
if (mime != null && (mime.toLowerCase().contains("video") || mime.toLowerCase().contains("gif"))) {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
new HttpsConnection(TootActivity.this, instance).upload(inputStream, filename, account, TootActivity.this);
} else if (mime != null && mime.toLowerCase().contains("image")) {
if( photo_editor) {
Intent intent = new Intent(TootActivity.this, PhotoEditorActivity.class);
Bundle b = new Bundle();
intent.putExtra("imageUri", data.getData().toString());
intent.putExtras(b);
startActivity(intent);
}else{
new asyncPicture(TootActivity.this, account, data.getData()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}else {
Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show();
String filename = Helper.getFileName(TootActivity.this, data.getData());
ContentResolver cr = getContentResolver();
String mime = cr.getType(data.getData());
if (mime != null && (mime.toLowerCase().contains("video") || mime.toLowerCase().contains("gif"))) {
upload(TootActivity.this, data.getData(), filename);
} else if (mime != null && mime.toLowerCase().contains("image")) {
if( photo_editor) {
Intent intent = new Intent(TootActivity.this, PhotoEditorActivity.class);
Bundle b = new Bundle();
intent.putExtra("imageUri", data.getData().toString());
intent.putExtras(b);
startActivity(intent);
}else{
upload(TootActivity.this, data.getData(), filename);
}
} catch (FileNotFoundException e) {
}else {
Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show();
toot_picture.setEnabled(true);
toot_it.setEnabled(true);
}
}
@ -1019,7 +997,7 @@ public class TootActivity extends BaseActivity implements OnPostActionInterface,
static class asyncPicture extends AsyncTask<Void, Void, Void> {
class asyncPicture extends AsyncTask<Void, Void, Void> {
ByteArrayInputStream bs;
WeakReference<Activity> activityWeakReference;
@ -1067,7 +1045,7 @@ public class TootActivity extends BaseActivity implements OnPostActionInterface,
toot_it.setEnabled(false);
String filename = Helper.getFileName(this.activityWeakReference.get(), uriFile);
filesMap.put(filename, uriFile);
new HttpsConnection(this.activityWeakReference.get(), instance).upload(bs, filename,account, (TootActivity) this.activityWeakReference.get());
upload(activityWeakReference.get(), uriFile, filename);
}
}
}
@ -1084,22 +1062,15 @@ public class TootActivity extends BaseActivity implements OnPostActionInterface,
Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show();
return;
}
try {
String filename = Helper.getFileName(TootActivity.this, imageUri);
ContentResolver cr = getContentResolver();
String mime = cr.getType(imageUri);
if(mime != null && (mime.toLowerCase().contains("video") || mime.toLowerCase().contains("gif")) ) {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
new HttpsConnection(TootActivity.this, instance).upload(inputStream, filename, account, TootActivity.this);
} else if(mime != null && mime.toLowerCase().contains("image")) {
new asyncPicture(TootActivity.this, account, intent.getData()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else {
Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
String filename = Helper.getFileName(TootActivity.this, imageUri);
ContentResolver cr = getContentResolver();
String mime = cr.getType(imageUri);
if(mime != null && (mime.toLowerCase().contains("video") || mime.toLowerCase().contains("gif")) ) {
upload(TootActivity.this, imageUri, filename);
} else if(mime != null && mime.toLowerCase().contains("image")) {
new asyncPicture(TootActivity.this, account, intent.getData()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else {
Toasty.error(getApplicationContext(),getString(R.string.toot_select_image_error),Toast.LENGTH_LONG).show();
toot_picture.setEnabled(true);
toot_it.setEnabled(true);
}
}
@ -1755,139 +1726,21 @@ public class TootActivity extends BaseActivity implements OnPostActionInterface,
return true;
}
@Override
public void onRetrieveAttachment(final Attachment attachment, String fileName, Error error) {
if( error != null || attachment == null){
if( error != null)
Toasty.error(getApplicationContext(), error.getError(), Toast.LENGTH_LONG).show();
else
Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show();
if( attachments.size() == 0 )
toot_picture_container.setVisibility(View.GONE);
toot_picture.setEnabled(true);
toot_it.setEnabled(true);
return;
}
boolean alreadyAdded = false;
int index = 0;
for(Attachment attach_: this.attachments){
if( attach_.getId().equals(attachment.getId())){
alreadyAdded = true;
break;
}
index++;
}
if( !alreadyAdded){
toot_picture_container.setVisibility(View.VISIBLE);
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()));
if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){
if( fileName != null && filesMap.containsKey(fileName)){
Uri uri = filesMap.get(fileName);
Glide.with(imageView.getContext())
.asBitmap()
.load(uri)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
});
}
}else {
Glide.with(imageView.getContext())
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
});
}
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);
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, false);
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(String.format("%s\n\n%s",toot_content.getText().toString(), attachment.getText_url()));
toot_space_left.setText(String.valueOf(countLength()));
//Moves the cursor
toot_content.setSelection(selectionBefore);
}
imageView.setTag(attachment.getId());
toot_picture_container.addView(imageView, attachments.size(), imParams);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
showRemove(imageView.getId());
return false;
}
});
String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null);
if (instanceVersion != null) {
Version currentVersion = new Version(instanceVersion);
Version minVersion = new Version("2.0");
if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) {
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAddDescription(attachment);
}
});
}
}
attachments.add(attachment);
addBorder();
if (attachments.size() < max_media_count)
toot_picture.setEnabled(true);
toot_it.setEnabled(true);
toot_sensitive.setVisibility(View.VISIBLE);
if( account.isSensitive()){
toot_sensitive.setChecked(true);
}
picture_scrollview.setVisibility(View.VISIBLE);
}else {
if( attachments.size() > index && attachment.getDescription() != null) {
attachments.get(index).setDescription(attachment.getDescription());
}
}
}
@Override
public void onDownloaded(String pathToFile, String url, Error error) {
picture_scrollview.setVisibility(View.VISIBLE);
Bitmap pictureMention = BitmapFactory.decodeFile(pathToFile);
if( pictureMention != null) {
String filename = pathToFile.substring(pathToFile.lastIndexOf("/") + 1);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if( filename.contains(".png") || filename.contains(".PNG"))
pictureMention.compress(Bitmap.CompressFormat.PNG, 0, bos);
else
pictureMention.compress(Bitmap.CompressFormat.JPEG, 80, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
toot_picture_container.setVisibility(View.VISIBLE);
toot_picture.setEnabled(false);
toot_it.setEnabled(false);
new HttpsConnection(TootActivity.this, instance).upload(bs, filename, account, TootActivity.this);
}
Uri uri = Uri.fromFile(new File(pathToFile));
String filename = FileNameCleaner.cleanFileName(url);
toot_picture_container.setVisibility(View.VISIBLE);
toot_picture.setEnabled(false);
toot_it.setEnabled(false);
upload(TootActivity.this, uri, filename);
}
@Override
public void onRetrieveAttachment(Attachment attachment, String fileName, Error error) {
}
@Override
@ -2280,6 +2133,180 @@ public class TootActivity extends BaseActivity implements OnPostActionInterface,
}
}
private void upload(Context context, Uri uri, String fname){
try {
final String fileName = FileNameCleaner.cleanFileName(fname);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String scheme = sharedpreferences.getString(Helper.SET_ONION_SCHEME+Helper.getLiveInstance(context), "https");
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
String url = null;
if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
url = scheme + "://" + Helper.getLiveInstance(context) + "/api/v1/media";
}else {
url = scheme + "://" + Helper.getLiveInstance(context) + "/api/media/upload.json";
}
UploadNotificationConfig uploadConfig = new UploadNotificationConfig();
uploadConfig
.setClearOnActionForAllStatuses(true);
uploadConfig.getProgress().message = getString(R.string.uploading);
uploadConfig.getCompleted().autoClear = true;
MultipartUploadRequest request = new MultipartUploadRequest(context, url)
.addHeader("Authorization", "Bearer " + token)
.setNotificationConfig(uploadConfig);
if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
request.addFileToUpload(uri.toString().replace("file://",""), "file");
}else {
request.addFileToUpload(uri.toString().replace("file://",""), "media");
};
request.addParameter("filename", fileName).setMaxRetries(1)
.setDelegate(new UploadStatusDelegate() {
@Override
public void onProgress(Context context, UploadInfo uploadInfo) {
// your code here
}
@Override
public void onError(Context context, UploadInfo uploadInfo, ServerResponse serverResponse,
Exception exception) {
Toasty.error(getApplicationContext(), getString(R.string.toast_error), Toast.LENGTH_LONG).show();
if( attachments.size() == 0 )
toot_picture_container.setVisibility(View.GONE);
toot_picture.setEnabled(true);
toot_it.setEnabled(true);
exception.printStackTrace();
}
@Override
public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {
Attachment attachment;
JSONObject response = null;
try {
response = new JSONObject(serverResponse.getBodyAsString());
if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
attachment = API.parseAttachmentResponse(response);
else
attachment = GNUAPI.parseUploadedAttachmentResponse(response);
boolean alreadyAdded = false;
int index = 0;
for(Attachment attach_: attachments){
if( attach_.getId().equals(attachment.getId())){
alreadyAdded = true;
break;
}
index++;
}
if( !alreadyAdded){
toot_picture_container.setVisibility(View.VISIBLE);
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()));
if( MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA){
if( fileName != null && filesMap.containsKey(fileName)){
Uri uri = filesMap.get(fileName);
Glide.with(imageView.getContext())
.asBitmap()
.load(uri)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
});
}
}else {
Glide.with(imageView.getContext())
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
});
}
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);
final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, false);
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(String.format("%s\n\n%s",toot_content.getText().toString(), attachment.getText_url()));
toot_space_left.setText(String.valueOf(countLength()));
//Moves the cursor
toot_content.setSelection(selectionBefore);
}
imageView.setTag(attachment.getId());
toot_picture_container.addView(imageView, attachments.size(), imParams);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
showRemove(imageView.getId());
return false;
}
});
String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION + userId + instance, null);
if (instanceVersion != null) {
Version currentVersion = new Version(instanceVersion);
Version minVersion = new Version("2.0");
if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) {
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAddDescription(attachment);
}
});
}
}
attachments.add(attachment);
addBorder();
if (attachments.size() < max_media_count)
toot_picture.setEnabled(true);
toot_it.setEnabled(true);
toot_sensitive.setVisibility(View.VISIBLE);
if( account.isSensitive()){
toot_sensitive.setChecked(true);
}
picture_scrollview.setVisibility(View.VISIBLE);
}else {
if( attachments.size() > index && attachment.getDescription() != null) {
attachments.get(index).setDescription(attachment.getDescription());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(Context context, UploadInfo uploadInfo) {
// your code here
}
})
.startUpload();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@Override
public void onRetrieveSearch(APIResponse apiResponse) {
if( pp_progress != null && pp_actionBar != null) {

View File

@ -4904,7 +4904,7 @@ public class API {
* @param resobj JSONObject
* @return Relationship
*/
static Attachment parseAttachmentResponse(JSONObject resobj){
public static Attachment parseAttachmentResponse(JSONObject resobj){
Attachment attachment = new Attachment();
try {

View File

@ -2265,7 +2265,7 @@ public class GNUAPI {
* @param resobj JSONObject
* @return Relationship
*/
static Attachment parseUploadedAttachmentResponse(JSONObject resobj){
public static Attachment parseUploadedAttachmentResponse(JSONObject resobj){
Attachment attachment = new Attachment();
try {

View File

@ -1216,339 +1216,6 @@ public class HttpsConnection {
}
/**
* Upload method - https only
* @param inputStream InputStream of the file to upload
* @param listener - OnRetrieveAttachmentInterface: listener to send information about attachment once uploaded.
*/
public void upload(final InputStream inputStream, String fname, Account account, final OnRetrieveAttachmentInterface listener) {
final String fileName = FileNameCleaner.cleanFileName(fname);
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
if( account == null){
return;
}
this.instance = account.getInstance();
String token = account.getToken();
if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
URL url;
if(MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
url = new URL("https://" + account.getInstance() + "/api/v1/media");
else
url = new URL("https://" + account.getInstance() + "/api/media/upload.json");
ByteArrayOutputStream ous = null;
try {
try {
byte[] buffer = new byte[CHUNK_SIZE]; // or other buffer size
ous = new ByteArrayOutputStream();
int read;
while ((read = inputStream.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
ous.flush();
} finally {
if (ous != null)
ous.close();
}
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
}
byte[] pixels = ous.toByteArray();
int lengthSent = pixels.length;
lengthSent += (twoHyphens + boundary + lineEnd).getBytes().length;
lengthSent += (twoHyphens + boundary + twoHyphens +lineEnd).getBytes().length;
if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
lengthSent += ("Content-Disposition: form-data; name=\"file\"; filename=\""+fileName+"\"" + lineEnd).getBytes().length;
else
lengthSent += ("Content-Disposition: form-data; name=\"media\"; filename=\""+fileName+"\"" + lineEnd).getBytes().length;
lengthSent += 2 * (lineEnd).getBytes().length;
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setFixedLengthStreamingMode(lengthSent);
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory(instance));
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setUseCaches(false);
httpsURLConnection.setRequestMethod("POST");
if (token != null && !token.startsWith("Basic "))
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
else if( token != null && token.startsWith("Basic "))
httpsURLConnection.setRequestProperty("Authorization", token);
httpsURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpsURLConnection.setRequestProperty("Cache-Control", "no-cache");
httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpsURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(httpsURLConnection.getOutputStream());
request.writeBytes(twoHyphens + boundary + lineEnd);
if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""+fileName+"\"" + lineEnd);
else
request.writeBytes("Content-Disposition: form-data; name=\"media\"; filename=\""+fileName+"\"" + lineEnd);
request.writeBytes(lineEnd);
//request.write(pixels);
int totalSize = pixels.length;
int bytesTransferred = 0;
while (bytesTransferred < totalSize) {
int nextChunkSize = totalSize - bytesTransferred;
if (nextChunkSize > CHUNK_SIZE) {
nextChunkSize = CHUNK_SIZE;
}
request.write(pixels, bytesTransferred, nextChunkSize);
bytesTransferred += nextChunkSize;
final int progress = 100 * bytesTransferred / totalSize;
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(progress>0?progress:101);
}
});
request.flush();
}
request.writeBytes(lineEnd);
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
request.flush();
request.close();
if (200 != httpsURLConnection.getResponseCode()) {
String error = null;
if( httpsURLConnection.getErrorStream() != null) {
InputStream stream = httpsURLConnection.getErrorStream();
if (stream == null) {
stream = httpsURLConnection.getInputStream();
}
try (Scanner scanner = new Scanner(stream)) {
scanner.useDelimiter("\\Z");
error = scanner.next();
}catch (Exception ignored){}
}
int responseCode = httpsURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
InputStream responseStream = new BufferedInputStream(httpsURLConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String response = converToString(httpsURLConnection.getInputStream());
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(101);
}
});
Attachment attachment;
if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
attachment = API.parseAttachmentResponse(new JSONObject(response));
else
attachment = GNUAPI.parseUploadedAttachmentResponse(new JSONObject(response));
responseStreamReader.close();
responseStream.close();
httpsURLConnection.getInputStream().close();
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(attachment, fileName,null);
}
});
} catch (Exception e) {
e.printStackTrace();
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(101);
}
});
final Error error = new Error();
error.setError(e.getMessage());
if (httpsURLConnection != null)
try {
httpsURLConnection.getInputStream().close();
} catch (Exception ignored) { }
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(null, fileName, error);
}
});
}
}
}).start();
}else {
new Thread(new Runnable() {
@Override
public void run() {
try {
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context));
Account account = new AccountDAO(context, db).getUniqAccount(userId, instance);
final URL url = new URL("http://" + account.getInstance() + "/api/v1/media");
ByteArrayOutputStream ous = null;
try {
try {
byte[] buffer = new byte[CHUNK_SIZE]; // or other buffer size
ous = new ByteArrayOutputStream();
int read;
while ((read = inputStream.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
ous.flush();
} finally {
if (ous != null)
ous.close();
}
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {}
byte[] pixels = ous.toByteArray();
int lengthSent = pixels.length;
lengthSent += (twoHyphens + boundary + lineEnd).getBytes().length;
lengthSent += (twoHyphens + boundary + twoHyphens +lineEnd).getBytes().length;
lengthSent += ("Content-Disposition: form-data; name=\"file\";filename=\""+fileName+"\"" + lineEnd).getBytes().length;
lengthSent += 2 * (lineEnd).getBytes().length;
if( proxy !=null )
httpURLConnection = (HttpURLConnection)url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setFixedLengthStreamingMode(lengthSent);
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
if (token != null && !token.startsWith("Basic "))
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
else if( token != null && token.startsWith("Basic "))
httpURLConnection.setRequestProperty("Authorization", token);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);
DataOutputStream request = new DataOutputStream(httpURLConnection.getOutputStream());
request.writeBytes(twoHyphens + boundary + lineEnd);
request.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+fileName+"\"" + lineEnd);
request.writeBytes(lineEnd);
//request.write(pixels);
int totalSize = pixels.length;
int bytesTransferred = 0;
while (bytesTransferred < totalSize) {
int nextChunkSize = totalSize - bytesTransferred;
if (nextChunkSize > CHUNK_SIZE) {
nextChunkSize = CHUNK_SIZE;
}
request.write(pixels, bytesTransferred, nextChunkSize);
bytesTransferred += nextChunkSize;
final int progress = 100 * bytesTransferred / totalSize;
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(progress>0?progress:101);
}});
request.flush();
}
request.writeBytes(lineEnd);
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
request.flush();
request.close();
if (200 != httpURLConnection.getResponseCode()) {
String error = null;
if( httpURLConnection.getErrorStream() != null) {
InputStream stream = httpURLConnection.getErrorStream();
if (stream == null) {
stream = httpURLConnection.getInputStream();
}
try (Scanner scanner = new Scanner(stream)) {
scanner.useDelimiter("\\Z");
error = scanner.next();
}
}
int responseCode = httpURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
InputStream responseStream = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String response = converToString(httpsURLConnection.getInputStream());
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(101);
}});
Attachment attachment;
if( MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.GNU && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA)
attachment = API.parseAttachmentResponse(new JSONObject(response));
else
attachment = GNUAPI.parseUploadedAttachmentResponse(new JSONObject(response));
responseStreamReader.close();
responseStream.close();
httpURLConnection.getInputStream().close();
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(attachment, fileName,null);
}});
}catch (Exception e) {
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(101);
}});
final Error error = new Error();
error.setError(e.getMessage());
if(httpURLConnection != null)
try {
httpsURLConnection.getInputStream().close();
} catch (Exception ignored) { }
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(null, fileName,error);
}});
}
}
}).start();
}
}
public String put(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if( urlConnection.startsWith("https://")) {

View File

@ -3984,4 +3984,11 @@ public class Helper {
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
}