Skip to content

Commit 409f551

Browse files
committed
Added server address calibration
1 parent 4e52275 commit 409f551

File tree

9 files changed

+301
-67
lines changed

9 files changed

+301
-67
lines changed

.idea/deploymentTargetSelector.xml

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/other.xml

Lines changed: 22 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

app/src/main/AndroidManifest.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454

5555
<activity android:name=".StartActivity" />
5656
<activity android:name=".ui.NetSelectActivity"/>
57+
<activity android:name=".ui.prefs.ServerPingActivity"/>
5758
<activity android:name=".ui.prefs.BlacklistActivity" />
5859
<activity android:name=".ui.prefs.custom.AddActionActivity"
5960
android:windowSoftInputMode="adjustNothing|stateHidden"/>

app/src/main/java/com/noti/main/service/NotiListenerService.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import android.widget.Toast;
2727

2828
import androidx.annotation.Nullable;
29+
import androidx.core.app.NotificationCompat;
2930

3031
import com.android.volley.Request;
3132
import com.android.volley.toolbox.JsonObjectRequest;
@@ -414,6 +415,12 @@ private void sendNormalNotification(Notification notification, String PackageNam
414415
Icon LargeIcon = notification.getLargeIcon();
415416
Icon SmallIcon = notification.getSmallIcon();
416417

418+
if(BuildConfig.DEBUG) {
419+
//TODO: refactor notification logic to LiveNotificationData Class
420+
Bitmap BigIcon = (Bitmap) notification.extras.get(NotificationCompat.EXTRA_LARGE_ICON_BIG);
421+
Bitmap BigPicture = (Bitmap) notification.extras.get(NotificationCompat.EXTRA_PICTURE);
422+
}
423+
417424
if (LargeIcon != null)
418425
ICON = getBitmapFromDrawable(LargeIcon.loadDrawable(packageContext));
419426
else if (SmallIcon != null) {

app/src/main/java/com/noti/main/service/backend/PacketRequester.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ public Map<String, String> getHeaders() {
7272
}
7373

7474
public static String getDefaultApiAddress(SharedPreferences prefs, String serviceType, boolean isDebug) {
75-
// TODO: Auto-find available API addresses
7675
String apiDomain = prefs.getString(PacketConst.API_PREFS_DOMAIN_KEY, PacketConst.API_DOMAIN);
7776
return String.format(PacketConst.API_ROUTE_SCHEMA, apiDomain,
7877
isDebug ? PacketConst.API_DEBUG_ROUTE : PacketConst.API_PUBLIC_ROUTE, serviceType);

app/src/main/java/com/noti/main/ui/options/OtherPreference.java

Lines changed: 2 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,13 @@
2828
import com.kieronquinn.monetcompat.core.MonetCompat;
2929
import com.noti.main.Application;
3030
import com.noti.main.R;
31-
import com.noti.main.service.backend.PacketConst;
32-
import com.noti.main.service.backend.PacketRequester;
33-
import com.noti.main.service.backend.ResultPacket;
31+
import com.noti.main.ui.prefs.ServerPingActivity;
3432
import com.noti.main.ui.prefs.custom.CustomFragment;
3533
import com.noti.main.utils.network.AESCrypto;
3634
import com.noti.main.utils.ui.SwitchedPreference;
3735
import com.noti.main.utils.ui.ToastHelper;
3836

39-
import org.json.JSONObject;
40-
41-
import java.io.IOException;
4237
import java.util.Date;
43-
import java.util.Locale;
44-
4538
import me.pushy.sdk.Pushy;
4639

4740
public class OtherPreference extends PreferenceFragmentCompat {
@@ -435,61 +428,7 @@ public boolean onPreferenceTreeClick(Preference preference) {
435428
break;
436429

437430
case "PingTestBackend":
438-
ToastHelper.show(mContext, "Please wait for a minute to check...", ToastHelper.LENGTH_LONG);
439-
long currentTime = System.currentTimeMillis();
440-
441-
try {
442-
JSONObject serverBody = new JSONObject();
443-
PacketRequester.addToRequestQueue(mContext, PacketConst.SERVICE_TYPE_PING_SERVER, serverBody, response -> {
444-
String cause = """
445-
Time taken: %d (ms)
446-
Server Version: %s
447-
""";
448-
try {
449-
MaterialAlertDialogBuilder successDialog = new MaterialAlertDialogBuilder(new ContextThemeWrapper(mContext, R.style.Theme_App_Palette_Dialog));
450-
successDialog.setTitle("Test Success");
451-
successDialog.setIcon(R.drawable.ic_info_outline_black_24dp);
452-
successDialog.setMessage(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - currentTime), ResultPacket.parseFrom(response.toString()).getExtraData()));
453-
successDialog.setPositiveButton("Close", (d, w) -> { });
454-
successDialog.show();
455-
} catch (IOException e) {
456-
throw new RuntimeException(e);
457-
}
458-
}, error -> {
459-
MaterialAlertDialogBuilder errorDialog = new MaterialAlertDialogBuilder(new ContextThemeWrapper(mContext, R.style.Theme_App_Palette_Dialog));
460-
String cause;
461-
462-
if(error.networkResponse == null) {
463-
cause = """
464-
Time taken: %d (ms)
465-
Exception: %s
466-
""";
467-
errorDialog.setMessage(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - currentTime), error.getMessage()));
468-
} else {
469-
cause = """
470-
Time taken: %d (ms)
471-
Error code: %s
472-
""";
473-
errorDialog.setMessage(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - currentTime), error.networkResponse.statusCode));
474-
}
475-
476-
errorDialog.setTitle("Test Failed");
477-
errorDialog.setIcon(R.drawable.ic_info_outline_black_24dp);
478-
errorDialog.setPositiveButton("Close", (d, w) -> { });
479-
errorDialog.show();
480-
});
481-
} catch (Exception e) {
482-
String cause = """
483-
Time taken: %d (ms)
484-
Exception: %s
485-
""";
486-
MaterialAlertDialogBuilder errorDialog = new MaterialAlertDialogBuilder(new ContextThemeWrapper(mContext, R.style.Theme_App_Palette_Dialog));
487-
errorDialog.setTitle("Test Failed");
488-
errorDialog.setIcon(R.drawable.ic_info_outline_black_24dp);
489-
errorDialog.setMessage(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - currentTime), e.getMessage()));
490-
errorDialog.setPositiveButton("Close", (d, w) -> { });
491-
errorDialog.show();
492-
}
431+
startActivity(new Intent(mContext, ServerPingActivity.class));
493432
break;
494433

495434
case "SplitInterval":
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
package com.noti.main.ui.prefs;
2+
3+
import android.annotation.SuppressLint;
4+
import android.os.Bundle;
5+
import android.util.Log;
6+
import android.view.View;
7+
import android.widget.ProgressBar;
8+
import android.widget.TextView;
9+
10+
import androidx.annotation.Nullable;
11+
import androidx.appcompat.app.AppCompatActivity;
12+
import androidx.appcompat.content.res.AppCompatResources;
13+
import androidx.appcompat.widget.AppCompatImageView;
14+
15+
import com.android.volley.Response;
16+
import com.google.android.gms.tasks.OnCompleteListener;
17+
import com.google.android.material.appbar.MaterialToolbar;
18+
import com.google.firebase.firestore.FirebaseFirestore;
19+
import com.google.firebase.firestore.QuerySnapshot;
20+
21+
import com.noti.main.Application;
22+
import com.noti.main.R;
23+
import com.noti.main.service.backend.PacketConst;
24+
import com.noti.main.service.backend.PacketRequester;
25+
import com.noti.main.service.backend.ResultPacket;
26+
27+
import org.json.JSONException;
28+
import org.json.JSONObject;
29+
30+
import java.io.IOException;
31+
import java.util.Locale;
32+
import java.util.Objects;
33+
34+
@SuppressLint("SetTextI18n")
35+
public class ServerPingActivity extends AppCompatActivity {
36+
37+
AppCompatImageView pingStateEmoji;
38+
ProgressBar pingStateProgress;
39+
TextView pingStateTitle;
40+
TextView pingStateDescription;
41+
42+
long startTime;
43+
Response.Listener<JSONObject> successListener = response -> {
44+
try {
45+
pingStateProgress.setVisibility(View.GONE);
46+
pingStateEmoji.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_fluent_accessibility_checkmark_24_regular));
47+
pingStateTitle.setText("Server Calibration and Test Done.");
48+
String cause = """
49+
Time taken: %d (ms)
50+
Server Version: %s
51+
""";
52+
setPingStateDescription(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - startTime), ResultPacket.parseFrom(response.toString()).getExtraData()));
53+
} catch (IOException e) {
54+
setError(e);
55+
}
56+
};
57+
58+
@Override
59+
protected void onCreate(@Nullable Bundle savedInstanceState) {
60+
super.onCreate(savedInstanceState);
61+
setContentView(R.layout.activity_ping_server);
62+
getWindow().setStatusBarColor(getResources().getColor(R.color.ui_bg_toolbar, null));
63+
((MaterialToolbar)findViewById(R.id.toolbar)).setNavigationOnClickListener((v) -> this.finish());
64+
65+
pingStateEmoji = findViewById(R.id.pingStateEmoji);
66+
pingStateProgress = findViewById(R.id.pingStateProgress);
67+
pingStateTitle = findViewById(R.id.pingStateTitle);
68+
pingStateDescription = findViewById(R.id.pingStateDescription);
69+
pingStateDescription.setVisibility(View.GONE);
70+
71+
if (getCurrentDns().equals(PacketConst.API_DOMAIN)) {
72+
performDefaultDnsTest();
73+
} else {
74+
pingStateEmoji.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_fluent_plug_connected_24_regular));
75+
pingStateTitle.setText("Performing current DNS ping test...");
76+
performSavedDnsPing();
77+
}
78+
}
79+
80+
void performSavedDnsPing() {
81+
startTime = System.currentTimeMillis();
82+
try {
83+
JSONObject serverBody = new JSONObject();
84+
PacketRequester.addToRequestQueue(this, PacketConst.SERVICE_TYPE_PING_SERVER, serverBody, successListener, error -> {
85+
if (error.networkResponse == null) {
86+
setError(error);
87+
} else {
88+
performDefaultDnsTest();
89+
}
90+
});
91+
} catch (JSONException e) {
92+
setError(e);
93+
}
94+
}
95+
96+
void performDefaultDnsTest() {
97+
startTime = System.currentTimeMillis();
98+
setDnsToPreference(PacketConst.API_DOMAIN);
99+
100+
pingStateEmoji.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_fluent_plug_connected_settings_24_regular));
101+
pingStateTitle.setText("Performing built-in DNS ping test...");
102+
103+
try {
104+
JSONObject serverBody = new JSONObject();
105+
PacketRequester.addToRequestQueue(this, PacketConst.SERVICE_TYPE_PING_SERVER, serverBody, successListener, error -> {
106+
if (error.networkResponse == null) {
107+
setError(error);
108+
} else {
109+
pingStateEmoji.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_fluent_database_search_24_regular));
110+
pingStateTitle.setText("Getting preferred DNS from Database...");
111+
Log.d("ErrorCode", "Dns: " + getCurrentDns() + " Code: " + error.networkResponse);
112+
113+
OnCompleteListener<QuerySnapshot> onDBCompleteListener = task -> {
114+
if (task.isSuccessful() && task.getResult() != null) {
115+
pingStateEmoji.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_fluent_plug_connected_24_regular));
116+
pingStateTitle.setText("Performing external DNS ping test...");
117+
118+
QuerySnapshot document = task.getResult();
119+
String recommendedDns = document.getDocuments().get(0).getString("availableDns");
120+
performExternalDnsPing(recommendedDns);
121+
} else {
122+
setError(Objects.requireNonNullElse(task.getException(), new IllegalStateException("Error occurred while trying to query DB")));
123+
}
124+
};
125+
126+
FirebaseFirestore mFirebaseFireStore = FirebaseFirestore.getInstance();
127+
mFirebaseFireStore.collection("ApiKey")
128+
.get()
129+
.addOnCompleteListener(onDBCompleteListener);
130+
}
131+
});
132+
} catch (Exception e) {
133+
setError(e);
134+
}
135+
}
136+
137+
void performExternalDnsPing(String dnsAddress) {
138+
setDnsToPreference(dnsAddress);
139+
startTime = System.currentTimeMillis();
140+
141+
try {
142+
JSONObject serverBody = new JSONObject();
143+
PacketRequester.addToRequestQueue(this, PacketConst.SERVICE_TYPE_PING_SERVER, serverBody, successListener, error -> {
144+
setError(error);
145+
if (error.networkResponse != null) {
146+
String cause = """
147+
Time taken: %d (ms)
148+
Error code: %s
149+
""";
150+
setPingStateDescription(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - startTime), error.networkResponse.statusCode));
151+
setDnsToPreference(PacketConst.API_DOMAIN);
152+
}
153+
}
154+
);
155+
} catch (JSONException e) {
156+
setError(e);
157+
}
158+
}
159+
160+
String getCurrentDns() {
161+
return getSharedPreferences(Application.PREFS_NAME, MODE_PRIVATE)
162+
.getString(PacketConst.API_PREFS_DOMAIN_KEY, PacketConst.API_DOMAIN);
163+
}
164+
165+
void setDnsToPreference(String dns) {
166+
getSharedPreferences(Application.PREFS_NAME, MODE_PRIVATE).edit()
167+
.putString(PacketConst.API_PREFS_DOMAIN_KEY, dns).apply();
168+
}
169+
170+
void setError(Exception error) {
171+
pingStateProgress.setVisibility(View.GONE);
172+
pingStateEmoji.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_fluent_globe_error_24_regular));
173+
pingStateTitle.setText("Server calibration failed.");
174+
175+
String cause = """
176+
Time taken: %d (ms)
177+
Exception: %s
178+
""";
179+
String message = Objects.requireNonNullElse(error.getMessage(), "No message");
180+
setPingStateDescription(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - startTime), message));
181+
}
182+
183+
void setPingStateDescription(String description) {
184+
pingStateDescription.setVisibility(View.VISIBLE);
185+
pingStateDescription.setText(description);
186+
}
187+
}

0 commit comments

Comments
 (0)