eu.codeplumbers.cosi.wizards.firstrun.ConnectFragment.java Source code

Java tutorial

Introduction

Here is the source code for eu.codeplumbers.cosi.wizards.firstrun.ConnectFragment.java

Source

/*
 *     Cos android client for Cozy Cloud
 *
 *     Copyright (C)  2016 Hamza Abdelkebir
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package eu.codeplumbers.cosi.wizards.firstrun;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tech.freak.wizardpager.ui.PageFragmentCallbacks;

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

import eu.codeplumbers.cosi.R;
import eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask;
import eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask;
import eu.codeplumbers.cosi.db.models.Device;
import eu.codeplumbers.cosi.utils.Constants;

/**
 * Created by thor on 25/01/15.
 */
public class ConnectFragment extends Fragment {
    private static final String ARG_KEY = "connectKey";

    private PageFragmentCallbacks mCallbacks;
    private String mKey;
    private ConnectPage mPage;
    private EditText mUrl;
    private EditText mUsername;
    private EditText mPassword;
    private EditText mDeviceName;
    private Button btnRegisterDevice;
    private boolean designOK;

    public static ConnectFragment create(String key) {
        Bundle args = new Bundle();
        args.putString(ARG_KEY, key);

        ConnectFragment fragment = new ConnectFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public ConnectFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        mKey = args.getString(ARG_KEY);
        mPage = (ConnectPage) mCallbacks.onGetPage(mKey);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_connect, container, false);
        ((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle());

        designOK = false;

        mUrl = (EditText) rootView.findViewById(R.id.cozy_url);
        mUsername = (EditText) rootView.findViewById(R.id.cozy_username);
        mPassword = (EditText) rootView.findViewById(R.id.cozy_password);
        mDeviceName = (EditText) rootView.findViewById(R.id.cozy_device_name);

        String deviceName = android.os.Build.MODEL;
        String deviceMan = android.os.Build.MANUFACTURER;

        mDeviceName.setText("Android-" + deviceMan + "-" + deviceName + "-Cosi");
        mDeviceName.setEnabled(false);

        btnRegisterDevice = (Button) rootView.findViewById(R.id.btnRegisterDevice);

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (!(activity instanceof PageFragmentCallbacks)) {
            throw new ClassCastException("Activity must implement PageFragmentCallbacks");
        }

        mCallbacks = (PageFragmentCallbacks) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mUrl.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mPage.getData().putString(ConnectPage.URL_DATA_KEY,
                        (editable != null) ? editable.toString() : null);
                mPage.notifyDataChanged();
            }
        });

        mUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mPage.getData().putString(ConnectPage.USERNAME_DATA_KEY,
                        (editable != null) ? editable.toString() : null);
                mPage.notifyDataChanged();
            }
        });

        mPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mPage.getData().putString(ConnectPage.PASSWORD_DATA_KEY,
                        (editable != null) ? editable.toString() : null);
                mPage.notifyDataChanged();
            }
        });

        mDeviceName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mPage.getData().putString(ConnectPage.DEVICE_NAME_DATA_KEY,
                        (editable != null) ? editable.toString() : null);
                mPage.notifyDataChanged();
            }
        });

        btnRegisterDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean mUrlOk = true;
                boolean mPasswordOk = true;

                if (mUrl.getText().toString().isEmpty()) {
                    mUrl.setError("Cozy URL can not be empty!");
                    mUrlOk = false;
                }
                if (mPassword.getText().toString().isEmpty()) {
                    mPassword.setError("Your password can not be empty!");
                    mPasswordOk = false;
                }

                if (mPasswordOk && mPasswordOk) {
                    if (!mUrl.getText().toString().startsWith(Constants.HTTPS)) {
                        mUrl.setText(Constants.HTTPS + mUrl.getText().toString());
                    }

                    btnRegisterDevice.setEnabled(false);
                    registerDevice();
                }
            }
        });
    }

    /**
     * Do register device
     */
    private void registerDevice() {
        String url = mUrl.getText().toString();
        String password = mPassword.getText().toString();
        String deviceName = mDeviceName.getText().toString();

        final JSONObject deviceJson = new JSONObject();
        final JSONObject permissionJson = new JSONObject();
        final JSONObject desc = new JSONObject();
        try {
            desc.put("description", "sync all my cozy data");
            permissionJson.put("All", desc);
            deviceJson.put("login", deviceName);
            deviceJson.put("permissions", permissionJson);

            new RegisterDeviceTask(url, password, deviceJson.toString(), this).execute();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void onRegisterSuccess(Device device) {
        mPage.getData().putBoolean(ConnectPage.CONNECTION_OK_DATA_KEY, true);

        mPage.getData().putString(ConnectPage.URL_DATA_KEY, mUrl.getText().toString());

        mPage.getData().putString(ConnectPage.DEVICE_NAME_DATA_KEY, mDeviceName.getText().toString());

        mPage.notifyDataChanged();
        btnRegisterDevice.setEnabled(false);

        new CheckDesignDocumentsTask(this).execute(
                new String[] { "Sms", "Note", "File", "Folder", "Call", "Place", "LoyaltyCard", "Expense" });
    }

    public void onRegisterFailure(String errorMessage) {
        mPage.getData().putBoolean(ConnectPage.CONNECTION_OK_DATA_KEY, false);
        mPage.getData().putString(ConnectPage.URL_DATA_KEY, "");

        mPage.getData().putString(ConnectPage.DEVICE_NAME_DATA_KEY, mDeviceName.getText().toString());

        mPage.notifyDataChanged();
        btnRegisterDevice.setEnabled(true);

        if (errorMessage.equalsIgnoreCase(Constants.API_ERROR_NAME_EXISTS)) {
            showGiveDevicePasswordDialog();
        } else {
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
        }
    }

    private void showGiveDevicePasswordDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setTitle("Register your device");
        alertDialog.setMessage("Your device is already registered\n Please type your device token");

        final EditText input = new EditText(getActivity());

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        input.setLayoutParams(lp);
        alertDialog.setView(input);

        alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String password = input.getText().toString();

                if (!password.isEmpty()) {
                    final JSONObject permissionJson = new JSONObject();
                    final JSONObject desc = new JSONObject();
                    try {
                        Device device = new Device();
                        device.setUrl(mUrl.getText().toString());
                        device.setLogin(mDeviceName.getText().toString());
                        device.setPassword(password);

                        desc.put("description", "sync all my cozy data");
                        permissionJson.put("All", desc);

                        device.setPermissions(permissionJson.toString());
                        device.setFirstSyncDone(false);
                        device.setSyncCalls(false);
                        device.setSyncContacts(false);
                        device.setSyncFiles(false);
                        device.setSyncNotes(false);

                        device.save();

                        onRegisterSuccess(device);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    input.setError("Your device token can not be empty!");
                }
            }
        });
        alertDialog.show();
    }

    public void onDesignsOK() {
        designOK = true;

        mPage.getData().putBoolean(ConnectPage.DESIGN_OK_DATA_KEY, true);

        mPage.notifyDataChanged();
        btnRegisterDevice.setEnabled(false);
    }

    public void onDesignFailure(String errorMessage) {
        designOK = false;
        mPage.getData().putBoolean(ConnectPage.DESIGN_OK_DATA_KEY, false);
        mPage.notifyDataChanged();
        btnRegisterDevice.setEnabled(false);
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
    }
}