fedilab-Android-App/app/src/main/java/fr/gouv/etalab/mastodon/client/HttpsConnection.java

1703 lines
83 KiB
Java
Raw Normal View History

2017-11-18 08:27:25 +01:00
package fr.gouv.etalab.mastodon.client;
/* Copyright 2017 Thomas Schneider
*
* This file is a part of Mastalab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Mastalab; if not,
* see <http://www.gnu.org/licenses>. */
2017-11-18 09:30:58 +01:00
import android.content.Context;
2017-11-18 11:25:04 +01:00
import android.content.SharedPreferences;
2018-08-16 12:08:38 +02:00
import android.database.sqlite.SQLiteDatabase;
2017-11-18 09:30:58 +01:00
import android.os.Build;
import android.text.Html;
import android.text.SpannableString;
import com.google.common.io.ByteStreams;
2017-11-18 09:44:54 +01:00
import org.json.JSONObject;
2017-11-18 09:30:58 +01:00
import java.io.BufferedInputStream;
2017-11-18 08:27:25 +01:00
import java.io.BufferedReader;
2017-11-18 09:30:58 +01:00
import java.io.ByteArrayOutputStream;
2017-11-18 08:27:25 +01:00
import java.io.DataOutputStream;
2017-11-18 09:30:58 +01:00
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
2017-11-18 08:27:25 +01:00
import java.io.IOException;
2017-11-18 09:30:58 +01:00
import java.io.InputStream;
2017-11-18 08:27:25 +01:00
import java.io.InputStreamReader;
2018-04-22 18:02:00 +02:00
import java.io.OutputStream;
2018-01-19 18:59:30 +01:00
import java.net.Authenticator;
2017-11-18 12:22:41 +01:00
import java.net.HttpURLConnection;
2018-01-19 18:59:30 +01:00
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
2017-11-18 08:27:25 +01:00
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
2018-08-17 18:55:38 +02:00
import java.util.Scanner;
2017-11-18 08:27:25 +01:00
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
2017-11-18 12:22:41 +01:00
import fr.gouv.etalab.mastodon.R;
2017-11-18 19:31:43 +01:00
import fr.gouv.etalab.mastodon.activities.MediaActivity;
import fr.gouv.etalab.mastodon.activities.TootActivity;
2018-08-16 12:08:38 +02:00
import fr.gouv.etalab.mastodon.client.Entities.Account;
2017-11-18 09:44:54 +01:00
import fr.gouv.etalab.mastodon.client.Entities.Attachment;
2017-11-18 11:25:04 +01:00
import fr.gouv.etalab.mastodon.client.Entities.Error;
import fr.gouv.etalab.mastodon.helper.Helper;
2017-11-18 12:22:41 +01:00
import fr.gouv.etalab.mastodon.interfaces.OnDownloadInterface;
2017-11-18 09:30:58 +01:00
import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAttachmentInterface;
2018-08-16 12:08:38 +02:00
import fr.gouv.etalab.mastodon.sqlite.AccountDAO;
import fr.gouv.etalab.mastodon.sqlite.Sqlite;
2017-11-18 09:30:58 +01:00
2017-11-18 08:27:25 +01:00
/**
* Created by Thomas on 17/11/2017.
* Manage http queries
*/
public class HttpsConnection {
private HttpsURLConnection httpsURLConnection;
2018-01-24 15:56:33 +01:00
private HttpURLConnection httpURLConnection;
2017-11-18 08:27:25 +01:00
private String since_id, max_id;
2017-11-18 09:30:58 +01:00
private Context context;
2017-11-22 07:51:12 +01:00
private int CHUNK_SIZE = 4096;
2018-01-19 18:59:30 +01:00
private SharedPreferences sharedpreferences;
private Proxy proxy;
2017-11-18 09:30:58 +01:00
2017-11-18 11:25:04 +01:00
public HttpsConnection(Context context){
2017-11-18 09:30:58 +01:00
this.context = context;
2018-01-19 18:59:30 +01:00
sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean proxyEnabled = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false);
2018-01-20 09:46:28 +01:00
int type = sharedpreferences.getInt(Helper.SET_PROXY_TYPE, 0);
2018-01-19 18:59:30 +01:00
proxy = null;
if( proxyEnabled ){
2018-08-30 17:48:32 +02:00
try {
String host = sharedpreferences.getString(Helper.SET_PROXY_HOST, "127.0.0.1");
int port = sharedpreferences.getInt(Helper.SET_PROXY_PORT, 8118);
if( type == 0 )
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
else
proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(host, port));
final String login = sharedpreferences.getString(Helper.SET_PROXY_LOGIN, null);
final String pwd = sharedpreferences.getString(Helper.SET_PROXY_PASSWORD, null);
if( login != null) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
assert pwd != null;
return (new PasswordAuthentication(login,
pwd.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
}catch (Exception e){
proxy = null;
2018-01-19 18:59:30 +01:00
}
2018-08-30 17:48:32 +02:00
2018-01-19 18:59:30 +01:00
}
2017-11-18 09:30:58 +01:00
}
2017-11-18 08:27:25 +01:00
2017-12-10 18:37:58 +01:00
2017-11-18 12:22:41 +01:00
@SuppressWarnings("ConstantConditions")
2017-11-18 08:27:25 +01:00
public String get(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if( urlConnection.startsWith("https://")) {
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
2017-11-18 14:10:53 +01:00
}
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
URL url = new URL(urlConnection + "?" + postData);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setRequestProperty("http.keepAlive", "false");
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
if (token != null)
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpsURLConnection.setRequestMethod("GET");
String response;
if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) {
response = converToString(httpsURLConnection.getInputStream());
} else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
int responseCode = httpsURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpsURLConnection.getInputStream().close();
return response;
}else {
Map<String,Object> params = new LinkedHashMap<>();
if( paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
}
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
URL url = new URL(urlConnection + "?" + postData);
if( proxy !=null )
httpURLConnection = (HttpURLConnection)url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(timeout * 1000);
httpURLConnection.setRequestProperty("http.keepAlive", "false");
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
if( token != null)
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpURLConnection.setRequestMethod("GET");
String response;
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
response = converToString(httpsURLConnection.getInputStream());
}else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
int responseCode = httpURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpURLConnection.getInputStream().close();
return response;
2017-11-18 08:27:25 +01:00
}
}
2017-12-10 18:37:58 +01:00
public String get(String urlConnection) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if( urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
2018-01-19 18:59:30 +01:00
if( proxy !=null )
httpsURLConnection = (HttpsURLConnection)url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection)url.openConnection();
2017-12-10 18:37:58 +01:00
httpsURLConnection.setConnectTimeout(30 * 1000);
httpsURLConnection.setRequestProperty("http.keepAlive", "false");
httpsURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");
2017-12-12 18:17:01 +01:00
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
2017-12-10 18:37:58 +01:00
httpsURLConnection.setRequestMethod("GET");
String response;
2017-12-10 18:37:58 +01:00
if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) {
getSinceMaxId();
response = converToString(httpsURLConnection.getInputStream());
}else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
int responseCode = httpsURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
2017-12-10 18:37:58 +01:00
}
getSinceMaxId();
httpsURLConnection.getInputStream().close();
return response;
2017-12-10 18:37:58 +01:00
}else{
URL url = new URL(urlConnection);
2018-01-19 18:59:30 +01:00
if( proxy !=null )
httpURLConnection = (HttpURLConnection)url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection)url.openConnection();
2017-12-10 18:37:58 +01:00
httpURLConnection.setConnectTimeout(30 * 1000);
httpURLConnection.setRequestProperty("http.keepAlive", "false");
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");
httpURLConnection.setRequestMethod("GET");
String response;
2017-12-10 18:37:58 +01:00
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
getSinceMaxId();
response = converToString(httpsURLConnection.getInputStream());
}else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
int responseCode = httpURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
2017-12-10 18:37:58 +01:00
}
getSinceMaxId();
httpURLConnection.getInputStream().close();
return response;
2017-12-10 18:37:58 +01:00
}
}
2017-11-18 08:27:25 +01:00
public String post(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
2018-01-24 15:56:33 +01:00
if( urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
2017-11-18 14:10:53 +01:00
}
2018-01-24 15:56:33 +01:00
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
2017-11-18 08:27:25 +01:00
2018-01-24 15:56:33 +01:00
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
httpsURLConnection.setRequestMethod("POST");
if (token != null)
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
2017-11-18 14:10:53 +01:00
2018-01-24 15:56:33 +01:00
httpsURLConnection.getOutputStream().write(postDataBytes);
String response;
if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) {
getSinceMaxId();
response = converToString(httpsURLConnection.getInputStream());
2018-01-24 15:56:33 +01:00
} else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-01-24 15:56:33 +01:00
int responseCode = httpsURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpsURLConnection.getInputStream().close();
2018-01-24 15:56:33 +01:00
return response;
}else {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
}
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
if (token != null)
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
httpURLConnection.getOutputStream().write(postDataBytes);
String response;
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
getSinceMaxId();
response = converToString(httpsURLConnection.getInputStream());
2018-01-24 15:56:33 +01:00
} else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-01-24 15:56:33 +01:00
int responseCode = httpURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpURLConnection.getInputStream().close();
return response;
}
2017-11-18 08:27:25 +01:00
}
2017-12-27 08:57:07 +01:00
/***
* Download method which works for http and https connections
* @param downloadUrl String download url
* @param listener OnDownloadInterface, listener which manages progress
*/
2017-11-18 12:22:41 +01:00
public void download(final String downloadUrl, final OnDownloadInterface listener) {
new Thread(new Runnable() {
@Override
public void run() {
URL url;
2017-12-27 08:36:55 +01:00
HttpsURLConnection httpsURLConnection = null;
HttpURLConnection httpURLConnection = null;
if (downloadUrl.startsWith("https://")) {
try {
url = new URL(downloadUrl);
2018-01-19 18:59:30 +01:00
if( proxy !=null )
httpsURLConnection = (HttpsURLConnection)url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection)url.openConnection();
2017-12-27 08:36:55 +01:00
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
int responseCode = httpsURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpsURLConnection.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1,
downloadUrl.length());
2017-11-18 12:22:41 +01:00
}
2017-12-27 08:36:55 +01:00
// opens input stream from the HTTP connection
InputStream inputStream = httpsURLConnection.getInputStream();
File saveDir = context.getCacheDir();
final String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead;
byte[] buffer = new byte[CHUNK_SIZE];
int contentSize = httpsURLConnection.getContentLength();
int downloadedFileSize = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
downloadedFileSize += bytesRead;
if (context instanceof MediaActivity) {
final int currentProgress = (downloadedFileSize * 100) / contentSize;
((MediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(currentProgress>0?currentProgress:101);
2017-12-27 08:36:55 +01:00
}
});
}
}
outputStream.close();
inputStream.close();
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(saveFilePath, downloadUrl, null);
}
});
if (context instanceof MediaActivity)
((MediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(saveFilePath, downloadUrl, null);
}
});
2017-11-18 12:22:41 +01:00
} else {
2017-12-27 08:36:55 +01:00
final Error error = new Error();
error.setError(String.valueOf(responseCode));
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(null, downloadUrl, error);
}
});
if (context instanceof MediaActivity)
2017-11-19 16:32:00 +01:00
((MediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
2017-12-27 08:36:55 +01:00
listener.onDownloaded(null, downloadUrl, error);
2017-11-19 16:32:00 +01:00
}
});
2017-12-27 08:36:55 +01:00
2017-11-18 12:22:41 +01:00
}
2017-12-27 08:36:55 +01:00
} catch (IOException e) {
Error error = new Error();
error.setError(context.getString(R.string.toast_error));
}
} else {
try {
url = new URL(downloadUrl);
2018-01-19 18:59:30 +01:00
if( proxy !=null )
httpURLConnection = (HttpURLConnection)url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection)url.openConnection();
2017-12-27 08:36:55 +01:00
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpURLConnection.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1,
downloadUrl.length());
}
// opens input stream from the HTTP connection
InputStream inputStream = httpURLConnection.getInputStream();
File saveDir = context.getCacheDir();
final String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead;
byte[] buffer = new byte[CHUNK_SIZE];
int contentSize = httpURLConnection.getContentLength();
int downloadedFileSize = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
downloadedFileSize += bytesRead;
if (context instanceof MediaActivity) {
final int currentProgress = (downloadedFileSize * 100) / contentSize;
((MediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(currentProgress>0?currentProgress:101);
2017-12-27 08:36:55 +01:00
}
});
}
}
outputStream.close();
inputStream.close();
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(saveFilePath, downloadUrl, null);
}
});
if (context instanceof MediaActivity)
((MediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(saveFilePath, downloadUrl, null);
}
});
} else {
final Error error = new Error();
error.setError(String.valueOf(responseCode));
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(null, downloadUrl, error);
}
});
if (context instanceof MediaActivity)
((MediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(null, downloadUrl, error);
}
});
2017-11-18 19:25:00 +01:00
2017-12-27 08:36:55 +01:00
}
} catch (IOException e) {
Error error = new Error();
error.setError(context.getString(R.string.toast_error));
2017-11-18 12:22:41 +01:00
}
2017-12-27 08:36:55 +01:00
}
2017-11-18 12:22:41 +01:00
}
}).start();
2017-11-26 19:10:42 +01:00
}
2017-12-13 11:09:58 +01:00
public InputStream getPicture(final String downloadUrl) {
2018-01-24 15:56:33 +01:00
if( downloadUrl.startsWith("https://")) {
2018-01-17 15:22:44 +01:00
try {
2018-01-24 15:56:33 +01:00
URL url = new URL(downloadUrl);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
int responseCode = httpsURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
// opens input stream from the HTTP connection
return httpsURLConnection.getInputStream();
}
2018-01-17 15:22:44 +01:00
httpsURLConnection.getInputStream().close();
2018-01-24 15:56:33 +01:00
} catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) {
2018-01-17 15:22:44 +01:00
}
2018-01-24 15:56:33 +01:00
if (httpsURLConnection != null)
try {
httpsURLConnection.getInputStream().close();
2018-09-02 15:46:55 +02:00
} catch (Exception ignored) { }
2018-01-24 15:56:33 +01:00
return null;
}else {
try {
URL url = new URL(downloadUrl);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
// opens input stream from the HTTP connection
return httpURLConnection.getInputStream();
}
httpURLConnection.getInputStream().close();
} catch (IOException ignored) {
}
if (httpURLConnection != null)
try {
httpURLConnection.getInputStream().close();
} catch (Exception ignored) { }
2018-01-24 15:56:33 +01:00
return null;
}
2017-12-13 11:09:58 +01:00
}
2018-05-10 09:50:19 +02:00
enum imageType{
AVATAR,
BANNER
}
2018-04-22 18:02:00 +02:00
@SuppressWarnings("SameParameterValue")
2018-05-10 09:50:19 +02:00
private void patchImage(String urlConnection, int timeout, imageType it, InputStream image, String fileName, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
2018-04-22 18:02:00 +02:00
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
if( urlConnection.startsWith("https://")) {
2018-05-10 09:50:19 +02:00
HttpsURLConnection httpsURLConnection;
2018-04-22 18:02:00 +02:00
URL url = new URL(urlConnection);
2018-05-10 09:50:19 +02:00
int lengthSentImage = 0;
byte[] pixelsImage = new byte[0];
if( image != null) {
2018-04-22 18:02:00 +02:00
ByteArrayOutputStream ous = null;
try {
try {
byte[] buffer = new byte[CHUNK_SIZE];
ous = new ByteArrayOutputStream();
int read;
2018-05-10 09:50:19 +02:00
while ((read = image.read(buffer)) != -1) {
2018-04-22 18:02:00 +02:00
ous.write(buffer, 0, read);
}
ous.flush();
} finally {
if (ous != null)
ous.close();
}
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
}
2018-05-10 09:50:19 +02:00
pixelsImage = ous.toByteArray();
2018-04-22 18:02:00 +02:00
2018-05-10 09:50:19 +02:00
lengthSentImage = pixelsImage.length;
lengthSentImage += 2 * (twoHyphens + boundary + twoHyphens + lineEnd).getBytes().length;
if( it == imageType.AVATAR)
lengthSentImage += ("Content-Disposition: form-data; name=\"avatar\";filename=\""+fileName+"\"" + lineEnd).getBytes().length;
else
lengthSentImage += ("Content-Disposition: form-data; name=\"header\";filename=\""+fileName+"\"" + lineEnd).getBytes().length;
lengthSentImage += 2 * (lineEnd).getBytes().length;
2018-04-22 18:02:00 +02:00
}
2018-04-22 18:02:00 +02:00
2018-05-10 09:50:19 +02:00
int lengthSent = lengthSentImage + (twoHyphens + boundary + twoHyphens + lineEnd).getBytes().length;
2018-04-22 18:02:00 +02:00
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setUseCaches(false);
if( Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT ){
httpsURLConnection.setRequestMethod("PATCH");
}else {
httpsURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
httpsURLConnection.setRequestMethod("POST");
}
2018-05-10 09:50:19 +02:00
httpsURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpsURLConnection.setRequestProperty("Cache-Control", "no-cache");
2018-04-22 18:02:00 +02:00
httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
2018-05-10 09:50:19 +02:00
httpsURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);
2018-04-22 18:02:00 +02:00
if (token != null)
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
2018-05-10 09:50:19 +02:00
httpsURLConnection.setFixedLengthStreamingMode(lengthSent);
2018-04-22 18:02:00 +02:00
2018-04-23 07:00:12 +02:00
OutputStream outputStream = httpsURLConnection.getOutputStream();
2018-05-10 09:50:19 +02:00
outputStream.write((twoHyphens + boundary + twoHyphens + lineEnd).getBytes("UTF-8"));
if(lengthSentImage > 0){
2018-04-23 07:00:12 +02:00
DataOutputStream request = new DataOutputStream(outputStream);
2018-05-10 09:50:19 +02:00
int totalSize = pixelsImage.length;
2018-04-22 18:02:00 +02:00
int bytesTransferred = 0;
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
2018-05-10 09:50:19 +02:00
if( it == imageType.AVATAR)
request.writeBytes("Content-Disposition: form-data; name=\"avatar\";filename=\""+fileName+"\"" + lineEnd);
else
request.writeBytes("Content-Disposition: form-data; name=\"header\";filename=\""+fileName+"\"" + lineEnd);
2018-04-22 18:02:00 +02:00
request.writeBytes(lineEnd);
while (bytesTransferred < totalSize) {
int nextChunkSize = totalSize - bytesTransferred;
if (nextChunkSize > CHUNK_SIZE) {
nextChunkSize = CHUNK_SIZE;
}
2018-05-10 09:50:19 +02:00
request.write(pixelsImage, bytesTransferred, nextChunkSize);
2018-04-22 18:02:00 +02:00
bytesTransferred += nextChunkSize;
2018-04-23 07:00:12 +02:00
request.flush();
2018-04-22 18:02:00 +02:00
}
request.writeBytes(lineEnd);
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
request.flush();
}
if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) {
2018-05-10 09:50:19 +02:00
new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream()));
2018-04-22 18:02:00 +02:00
} else {
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-04-22 18:02:00 +02:00
int responseCode = httpsURLConnection.getResponseCode();
try {
httpsURLConnection.getInputStream().close();
}catch (Exception ignored){}
throw new HttpsConnectionException(responseCode, error);
}
httpsURLConnection.getInputStream().close();
}else {
2018-05-10 09:50:19 +02:00
HttpURLConnection httpURLConnection;
2018-04-22 18:02:00 +02:00
URL url = new URL(urlConnection);
2018-05-10 09:50:19 +02:00
int lengthSentImage = 0;
byte[] pixelsImage = new byte[0];
if( image != null) {
2018-04-23 13:42:21 +02:00
ByteArrayOutputStream ous = null;
try {
try {
byte[] buffer = new byte[CHUNK_SIZE];
ous = new ByteArrayOutputStream();
int read;
2018-05-10 09:50:19 +02:00
while ((read = image.read(buffer)) != -1) {
2018-04-23 13:42:21 +02:00
ous.write(buffer, 0, read);
}
ous.flush();
} finally {
if (ous != null)
ous.close();
}
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
}
2018-05-10 09:50:19 +02:00
pixelsImage = ous.toByteArray();
2018-04-23 13:42:21 +02:00
2018-05-10 09:50:19 +02:00
lengthSentImage = pixelsImage.length;
lengthSentImage += 2 * (twoHyphens + boundary + twoHyphens + lineEnd).getBytes().length;
if( it == imageType.AVATAR)
lengthSentImage += ("Content-Disposition: form-data; name=\"avatar\";filename=\""+fileName+"\"" + lineEnd).getBytes().length;
else
lengthSentImage += ("Content-Disposition: form-data; name=\"header\";filename=\""+fileName+"\"" + lineEnd).getBytes().length;
lengthSentImage += 2 * (lineEnd).getBytes().length;
2018-04-23 13:42:21 +02:00
}
2018-05-10 09:50:19 +02:00
int lengthSent = lengthSentImage + (twoHyphens + boundary + twoHyphens + lineEnd).getBytes().length;
2018-04-22 18:02:00 +02:00
if (proxy != null)
2018-05-10 09:50:19 +02:00
httpURLConnection = (HttpsURLConnection) url.openConnection(proxy);
2018-04-22 18:02:00 +02:00
else
2018-05-10 09:50:19 +02:00
httpURLConnection = (HttpsURLConnection) url.openConnection();
2018-04-22 18:02:00 +02:00
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
2018-04-23 13:42:21 +02:00
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
if( Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT ){
httpURLConnection.setRequestMethod("PATCH");
}else {
httpURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
httpURLConnection.setRequestMethod("POST");
}
2018-05-10 09:50:19 +02:00
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
2018-04-23 13:42:21 +02:00
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
2018-05-10 09:50:19 +02:00
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);
2018-04-22 18:02:00 +02:00
if (token != null)
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
2018-05-10 09:50:19 +02:00
httpURLConnection.setFixedLengthStreamingMode(lengthSent);
2018-04-23 13:42:21 +02:00
OutputStream outputStream = httpURLConnection.getOutputStream();
2018-05-10 09:50:19 +02:00
outputStream.write((twoHyphens + boundary + twoHyphens + lineEnd).getBytes("UTF-8"));
if(lengthSentImage > 0){
2018-04-23 13:42:21 +02:00
DataOutputStream request = new DataOutputStream(outputStream);
2018-05-10 09:50:19 +02:00
int totalSize = pixelsImage.length;
2018-04-23 13:42:21 +02:00
int bytesTransferred = 0;
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
2018-05-10 09:50:19 +02:00
if( it == imageType.AVATAR)
request.writeBytes("Content-Disposition: form-data; name=\"avatar\";filename=\""+fileName+"\"" + lineEnd);
else
request.writeBytes("Content-Disposition: form-data; name=\"header\";filename=\""+fileName+"\"" + lineEnd);
2018-04-23 13:42:21 +02:00
request.writeBytes(lineEnd);
while (bytesTransferred < totalSize) {
int nextChunkSize = totalSize - bytesTransferred;
if (nextChunkSize > CHUNK_SIZE) {
nextChunkSize = CHUNK_SIZE;
}
2018-05-10 09:50:19 +02:00
request.write(pixelsImage, bytesTransferred, nextChunkSize);
2018-04-23 13:42:21 +02:00
bytesTransferred += nextChunkSize;
request.flush();
}
request.writeBytes(lineEnd);
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
request.flush();
}
2018-05-10 09:50:19 +02:00
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
new String(ByteStreams.toByteArray(httpURLConnection.getInputStream()));
} else {
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-05-10 09:50:19 +02:00
int responseCode = httpURLConnection.getResponseCode();
try {
httpURLConnection.getInputStream().close();
}catch (Exception ignored){}
throw new HttpsConnectionException(responseCode, error);
}
httpURLConnection.getInputStream().close();
}
}
@SuppressWarnings("SameParameterValue")
void patch(String urlConnection, int timeout, HashMap<String, String> paramaters, InputStream avatar, String avatarName, InputStream header, String headerName, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if( urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
}
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = (postData.toString()).getBytes("UTF-8");
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
if( Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT ){
httpsURLConnection.setRequestMethod("PATCH");
}else {
httpsURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
httpsURLConnection.setRequestMethod("POST");
}
if (token != null)
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
httpsURLConnection.setDoOutput(true);
OutputStream outputStream = httpsURLConnection.getOutputStream();
outputStream.write(postDataBytes);
if( avatar != null)
patchImage(urlConnection,120,imageType.AVATAR, avatar,avatarName,token);
if( header != null)
patchImage(urlConnection,120,imageType.BANNER, header,headerName,token);
if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) {
new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream()));
} else {
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-05-10 09:50:19 +02:00
int responseCode = httpsURLConnection.getResponseCode();
try {
httpsURLConnection.getInputStream().close();
}catch (Exception ignored){}
throw new HttpsConnectionException(responseCode, error);
}
httpsURLConnection.getInputStream().close();
}else {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
2018-04-23 13:42:21 +02:00
}
}
2018-05-10 09:50:19 +02:00
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = (postData.toString()).getBytes("UTF-8");
2018-04-23 13:42:21 +02:00
2018-05-10 09:50:19 +02:00
if (proxy != null)
httpURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
if( Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT ){
httpURLConnection.setRequestMethod("PATCH");
}else {
httpURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
httpURLConnection.setRequestMethod("POST");
}
if (token != null)
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(postDataBytes);
if( avatar != null)
patchImage(urlConnection,120,imageType.AVATAR, avatar,avatarName,token);
if( header != null)
patchImage(urlConnection,120,imageType.BANNER, header,headerName,token);
2018-04-22 18:02:00 +02:00
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
new String(ByteStreams.toByteArray(httpURLConnection.getInputStream()));
} else {
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-04-22 18:02:00 +02:00
int responseCode = httpURLConnection.getResponseCode();
2018-04-23 13:42:21 +02:00
try {
httpURLConnection.getInputStream().close();
}catch (Exception ignored){}
2018-04-22 18:02:00 +02:00
throw new HttpsConnectionException(responseCode, error);
}
httpURLConnection.getInputStream().close();
}
}
2017-12-27 08:57:07 +01:00
/**
* Upload method - https only
* @param inputStream InputStream of the file to upload
* @param listener - OnRetrieveAttachmentInterface: listener to send information about attachment once uploaded.
*/
2018-08-16 12:08:38 +02:00
public void upload(final InputStream inputStream, String fileName, String tokenUsed, final OnRetrieveAttachmentInterface listener) {
2018-01-24 15:56:33 +01:00
if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) {
new Thread(new Runnable() {
@Override
public void run() {
try {
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
2018-08-16 12:08:38 +02:00
String token;
if( tokenUsed == null)
token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
else
token = tokenUsed;
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account account = new AccountDAO(context, db).getAccountByToken(token);
final URL url = new URL("https://" + account.getInstance() + "/api/v1/media");
2018-01-24 15:56:33 +01:00
ByteArrayOutputStream ous = null;
2017-11-18 09:30:58 +01:00
try {
2018-01-24 15:56:33 +01:00
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();
2017-11-18 09:30:58 +01:00
}
2018-01-24 15:56:33 +01:00
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
2017-11-18 09:30:58 +01:00
}
2018-01-24 15:56:33 +01:00
byte[] pixels = ous.toByteArray();
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
int lengthSent = pixels.length;
2018-08-30 17:48:32 +02:00
lengthSent += (twoHyphens + boundary + lineEnd).getBytes().length;
lengthSent += (twoHyphens + boundary + twoHyphens +lineEnd).getBytes().length;
2018-08-29 16:15:11 +02:00
lengthSent += ("Content-Disposition: form-data; name=\"file\"; filename=\""+fileName+"\"" + lineEnd).getBytes().length;
2018-01-24 15:56:33 +01:00
lengthSent += 2 * (lineEnd).getBytes().length;
2017-11-22 07:51:12 +01:00
2018-01-24 15:56:33 +01:00
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setFixedLengthStreamingMode(lengthSent);
2017-11-22 09:04:31 +01:00
2018-01-24 15:56:33 +01:00
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setUseCaches(false);
2017-11-22 07:51:12 +01:00
2018-01-24 15:56:33 +01:00
httpsURLConnection.setRequestMethod("POST");
if (token != null)
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + 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);
2017-11-22 07:51:12 +01:00
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
DataOutputStream request = new DataOutputStream(httpsURLConnection.getOutputStream());
2017-11-18 09:30:58 +01:00
2018-08-30 17:48:32 +02:00
request.writeBytes(twoHyphens + boundary + lineEnd);
2018-08-29 16:15:11 +02:00
request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""+fileName+"\"" + lineEnd);
2018-01-24 15:56:33 +01:00
request.writeBytes(lineEnd);
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
//request.write(pixels);
2017-11-18 09:44:54 +01:00
2018-01-24 15:56:33 +01:00
int totalSize = pixels.length;
int bytesTransferred = 0;
2017-11-22 07:51:12 +01:00
2017-11-18 09:44:54 +01:00
2018-01-24 15:56:33 +01:00
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);
2018-01-24 15:56:33 +01:00
}
});
request.flush();
2017-11-18 09:44:54 +01:00
}
2018-01-24 15:56:33 +01:00
request.writeBytes(lineEnd);
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
request.flush();
request.close();
2017-11-18 09:44:54 +01:00
2017-11-22 07:51:12 +01:00
2018-01-24 15:56:33 +01:00
if (200 != httpsURLConnection.getResponseCode()) {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-29 16:15:11 +02:00
}catch (Exception ignored){}
2018-08-17 18:55:38 +02:00
}
2018-01-24 15:56:33 +01:00
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());
2018-01-24 15:56:33 +01:00
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
2018-01-24 15:56:33 +01:00
listener.onUpdateProgress(101);
}
});
2018-01-24 15:56:33 +01:00
final Attachment attachment = API.parseAttachmentResponse(new JSONObject(response));
responseStreamReader.close();
responseStream.close();
httpsURLConnection.getInputStream().close();
2018-01-24 15:56:33 +01:00
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(attachment, null);
}
});
} catch (Exception e) {
2018-08-16 12:08:38 +02:00
e.printStackTrace();
2018-01-24 15:56:33 +01:00
((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();
2018-09-02 11:31:33 +02:00
} catch (Exception ignored) { }
2018-01-24 15:56:33 +01:00
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(null, error);
}
});
}
2018-01-24 15:56:33 +01:00
}
}).start();
}else {
new Thread(new Runnable() {
@Override
public void run() {
try {
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
2018-08-16 12:08:38 +02:00
String token;
if( tokenUsed == null)
token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
else
token = tokenUsed;
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
Account account = new AccountDAO(context, db).getAccountByToken(token);
final URL url = new URL("http://" + account.getInstance() + "/api/v1/media");
2018-01-24 15:56:33 +01:00
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();
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
int lengthSent = pixels.length;
2018-08-30 17:48:32 +02:00
lengthSent += (twoHyphens + boundary + lineEnd).getBytes().length;
lengthSent += (twoHyphens + boundary + twoHyphens +lineEnd).getBytes().length;
2018-04-23 13:57:26 +02:00
lengthSent += ("Content-Disposition: form-data; name=\"file\";filename=\""+fileName+"\"" + lineEnd).getBytes().length;
2018-01-24 15:56:33 +01:00
lengthSent += 2 * (lineEnd).getBytes().length;
2018-01-24 15:56:33 +01:00
if( proxy !=null )
httpURLConnection = (HttpURLConnection)url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setFixedLengthStreamingMode(lengthSent);
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
2018-01-24 15:56:33 +01:00
httpURLConnection.setRequestMethod("POST");
if (token != null)
httpURLConnection.setRequestProperty("Authorization", "Bearer " + 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());
2018-08-30 17:48:32 +02:00
request.writeBytes(twoHyphens + boundary + lineEnd);
2018-04-23 13:57:26 +02:00
request.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+fileName+"\"" + lineEnd);
2018-01-24 15:56:33 +01:00
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);
2018-01-24 15:56:33 +01:00
}});
request.flush();
}
2018-01-24 15:56:33 +01:00
request.writeBytes(lineEnd);
request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
request.flush();
request.close();
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
if (200 != httpURLConnection.getResponseCode()) {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
}
}
2018-01-24 15:56:33 +01:00
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());
2018-01-24 15:56:33 +01:00
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(101);
}});
final Attachment attachment = API.parseAttachmentResponse(new JSONObject(response));
responseStreamReader.close();
responseStream.close();
httpURLConnection.getInputStream().close();
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(attachment, 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 {
2018-09-02 11:31:33 +02:00
httpsURLConnection.getInputStream().close();
} catch (Exception ignored) { }
2018-01-24 15:56:33 +01:00
((TootActivity)context).runOnUiThread(new Runnable() {
public void run() {
listener.onRetrieveAttachment(null, error);
}});
2017-11-18 09:30:58 +01:00
2018-01-24 15:56:33 +01:00
}
}
}).start();
}
2017-11-18 09:30:58 +01:00
}
2017-11-18 08:27:25 +01:00
public String put(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
2018-01-24 15:56:33 +01:00
if( urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
2017-11-18 14:10:53 +01:00
}
2018-01-24 15:56:33 +01:00
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
2017-11-18 08:27:25 +01:00
2018-01-24 15:56:33 +01:00
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
if (token != null)
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
2017-11-18 14:10:53 +01:00
2018-01-24 15:56:33 +01:00
httpsURLConnection.setRequestMethod("PUT");
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
2017-11-18 14:10:53 +01:00
2018-01-24 15:56:33 +01:00
httpsURLConnection.getOutputStream().write(postDataBytes);
String response;
if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) {
getSinceMaxId();
response = converToString(httpsURLConnection.getInputStream());
2018-01-24 15:56:33 +01:00
} else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-01-24 15:56:33 +01:00
int responseCode = httpsURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpsURLConnection.getInputStream().close();
2018-01-24 15:56:33 +01:00
return response;
}else{
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
}
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpURLConnection.setConnectTimeout(timeout * 1000);
if (token != null)
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.getOutputStream().write(postDataBytes);
String response;
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
getSinceMaxId();
response = converToString(httpsURLConnection.getInputStream());
2018-01-24 15:56:33 +01:00
} else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-01-24 15:56:33 +01:00
int responseCode = httpURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
getSinceMaxId();
httpURLConnection.getInputStream().close();
return response;
}
2017-11-18 08:27:25 +01:00
}
public int delete(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
2018-01-24 15:56:33 +01:00
if( urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
Map<String, Object> params = new LinkedHashMap<>();
if (paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
2017-11-18 14:10:53 +01:00
}
2018-01-24 15:56:33 +01:00
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
2017-11-18 08:27:25 +01:00
2018-01-24 15:56:33 +01:00
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory());
if (token != null)
httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpsURLConnection.setRequestMethod("DELETE");
httpsURLConnection.setConnectTimeout(timeout * 1000);
httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
2018-01-24 15:56:33 +01:00
httpsURLConnection.getOutputStream().write(postDataBytes);
2018-01-24 15:56:33 +01:00
if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) {
getSinceMaxId();
httpsURLConnection.getInputStream().close();
return httpsURLConnection.getResponseCode();
} else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-01-24 15:56:33 +01:00
int responseCode = httpsURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
2017-11-18 08:27:25 +01:00
}else {
2018-01-24 15:56:33 +01:00
URL url = new URL(urlConnection);
Map<String,Object> params = new LinkedHashMap<>();
if( paramaters != null) {
Iterator it = paramaters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
params.put(pair.getKey().toString(), pair.getValue());
it.remove();
}
}
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(String.valueOf(param.getValue()));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
if( proxy !=null )
httpURLConnection = (HttpURLConnection)url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT);
if( token != null)
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.setConnectTimeout(timeout * 1000);
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
httpURLConnection.getOutputStream().write(postDataBytes);
if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) {
getSinceMaxId();
httpURLConnection.getInputStream().close();
return httpURLConnection.getResponseCode();
}else {
2018-04-22 13:16:52 +02:00
String error = null;
2018-08-17 18:55:38 +02:00
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();
2018-08-19 10:57:24 +02:00
}catch (Exception e){e.printStackTrace();}
2018-08-17 18:55:38 +02:00
}
2018-01-24 15:56:33 +01:00
int responseCode = httpURLConnection.getResponseCode();
throw new HttpsConnectionException(responseCode, error);
}
2017-11-18 08:27:25 +01:00
}
}
public String getSince_id() {
return since_id;
}
public String getMax_id() {
return max_id;
}
private void getSinceMaxId(){
2018-01-24 15:56:33 +01:00
if( Helper.getLiveInstanceWithProtocol(context) == null)
2018-01-14 19:03:20 +01:00
return;
2018-01-24 15:56:33 +01:00
if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) {
if (httpsURLConnection == null)
return;
Map<String, List<String>> map = httpsURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
2018-08-24 17:44:36 +02:00
if (entry.toString().startsWith("Link") || entry.toString().startsWith("link") ) {
2018-01-24 15:56:33 +01:00
Pattern patternMaxId = Pattern.compile("max_id=([0-9]{1,}).*");
Matcher matcherMaxId = patternMaxId.matcher(entry.toString());
if (matcherMaxId.find()) {
max_id = matcherMaxId.group(1);
}
if (entry.toString().startsWith("Link")) {
Pattern patternSinceId = Pattern.compile("since_id=([0-9]{1,}).*");
Matcher matcherSinceId = patternSinceId.matcher(entry.toString());
if (matcherSinceId.find()) {
since_id = matcherSinceId.group(1);
}
}
2017-11-18 08:27:25 +01:00
}
2018-01-24 15:56:33 +01:00
}
}else {
if (httpURLConnection == null)
return;
Map<String, List<String>> map = httpURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
2018-08-24 17:44:36 +02:00
if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) {
2018-01-24 15:56:33 +01:00
Pattern patternMaxId = Pattern.compile("max_id=([0-9]{1,}).*");
Matcher matcherMaxId = patternMaxId.matcher(entry.toString());
if (matcherMaxId.find()) {
max_id = matcherMaxId.group(1);
2017-11-18 08:27:25 +01:00
}
2018-01-24 15:56:33 +01:00
if (entry.toString().startsWith("Link")) {
Pattern patternSinceId = Pattern.compile("since_id=([0-9]{1,}).*");
Matcher matcherSinceId = patternSinceId.matcher(entry.toString());
if (matcherSinceId.find()) {
since_id = matcherSinceId.group(1);
}
2017-11-19 07:25:43 +01:00
2018-01-24 15:56:33 +01:00
}
2017-11-18 08:27:25 +01:00
}
}
}
}
private String converToString(InputStream inputStream) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder(inputStream.available());
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
return total.toString();
}
2017-12-02 14:54:25 +01:00
int getActionCode() {
2018-01-24 15:56:33 +01:00
if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) {
try {
return httpsURLConnection.getResponseCode();
} catch (IOException e) {
return -1;
}
}else {
try {
return httpURLConnection.getResponseCode();
} catch (IOException e) {
return -1;
}
2017-11-18 14:10:53 +01:00
}
2017-11-18 09:30:58 +01:00
}
2017-11-18 08:27:25 +01:00
public class HttpsConnectionException extends Exception {
private int statusCode;
private String message;
HttpsConnectionException(int statusCode, String message) {
this.statusCode = statusCode;
SpannableString spannableString;
2018-08-24 15:47:16 +02:00
if( message != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
spannableString = new SpannableString(Html.fromHtml(message, Html.FROM_HTML_MODE_LEGACY));
else
//noinspection deprecation
spannableString = new SpannableString(Html.fromHtml(message));
}else {
spannableString = new SpannableString(context.getString(R.string.toast_error));
}
this.message = spannableString.toString();
2017-11-18 08:27:25 +01:00
}
public int getStatusCode() {
return statusCode;
}
@Override
public String getMessage() {
return message;
}
2017-11-18 08:27:25 +01:00
}
}