Allows onion urls

This commit is contained in:
stom79 2018-01-24 15:56:33 +01:00
parent 66e19d9ebd
commit b058df8353
12 changed files with 911 additions and 411 deletions

View File

@ -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();
}

View File

@ -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;

View File

@ -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()

View File

@ -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()

View File

@ -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()

View File

@ -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()

View File

@ -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;
}

View File

@ -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<Void, Void, Void> {
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);
}

View File

@ -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;
}

View File

@ -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,6 +206,7 @@ public class HttpsConnection {
public String post(String urlConnection, int timeout, HashMap<String, String> paramaters, 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) {
@ -254,6 +254,53 @@ public class HttpsConnection {
getSinceMaxId();
httpsURLConnection.getInputStream().close();
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 = 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;
}
}
@ -457,6 +504,7 @@ public class HttpsConnection {
public InputStream getPicture(final String downloadUrl) {
if( downloadUrl.startsWith("https://")) {
try {
URL url = new URL(downloadUrl);
if (proxy != null)
@ -472,7 +520,8 @@ public class HttpsConnection {
return httpsURLConnection.getInputStream();
}
httpsURLConnection.getInputStream().close();
} catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) {}
} catch (IOException | NoSuchAlgorithmException | KeyManagementException ignored) {
}
if (httpsURLConnection != null)
try {
httpsURLConnection.getInputStream().close();
@ -480,6 +529,31 @@ public class HttpsConnection {
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;
}
}
@ -490,6 +564,7 @@ public class HttpsConnection {
*/
public void upload(final InputStream inputStream, final OnRetrieveAttachmentInterface listener) {
if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) {
new Thread(new Runnable() {
@Override
public void run() {
@ -500,7 +575,7 @@ public class HttpsConnection {
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");
final URL url = new URL(Helper.getLiveInstanceWithProtocol(context) + "/api/v1/media");
ByteArrayOutputStream ous = null;
try {
try {
@ -516,7 +591,8 @@ public class HttpsConnection {
ous.close();
}
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {}
} catch (IOException ignored) {
}
byte[] pixels = ous.toByteArray();
int lengthSent = pixels.length;
@ -570,7 +646,8 @@ public class HttpsConnection {
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(progress);
}});
}
});
request.flush();
}
request.writeBytes(lineEnd);
@ -594,7 +671,8 @@ public class HttpsConnection {
((TootActivity) context).runOnUiThread(new Runnable() {
public void run() {
listener.onUpdateProgress(101);
}});
}
});
final Attachment attachment = API.parseAttachmentResponse(new JSONObject(response));
@ -602,6 +680,146 @@ public class HttpsConnection {
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(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);
@ -613,9 +831,9 @@ public class HttpsConnection {
}});
final Error error = new Error();
error.setError(e.getMessage());
if(httpsURLConnection != null)
if(httpURLConnection != null)
try {
httpsURLConnection.getInputStream().close();
httpURLConnection.getInputStream().close();
} catch (IOException e1) {
e1.printStackTrace();
}
@ -627,11 +845,11 @@ public class HttpsConnection {
}
}
}).start();
}
}
public String put(String urlConnection, int timeout, HashMap<String, String> paramaters, 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) {
@ -680,12 +898,62 @@ public class HttpsConnection {
getSinceMaxId();
httpsURLConnection.getInputStream().close();
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 = 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;
}
}
public String patch(String urlConnection, int timeout, HashMap<String, String> paramaters, 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) {
@ -733,11 +1001,60 @@ public class HttpsConnection {
getSinceMaxId();
httpsURLConnection.getInputStream().close();
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.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;
}
}
public int delete(String urlConnection, int timeout, HashMap<String, String> paramaters, 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) {
@ -783,6 +1100,52 @@ public class HttpsConnection {
httpsURLConnection.getInputStream().close();
throw new HttpsConnectionException(responseCode, error);
}
}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);
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);
}
}
}
public String getSince_id() {
@ -795,6 +1158,9 @@ public class HttpsConnection {
private void getSinceMaxId(){
if( Helper.getLiveInstanceWithProtocol(context) == null)
return;
if( Helper.getLiveInstanceWithProtocol(context).startsWith("https://")) {
if (httpsURLConnection == null)
return;
Map<String, List<String>> map = httpsURLConnection.getHeaderFields();
@ -815,14 +1181,44 @@ public class HttpsConnection {
}
}
}
}else {
if (httpURLConnection == null)
return;
Map<String, List<String>> map = httpURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> 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() {
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;
}
}
}
public class HttpsConnectionException extends Exception {

View File

@ -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())

View File

@ -156,12 +156,14 @@ 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())) {
if (Helper.instanceWithProtocol(account.getInstance()).startsWith("https")) {
try {
URL url = new URL("https://" + account.getInstance() + "/api/v1/streaming/user");
httpsURLConnection = (HttpsURLConnection) url.openConnection();
@ -213,7 +215,8 @@ public class LiveNotificationService extends Service {
try {
JSONObject eventJson = new JSONObject(event);
onRetrieveStreaming(eventStreaming, account, eventJson);
} catch (JSONException ignored) { ignored.printStackTrace();
} catch (JSONException ignored) {
ignored.printStackTrace();
}
}
}
@ -247,6 +250,93 @@ public class LiveNotificationService extends Service {
} 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) {
}
}
}
}
}
}