From b058df835380338689baceedf4d961999f39cfa8 Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 24 Jan 2018 15:56:33 +0100 Subject: [PATCH] Allows onion urls --- .../activities/EditProfileActivity.java | 2 +- .../mastodon/activities/LoginActivity.java | 7 +- .../activities/RemoteFollowActivity.java | 2 +- .../activities/ShowAccountActivity.java | 4 +- .../activities/ShowConversationActivity.java | 2 +- .../mastodon/activities/TootActivity.java | 2 +- .../activities/WebviewConnectActivity.java | 4 +- .../RetrieveRemoteDataAsyncTask.java | 3 +- .../fr/gouv/etalab/mastodon/client/API.java | 2 +- .../mastodon/client/HttpsConnection.java | 1030 ++++++++++++----- .../gouv/etalab/mastodon/helper/Helper.java | 20 +- .../services/LiveNotificationService.java | 244 ++-- 12 files changed, 911 insertions(+), 411 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java index 71f266b00..9b0a422cf 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java @@ -138,7 +138,7 @@ public class EditProfileActivity extends BaseActivity implements OnRetrieveAccou Account account = new AccountDAO(getApplicationContext(),db).getAccountByID(userId); String url = account.getAvatar(); if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar(); + url = Helper.getLiveInstanceWithProtocol(getApplicationContext()) + account.getAvatar(); } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java index 3da6d105c..3a6e46a74 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/LoginActivity.java @@ -252,7 +252,7 @@ public class LoginActivity extends BaseActivity { @Override public void run() { try { - final String response = new HttpsConnection(LoginActivity.this).post("https://" + instance + action, 30, parameters, null ); + final String response = new HttpsConnection(LoginActivity.this).post(Helper.instanceWithProtocol(instance) + action, 30, parameters, null ); runOnUiThread(new Runnable() { public void run() { JSONObject resobj; @@ -274,11 +274,12 @@ public class LoginActivity extends BaseActivity { i.putExtra("instance", instance); startActivity(i); } - } catch (JSONException ignored) {} + } catch (JSONException ignored) {ignored.printStackTrace();} } }); } catch (final Exception e) { + e.printStackTrace(); runOnUiThread(new Runnable() { public void run() { String message; @@ -326,7 +327,7 @@ public class LoginActivity extends BaseActivity { @Override public void run() { try { - final String response = new HttpsConnection(LoginActivity.this).post("https://" + instance + "/oauth/token", 30, parameters, null ); + final String response = new HttpsConnection(LoginActivity.this).post(Helper.instanceWithProtocol(instance) + "/oauth/token", 30, parameters, null ); runOnUiThread(new Runnable() { public void run() { JSONObject resobj; diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java index 6bb270488..325623f4d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java @@ -144,7 +144,7 @@ public class RemoteFollowActivity extends BaseActivity implements OnRetrieveRemo Account account = new AccountDAO(getApplicationContext(),db).getAccountByID(userId); String url = account.getAvatar(); if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar(); + url = Helper.getLiveInstanceWithProtocol(getApplicationContext()) + account.getAvatar(); } Glide.with(getApplicationContext()) .asBitmap() diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java index 52390157e..3c04a56b3 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java @@ -412,7 +412,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt } String urlHeader = account.getHeader(); if (urlHeader.startsWith("/")) { - urlHeader = "https://" + Helper.getLiveInstance(ShowAccountActivity.this) + account.getHeader(); + urlHeader = Helper.getLiveInstanceWithProtocol(ShowAccountActivity.this) + account.getHeader(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && !urlHeader.contains("missing.png")) { @@ -451,7 +451,7 @@ public class ShowAccountActivity extends BaseActivity implements OnPostActionInt pp_actionBar = findViewById(R.id.pp_actionBar); String url = account.getAvatar(); if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar(); + url = Helper.getLiveInstanceWithProtocol(getApplicationContext()) + account.getAvatar(); } Glide.with(getApplicationContext()) .asBitmap() diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java index e05ec1ac2..a7e81e1fd 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java @@ -151,7 +151,7 @@ public class ShowConversationActivity extends BaseActivity implements OnRetrieve Account account = new AccountDAO(getApplicationContext(),db).getAccountByID(userId); String url = account.getAvatar(); if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar(); + url = Helper.getLiveInstanceWithProtocol(getApplicationContext()) + account.getAvatar(); } Glide.with(getApplicationContext()) .asBitmap() diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 7e431eec6..9456f2771 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -347,7 +347,7 @@ public class TootActivity extends BaseActivity implements OnRetrieveSearcAccount String url = account.getAvatar(); if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar(); + url = Helper.getLiveInstanceWithProtocol(getApplicationContext()) + account.getAvatar(); } Glide.with(getApplicationContext()) .asBitmap() diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java index 276c147a7..35864e9cd 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java @@ -119,7 +119,7 @@ public class WebviewConnectActivity extends BaseActivity { @Override public void run() { try { - final String response = new HttpsConnection(WebviewConnectActivity.this).post("https://" + instance + action, 30, parameters, null); + final String response = new HttpsConnection(WebviewConnectActivity.this).post(Helper.instanceWithProtocol(instance) + action, 30, parameters, null); JSONObject resobj; try { resobj = new JSONObject(response); @@ -160,7 +160,7 @@ public class WebviewConnectActivity extends BaseActivity { queryString += "&" + Helper.REDIRECT_URI + "="+ Uri.encode(Helper.REDIRECT_CONTENT_WEB); queryString += "&" + Helper.RESPONSE_TYPE +"=code"; queryString += "&" + Helper.SCOPE +"=" + Helper.OAUTH_SCOPES; - return "https://" + instance + Helper.EP_AUTHORIZE + "?" + queryString; + return Helper.instanceWithProtocol(instance) + Helper.EP_AUTHORIZE + "?" + queryString; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteDataAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteDataAsyncTask.java index 23806c04b..fcaf9a6ee 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteDataAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteDataAsyncTask.java @@ -19,6 +19,7 @@ import android.os.AsyncTask; import java.lang.ref.WeakReference; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Results; +import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRemoteAccountInterface; @@ -38,7 +39,7 @@ public class RetrieveRemoteDataAsyncTask extends AsyncTask { public RetrieveRemoteDataAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface){ - this.url = "https://" + instance + "/@" + username; + this.url = Helper.instanceWithProtocol(instance) + "/@" + username; this.listener = onRetrieveRemoteAccountInterface; this.contextReference = new WeakReference<>(context); } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java index 54c9a3ea3..3a26febcc 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java @@ -2030,7 +2030,7 @@ public class API { private String getAbsoluteUrl(String action) { - return "https://" + this.instance + "/api/v1" + action; + return Helper.instanceWithProtocol(this.instance) + "/api/v1" + action; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/HttpsConnection.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/HttpsConnection.java index 44d88f837..1d4455c89 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/HttpsConnection.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/HttpsConnection.java @@ -67,6 +67,7 @@ public class HttpsConnection { private HttpsURLConnection httpsURLConnection; + private HttpURLConnection httpURLConnection; private String since_id, max_id; private Context context; private int CHUNK_SIZE = 4096; @@ -152,8 +153,6 @@ public class HttpsConnection { public String get(String urlConnection) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - HttpsURLConnection httpsURLConnection; - HttpURLConnection httpURLConnection; if( urlConnection.startsWith("https://")) { URL url = new URL(urlConnection); if( proxy !=null ) @@ -207,53 +206,101 @@ public class HttpsConnection { public String post(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - URL url = new URL(urlConnection); - Map 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(); + if( urlConnection.startsWith("https://")) { + URL url = new URL(urlConnection); + Map 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 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"); + StringBuilder postData = new StringBuilder(); + for (Map.Entry 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.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)); + 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)); - httpsURLConnection.getOutputStream().write(postDataBytes); - String response; - if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { + httpsURLConnection.getOutputStream().write(postDataBytes); + String response; + if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { + getSinceMaxId(); + response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); + } else { + String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); + int responseCode = httpsURLConnection.getResponseCode(); + httpsURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } getSinceMaxId(); - response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); - }else { - String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); - int responseCode = httpsURLConnection.getResponseCode(); httpsURLConnection.getInputStream().close(); - throw new HttpsConnectionException(responseCode, error); + return response; + }else { + URL url = new URL(urlConnection); + Map 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 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 = new String(ByteStreams.toByteArray(httpURLConnection.getInputStream())); + } else { + String error = new String(ByteStreams.toByteArray(httpURLConnection.getErrorStream())); + int responseCode = httpURLConnection.getResponseCode(); + httpURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } + getSinceMaxId(); + httpURLConnection.getInputStream().close(); + return response; } - getSinceMaxId(); - httpsURLConnection.getInputStream().close(); - return response; } @@ -457,29 +504,56 @@ public class HttpsConnection { public InputStream getPicture(final String downloadUrl) { - try { - 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(); - } - httpsURLConnection.getInputStream().close(); - } catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) {} - if(httpsURLConnection != null) + if( downloadUrl.startsWith("https://")) { try { + 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(); + } httpsURLConnection.getInputStream().close(); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) { } - return null; + if (httpsURLConnection != null) + try { + httpsURLConnection.getInputStream().close(); + } catch (IOException e) { + e.printStackTrace(); + } + 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 (IOException e) { + e.printStackTrace(); + } + return null; + } } @@ -489,299 +563,588 @@ public class HttpsConnection { * @param listener - OnRetrieveAttachmentInterface: listener to send information about attachment once uploaded. */ public void upload(final InputStream inputStream, final OnRetrieveAttachmentInterface listener) { - - new Thread(new Runnable() { - @Override - public void run() { - try { - - String twoHyphens = "--"; - String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; - String lineEnd = "\r\n"; - - String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); - final URL url = new URL("https://"+Helper.getLiveInstance(context)+"/api/v1/media"); - ByteArrayOutputStream ous = null; + + 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"; + + String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); + final URL url = new URL(Helper.getLiveInstanceWithProtocol(context) + "/api/v1/media"); + ByteArrayOutputStream ous = null; 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); + 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(); } - ous.flush(); - } finally { - if (ous != null) - ous.close(); + } catch (FileNotFoundException ignored) { + } catch (IOException ignored) { } - } catch (FileNotFoundException ignored) { - } catch (IOException ignored) {} - byte[] pixels = ous.toByteArray(); + byte[] pixels = ous.toByteArray(); - int lengthSent = pixels.length; - lengthSent += 2 * (twoHyphens + boundary + twoHyphens + lineEnd).getBytes().length; - lengthSent += ("Content-Disposition: form-data; name=\"file\";filename=\"picture.png\"" + lineEnd).getBytes().length; - lengthSent += 2 * (lineEnd).getBytes().length; + int lengthSent = pixels.length; + lengthSent += 2 * (twoHyphens + boundary + twoHyphens + lineEnd).getBytes().length; + lengthSent += ("Content-Disposition: form-data; name=\"file\";filename=\"picture.png\"" + lineEnd).getBytes().length; + lengthSent += 2 * (lineEnd).getBytes().length; - if( proxy !=null ) - httpsURLConnection = (HttpsURLConnection)url.openConnection(proxy); - else - httpsURLConnection = (HttpsURLConnection)url.openConnection(); - httpsURLConnection.setFixedLengthStreamingMode(lengthSent); + 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()); - httpsURLConnection.setDoInput(true); - httpsURLConnection.setDoOutput(true); - httpsURLConnection.setUseCaches(false); + httpsURLConnection.setRequestProperty("User-Agent", Helper.USER_AGENT); + httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory()); + httpsURLConnection.setDoInput(true); + httpsURLConnection.setDoOutput(true); + httpsURLConnection.setUseCaches(false); - 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); + 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); - DataOutputStream request = new DataOutputStream(httpsURLConnection.getOutputStream()); + DataOutputStream request = new DataOutputStream(httpsURLConnection.getOutputStream()); - request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); - request.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"picture.png\"" + lineEnd); - request.writeBytes(lineEnd); + request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); + request.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"picture.png\"" + lineEnd); + request.writeBytes(lineEnd); - //request.write(pixels); + //request.write(pixels); - int totalSize = pixels.length; - int bytesTransferred = 0; + int totalSize = pixels.length; + int bytesTransferred = 0; - while (bytesTransferred < totalSize) { - int nextChunkSize = totalSize - bytesTransferred; - if (nextChunkSize > CHUNK_SIZE) { - nextChunkSize = CHUNK_SIZE; + 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); + } + }); + request.flush(); } - request.write(pixels, bytesTransferred, nextChunkSize); - bytesTransferred += nextChunkSize; + request.writeBytes(lineEnd); + request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); + request.flush(); + request.close(); - final int progress = 100 * bytesTransferred / totalSize; + if (200 != httpsURLConnection.getResponseCode()) { + String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); + int responseCode = httpsURLConnection.getResponseCode(); + httpsURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } + + InputStream responseStream = new BufferedInputStream(httpsURLConnection.getInputStream()); + + BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); + + String response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); + ((TootActivity) context).runOnUiThread(new Runnable() { + public void run() { + listener.onUpdateProgress(101); + } + }); + + + final Attachment attachment = API.parseAttachmentResponse(new JSONObject(response)); + responseStreamReader.close(); + responseStream.close(); + httpsURLConnection.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 (httpsURLConnection != null) + try { + httpsURLConnection.getInputStream().close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + ((TootActivity) context).runOnUiThread(new Runnable() { + public void run() { + listener.onRetrieveAttachment(null, error); + } + }); + + } + } + }).start(); + }else { + new Thread(new Runnable() { + @Override + public void run() { + try { + + String twoHyphens = "--"; + String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; + String lineEnd = "\r\n"; + + String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); + final URL url = new URL(Helper.getLiveInstanceWithProtocol(context)+"/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 += 2 * (twoHyphens + boundary + twoHyphens + lineEnd).getBytes().length; + lengthSent += ("Content-Disposition: form-data; name=\"file\";filename=\"picture.png\"" + 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) + 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()); + + request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); + request.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"picture.png\"" + 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); + }}); + request.flush(); + } + request.writeBytes(lineEnd); + request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); + request.flush(); + request.close(); + + + if (200 != httpURLConnection.getResponseCode()) { + String error = new String(ByteStreams.toByteArray(httpURLConnection.getErrorStream())); + int responseCode = httpURLConnection.getResponseCode(); + httpURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } + + InputStream responseStream = new BufferedInputStream(httpURLConnection.getInputStream()); + + BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); + + String response = new String(ByteStreams.toByteArray(httpURLConnection.getInputStream())); ((TootActivity)context).runOnUiThread(new Runnable() { public void run() { - listener.onUpdateProgress(progress); + listener.onUpdateProgress(101); }}); - request.flush(); + + + 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 { + httpURLConnection.getInputStream().close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + ((TootActivity)context).runOnUiThread(new Runnable() { + public void run() { + listener.onRetrieveAttachment(null, error); + }}); + } - request.writeBytes(lineEnd); - request.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); - request.flush(); - request.close(); - - - if (200 != httpsURLConnection.getResponseCode()) { - String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); - int responseCode = httpsURLConnection.getResponseCode(); - httpsURLConnection.getInputStream().close(); - throw new HttpsConnectionException(responseCode, error); - } - - InputStream responseStream = new BufferedInputStream(httpsURLConnection.getInputStream()); - - BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); - - String response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); - ((TootActivity)context).runOnUiThread(new Runnable() { - public void run() { - listener.onUpdateProgress(101); - }}); - - - final Attachment attachment = API.parseAttachmentResponse(new JSONObject(response)); - responseStreamReader.close(); - responseStream.close(); - httpsURLConnection.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(httpsURLConnection != null) - try { - httpsURLConnection.getInputStream().close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - ((TootActivity)context).runOnUiThread(new Runnable() { - public void run() { - listener.onRetrieveAttachment(null, error); - }}); - } - } - }).start(); - - + }).start(); + } } public String put(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - URL url = new URL(urlConnection); - Map 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(); + if( urlConnection.startsWith("https://")) { + URL url = new URL(urlConnection); + Map 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 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"); + StringBuilder postData = new StringBuilder(); + for (Map.Entry 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( token != null) - httpsURLConnection.setRequestProperty("Authorization", "Bearer " + token); - httpsURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); + 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)); - httpsURLConnection.setRequestMethod("PUT"); - httpsURLConnection.setDoInput(true); - httpsURLConnection.setDoOutput(true); + httpsURLConnection.setRequestMethod("PUT"); + httpsURLConnection.setDoInput(true); + httpsURLConnection.setDoOutput(true); - httpsURLConnection.getOutputStream().write(postDataBytes); - String response; - if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { + httpsURLConnection.getOutputStream().write(postDataBytes); + String response; + if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { + getSinceMaxId(); + response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); + } else { + String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); + int responseCode = httpsURLConnection.getResponseCode(); + httpsURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } getSinceMaxId(); - response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); - }else { - String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); - int responseCode = httpsURLConnection.getResponseCode(); httpsURLConnection.getInputStream().close(); - throw new HttpsConnectionException(responseCode, error); + return response; + }else{ + URL url = new URL(urlConnection); + Map 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 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 = new String(ByteStreams.toByteArray(httpURLConnection.getInputStream())); + } else { + String error = new String(ByteStreams.toByteArray(httpURLConnection.getErrorStream())); + int responseCode = httpURLConnection.getResponseCode(); + httpURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } + getSinceMaxId(); + httpURLConnection.getInputStream().close(); + return response; } - getSinceMaxId(); - httpsURLConnection.getInputStream().close(); - return response; } public String patch(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - URL url = new URL(urlConnection); - Map 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(); + if( urlConnection.startsWith("https://")) { + URL url = new URL(urlConnection); + Map 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 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"); + StringBuilder postData = new StringBuilder(); + for (Map.Entry 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()); - httpsURLConnection.setRequestMethod("PATCH"); - 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); + 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.setRequestMethod("PATCH"); + 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); - httpsURLConnection.getOutputStream().write(postDataBytes); - String response; - if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { + httpsURLConnection.getOutputStream().write(postDataBytes); + String response; + if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { + getSinceMaxId(); + response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); + } else { + String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); + int responseCode = httpsURLConnection.getResponseCode(); + httpsURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } getSinceMaxId(); - response = new String(ByteStreams.toByteArray(httpsURLConnection.getInputStream())); - }else { - String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); - int responseCode = httpsURLConnection.getResponseCode(); httpsURLConnection.getInputStream().close(); - throw new HttpsConnectionException(responseCode, error); + return response; + }else { + URL url = new URL(urlConnection); + Map 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 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.setRequestMethod("PATCH"); + 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); + + httpURLConnection.getOutputStream().write(postDataBytes); + String response; + if (httpURLConnection.getResponseCode() >= 200 && httpURLConnection.getResponseCode() < 400) { + getSinceMaxId(); + response = new String(ByteStreams.toByteArray(httpURLConnection.getInputStream())); + } else { + String error = new String(ByteStreams.toByteArray(httpURLConnection.getErrorStream())); + int responseCode = httpURLConnection.getResponseCode(); + httpURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } + getSinceMaxId(); + httpURLConnection.getInputStream().close(); + return response; } - getSinceMaxId(); - httpsURLConnection.getInputStream().close(); - return response; } public int delete(String urlConnection, int timeout, HashMap paramaters, String token) throws IOException, NoSuchAlgorithmException, KeyManagementException, HttpsConnectionException { - URL url = new URL(urlConnection); - Map 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(); + if( urlConnection.startsWith("https://")) { + URL url = new URL(urlConnection); + Map 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 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"); + StringBuilder postData = new StringBuilder(); + for (Map.Entry 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.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)); + 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)); - httpsURLConnection.getOutputStream().write(postDataBytes); + httpsURLConnection.getOutputStream().write(postDataBytes); - if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { - getSinceMaxId(); - httpsURLConnection.getInputStream().close(); - return httpsURLConnection.getResponseCode(); + if (httpsURLConnection.getResponseCode() >= 200 && httpsURLConnection.getResponseCode() < 400) { + getSinceMaxId(); + httpsURLConnection.getInputStream().close(); + return httpsURLConnection.getResponseCode(); + } else { + String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); + int responseCode = httpsURLConnection.getResponseCode(); + httpsURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } }else { - String error = new String(ByteStreams.toByteArray(httpsURLConnection.getErrorStream())); - int responseCode = httpsURLConnection.getResponseCode(); - httpsURLConnection.getInputStream().close(); - throw new HttpsConnectionException(responseCode, error); + URL url = new URL(urlConnection); + Map 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 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 { + String error = new String(ByteStreams.toByteArray(httpURLConnection.getErrorStream())); + int responseCode = httpURLConnection.getResponseCode(); + httpURLConnection.getInputStream().close(); + throw new HttpsConnectionException(responseCode, error); + } } } @@ -795,33 +1158,66 @@ public class HttpsConnection { private void getSinceMaxId(){ - if( httpsURLConnection == null) + if( Helper.getLiveInstanceWithProtocol(context) == null) return; - Map> map = httpsURLConnection.getHeaderFields(); - for (Map.Entry> entry : map.entrySet()) { - if( entry.toString().startsWith("Link")){ - 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); + if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) { + if (httpsURLConnection == null) + return; + Map> map = httpsURLConnection.getHeaderFields(); + for (Map.Entry> entry : map.entrySet()) { + if (entry.toString().startsWith("Link")) { + 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); + } + } + } + } + }else { + if (httpURLConnection == null) + return; + Map> map = httpURLConnection.getHeaderFields(); + for (Map.Entry> entry : map.entrySet()) { + if (entry.toString().startsWith("Link")) { + 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); + } + + } } } } } int getActionCode() { - try { - return httpsURLConnection.getResponseCode(); - } catch (IOException e) { - return -1; + 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; + } } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java index f81d48ae3..ac309e64e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java @@ -895,6 +895,18 @@ public class Helper { return null; } + public static String getLiveInstanceWithProtocol(Context context) { + return instanceWithProtocol(getLiveInstance(context)); + } + + public static String instanceWithProtocol(String instance){ + if( instance == null) + return null; + if( instance.endsWith(".onion")) + return "http://" + instance; + else + return "https://" + instance; + } @@ -958,7 +970,7 @@ public class Helper { item.setIcon(R.drawable.ic_person); String url = account.getAvatar(); if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(activity) + account.getAvatar(); + url = Helper.getLiveInstanceWithProtocol(activity) + account.getAvatar(); } Glide.with(activity.getApplicationContext()) .asBitmap() @@ -1093,7 +1105,7 @@ public class Helper { */ public static void loadPictureIcon(final Activity activity, String url, final ImageView imageView){ if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(activity) + url; + url = Helper.getLiveInstanceWithProtocol(activity) + url; } Glide.with(activity.getApplicationContext()) @@ -1169,14 +1181,14 @@ public class Helper { displayedName.setText(account.getDisplay_name()); String url = account.getAvatar(); if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(activity) + account.getAvatar(); + url = Helper.getLiveInstanceWithProtocol(activity) + account.getAvatar(); } Glide.with(activity.getApplicationContext()) .load(url) .into(profilePicture); String urlHeader = account.getHeader(); if( urlHeader.startsWith("/") ){ - urlHeader = "https://" + Helper.getLiveInstance(activity) + account.getHeader(); + urlHeader = Helper.getLiveInstanceWithProtocol(activity) + account.getHeader(); } if (!urlHeader.contains("missing.png")) { Glide.with(activity.getApplicationContext()) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/services/LiveNotificationService.java b/app/src/main/java/fr/gouv/etalab/mastodon/services/LiveNotificationService.java index 7aadf8adb..26770928d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/services/LiveNotificationService.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/services/LiveNotificationService.java @@ -156,95 +156,185 @@ public class LiveNotificationService extends Service { private void taks(Account account){ InputStream inputStream = null; HttpsURLConnection httpsURLConnection = null; + HttpURLConnection httpURLConnection = null; BufferedReader reader = null; Helper.EventStreaming lastEvent = null; if( account != null){ isRunning.get(account.getAcct()+account.getInstance()); if(!isRunning.containsKey(account.getAcct()+account.getInstance()) || ! isRunning.get(account.getAcct()+account.getInstance())) { - try { - URL url = new URL("https://" + account.getInstance() + "/api/v1/streaming/user"); - httpsURLConnection = (HttpsURLConnection) url.openConnection(); - httpsURLConnection.setRequestProperty("Content-Type", "application/json"); - httpsURLConnection.setRequestProperty("Authorization", "Bearer " + account.getToken()); - httpsURLConnection.setRequestProperty("Connection", "Keep-Alive"); - httpsURLConnection.setRequestProperty("Keep-Alive", "header"); - httpsURLConnection.setRequestProperty("Connection", "close"); - httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory()); - httpsURLConnection.setRequestMethod("GET"); - if (httpsURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { - inputStream = new BufferedInputStream(httpsURLConnection.getInputStream()); - reader = new BufferedReader(new InputStreamReader(inputStream)); - String event; - Helper.EventStreaming eventStreaming; - while ((event = reader.readLine()) != null) { - isRunning.put(account.getAcct()+account.getInstance(), true); - if ((lastEvent == Helper.EventStreaming.NONE || lastEvent == null) && !event.startsWith("data: ")) { - switch (event.trim()) { - case "event: update": - lastEvent = Helper.EventStreaming.UPDATE; - break; - case "event: notification": - lastEvent = Helper.EventStreaming.NOTIFICATION; - break; - case "event: delete": - lastEvent = Helper.EventStreaming.DELETE; - break; - default: - lastEvent = Helper.EventStreaming.NONE; - } - } else { - if (!event.startsWith("data: ")) { - lastEvent = Helper.EventStreaming.NONE; - continue; - } - event = event.substring(6); - if (lastEvent == Helper.EventStreaming.UPDATE) { - eventStreaming = Helper.EventStreaming.UPDATE; - } else if (lastEvent == Helper.EventStreaming.NOTIFICATION) { - eventStreaming = Helper.EventStreaming.NOTIFICATION; - } else if (lastEvent == Helper.EventStreaming.DELETE) { - eventStreaming = Helper.EventStreaming.DELETE; - event = "{id:" + event + "}"; + if (Helper.instanceWithProtocol(account.getInstance()).startsWith("https")) { + try { + URL url = new URL("https://" + account.getInstance() + "/api/v1/streaming/user"); + httpsURLConnection = (HttpsURLConnection) url.openConnection(); + httpsURLConnection.setRequestProperty("Content-Type", "application/json"); + httpsURLConnection.setRequestProperty("Authorization", "Bearer " + account.getToken()); + httpsURLConnection.setRequestProperty("Connection", "Keep-Alive"); + httpsURLConnection.setRequestProperty("Keep-Alive", "header"); + httpsURLConnection.setRequestProperty("Connection", "close"); + httpsURLConnection.setSSLSocketFactory(new TLSSocketFactory()); + httpsURLConnection.setRequestMethod("GET"); + if (httpsURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { + inputStream = new BufferedInputStream(httpsURLConnection.getInputStream()); + reader = new BufferedReader(new InputStreamReader(inputStream)); + String event; + Helper.EventStreaming eventStreaming; + while ((event = reader.readLine()) != null) { + isRunning.put(account.getAcct() + account.getInstance(), true); + if ((lastEvent == Helper.EventStreaming.NONE || lastEvent == null) && !event.startsWith("data: ")) { + switch (event.trim()) { + case "event: update": + lastEvent = Helper.EventStreaming.UPDATE; + break; + case "event: notification": + lastEvent = Helper.EventStreaming.NOTIFICATION; + break; + case "event: delete": + lastEvent = Helper.EventStreaming.DELETE; + break; + default: + lastEvent = Helper.EventStreaming.NONE; + } } else { - eventStreaming = Helper.EventStreaming.UPDATE; - } - lastEvent = Helper.EventStreaming.NONE; - try { - JSONObject eventJson = new JSONObject(event); - onRetrieveStreaming(eventStreaming, account, eventJson); - } catch (JSONException ignored) { ignored.printStackTrace(); + if (!event.startsWith("data: ")) { + lastEvent = Helper.EventStreaming.NONE; + continue; + } + event = event.substring(6); + if (lastEvent == Helper.EventStreaming.UPDATE) { + eventStreaming = Helper.EventStreaming.UPDATE; + } else if (lastEvent == Helper.EventStreaming.NOTIFICATION) { + eventStreaming = Helper.EventStreaming.NOTIFICATION; + } else if (lastEvent == Helper.EventStreaming.DELETE) { + eventStreaming = Helper.EventStreaming.DELETE; + event = "{id:" + event + "}"; + } else { + eventStreaming = Helper.EventStreaming.UPDATE; + } + lastEvent = Helper.EventStreaming.NONE; + try { + JSONObject eventJson = new JSONObject(event); + onRetrieveStreaming(eventStreaming, account, eventJson); + } catch (JSONException ignored) { + ignored.printStackTrace(); + } } } + isRunning.put(account.getAcct() + account.getInstance(), false); } - isRunning.put(account.getAcct() + account.getInstance(), false); - } - } catch (Exception ignored) { - isRunning.put(account.getAcct() + account.getInstance(), false); - ignored.printStackTrace(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException ignored) { - } - } - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException ignored) { - } - } - if (inputStream != null) { - httpsURLConnection.disconnect(); - } - SystemClock.sleep(5000); - Intent streamingIntent = new Intent(this, LiveNotificationService.class); - streamingIntent.putExtra("userId", account.getId()); - try { - startService(streamingIntent); } catch (Exception ignored) { + isRunning.put(account.getAcct() + account.getInstance(), false); + ignored.printStackTrace(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ignored) { + } + } + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException ignored) { + } + } + if (inputStream != null) { + httpsURLConnection.disconnect(); + } + SystemClock.sleep(5000); + Intent streamingIntent = new Intent(this, LiveNotificationService.class); + streamingIntent.putExtra("userId", account.getId()); + try { + startService(streamingIntent); + } catch (Exception ignored) { + } + } + }else { + try { + URL url = new URL("https://" + account.getInstance() + "/api/v1/streaming/user"); + httpURLConnection = (HttpURLConnection) url.openConnection(); + httpURLConnection.setRequestProperty("Content-Type", "application/json"); + httpURLConnection.setRequestProperty("Authorization", "Bearer " + account.getToken()); + httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); + httpURLConnection.setRequestProperty("Keep-Alive", "header"); + httpURLConnection.setRequestProperty("Connection", "close"); + httpURLConnection.setRequestMethod("GET"); + if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { + inputStream = new BufferedInputStream(httpURLConnection.getInputStream()); + reader = new BufferedReader(new InputStreamReader(inputStream)); + String event; + Helper.EventStreaming eventStreaming; + while ((event = reader.readLine()) != null) { + isRunning.put(account.getAcct() + account.getInstance(), true); + if ((lastEvent == Helper.EventStreaming.NONE || lastEvent == null) && !event.startsWith("data: ")) { + switch (event.trim()) { + case "event: update": + lastEvent = Helper.EventStreaming.UPDATE; + break; + case "event: notification": + lastEvent = Helper.EventStreaming.NOTIFICATION; + break; + case "event: delete": + lastEvent = Helper.EventStreaming.DELETE; + break; + default: + lastEvent = Helper.EventStreaming.NONE; + } + } else { + if (!event.startsWith("data: ")) { + lastEvent = Helper.EventStreaming.NONE; + continue; + } + event = event.substring(6); + if (lastEvent == Helper.EventStreaming.UPDATE) { + eventStreaming = Helper.EventStreaming.UPDATE; + } else if (lastEvent == Helper.EventStreaming.NOTIFICATION) { + eventStreaming = Helper.EventStreaming.NOTIFICATION; + } else if (lastEvent == Helper.EventStreaming.DELETE) { + eventStreaming = Helper.EventStreaming.DELETE; + event = "{id:" + event + "}"; + } else { + eventStreaming = Helper.EventStreaming.UPDATE; + } + lastEvent = Helper.EventStreaming.NONE; + try { + JSONObject eventJson = new JSONObject(event); + onRetrieveStreaming(eventStreaming, account, eventJson); + } catch (JSONException ignored) { + ignored.printStackTrace(); + } + } + } + isRunning.put(account.getAcct() + account.getInstance(), false); + } + + } catch (Exception ignored) { + isRunning.put(account.getAcct() + account.getInstance(), false); + ignored.printStackTrace(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ignored) { + } + } + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException ignored) { + } + } + if (inputStream != null) { + httpURLConnection.disconnect(); + } + SystemClock.sleep(5000); + Intent streamingIntent = new Intent(this, LiveNotificationService.class); + streamingIntent.putExtra("userId", account.getId()); + try { + startService(streamingIntent); + } catch (Exception ignored) { + } } } }