Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 39 | Rev 44 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

package com.cesams.twogetskills.service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.cesams.twogetskills.Configuration;
import com.cesams.twogetskills.Constants;
import com.cesams.twogetskills.dao.AppDatabase;
import com.cesams.twogetskills.dao.DatabaseHelper;
import com.cesams.twogetskills.dao.SyncDao;
import com.cesams.twogetskills.entity.Sync;
import com.cesams.twogetskills.library.Functions;
import com.cesams.twogetskills.library.Http;
import com.cesams.twogetskills.library.UniqueID;
import com.cesams.twogetskills.preference.Preference;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

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

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class FcmMessagingService extends FirebaseMessagingService {


    private static final String TAG = "C2GS - FcmMessageServ";
   // private AppDatabase mAppDatabase;
    //boolean isSyncDevice = false;
    //boolean isSyncToken = false;
    Preference preference;



    @Override
    public void onCreate() {

        preference = Preference.getInstance(getApplicationContext());
        preference.load();
        //mAppDatabase = DatabaseHelper.getInstance(getApplicationContext()).getAppDatabase();
        super.onCreate();
        Log.e("BUG Token",  "FcmMessagingService - onCreate");
    }

    public void onMessageReceived(RemoteMessage remoteMessage) {


        Log.d("FcmMessagingService", "onMessageReceived");

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if(remoteMessage.getData().containsKey("command")) {
                String command = remoteMessage.getData().get("command").trim();

                Intent intent = new Intent(Constants.BROADCAST_TYPE_COMMAND);
                intent.putExtra("command", command);
                getApplicationContext().sendBroadcast(intent);
            }
        }
        if (remoteMessage.getNotification() != null) {
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();


            String command = "", url="";
            int new_capsules = 0;
            if (remoteMessage.getData().size() > 0) {
                Log.d(TAG, "Message data payload: " + remoteMessage.getData());

                if(remoteMessage.getData().containsKey("command")) {
                    command = remoteMessage.getData().get("command").trim();
                }

                if(remoteMessage.getData().containsKey("new_capsules")) {
                   new_capsules = Functions.Numero2Int(remoteMessage.getData().get("new_capsules"));
                }

                if(remoteMessage.getData().containsKey("url")) {
                    url = remoteMessage.getData().get("url");
                }
            }

            Log.d(TAG, "title = " + title);
            Log.d(TAG, "body = " + body);
            Log.d(TAG, "command = " + command);
            Log.d(TAG, "new_capsules = " + new_capsules);

            Intent intent = new Intent(Constants.BROADCAST_TYPE_NOTIFICATION);
            intent.putExtra("title", title);
            intent.putExtra("body", body);
            intent.putExtra("command", command);
            intent.putExtra("new_capsules", new_capsules);
            intent.putExtra("url",url);


            if(command.equals("content-refresh")){

                preference.setRefreshContentRequired(true);
            }

            getApplicationContext().sendBroadcast(intent);
        }
    }




    public void onNewToken(String fcm_token)
    {
        Log.e("BUG Token", "Token 2 :  " + fcm_token);
        /*
        Log.e("FcmMessagingService", "onNewToken token = " + fcm_token);

        String uuid = UniqueID.id(getApplicationContext());

        preference.setDeviceToken (fcm_token);
        preference.setDeviceUuid(uuid);
        preference.save();

        Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_DEVICE, uuid);
        mAppDatabase.getSyncDao().insert(sync);

        sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, fcm_token);
        mAppDatabase.getSyncDao().insert(sync);

        syncTokenFMCTo2getSkillServer();
        */

        Intent intent = new Intent(Constants.BROADCAST_TYPE_TOKEN);
        intent.putExtra("token", Functions.trimNull(fcm_token));
        getApplicationContext().sendBroadcast(intent);


    }

    /*
    private void syncTokenFMCTo2getSkillServer(){


        SyncDao syncDao = mAppDatabase.getSyncDao();
        List<Sync> records = syncDao.selectBatch();

        if(records.size() > 0) {
            syncToServer(records);
        }
}

    public void syncToServer(List<Sync> records) {

        for (Sync record : records) {
            if (record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {


                try {
                    Http http = new Http(this.getCacheDir());
                    OkHttpClient client = http.getHttpClient(false);

                    RequestBody formBody = new FormBody.Builder()
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID, String.valueOf(Configuration.APPLICATION_ID))
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE + " " + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName())
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
                            .build();

                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
                    Request request = new Request.Builder()
                            .url(Configuration.URL_DEVICE)
                            .post(formBody)
                            .build();

                    Call call = client.newCall(request);
                    call.enqueue(new okhttp3.Callback() {
                        public void onResponse(Call call, Response response)
                                throws IOException {
                           // isSyncDevice = false;
                            Log.d(TAG, "Response Device :  " + response.body().toString());

                            processResponseSyncToServer(response.body().string(), "device");
                        }

                        public void onFailure(Call call, IOException e) {
                            isSyncDevice = false;
                            Log.d(TAG, "Error :  " + e.getMessage());
                        }
                    });
                } catch (Exception e) {
                }
            }
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncDevice){

                //Sucede que intenta sincronizar primero el Token antes que el device.
                Log.e("Esta intentando","sync el token antes que device");
            }

            if (record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken && isSyncDevice) {
                isSyncToken = true;
                Log.d(TAG, "FCM");
                Log.e("Token a Sync", "" + record.getData());

                try {
                    Http http = new Http(this.getCacheDir());
                    OkHttpClient client = http.getHttpClient(false);

                    RequestBody formBody = new FormBody.Builder()
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID, preference.getDeviceUuid())
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
                            .build();

                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
                    Request request = new Request.Builder()
                            .url(Configuration.URL_FCM)
                            .post(formBody)
                            .build();

                    Call call = client.newCall(request);
                    call.enqueue(new okhttp3.Callback() {
                        public void onResponse(Call call, Response response)
                                throws IOException {
                            isSyncToken = false;
                            Log.e("Send FCM Token", "Procesando respuesta..");
                            processResponseSyncToServer(response.body().string(), "fcmtoken");
                        }

                        public void onFailure(Call call, IOException e) {
                            Log.d(TAG, "Error :  " + e.getMessage());
                            isSyncToken = false;
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        }
    }

    private void processResponseSyncToServer(String dataString, String origen)
    {
        boolean success = false;
        long sync_id = 0;

        Log.d(TAG, "processResponseServer = " + dataString);
        try {
            JSONObject objJSON = new JSONObject(dataString);
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
            if(success  && objJSON.has("data")) {
                JSONObject jsonObjectData = objJSON.getJSONObject("data");


                if(jsonObjectData.has("sync_id")) {
                    sync_id = jsonObjectData.getLong("sync_id");
                }

            }
            Log.d(TAG, "SyncID = " + sync_id);
            if(success && sync_id > 0) {
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
                mAppDatabase.getSyncDao().remove(sync_id);

                if(origen.equals("device"))
                {
                    Log.e("Sync","device exitoso, ahora sigo con TokenFCM");
                    isSyncDevice=true;
                    syncTokenFMCTo2getSkillServer();
                }
                if(origen.equals("fcmtoken")){
                    Log.e("Token", "termino de sync con exito");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }*/

}