CLean some classes

This commit is contained in:
tom79 2020-03-08 11:28:51 +01:00
parent d3bb1ad93f
commit b7b3a37a16
5 changed files with 157 additions and 247 deletions

View File

@ -46,6 +46,7 @@ import app.fedilab.android.client.Entities.Trends;
* Hydrate response from the API
*/
@SuppressWarnings("WeakerAccess")
public class APIResponse {
private List<Account> accounts = null;

View File

@ -22,9 +22,9 @@ import org.json.JSONObject;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.client.Entities.Results;
/**
@ -35,7 +35,6 @@ import app.fedilab.android.client.Entities.Results;
public class CustomSharing {
private Context context;
private Results results;
private CustomSharingResponse customSharingResponse;
private Error CustomSharingError;
@ -60,11 +59,7 @@ public class CustomSharing {
} catch (HttpsConnection.HttpsConnectionException e) {
e.printStackTrace();
setError(e.getStatusCode(), e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
} catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
e.printStackTrace();
}
customSharingResponse.setResponse(HTTPResponse);
@ -87,7 +82,7 @@ public class CustomSharing {
CustomSharingError.setStatusCode(statusCode);
String message = statusCode + " - " + error.getMessage();
try {
JSONObject jsonObject = new JSONObject(error.getMessage());
JSONObject jsonObject = new JSONObject(Objects.requireNonNull(error.getMessage()));
String errorM = jsonObject.get("error").toString();
message = "Error " + statusCode + " : " + errorM;
} catch (JSONException e) {

View File

@ -14,7 +14,6 @@ package app.fedilab.android.client;
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
@ -56,10 +55,7 @@ import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import app.fedilab.android.R;
import app.fedilab.android.activities.SlideMediaActivity;
@ -127,13 +123,7 @@ public class HttpsConnection {
}
if (instance != null && instance.endsWith(".onion")) {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@SuppressLint("BadHostnameVerifier")
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
HttpsURLConnection.setDefaultHostnameVerifier((arg0, arg1) -> true);
}
}
@ -146,10 +136,10 @@ public class HttpsConnection {
* @param paramaters HashMap<String, String> paramaters
* @param token String token
* @return String
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws HttpsConnectionException
* @throws IOException IOException
* @throws NoSuchAlgorithmException NoSuchAlgorithmException
* @throws KeyManagementException KeyManagementException
* @throws HttpsConnectionException HttpsConnectionException
*/
public String get(String urlConnection, int timeout, HashMap<String, String> paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
@ -462,10 +452,10 @@ public class HttpsConnection {
}
public String postJson(String urlConnection, int timeout, JsonObject jsonObject, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
String postJson(String urlConnection, int timeout, JsonObject jsonObject, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
if (urlConnection.startsWith("https://")) {
URL url = new URL(urlConnection);
byte[] postDataBytes = new byte[0];
byte[] postDataBytes;
postDataBytes = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
@ -569,7 +559,8 @@ public class HttpsConnection {
}
public String postMisskey(String urlConnection, int timeout, JSONObject paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
@SuppressWarnings("SameParameterValue")
String postMisskey(String urlConnection, int timeout, JSONObject paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException {
URL url = new URL(urlConnection);
byte[] postDataBytes = paramaters.toString().getBytes(StandardCharsets.UTF_8);
@ -629,189 +620,146 @@ public class HttpsConnection {
* @param listener OnDownloadInterface, listener which manages progress
*/
public void download(final String downloadUrl, final OnDownloadInterface listener) {
new Thread(new Runnable() {
@Override
public void run() {
URL url;
HttpsURLConnection httpsURLConnection = null;
HttpURLConnection httpURLConnection = null;
if (downloadUrl.startsWith("https://")) {
try {
url = new URL(downloadUrl);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpsURLConnection.getResponseCode();
new Thread(() -> {
URL url;
HttpsURLConnection httpsURLConnection;
HttpURLConnection httpURLConnection;
if (downloadUrl.startsWith("https://")) {
try {
url = new URL(downloadUrl);
if (proxy != null)
httpsURLConnection = (HttpsURLConnection) url.openConnection(proxy);
else
httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestProperty("User-Agent", 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");
// 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
);
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);
}
fileName = FileNameCleaner.cleanFileName(fileName);
// 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 SlideMediaActivity) {
final int currentProgress = (downloadedFileSize * 100) / contentSize;
((SlideMediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(currentProgress > 0 ? currentProgress : 101);
}
});
}
}
outputStream.close();
inputStream.close();
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(saveFilePath, downloadUrl, null);
}
});
if (context instanceof SlideMediaActivity)
((SlideMediaActivity) 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 SlideMediaActivity)
((SlideMediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(null, downloadUrl, error);
}
});
// extracts file name from URL
fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1
);
}
} catch (IOException e) {
Error error = new Error();
error.setError(context.getString(R.string.toast_error));
}
fileName = FileNameCleaner.cleanFileName(fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpsURLConnection.getInputStream();
File saveDir = context.getCacheDir();
final String saveFilePath = saveDir + File.separator + fileName;
} else {
try {
url = new URL(downloadUrl);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
// 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
);
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 SlideMediaActivity) {
final int currentProgress = (downloadedFileSize * 100) / contentSize;
((SlideMediaActivity) context).runOnUiThread(() -> listener.onUpdateProgress(currentProgress > 0 ? currentProgress : 101));
}
fileName = FileNameCleaner.cleanFileName(fileName);
// 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 SlideMediaActivity) {
final int currentProgress = (downloadedFileSize * 100) / contentSize;
((SlideMediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(currentProgress > 0 ? currentProgress : 101);
}
});
}
}
outputStream.close();
inputStream.close();
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(saveFilePath, downloadUrl, null);
}
});
if (context instanceof SlideMediaActivity)
((SlideMediaActivity) 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 SlideMediaActivity)
((SlideMediaActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onDownloaded(null, downloadUrl, error);
}
});
}
} catch (IOException e) {
Error error = new Error();
error.setError(context.getString(R.string.toast_error));
}
outputStream.close();
inputStream.close();
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(() -> listener.onDownloaded(saveFilePath, downloadUrl, null));
if (context instanceof SlideMediaActivity)
((SlideMediaActivity) context).runOnUiThread(() -> listener.onDownloaded(saveFilePath, downloadUrl, null));
} else {
final Error error = new Error();
error.setError(String.valueOf(responseCode));
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(() -> listener.onDownloaded(null, downloadUrl, error));
if (context instanceof SlideMediaActivity)
((SlideMediaActivity) context).runOnUiThread(() -> listener.onDownloaded(null, downloadUrl, error));
}
} catch (IOException e) {
Error error = new Error();
error.setError(context.getString(R.string.toast_error));
}
} else {
try {
url = new URL(downloadUrl);
if (proxy != null)
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
else
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", 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
);
}
fileName = FileNameCleaner.cleanFileName(fileName);
// 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 SlideMediaActivity) {
final int currentProgress = (downloadedFileSize * 100) / contentSize;
((SlideMediaActivity) context).runOnUiThread(() -> listener.onUpdateProgress(currentProgress > 0 ? currentProgress : 101));
}
}
outputStream.close();
inputStream.close();
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(() -> listener.onDownloaded(saveFilePath, downloadUrl, null));
if (context instanceof SlideMediaActivity)
((SlideMediaActivity) context).runOnUiThread(() -> listener.onDownloaded(saveFilePath, downloadUrl, null));
} else {
final Error error = new Error();
error.setError(String.valueOf(responseCode));
if (context instanceof TootActivity)
((TootActivity) context).runOnUiThread(() -> listener.onDownloaded(null, downloadUrl, error));
if (context instanceof SlideMediaActivity)
((SlideMediaActivity) context).runOnUiThread(() -> listener.onDownloaded(null, downloadUrl, error));
}
} catch (IOException e) {
Error error = new Error();
error.setError(context.getString(R.string.toast_error));
}
}
}).start();
}
@ -880,8 +828,6 @@ public class HttpsConnection {
} else {
IOUtils.copy(header, outputStream);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
@ -907,24 +853,24 @@ public class HttpsConnection {
@Override
public void onError(Context context, UploadInfo uploadInfo, ServerResponse serverResponse,
Exception exception) {
// your code here
//noinspection ResultOfMethodCallIgnored
file.delete();
}
@Override
public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
@Override
public void onCancelled(Context context, UploadInfo uploadInfo) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
})
.startUpload();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
} catch (MalformedURLException | FileNotFoundException e) {
e.printStackTrace();
}
}
@ -1374,31 +1320,6 @@ public class HttpsConnection {
return max_id;
}
private void getOKHttpHeader(Map<String, List<String>> headers) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) {
Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]{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-9a-zA-Z]{1,}).*");
Matcher matcherSinceId = patternSinceId.matcher(entry.toString());
if (matcherSinceId.find()) {
since_id = matcherSinceId.group(1);
}
}
} else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) {
Pattern patternMaxId = Pattern.compile("min-id=\\[([0-9a-zA-Z]{1,}).*\\]");
Matcher matcherMaxId = patternMaxId.matcher(entry.toString());
if (matcherMaxId.find()) {
max_id = matcherMaxId.group(1);
}
}
}
}
private void getSinceMaxId() {
if (Helper.getLiveInstanceWithProtocol(context) == null)
@ -1410,13 +1331,13 @@ public class HttpsConnection {
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) {
Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]{1,}).*");
Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]+).*");
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-9a-zA-Z]{1,}).*");
Pattern patternSinceId = Pattern.compile("since_id=([0-9a-zA-Z]+).*");
Matcher matcherSinceId = patternSinceId.matcher(entry.toString());
if (matcherSinceId.find()) {
since_id = matcherSinceId.group(1);
@ -1424,7 +1345,7 @@ public class HttpsConnection {
}
} else if (entry.toString().startsWith("Min-Id") || entry.toString().startsWith("min-id")) {
Pattern patternMaxId = Pattern.compile("min-id=\\[([0-9a-zA-Z]{1,}).*\\]");
Pattern patternMaxId = Pattern.compile("min-id=\\[([0-9a-zA-Z]+).*]");
Matcher matcherMaxId = patternMaxId.matcher(entry.toString());
if (matcherMaxId.find()) {
max_id = matcherMaxId.group(1);
@ -1437,13 +1358,13 @@ public class HttpsConnection {
Map<String, List<String>> map = httpURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.toString().startsWith("Link") || entry.toString().startsWith("link")) {
Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]{1,}).*");
Pattern patternMaxId = Pattern.compile("max_id=([0-9a-zA-Z]+).*");
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-9a-zA-Z]{1,}).*");
Pattern patternSinceId = Pattern.compile("since_id=([0-9a-zA-Z]+).*");
Matcher matcherSinceId = patternSinceId.matcher(entry.toString());
if (matcherSinceId.find()) {
since_id = matcherSinceId.group(1);
@ -1455,7 +1376,7 @@ public class HttpsConnection {
}
}
private String converToString(InputStream inputStream) throws IOException {
private String converToString(InputStream inputStream) {
java.util.Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
@ -1477,11 +1398,6 @@ public class HttpsConnection {
}
enum imageType {
AVATAR,
BANNER
}
public class HttpsConnectionException extends Exception {
private int statusCode;
@ -1494,7 +1410,6 @@ public class HttpsConnection {
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));

View File

@ -1,6 +1,7 @@
package app.fedilab.android.client;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import java.io.IOException;
@ -10,7 +11,6 @@ import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
@ -36,7 +36,7 @@ public class TLSSocketFactory extends SSLSocketFactory {
sslContext = SSLContext.getInstance("TLS");
isOnion = false;
sslContext.init(null, null, null);
} else {
} else { //Onion URLs
sslContext = SSLContext.getInstance("SSL");
isOnion = true;
TrustManager[] trustAllCerts = new TrustManager[]{
@ -45,10 +45,12 @@ public class TLSSocketFactory extends SSLSocketFactory {
return null;
}
@SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
@SuppressLint("TrustAllX509TrustManager")
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
@ -65,9 +67,6 @@ public class TLSSocketFactory extends SSLSocketFactory {
return this.sslContext;
}
public SSLEngine getSSLEngine() {
return this.sslContext.createSSLEngine();
}
@Override
public String[] getDefaultCipherSuites() {

View File

@ -19,7 +19,7 @@ import javax.net.ssl.SSLSocketFactory;
public class Tls12SocketFactory extends SSLSocketFactory {
private static final String[] TLS_V12_ONLY = {"TLSv1.2"};
final SSLSocketFactory delegate;
private final SSLSocketFactory delegate;
public Tls12SocketFactory(SSLSocketFactory base) {
this.delegate = base;