Search in sources :

Example 6 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class ConnectionHTTP method sendHttpResponsePolicies.

public static void sendHttpResponsePolicies(final Context context, final String taskId, final String data, final String sessionToken, final DataCallback callback) {
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                Routes routes = new Routes(context);
                MqttData cache = new MqttData(context);
                String url = routes.PluginFlyvemdmTaskstatusSearch(cache.getAgentId(), taskId);
                // First step get the taskstatus_id
                URL dataURL = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) dataURL.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(timeout);
                conn.setReadTimeout(readtimeout);
                HashMap<String, String> header = new HashMap();
                header.put("Content-Type", "application/json");
                header.put("Session-Token", sessionToken);
                StringBuilder logHeader = new StringBuilder();
                if (header != null) {
                    for (Map.Entry<String, String> entry : header.entrySet()) {
                        logHeader.append("- " + entry.getKey() + " : " + entry.getValue() + "\n");
                        conn.setRequestProperty(entry.getKey(), entry.getValue());
                    }
                } else {
                    logHeader.append("Empty");
                }
                if (conn.getResponseCode() >= 400) {
                    InputStream is = conn.getErrorStream();
                    final String result = inputStreamToString(is);
                    ConnectionHTTP.runOnUI(new Runnable() {

                        public void run() {
                            callback.callback(result);
                        }
                    });
                    return;
                }
                InputStream is = conn.getInputStream();
                final String requestResponse = inputStreamToString(is);
                String taskStatusId = "";
                try {
                    JSONObject objResponse = new JSONObject(requestResponse);
                    JSONArray arrayData = objResponse.getJSONArray("data");
                    taskStatusId = arrayData.getJSONObject(0).getString("2");
                } catch (Exception ex) {
                    FlyveLog.e(ConnectionHTTP.class.getClass().getName() + ", getWebData", ex.getClass() + " : " + ex.getMessage() + " Data : " + data + "Route : " + url);
                    return;
                }
                String response = "\n URL:\n" + url + "\n\n Method:\n" + conn.getRequestMethod() + "\n\n Code:\n" + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n Header:\n" + logHeader + "\n\n Data:\n" + data + "\n\n Response:\n" + requestResponse + "\n\n";
                LogDebug(response);
                try {
                    // second step update the status task
                    url = routes.PluginFlyvemdmTaskstatus(taskStatusId);
                    dataURL = new URL(url);
                    conn = (HttpURLConnection) dataURL.openConnection();
                    conn.setRequestMethod("PUT");
                    conn.setConnectTimeout(timeout);
                    conn.setReadTimeout(readtimeout);
                    header = new HashMap();
                    header.put("Content-Type", "application/json");
                    header.put("Session-Token", sessionToken);
                    logHeader = new StringBuilder();
                    if (header != null) {
                        for (Map.Entry<String, String> entry : header.entrySet()) {
                            logHeader.append("- " + entry.getKey() + " : " + entry.getValue() + "\n");
                            conn.setRequestProperty(entry.getKey(), entry.getValue());
                        }
                    } else {
                        logHeader.append("Empty");
                    }
                    // Send post request
                    conn.setDoOutput(true);
                    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                    os.writeBytes(data);
                    os.flush();
                    os.close();
                    if (conn.getResponseCode() >= 400) {
                        is = conn.getErrorStream();
                        final String result = inputStreamToString(is);
                        ConnectionHTTP.runOnUI(new Runnable() {

                            public void run() {
                                callback.callback(result);
                            }
                        });
                        return;
                    }
                    is = conn.getInputStream();
                    final String requestResponsePut = inputStreamToString(is);
                    response = "\n URL:\n" + url + "\n\n Method:\n" + conn.getRequestMethod() + "\n\n Code:\n" + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n Header:\n" + logHeader + "\n\n Data:\n" + data + "\n\n Response:\n" + requestResponse + "\n\n";
                    LogDebug(response);
                    ConnectionHTTP.runOnUI(new Runnable() {

                        public void run() {
                            callback.callback(requestResponsePut);
                        }
                    });
                } catch (final Exception ex) {
                    ConnectionHTTP.runOnUI(new Runnable() {

                        public void run() {
                            callback.callback(ex.getMessage());
                        }
                    });
                }
            } catch (final Exception ex) {
                ConnectionHTTP.runOnUI(new Runnable() {

                    public void run() {
                        callback.callback(EXCEPTION_HTTP + ex.getMessage());
                        FlyveLog.e(ConnectionHTTP.class.getClass().getName() + ", getWebData", ex.getClass() + " : " + ex.getMessage());
                    }
                });
            }
        }
    });
    t.start();
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) HashMap(java.util.HashMap) InputStream(java.io.InputStream) DataOutputStream(java.io.DataOutputStream) JSONArray(org.json.JSONArray) Routes(org.flyve.mdm.agent.core.Routes) URL(java.net.URL) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject)

Example 7 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class FragmentConfiguration method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    v = inflater.inflate(R.layout.fragment_configuration, container, false);
    cache = new AppData(FragmentConfiguration.this.getContext());
    Switch swNotifications = this.v.findViewById(R.id.swNotifications);
    swNotifications.setChecked(cache.getDisableNotification());
    swNotifications.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            cache.setDisableNotification(b);
        }
    });
    Switch swConnectionNotification = this.v.findViewById(R.id.swConnectionNotification);
    swConnectionNotification.setChecked(cache.getEnableNotificationConnection());
    swConnectionNotification.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            cache.setEnableNotificationConnection(b);
        }
    });
    Switch swDarkTheme = this.v.findViewById(R.id.swDarkTheme);
    swDarkTheme.setChecked(cache.getDarkTheme());
    swDarkTheme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            cache.setDarkTheme(b);
        }
    });
    // use for lock option
    Switch switchDrawOverlay = this.v.findViewById(R.id.swtDrawOverlay);
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        switchDrawOverlay.setChecked(Settings.canDrawOverlays(getActivity()));
        switchDrawOverlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getActivity().getPackageName()));
                startActivityForResult(intent, REQUEST_DRAWOVERLAY_CODE);
            }
        });
    } else {
        switchDrawOverlay.setVisibility(View.INVISIBLE);
    }
    Button btnClear = v.findViewById(R.id.btnClear);
    btnClear.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(FragmentConfiguration.this.getContext());
            builder.setTitle(R.string.danger);
            builder.setMessage(R.string.erase_all_data_question);
            builder.setPositiveButton(R.string.YES, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    LocalStorage localStorage = new LocalStorage(FragmentConfiguration.this.getContext());
                    localStorage.clearSettings();
                    new MqttData(FragmentConfiguration.this.getContext()).deleteAll();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton(R.string.NO, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Do nothing
                    dialog.dismiss();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
    });
    return v;
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) MqttData(org.flyve.mdm.agent.data.database.MqttData) DialogInterface(android.content.DialogInterface) Intent(android.content.Intent) View(android.view.View) LocalStorage(org.flyve.mdm.agent.data.localstorage.LocalStorage) Switch(android.widget.Switch) AppData(org.flyve.mdm.agent.data.localstorage.AppData) CompoundButton(android.widget.CompoundButton) Button(android.widget.Button) CompoundButton(android.widget.CompoundButton)

Example 8 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class PoliciesAsyncTask method doInBackground.

protected Boolean doInBackground(Object... object) {
    final Context context = (Context) object[0];
    final Integer action = (Integer) object[1];
    final String topic = (String) object[2];
    final String message = (String) object[3];
    mHandler.post(new Runnable() {

        public void run() {
            switch(action) {
                case LOCK:
                    {
                        if (!MDMAgent.isSecureVersion()) {
                            try {
                                JSONObject jsonObj = new JSONObject(message);
                                if (jsonObj.has("lock")) {
                                    String lock = jsonObj.getString("lock");
                                    AndroidPolicies androidPolicies = new AndroidPolicies(context, FlyveAdminReceiver.class);
                                    if (lock.equalsIgnoreCase("now")) {
                                        // lock screen
                                        androidPolicies.lockScreen(LockActivity.class, context);
                                        // lock device
                                        androidPolicies.lockDevice();
                                    } else {
                                        // unlock screen
                                        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M && Settings.canDrawOverlays(context)) {
                                            try {
                                                MDMAgent mainActivity = ((MDMAgent) context);
                                                mainActivity.getLockActivity().unlockScreen();
                                            } catch (Exception e) {
                                            }
                                        }
                                        // unlock device
                                        androidPolicies.unlockDevice();
                                        Helpers.sendBroadcast("unlock", "org.flyvemdm.finishlock", context);
                                    }
                                }
                            } catch (Exception ex) {
                                FlyveLog.e(this.getClass().getName() + ", LOCK ", ex.getMessage());
                            }
                        }
                    }
                case PING:
                    {
                        String data = "{\"input\":{\"_pong\":\"!\"}}";
                        Routes routes = new Routes(context);
                        MqttData cache = new MqttData(context);
                        String url = routes.pluginFlyvemdmAgent(cache.getAgentId());
                        pluginHttpResponse(context, url, data);
                    }
                    break;
                case WIPE:
                    {
                        if (!MDMAgent.isSecureVersion()) {
                            try {
                                JSONObject jsonObj = new JSONObject(message);
                                if (jsonObj.has("wipe") && "NOW".equalsIgnoreCase(jsonObj.getString("wipe"))) {
                                    sendStatusbyHttp(context, false);
                                    new AndroidPolicies(context, FlyveAdminReceiver.class).wipe();
                                }
                            } catch (Exception ex) {
                                FlyveLog.e(this.getClass().getName() + ", WIPE ", ex.getMessage());
                            }
                        }
                    }
                    break;
                case UNENROLL:
                    {
                        // set offline
                        sendStatusbyHttp(context, false);
                        // Remove all the information
                        new ApplicationData(context).deleteAll();
                        new FileData(context).deleteAll();
                        new MqttData(context).deleteAll();
                        new PoliciesData(context).deleteAll();
                    }
                    break;
                case GEOLOCATE:
                    {
                        FastLocationProvider fastLocationProvider = new FastLocationProvider();
                        Routes routes = new Routes(context);
                        final String url = routes.pluginFlyvemdmGeolocation();
                        boolean isAvailable = fastLocationProvider.getLocation(context, new FastLocationProvider.LocationResult() {

                            @Override
                            public void gotLocation(Location location) {
                                if (location == null) {
                                    FlyveLog.e(this.getClass().getName() + ", sendGPS", "without location yet...");
                                    try {
                                        JSONObject jsonPayload = new JSONObject();
                                        jsonPayload.put("_datetime", Helpers.getUnixTime(context));
                                        jsonPayload.put("_agents_id", new MqttData(context).getAgentId());
                                        jsonPayload.put("computers_id", new MqttData(context).getComputersId());
                                        jsonPayload.put("_gps", "off");
                                        JSONObject jsonInput = new JSONObject();
                                        jsonInput.put("input", jsonPayload);
                                        String payload = jsonInput.toString();
                                        pluginHttpResponse(context, url, payload);
                                    } catch (Exception ex) {
                                        Helpers.storeLog("fcm", "Error on GPS location", ex.getMessage());
                                    }
                                } else {
                                    try {
                                        String latitude = String.valueOf(location.getLatitude());
                                        String longitude = String.valueOf(location.getLongitude());
                                        // "{"input":{"_agents_id":":id","_datetime":":string","latitude":":float","longitude":":float"}}"
                                        JSONObject jsonGPS = new JSONObject();
                                        jsonGPS.put("latitude", latitude);
                                        jsonGPS.put("longitude", longitude);
                                        jsonGPS.put("_datetime", Helpers.getUnixTime(context));
                                        jsonGPS.put("_agents_id", new MqttData(context).getAgentId());
                                        jsonGPS.put("computers_id", new MqttData(context).getComputersId());
                                        JSONObject jsonInput = new JSONObject();
                                        jsonInput.put("input", jsonGPS);
                                        String payload = jsonInput.toString();
                                        pluginHttpResponse(context, url, payload);
                                    } catch (Exception ex) {
                                        FlyveLog.e(this.getClass().getName() + ", sendGPS", ex.getMessage());
                                        Helpers.storeLog("fcm", "Error on GPS location", ex.getMessage());
                                    }
                                }
                            }
                        });
                        if (!isAvailable) {
                            try {
                                JSONObject jsonPayload = new JSONObject();
                                jsonPayload.put("_datetime", Helpers.getUnixTime(context));
                                jsonPayload.put("_agents_id", new MqttData(context).getAgentId());
                                jsonPayload.put("_gps", "off");
                                jsonPayload.put("computers_id", new MqttData(context).getComputersId());
                                JSONObject jsonInput = new JSONObject();
                                jsonInput.put("input", jsonPayload);
                                String payload = jsonInput.toString();
                                pluginHttpResponse(context, url, payload);
                            } catch (Exception ex) {
                                Helpers.storeLog("fcm", "Error on GPS location", ex.getMessage());
                            }
                        }
                    }
                    break;
                case INVENTORY:
                    {
                        Inventory inventory = new Inventory();
                        inventory.getXMLInventory(context, new InventoryTask.OnTaskCompleted() {

                            @Override
                            public void onTaskSuccess(String s) {
                                Routes routes = new Routes(context);
                                MqttData cache = new MqttData(context);
                                String url = routes.pluginFlyvemdmAgent(cache.getAgentId());
                                try {
                                    JSONObject jsonPayload = new JSONObject();
                                    jsonPayload.put("_inventory", Helpers.base64encode(s));
                                    JSONObject jsonInput = new JSONObject();
                                    jsonInput.put("input", jsonPayload);
                                    String payload = jsonInput.toString();
                                    pluginHttpResponse(context, url, payload);
                                    Helpers.storeLog("fcm", "Inventory", "Inventory Send");
                                } catch (Exception ex) {
                                    Helpers.storeLog("fcm", "Error on json createInventory", ex.getMessage());
                                }
                            }

                            @Override
                            public void onTaskError(Throwable throwable) {
                                Helpers.storeLog("fcm", "Error on createInventory", throwable.getMessage());
                            }
                        });
                    }
                case POLICIES:
                    {
                        // Policy/passwordEnabled
                        callPolicy(context, PasswordEnablePolicy.class, PasswordEnablePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordQuality
                        callPolicy(context, PasswordQualityPolicy.class, PasswordQualityPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordMinLength
                        callPolicy(context, PasswordMinLengthPolicy.class, PasswordMinLengthPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordMinLowerCase
                        callPolicy(context, PasswordMinLowerCasePolicy.class, PasswordMinLowerCasePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordMinUpperCase
                        callPolicy(context, PasswordMinUpperCasePolicy.class, PasswordMinUpperCasePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordMinNonLetter
                        callPolicy(context, PasswordMinNonLetterPolicy.class, PasswordMinNonLetterPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordMinLetters
                        callPolicy(context, PasswordMinLetterPolicy.class, PasswordMinLetterPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordMinNumeric
                        callPolicy(context, PasswordMinNumericPolicy.class, PasswordMinNumericPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/passwordMinSymbols
                        callPolicy(context, PasswordMinSymbolsPolicy.class, PasswordMinSymbolsPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/MaximumFailedPasswordsForWipe
                        callPolicy(context, MaximumFailedPasswordForWipePolicy.class, MaximumFailedPasswordForWipePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/MaximumTimeToLock
                        callPolicy(context, MaximumTimeToLockPolicy.class, MaximumTimeToLockPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/storageEncryption
                        callPolicy(context, StorageEncryptionPolicy.class, StorageEncryptionPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableCamera
                        callPolicy(context, CameraPolicy.class, CameraPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableBluetooth
                        callPolicy(context, BluetoothPolicy.class, BluetoothPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableHostpotTethering
                        callPolicy(context, HostpotTetheringPolicy.class, HostpotTetheringPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableRoaming
                        callPolicy(context, RoamingPolicy.class, RoamingPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableWifi
                        callPolicy(context, WifiPolicy.class, WifiPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableSpeakerphone
                        callPolicy(context, SpeakerphonePolicy.class, SpeakerphonePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableCreateVpnProfiles
                        callPolicy(context, VPNPolicy.class, VPNPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStreamMusic
                        callPolicy(context, StreamMusicPolicy.class, StreamMusicPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStreamRing
                        callPolicy(context, StreamRingPolicy.class, StreamRingPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStreamAlarm
                        callPolicy(context, StreamAlarmPolicy.class, StreamAlarmPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStreamNotification
                        callPolicy(context, StreamNotificationPolicy.class, StreamNotificationPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStreamAccessibility
                        callPolicy(context, StreamAccessibilityPolicy.class, StreamAccessibilityPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStreamVoiceCall
                        callPolicy(context, StreamVoiceCallPolicy.class, StreamVoiceCallPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStreamDTMF
                        callPolicy(context, StreamVoiceCallPolicy.class, StreamVoiceCallPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableScreenCapture
                        // ROOT REQUIRED
                        callPolicy(context, ScreenCapturePolicy.class, ScreenCapturePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableAirplaneMode
                        // ROOT REQUIRED
                        callPolicy(context, AirplaneModePolicy.class, AirplaneModePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableGPS
                        // ROOT REQUIRED
                        callPolicy(context, GPSPolicy.class, GPSPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableMobileLine
                        // ROOT
                        callPolicy(context, MobileLinePolicy.class, MobileLinePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableNfc
                        // ROOT
                        callPolicy(context, NFCPolicy.class, NFCPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableStatusBar
                        // ROOT
                        callPolicy(context, StatusBarPolicy.class, StatusBarPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableUsbMtp
                        // ROOT
                        callPolicy(context, UsbMtpPolicy.class, UsbMtpPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableUsbPtp
                        // ROOT
                        callPolicy(context, UsbPtpPolicy.class, UsbPtpPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/disableUsbAdb
                        // ROOT
                        callPolicy(context, UsbAdbPolicy.class, UsbAdbPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/deployApp
                        // ROOT
                        callPolicy(context, DeployAppPolicy.class, DeployAppPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/removeApp
                        // ROOT
                        callPolicy(context, RemoveAppPolicy.class, RemoveAppPolicy.POLICY_NAME, priority, topic, message);
                        // Policy/deployFile
                        // ROOT
                        callPolicy(context, DeployFilePolicy.class, DeployFilePolicy.POLICY_NAME, priority, topic, message);
                        // Policy/removeFile
                        // ROOT
                        callPolicy(context, RemoveFilePolicy.class, RemoveFilePolicy.POLICY_NAME, priority, topic, message);
                    }
                    break;
                default:
            }
        }
    });
    return true;
}
Also used : Context(android.content.Context) MqttData(org.flyve.mdm.agent.data.database.MqttData) MDMAgent(org.flyve.mdm.agent.ui.MDMAgent) FlyveAdminReceiver(org.flyve.mdm.agent.receivers.FlyveAdminReceiver) ApplicationData(org.flyve.mdm.agent.data.database.ApplicationData) Routes(org.flyve.mdm.agent.core.Routes) PoliciesData(org.flyve.mdm.agent.data.database.PoliciesData) InventoryTask(org.flyve.inventory.InventoryTask) JSONObject(org.json.JSONObject) FastLocationProvider(org.flyve.mdm.agent.utils.FastLocationProvider) AndroidPolicies(org.flyve.policies.manager.AndroidPolicies) FileData(org.flyve.mdm.agent.data.database.FileData) Inventory(org.flyve.mdm.agent.utils.Inventory) Location(android.location.Location)

Example 9 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class EnrollmentModel method enroll.

@Override
public void enroll(final Activity activity, final List<UserData.EmailsData> arrEmails, final String firstName, final String lastName, final String phone, final String phone2, final String mobilePhone, final String inventory, final String photo, final String language, final String administrativeNumber, final String notificationToken, Context context) {
    StringBuilder errMsg = new StringBuilder(activity.getResources().getString(R.string.validate_error));
    boolean allow = true;
    Helpers.hideKeyboard(activity);
    if (arrEmails.isEmpty() || arrEmails.get(0).getEmail().equals("")) {
        errMsg.append(activity.getResources().getString(R.string.validate_email_at_least_one));
        allow = false;
    }
    if (firstName.trim().equals("")) {
        errMsg.append(activity.getResources().getString(R.string.validate_first_name));
        allow = false;
    }
    if (lastName.trim().equals("")) {
        errMsg.append(activity.getResources().getString(R.string.validate_last_name));
        allow = false;
    }
    if (notificationToken.equals("")) {
        errMsg.append(activity.getResources().getString(R.string.validate_fcm_token));
        allow = false;
    }
    if (inventory.contains("fail")) {
        errMsg.append(activity.getResources().getString(R.string.validate_inventory));
        allow = false;
    }
    // inventory running
    if (inventory.equals("")) {
        errMsg.append(activity.getResources().getString(R.string.inventory_not_exists));
        allow = false;
    }
    if (!allow) {
        presenter.showSnackError(CommonErrorType.ENROLLMENT_FIELD_VALIDATION, activity.getResources().getString(R.string.validate_check_details));
        presenter.showDetailError(CommonErrorType.ENROLLMENT_FIELD_VALIDATION, errMsg.toString());
        return;
    }
    try {
        MqttData cache = new MqttData(activity);
        String invitationToken = cache.getInvitationToken();
        JSONObject payload = new JSONObject();
        String mInventory = Helpers.base64encode(inventory.trim());
        // get first email
        payload.put("_email", arrEmails.get(0).getEmail());
        payload.put("_invitation_token", invitationToken);
        payload.put("_serial", Helpers.getDeviceSerial());
        payload.put("_uuid", new Hardware(activity).getUUID());
        payload.put("csr", "");
        payload.put("firstname", firstName);
        payload.put("lastname", lastName);
        payload.put("phone", phone);
        payload.put("version", BuildConfig.VERSION_NAME);
        payload.put("type", "android");
        payload.put("has_system_permission", Helpers.isSystemApp(activity));
        payload.put("inventory", mInventory);
        // could be mqtt or fcm
        payload.put("notification_type", "fcm");
        // this is the token get from fcm register
        payload.put("notification_token", notificationToken);
        FlyveLog.d(mInventory);
        EnrollmentHelper enroll = new EnrollmentHelper(activity);
        enroll.enrollment(payload, new EnrollmentHelper.EnrollCallBack() {

            @Override
            public void onSuccess(String data) {
                // -------------------------------
                // Store user information
                // -------------------------------
                UserData userData = new UserData(activity);
                userData.setFirstName(firstName);
                userData.setLastName(lastName);
                userData.setEmails(arrEmails);
                userData.setPicture(photo);
                userData.setLanguage(language);
                userData.setAdministrativeNumber(administrativeNumber);
                // -------------------------------
                // Remove Deeplink information
                // -------------------------------
                MqttData cache = new MqttData(activity);
                cache.setInvitationToken("");
                presenter.enrollSuccess();
            }

            @Override
            public void onError(int type, String error) {
                presenter.showSnackError(type, error);
            }
        });
    } catch (Exception ex) {
        presenter.showSnackError(CommonErrorType.ENROLLMENT_REQUEST_EXCEPTION, ex.getMessage());
    }
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) JSONObject(org.json.JSONObject) UserData(org.flyve.mdm.agent.data.localstorage.UserData) Hardware(org.flyve.inventory.categories.Hardware)

Example 10 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class DeeplinkModel method saveMQTTConfig.

@Override
public void saveMQTTConfig(Context context, String url, String userToken, String invitationToken) {
    MqttData cache = new MqttData(context);
    cache.setUrl(url);
    cache.setUserToken(userToken);
    cache.setInvitationToken(invitationToken);
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData)

Aggregations

MqttData (org.flyve.mdm.agent.data.database.MqttData)14 JSONObject (org.json.JSONObject)5 View (android.view.View)4 Routes (org.flyve.mdm.agent.core.Routes)4 Intent (android.content.Intent)3 InventoryTask (org.flyve.inventory.InventoryTask)3 FloatingActionButton (android.support.design.widget.FloatingActionButton)2 TextView (android.widget.TextView)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 HttpURLConnection (java.net.HttpURLConnection)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 Hardware (org.flyve.inventory.categories.Hardware)2 UserData (org.flyve.mdm.agent.data.localstorage.UserData)2 Context (android.content.Context)1 DialogInterface (android.content.DialogInterface)1 Location (android.location.Location)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1