Search in sources :

Example 1 with WebAppHelper

use of com.eveningoutpost.dexdrip.utils.WebAppHelper in project xDrip by NightscoutFoundation.

the class ActivityRecognizedService method evaluateRequestReceivedCounters.

private static void evaluateRequestReceivedCounters(boolean disable, Context context) {
    final long requested_all_time = addInternalPrefsLong(REQUESTED, REQUESTED_ALL_TIME);
    final long received_all_time = addInternalPrefsLong(RECEIVED, RECEIVED_ALL_TIME);
    // TODO check connectivity
    // TODO use preferences for last send time - don't report more than once every 3 days
    final double ratio = ((received_all_time * 100) / requested_all_time);
    if (d)
        Log.d(TAG, "evaluteRequestReceived: " + requested_all_time + "/" + received_all_time + " " + JoH.qs(ratio, 2));
    // TODO use persistent rate limit
    if (JoH.ratelimit("evalute-request-received", 86400) || (disable)) {
        if (Pref.getBoolean("enable_crashlytics", true)) {
            new WebAppHelper(null).executeOnExecutor(xdrip.executor, xdrip.getAppContext().getString(R.string.wserviceurl) + "/joh-mreport/" + (disable ? 1 : 0) + "/" + requested_all_time + "/" + received_all_time + "/" + JoH.qs(ratio, 0) + "/" + JoH.base64encode(JoH.getDeviceDetails()));
        }
    }
    // mutually exclusive logic
    if ((!disable) && (requested_all_time > 100) && (ratio < 90) && (!PowerStateReceiver.is_power_connected()) && (JoH.isAnyNetworkConnected()) && (JoH.ratelimit("disable_motion", 86400))) {
        disableMotionTrackingDueToErrors(context);
    }
}
Also used : WebAppHelper(com.eveningoutpost.dexdrip.utils.WebAppHelper)

Example 2 with WebAppHelper

use of com.eveningoutpost.dexdrip.utils.WebAppHelper in project xDrip by NightscoutFoundation.

the class ParakeetHelper method parakeetSetupMode.

// put parakeet in to setup mode on next checkin
public static void parakeetSetupMode(Context context) {
    String url = getParakeetSetupURL(context);
    if (url == null) {
        toast(context, "Can't find parakeet app engine URL!");
        return;
    }
    new WebAppHelper(new ParakeetHelper.ServiceCallback()).executeOnExecutor(xdrip.executor, url);
}
Also used : WebAppHelper(com.eveningoutpost.dexdrip.utils.WebAppHelper)

Example 3 with WebAppHelper

use of com.eveningoutpost.dexdrip.utils.WebAppHelper in project xDrip-plus by jamorham.

the class ActivityRecognizedService method evaluateRequestReceivedCounters.

private static void evaluateRequestReceivedCounters(boolean disable, Context context) {
    final long requested_all_time = addInternalPrefsLong(REQUESTED, REQUESTED_ALL_TIME);
    final long received_all_time = addInternalPrefsLong(RECEIVED, RECEIVED_ALL_TIME);
    // TODO check connectivity
    // TODO use preferences for last send time - don't report more than once every 3 days
    final double ratio = ((received_all_time * 100) / requested_all_time);
    if (d)
        Log.d(TAG, "evaluteRequestReceived: " + requested_all_time + "/" + received_all_time + " " + JoH.qs(ratio, 2));
    // TODO use persistent rate limit
    if (JoH.ratelimit("evalute-request-received", 86400) || (disable)) {
        if (Pref.getBoolean("enable_crashlytics", true)) {
            new WebAppHelper(null).executeOnExecutor(xdrip.executor, xdrip.getAppContext().getString(R.string.wserviceurl) + "/joh-mreport/" + (disable ? 1 : 0) + "/" + requested_all_time + "/" + received_all_time + "/" + JoH.qs(ratio, 0) + "/" + JoH.base64encode(JoH.getDeviceDetails()));
        }
    }
    // mutually exclusive logic
    if ((!disable) && (requested_all_time > 100) && (ratio < 90) && (!PowerStateReceiver.is_power_connected()) && (JoH.isAnyNetworkConnected()) && (JoH.ratelimit("disable_motion", 86400))) {
        disableMotionTrackingDueToErrors(context);
    }
}
Also used : WebAppHelper(com.eveningoutpost.dexdrip.utils.WebAppHelper)

Example 4 with WebAppHelper

use of com.eveningoutpost.dexdrip.utils.WebAppHelper in project xDrip by NightscoutFoundation.

the class GcmListenerSvc method onMessageReceived.

@Override
public void onMessageReceived(RemoteMessage rmessage) {
    final PowerManager.WakeLock wl = JoH.getWakeLock("xdrip-onMsgRec", 120000);
    try {
        if (rmessage == null)
            return;
        if (GcmActivity.cease_all_activity)
            return;
        String from = rmessage.getFrom();
        final Bundle data = new Bundle();
        for (Map.Entry<String, String> entry : rmessage.getData().entrySet()) {
            data.putString(entry.getKey(), entry.getValue());
        }
        if (from == null)
            from = "null";
        String message = data.getString("message");
        Log.d(TAG, "From: " + from);
        if (message != null) {
            Log.d(TAG, "Message: " + message);
        } else {
            message = "null";
        }
        final Bundle notification = data.getBundle("notification");
        if (notification != null) {
            Log.d(TAG, "Processing notification bundle");
            try {
                sendNotification(notification.getString("body"), notification.getString("title"));
            } catch (NullPointerException e) {
                Log.d(TAG, "Null pointer exception within sendnotification");
            }
        }
        if (from.startsWith(getString(R.string.gcmtpc))) {
            String xfrom = data.getString("xfrom");
            String payload = data.getString("datum");
            String action = data.getString("action");
            if ((xfrom != null) && (xfrom.equals(GcmActivity.token))) {
                GcmActivity.queueAction(action + payload);
                return;
            }
            String[] tpca = from.split("/");
            if ((tpca[2] != null) && (tpca[2].length() > 30) && (!tpca[2].equals(GcmActivity.myIdentity()))) {
                Log.e(TAG, "Received invalid channel: " + from + " instead of: " + GcmActivity.myIdentity());
                if ((GcmActivity.myIdentity() != null) && (GcmActivity.myIdentity().length() > 30)) {
                    try {
                        FirebaseMessaging.getInstance().unsubscribeFromTopic(tpca[2]);
                    } catch (Exception e) {
                        Log.e(TAG, "Exception unsubscribing: " + e.toString());
                    }
                }
                return;
            }
            byte[] bpayload = null;
            if (payload == null)
                payload = "";
            if (action == null)
                action = "null";
            if (payload.length() > 16) {
                if (GoogleDriveInterface.keyInitialized()) {
                    // handle binary message types
                    switch(action) {
                        case "btmm":
                        case "bgmm":
                            bpayload = CipherUtils.decryptStringToBytes(payload);
                            if (JoH.checkChecksum(bpayload)) {
                                bpayload = Arrays.copyOfRange(bpayload, 0, bpayload.length - 4);
                                Log.d(TAG, "Binary payload received: length: " + bpayload.length + " orig: " + payload.length());
                            } else {
                                Log.e(TAG, "Invalid binary payload received, possible key mismatch: ");
                                bpayload = null;
                            }
                            payload = "binary";
                            break;
                        default:
                            if (action.equals("sensorupdate")) {
                                try {
                                    Log.i(TAG, "payload for sensorupdate " + payload);
                                    byte[] inbytes = Base64.decode(payload, Base64.NO_WRAP);
                                    byte[] inbytes1 = JoH.decompressBytesToBytes(CipherUtils.decryptBytes(inbytes));
                                    payload = new String(inbytes1, "UTF-8");
                                    Log.d(TAG, "inbytes size = " + inbytes.length + " inbytes1 size " + inbytes1.length + "payload len " + payload.length());
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, "Got unsupported encoding on UTF8 " + e.toString());
                                    payload = "";
                                }
                            } else {
                                String decrypted_payload = CipherUtils.decryptString(payload);
                                if (decrypted_payload.length() > 0) {
                                    payload = decrypted_payload;
                                } else {
                                    Log.e(TAG, "Couldn't decrypt payload!");
                                    payload = "";
                                    Home.toaststaticnext("Having problems decrypting incoming data - check keys");
                                }
                            }
                    }
                } else {
                    Log.e(TAG, "Couldn't decrypt as key not initialized");
                    payload = "";
                }
            } else {
                if (payload.length() > 0)
                    UserError.Log.wtf(TAG, "Got short payload: " + payload + " on action: " + action);
            }
            Log.i(TAG, "Got action: " + action + " with payload: " + payload);
            lastMessageReceived = JoH.tsl();
            // new treatment
            if (action.equals("nt")) {
                Log.i(TAG, "Attempting GCM push to Treatment");
                if (Home.get_master_or_follower() && Home.follower_or_accept_follower())
                    GcmActivity.pushTreatmentFromPayloadString(payload);
            } else if (action.equals("dat")) {
                Log.i(TAG, "Attempting GCM delete all treatments");
                if (Home.get_master_or_follower() && Home.follower_or_accept_follower())
                    Treatments.delete_all();
            } else if (action.equals("dt")) {
                Log.i(TAG, "Attempting GCM delete specific treatment");
                if (Home.get_master_or_follower() && Home.follower_or_accept_follower())
                    Treatments.delete_by_uuid(filter(payload));
            } else if (action.equals("clc")) {
                Log.i(TAG, "Attempting to clear last calibration");
                if (Home.get_master_or_follower() && Home.follower_or_accept_follower()) {
                    if (payload.length() > 0) {
                        Calibration.clearCalibrationByUUID(payload);
                    } else {
                        Calibration.clearLastCalibration();
                    }
                }
            } else if (action.equals("cal")) {
                if (Home.get_master_or_follower() && Home.follower_or_accept_follower()) {
                    String[] message_array = filter(payload).split("\\s+");
                    if ((message_array.length == 3) && (message_array[0].length() > 0) && (message_array[1].length() > 0) && (message_array[2].length() > 0)) {
                        // [0]=timestamp [1]=bg_String [2]=bgAge
                        Intent calintent = new Intent();
                        calintent.setClassName(getString(R.string.local_target_package), "com.eveningoutpost.dexdrip.AddCalibration");
                        calintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        long timediff = (long) ((new Date().getTime() - Double.parseDouble(message_array[0])) / 1000);
                        Log.i(TAG, "Remote calibration latency calculated as: " + Long.toString(timediff) + " seconds");
                        if (timediff > 0) {
                            message_array[2] = Long.toString(Long.parseLong(message_array[2]) + timediff);
                        }
                        Log.i(TAG, "Processing remote CAL " + message_array[1] + " age: " + message_array[2]);
                        calintent.putExtra("bg_string", message_array[1]);
                        calintent.putExtra("bg_age", message_array[2]);
                        if (timediff < 3600) {
                            getApplicationContext().startActivity(calintent);
                        }
                    } else {
                        Log.e(TAG, "Invalid CAL payload");
                    }
                }
            } else if (action.equals("cal2")) {
                Log.i(TAG, "Received cal2 packet");
                if (Home.get_master() && Home.follower_or_accept_follower()) {
                    final NewCalibration newCalibration = GcmActivity.getNewCalibration(payload);
                    if (newCalibration != null) {
                        final Intent calintent = new Intent();
                        calintent.setClassName(getString(R.string.local_target_package), "com.eveningoutpost.dexdrip.AddCalibration");
                        calintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        long timediff = (long) ((new Date().getTime() - newCalibration.timestamp) / 1000);
                        Log.i(TAG, "Remote calibration latency calculated as: " + timediff + " seconds");
                        Long bg_age = newCalibration.offset;
                        if (timediff > 0) {
                            bg_age += timediff;
                        }
                        Log.i(TAG, "Processing remote CAL " + newCalibration.bgValue + " age: " + bg_age);
                        calintent.putExtra("bg_string", "" + (Pref.getString("units", "mgdl").equals("mgdl") ? newCalibration.bgValue : newCalibration.bgValue * Constants.MGDL_TO_MMOLL));
                        calintent.putExtra("bg_age", "" + bg_age);
                        if (timediff < 3600) {
                            getApplicationContext().startActivity(calintent);
                        } else {
                            Log.w(TAG, "warninig ignoring calibration because timediff is " + timediff);
                        }
                    }
                } else {
                    Log.e(TAG, "Received cal2 packet packet but we are not a master, so ignoring it");
                }
            } else if (action.equals("ping")) {
                if (payload.length() > 0) {
                    RollCall.Seen(payload);
                }
            // don't respond to wakeup pings
            } else if (action.equals("rlcl")) {
                if (Home.get_master_or_follower()) {
                    if (payload.length() > 0) {
                        RollCall.Seen(payload);
                    }
                    GcmActivity.requestPing();
                }
            } else if (action.equals("p")) {
                GcmActivity.send_ping_reply();
            } else if (action.equals("q")) {
                Home.toaststatic("Received ping reply");
            } else if (action.equals("plu")) {
                // process map update
                if (Home.get_follower()) {
                    MapsActivity.newMapLocation(payload, (long) JoH.ts());
                }
            } else if (action.equals("sbu")) {
                if (Home.get_follower()) {
                    Log.i(TAG, "Received sensor battery level update");
                    Sensor.updateBatteryLevel(Integer.parseInt(payload), true);
                    TransmitterData.updateTransmitterBatteryFromSync(Integer.parseInt(payload));
                }
            } else if (action.equals("bbu")) {
                if (Home.get_follower()) {
                    Log.i(TAG, "Received bridge battery level update");
                    Pref.setInt("bridge_battery", Integer.parseInt(payload));
                    CheckBridgeBattery.checkBridgeBattery();
                }
            } else if (action.equals("pbu")) {
                if (Home.get_follower()) {
                    Log.i(TAG, "Received parakeet battery level update");
                    Pref.setInt("parakeet_battery", Integer.parseInt(payload));
                    CheckBridgeBattery.checkParakeetBattery();
                }
            } else if (action.equals("psu")) {
                if (Home.get_follower()) {
                    Log.i(TAG, "Received pump status update");
                    PumpStatus.fromJson(payload);
                }
            } else if (action.equals("not")) {
                if (Home.get_follower()) {
                    try {
                        final int GCM_NOTIFICATION_ITEM = 543;
                        final String[] payloadA = payload.split("\\^");
                        final String title = payloadA[0];
                        final String body = payloadA[1];
                        final PendingIntent pendingIntent = android.app.PendingIntent.getActivity(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), Home.class), android.app.PendingIntent.FLAG_UPDATE_CURRENT);
                        showNotification(title, body, pendingIntent, GCM_NOTIFICATION_ITEM, true, true, false);
                    } catch (Exception e) {
                        UserError.Log.e(TAG, "Error showing follower notification with payload: " + payload);
                    }
                }
            } else if (action.equals("sbr")) {
                if ((Home.get_master()) && JoH.ratelimit("gcm-sbr", 300)) {
                    Log.i(TAG, "Received sensor battery request");
                    if (Sensor.currentSensor() != null) {
                        try {
                            TransmitterData td = TransmitterData.last();
                            if ((td != null) && (td.sensor_battery_level != 0)) {
                                GcmActivity.sendSensorBattery(td.sensor_battery_level);
                            } else {
                                GcmActivity.sendSensorBattery(Sensor.currentSensor().latest_battery_level);
                            }
                        } catch (NullPointerException e) {
                            Log.e(TAG, "Cannot send sensor battery as sensor is null");
                        }
                    } else {
                        Log.d(TAG, "No active sensor so not sending anything.");
                    }
                }
            } else if (action.equals("amu")) {
                if ((Pref.getBoolean("motion_tracking_enabled", false)) && (Pref.getBoolean("use_remote_motion", false))) {
                    if (!Pref.getBoolean("act_as_motion_master", false)) {
                        ActivityRecognizedService.spoofActivityRecogniser(getApplicationContext(), payload);
                    } else {
                        Home.toaststaticnext("Receiving motion updates from a different master! Make only one the master!");
                    }
                }
            } else if (action.equals("sra")) {
                if ((Home.get_follower() || Home.get_master())) {
                    if (Pref.getBooleanDefaultFalse("accept_remote_snoozes")) {
                        try {
                            long snoozed_time = 0;
                            String sender_ssid = "";
                            try {
                                snoozed_time = Long.parseLong(payload);
                            } catch (NumberFormatException e) {
                                String[] ii = payload.split("\\^");
                                snoozed_time = Long.parseLong(ii[0]);
                                if (ii.length > 1)
                                    sender_ssid = JoH.base64decode(ii[1]);
                            }
                            if (!Pref.getBooleanDefaultFalse("remote_snoozes_wifi_match") || JoH.getWifiFuzzyMatch(sender_ssid, JoH.getWifiSSID())) {
                                if (Math.abs(JoH.tsl() - snoozed_time) < 300000) {
                                    if (JoH.pratelimit("received-remote-snooze", 30)) {
                                        AlertPlayer.getPlayer().Snooze(xdrip.getAppContext(), -1, false);
                                        UserError.Log.ueh(TAG, "Accepted remote snooze");
                                        JoH.static_toast_long("Received remote snooze!");
                                    } else {
                                        Log.e(TAG, "Rate limited remote snooze");
                                    }
                                } else {
                                    UserError.Log.uel(TAG, "Ignoring snooze as outside 5 minute window, sync lag or clock difference");
                                }
                            } else {
                                UserError.Log.uel(TAG, "Ignoring snooze as wifi network names do not match closely enough");
                            }
                        } catch (Exception e) {
                            UserError.Log.e(TAG, "Exception processing remote snooze: " + e);
                        }
                    } else {
                        UserError.Log.uel(TAG, "Rejecting remote snooze");
                    }
                }
            } else if (action.equals("bgs")) {
                Log.i(TAG, "Received BG packet(s)");
                if (Home.get_follower()) {
                    String[] bgs = payload.split("\\^");
                    for (String bgr : bgs) {
                        BgReading.bgReadingInsertFromJson(bgr);
                    }
                    if (Pref.getBooleanDefaultFalse("follower_chime") && JoH.pratelimit("bgs-notify", 1200)) {
                        JoH.showNotification("New glucose data @" + JoH.hourMinuteString(), "Follower Chime: will alert whenever it has been more than 20 minutes since last", null, 60311, true, true, true);
                    }
                } else {
                    Log.e(TAG, "Received remote BG packet but we are not set as a follower");
                }
            // Home.staticRefreshBGCharts();
            } else if (action.equals("bfb")) {
                final String[] bfb = payload.split("\\^");
                if (Pref.getString("dex_collection_method", "").equals("Follower")) {
                    Log.i(TAG, "Processing backfill location packet as we are a follower");
                    staticKey = CipherUtils.hexToBytes(bfb[1]);
                    final Handler mainHandler = new Handler(getMainLooper());
                    final Runnable myRunnable = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                new WebAppHelper(new GcmListenerSvc.ServiceCallback()).executeOnExecutor(xdrip.executor, getString(R.string.wserviceurl) + "/joh-getsw/" + bfb[0]);
                            } catch (Exception e) {
                                Log.e(TAG, "Exception processing run on ui thread: " + e);
                            }
                        }
                    };
                    mainHandler.post(myRunnable);
                } else {
                    Log.i(TAG, "Ignoring backfill location packet as we are not follower");
                }
            } else if (action.equals("bfr")) {
                if (Pref.getBooleanDefaultFalse("plus_follow_master")) {
                    Log.i(TAG, "Processing backfill location request as we are master");
                    GcmActivity.syncBGTable2();
                }
            } else if (action.equals("sensorupdate")) {
                Log.i(TAG, "Received sensorupdate packet(s)");
                if (Home.get_follower()) {
                    GcmActivity.upsertSensorCalibratonsFromJson(payload);
                } else {
                    Log.e(TAG, "Received sensorupdate packets but we are not set as a follower");
                }
            } else if (action.equals("sensor_calibrations_update")) {
                if (Home.get_master()) {
                    Log.i(TAG, "Received request for sensor calibration update");
                    GcmActivity.syncSensor(Sensor.currentSensor(), false);
                }
            } else if (action.equals("btmm")) {
                if (Home.get_master_or_follower() && Home.follower_or_accept_follower()) {
                    BloodTest.processFromMultiMessage(bpayload);
                } else {
                    Log.i(TAG, "Receive multi blood test but we are neither master or follower");
                }
            } else if (action.equals("bgmm")) {
                if (Home.get_follower()) {
                    BgReading.processFromMultiMessage(bpayload);
                } else {
                    Log.i(TAG, "Receive multi glucose readings but we are not a follower");
                }
            } else {
                Log.e(TAG, "Received message action we don't know about: " + action);
            }
        } else {
            // direct downstream message.
            Log.i(TAG, "Received downstream message: " + message);
        }
    } finally {
        JoH.releaseWakeLock(wl);
    }
}
Also used : Bundle(android.os.Bundle) WebAppHelper(com.eveningoutpost.dexdrip.utils.WebAppHelper) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Handler(android.os.Handler) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) WakefulBroadcastReceiver.completeWakefulIntent(android.support.v4.content.WakefulBroadcastReceiver.completeWakefulIntent) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Date(java.util.Date) PowerManager(android.os.PowerManager) TransmitterData(com.eveningoutpost.dexdrip.Models.TransmitterData) PendingIntent(android.app.PendingIntent) Map(java.util.Map)

Example 5 with WebAppHelper

use of com.eveningoutpost.dexdrip.utils.WebAppHelper in project xDrip-plus by jamorham.

the class ParakeetHelper method parakeetSetupMode.

// put parakeet in to setup mode on next checkin
public static void parakeetSetupMode(Context context) {
    String url = getParakeetSetupURL(context);
    if (url == null) {
        toast(context, "Can't find parakeet app engine URL!");
        return;
    }
    new WebAppHelper(new ParakeetHelper.ServiceCallback()).executeOnExecutor(xdrip.executor, url);
}
Also used : WebAppHelper(com.eveningoutpost.dexdrip.utils.WebAppHelper)

Aggregations

WebAppHelper (com.eveningoutpost.dexdrip.utils.WebAppHelper)6 PendingIntent (android.app.PendingIntent)2 Intent (android.content.Intent)2 Bundle (android.os.Bundle)2 Handler (android.os.Handler)2 PowerManager (android.os.PowerManager)2 WakefulBroadcastReceiver.completeWakefulIntent (android.support.v4.content.WakefulBroadcastReceiver.completeWakefulIntent)2 TransmitterData (com.eveningoutpost.dexdrip.Models.TransmitterData)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Date (java.util.Date)2 Map (java.util.Map)2