Skip to content

Commit

Permalink
Added backend ping test menu
Browse files Browse the repository at this point in the history
  • Loading branch information
choiman1559 committed Jul 13, 2024
1 parent a398afa commit bd2aec8
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import com.noti.main.Application;
import com.noti.main.R;
import com.noti.main.StartActivity;
import com.noti.main.service.NotiListenerService;
import com.noti.main.service.backend.PacketConst;
import com.noti.main.service.backend.PacketRequester;
import com.noti.main.service.backend.ResultPacket;
Expand All @@ -43,7 +42,6 @@ public class MediaSession {
public final static String MEDIA_CONTROL = "media_control";

private final SharedPreferences prefs;
private final String UID;
private static String deviceId = "";
private static String deviceName = "";

Expand Down Expand Up @@ -91,14 +89,13 @@ public void onSeekTo(long pos) {
}
};

public MediaSession(Context context, String device_name, String device_id, String userID) {
public MediaSession(Context context, String device_name, String device_id) {
this.context = context;
this.notificationPlayer = new MediaPlayer(context, device_name, device_id);

prefs = context.getSharedPreferences(Application.PREFS_NAME, Context.MODE_PRIVATE);
deviceId = device_id;
deviceName = device_name;
UID = userID;
initMediaSession();
}

Expand All @@ -125,11 +122,6 @@ public void updateBitmap(JSONObject npd) throws JSONException, NoSuchAlgorithmEx
JSONObject serverBody = new JSONObject();
serverBody.put(PacketConst.KEY_ACTION_TYPE, PacketConst.REQUEST_GET_SHORT_TERM_DATA);
serverBody.put(PacketConst.KEY_DATA_KEY, finalUniqueId);
serverBody.put(PacketConst.KEY_UID, UID);

serverBody.put(PacketConst.KEY_DEVICE_ID, NotiListenerService.getUniqueID());
serverBody.put(PacketConst.KEY_DEVICE_NAME, NotiListenerService.getDeviceName());

serverBody.put(PacketConst.KEY_SEND_DEVICE_ID, deviceId);
serverBody.put(PacketConst.KEY_SEND_DEVICE_NAME, deviceName);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ public void processReception(Map<String, String> map, Context context) {
synchronized (playingSessionMap) {
MediaSession current;
if (!playingSessionMap.containsKey(map.get("device_id"))) {
current = new MediaSession(this, map.get("device_name"), map.get("device_id"), prefs.getString("UID", ""));
current = new MediaSession(this, map.get("device_name"), map.get("device_id"));
playingSessionMap.put(map.get("device_id"), current);
} else {
current = playingSessionMap.get(map.get("device_id"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
import com.google.firebase.auth.FirebaseUser;

import com.noti.main.Application;
import com.noti.main.service.NotiListenerService;
import com.noti.main.utils.network.JsonRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
Expand All @@ -22,12 +24,16 @@

public class PacketRequester {
public static void addToRequestQueue(Context context, String serviceType, JSONObject packetBody,
Response.Listener<org. json. JSONObject> listener, @Nullable Response.ErrorListener errorListener) {
Response.Listener<org. json. JSONObject> listener, @Nullable Response.ErrorListener errorListener) throws JSONException {

SharedPreferences prefs = context.getSharedPreferences(Application.PREFS_NAME, Context.MODE_PRIVATE);
final String URI = getApiAddress(serviceType, prefs.getBoolean("useDebugBackend", false));
boolean notUseAuthentication = prefs.getBoolean("notUseAuthentication", false);

packetBody.put(PacketConst.KEY_UID, prefs.getString("UID", ""));
packetBody.put(PacketConst.KEY_DEVICE_ID, NotiListenerService.getUniqueID());
packetBody.put(PacketConst.KEY_DEVICE_NAME, NotiListenerService.getDeviceName());

if(notUseAuthentication) {
postPacket(context, null, URI, packetBody, listener, errorListener);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,9 @@ public static void postLiveNotificationData(Context context, Map<String, String>
JSONObject serverBody = new JSONObject();
serverBody.put(PacketConst.KEY_ACTION_TYPE, PacketConst.REQUEST_POST_SHORT_TERM_DATA);
serverBody.put(PacketConst.KEY_DATA_KEY, finalUniqueId);
serverBody.put(PacketConst.KEY_UID, userId);
serverBody.put(PacketConst.KEY_EXTRA_DATA, notificationData);

serverBody.put(PacketConst.KEY_SEND_DEVICE_ID, sendDeviceId);
serverBody.put(PacketConst.KEY_SEND_DEVICE_NAME, sendDeviceName);
serverBody.put(PacketConst.KEY_DEVICE_ID, deviceId);
serverBody.put(PacketConst.KEY_DEVICE_NAME, deviceName);

PacketRequester.addToRequestQueue(context, PacketConst.SERVICE_TYPE_LIVE_NOTIFICATION, serverBody, response -> {
try {
Expand All @@ -102,10 +98,6 @@ public static void postLiveNotificationData(Context context, Map<String, String>
}

public static void getLiveNotificationData(Context context, Map<String, String> map) throws NoSuchAlgorithmException, JSONException {
SharedPreferences prefs = context.getSharedPreferences(Application.PREFS_NAME, Context.MODE_PRIVATE);

String deviceId = NotiListenerService.getUniqueID();
String deviceName = NotiListenerService.getDeviceName();
String sendDeviceId = map.get(PacketConst.KEY_DEVICE_ID);
String sendDeviceName = map.get(PacketConst.KEY_DEVICE_NAME);

Expand All @@ -121,12 +113,8 @@ public static void getLiveNotificationData(Context context, Map<String, String>
JSONObject serverBody = new JSONObject();
serverBody.put(PacketConst.KEY_ACTION_TYPE, PacketConst.REQUEST_GET_SHORT_TERM_DATA);
serverBody.put(PacketConst.KEY_DATA_KEY, finalUniqueId);
serverBody.put(PacketConst.KEY_UID, prefs.getString("UID", ""));

serverBody.put(PacketConst.KEY_SEND_DEVICE_ID, sendDeviceId);
serverBody.put(PacketConst.KEY_SEND_DEVICE_NAME, sendDeviceName);
serverBody.put(PacketConst.KEY_DEVICE_ID, deviceId);
serverBody.put(PacketConst.KEY_DEVICE_NAME, deviceName);

if("true".equals(map.get(PacketConst.KEY_IS_SUCCESS))) {
PacketRequester.addToRequestQueue(context, PacketConst.SERVICE_TYPE_LIVE_NOTIFICATION, serverBody, response -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,12 +230,8 @@ synchronized void sendMetadata(MediaReceiverPlayer player) {
JSONObject serverBody = new JSONObject();
serverBody.put(PacketConst.KEY_ACTION_TYPE, PacketConst.REQUEST_POST_SHORT_TERM_DATA);
serverBody.put(PacketConst.KEY_DATA_KEY, finalUniqueId);
serverBody.put(PacketConst.KEY_UID, prefs.getString("UID", ""));
serverBody.put(PacketConst.KEY_EXTRA_DATA, serializedBitmap);

serverBody.put(PacketConst.KEY_DEVICE_ID, DEVICE_ID);
serverBody.put(PacketConst.KEY_DEVICE_NAME, DEVICE_NAME);

PacketRequester.addToRequestQueue(context, PacketConst.SERVICE_TYPE_IMAGE_CACHE, serverBody, response -> {
try {
ResultPacket resultPacket = ResultPacket.parseFrom(response.toString());
Expand Down
87 changes: 68 additions & 19 deletions app/src/main/java/com/noti/main/ui/options/OtherPreference.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,19 @@
import com.kieronquinn.monetcompat.core.MonetCompat;
import com.noti.main.Application;
import com.noti.main.R;
import com.noti.main.service.backend.PacketConst;
import com.noti.main.service.backend.PacketRequester;
import com.noti.main.service.backend.ResultPacket;
import com.noti.main.ui.prefs.custom.CustomFragment;
import com.noti.main.utils.network.AESCrypto;
import com.noti.main.utils.ui.ToastHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;
import java.util.Locale;

import me.pushy.sdk.Pushy;

Expand All @@ -51,6 +59,7 @@ public class OtherPreference extends PreferenceFragmentCompat {
Preference UpdateChannel;
Preference SaveLastSelectedItem;
Preference NewCardRadius;
Preference PingTestBackend;

Preference UseDataEncryption;
Preference UseDataEncryptionPassword;
Expand Down Expand Up @@ -95,6 +104,7 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
UpdateChannel = findPreference("UpdateChannel");
SaveLastSelectedItem = findPreference("SaveLastSelectedItem");
NewCardRadius = findPreference("NewCardRadius");
PingTestBackend = findPreference("PingTestBackend");

UseDataEncryption = findPreference("UseDataEncryption");
UseDataEncryptionPassword = findPreference("UseDataEncryptionPassword");
Expand All @@ -120,7 +130,7 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
return true;
});

boolean ifUIDBlank = prefs.getString("UID", "").equals("");
boolean ifUIDBlank = prefs.getString("UID", "").isEmpty();
if(ifUIDBlank) {
((SwitchPreference)UseDataEncryption).setChecked(false);
UseDataEncryption.setEnabled(false);
Expand Down Expand Up @@ -189,7 +199,7 @@ public boolean onPreferenceTreeClick(Preference preference) {

dialog.setPositiveButton("Apply", (d, w) -> {
String value = editText.getText().toString();
if (value.equals("")) {
if (value.isEmpty()) {
ToastHelper.show(mContext, "Please Input Value", "DISMISS", ToastHelper.LENGTH_SHORT);
} else {
int IntValue = Integer.parseInt(value);
Expand Down Expand Up @@ -236,7 +246,7 @@ public boolean onPreferenceTreeClick(Preference preference) {

dialog.setPositiveButton("Apply", (d, w) -> {
String value = editText.getText().toString();
if (value.equals("")) {
if (value.isEmpty()) {
ToastHelper.show(mContext, "Please Input Value", "DISMISS", ToastHelper.LENGTH_SHORT);
} else {
int IntValue = Integer.parseInt(value);
Expand Down Expand Up @@ -293,20 +303,12 @@ public boolean onPreferenceTreeClick(Preference preference) {
case "TestNotification":
Notify.NotifyImportance importance;
String value = prefs.getString("importance", "Default");
switch (value) {
case "Default":
importance = Notify.NotifyImportance.MAX;
break;
case "Low":
importance = Notify.NotifyImportance.LOW;
break;
case "High":
importance = Notify.NotifyImportance.HIGH;
break;
default:
importance = Notify.NotifyImportance.MIN;
break;
}
importance = switch (value) {
case "Default" -> Notify.NotifyImportance.MAX;
case "Low" -> Notify.NotifyImportance.LOW;
case "High" -> Notify.NotifyImportance.HIGH;
default -> Notify.NotifyImportance.MIN;
};

Notify.build(mContext)
.setTitle("test (" + (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE) + ")")
Expand Down Expand Up @@ -339,7 +341,7 @@ public boolean onPreferenceTreeClick(Preference preference) {
editText.setGravity(Gravity.START);

String rawPassword = prefs.getString("EncryptionPassword", "");
if(rawPassword.equals("")) editText.setText("");
if(rawPassword.isEmpty()) editText.setText("");
else {
String uid = mAuth.getUid();
if(uid != null) {
Expand All @@ -362,7 +364,7 @@ public boolean onPreferenceTreeClick(Preference preference) {

dialog.setPositiveButton("Apply", (d, w) -> {
String values = editText.getText().toString();
if (values.equals("")) {
if (values.isEmpty()) {
ToastHelper.show(mContext, "Please Input password","DISMISS", ToastHelper.LENGTH_SHORT);
} else if(values.length() > 20) {
ToastHelper.show(mContext, "Password too long! maximum 20 chars.", "DISMISS",ToastHelper.LENGTH_SHORT);
Expand All @@ -389,6 +391,53 @@ public boolean onPreferenceTreeClick(Preference preference) {
dialog.setPositiveButton("Close", (d, w) -> { });
dialog.show();
break;

case "PingTestBackend":
ToastHelper.show(mContext, "Please wait for a minute to check...", ToastHelper.LENGTH_LONG);
long currentTime = System.currentTimeMillis();

try {
JSONObject serverBody = new JSONObject();
PacketRequester.addToRequestQueue(mContext, PacketConst.SERVICE_TYPE_PING_SERVER, serverBody, response -> {
String cause = """
Time taken: %d (ms)
Server Version: %s
""";
try {
MaterialAlertDialogBuilder successDialog = new MaterialAlertDialogBuilder(new ContextThemeWrapper(mContext, R.style.Theme_App_Palette_Dialog));
successDialog.setTitle("Test Success");
successDialog.setIcon(R.drawable.ic_info_outline_black_24dp);
successDialog.setMessage(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - currentTime), ResultPacket.parseFrom(response.toString()).getExtraData()));
successDialog.setPositiveButton("Close", (d, w) -> { });
successDialog.show();
} catch (IOException e) {
throw new RuntimeException(e);
}
}, error -> {
String cause = """
Time taken: %d (ms)
Error code: %d
""";
MaterialAlertDialogBuilder errorDialog = new MaterialAlertDialogBuilder(new ContextThemeWrapper(mContext, R.style.Theme_App_Palette_Dialog));
errorDialog.setTitle("Test Failed");
errorDialog.setIcon(R.drawable.ic_info_outline_black_24dp);
errorDialog.setMessage(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - currentTime), error.networkResponse.statusCode));
errorDialog.setPositiveButton("Close", (d, w) -> { });
errorDialog.show();
});
} catch (JSONException e) {
String cause = """
Time taken: %d (ms)
Exception: %s
""";
MaterialAlertDialogBuilder errorDialog = new MaterialAlertDialogBuilder(new ContextThemeWrapper(mContext, R.style.Theme_App_Palette_Dialog));
errorDialog.setTitle("Test Failed");
errorDialog.setIcon(R.drawable.ic_info_outline_black_24dp);
errorDialog.setMessage(String.format(Locale.getDefault(), cause, (System.currentTimeMillis() - currentTime), e.getCause()));
errorDialog.setPositiveButton("Close", (d, w) -> { });
errorDialog.show();
}
break;
}
return super.onPreferenceTreeClick(preference);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.noti.main.ui.pair.action;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
Expand Down Expand Up @@ -29,6 +30,7 @@
import com.noti.main.service.livenoti.LiveNotificationData;
import com.noti.main.ui.receive.NotificationViewActivity;
import com.noti.main.utils.network.CompressStringUtil;
import com.noti.main.utils.ui.ToastHelper;

import java.util.Locale;

Expand Down Expand Up @@ -176,13 +178,18 @@ public LiveNotiItemHolder(Context context, LiveNotificationData liveNotification
liveNotiBigIcon.setVisibility(View.GONE);
}

remoteRunButton.setOnClickListener((v) -> NotificationViewActivity.receptionNotification(context, liveNotificationObj.appPackage, Device_name, Device_id, liveNotificationObj.key, true, true));
remoteRunButton.setOnClickListener((v) -> {
NotificationViewActivity.receptionNotification(context, liveNotificationObj.appPackage, Device_name, Device_id, liveNotificationObj.key, true, true);
ToastHelper.show((Activity) context, "Remote run request has been sent","Ok", ToastHelper.LENGTH_SHORT);
});

dismissButton.setOnClickListener((v) -> {
liveNotiLayout.removeView(liveNotiItem);
if(lastSelectedItemHolder == this) {
lastSelectedItemHolder = null;
}
NotificationViewActivity.receptionNotification(context, liveNotificationObj.appPackage, Device_name, Device_id, liveNotificationObj.key, false, true);
ToastHelper.show((Activity) context, "Dismiss request has been sent","Ok", ToastHelper.LENGTH_SHORT);
});

liveNotiActionMenuLayout.setVisibility(View.GONE);
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/res/xml/other_preferences.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@
android:icon="@drawable/ic_info_outline_black_24dp"
android:key="EncryptionInfo"
android:summary="Changing options on these backend servers does not guarantee availability or reliability." />
<Preference
android:key="PingTestBackend"
android:icon="@drawable/ic_fluent_checkbox_checked_24_regular"
android:title="Perform ping test to server"
android:summary="Press this menu to check\nwhether server is alive or not" />
</PreferenceCategory>

<PreferenceCategory android:title="Interface">
Expand Down

0 comments on commit bd2aec8

Please sign in to comment.