Search in sources :

Example 1 with CloudTeam

use of com.cpjd.models.CloudTeam in project Roblu by wdavies973.

the class EventDepacker method run.

@Override
public void run() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
    StrictMode.setThreadPolicy(policy);
    Log.d("RBS", "Executing EventDepacker task...");
    ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    RSettings settings = io.loadSettings();
    RSyncSettings cloudSettings = io.loadCloudSettings();
    cloudSettings.setTeamSyncID(0);
    cloudSettings.getCheckoutSyncIDs().clear();
    cloudSettings.setPurgeRequested(false);
    io.saveCloudSettings(cloudSettings);
    Request r = new Request(settings.getServerIP());
    CloudTeamRequest ctr = new CloudTeamRequest(r, settings.getCode());
    if (teamNumber != -1) {
        ctr.setCode("");
        ctr.setTeamNumber(teamNumber);
    }
    CloudCheckoutRequest ccr = new CloudCheckoutRequest(r, settings.getCode());
    if (teamNumber != -1) {
        ccr.setTeamCode("");
        ccr.setTeamNumber(teamNumber);
    }
    if (teamNumber == -1 && (settings.getCode() == null || settings.getCode().equals(""))) {
        if (listener != null)
            listener.errorOccurred("No team code found in settings. Unable to import event.");
        return;
    }
    // Ping
    if (!r.ping()) {
        if (listener != null)
            listener.errorOccurred("It appears as though the server is offline. Try again later.");
        return;
    }
    if (!ctr.isActive()) {
        if (listener != null)
            listener.errorOccurred("No event found on Roblu Cloud.");
        return;
    }
    /*
         * Download everything
         *
         */
    CloudTeam team = ctr.getTeam(-1);
    REvent event;
    try {
        // Create a new event
        event = new REvent(io.getNewEventID(), team.getActiveEventName());
        event.setKey(team.getTbaKey());
        // should be -1 if cloud is not enabled
        event.setReadOnlyTeamNumber(teamNumber);
        event.setID(io.getNewEventID());
        event.setCloudEnabled(true);
        io.saveEvent(event);
        settings.setTeamNumber((int) team.getNumber());
        settings.setRui(mapper.readValue(team.getUi(), RUI.class));
        io.saveSettings(settings);
        RForm form = mapper.readValue(team.getForm(), RForm.class);
        io.saveForm(event.getID(), form);
    } catch (Exception e) {
        Log.d("RBS", "Failed to download event");
        listener.errorOccurred("Failed to import Roblu Cloud event.");
        return;
    }
    /*
         * Un-package checkouts into a teams array
         */
    ArrayList<RCheckout> checkouts = new ArrayList<>();
    try {
        CloudCheckout[] pulledCheckouts = ccr.pullCheckouts(null, true);
        for (CloudCheckout s : pulledCheckouts) checkouts.add(mapper.readValue(s.getContent(), RCheckout.class));
    } catch (IOException e) {
        Log.d("RBS", "Failed to de-package checkouts.");
        listener.errorOccurred("Failed to import Roblu Cloud event.");
        return;
    }
    /*
         * Start sorting the checkouts into teams
         */
    ArrayList<RTeam> teams = new ArrayList<>();
    for (RCheckout checkout : checkouts) {
        // First, check if the team has already been created
        boolean found = false;
        for (RTeam t : teams) {
            if (t.getID() == checkout.getTeam().getID()) {
                // Add the checkout information to the team
                t.getTabs().addAll(checkout.getTeam().getTabs());
                found = true;
                break;
            }
            t.setLastEdit(checkout.getTime());
        }
        // If not found, create a new team
        if (!found) {
            RTeam newTeam = new RTeam(checkout.getTeam().getName(), checkout.getTeam().getNumber(), checkout.getTeam().getID());
            newTeam.setTabs(new ArrayList<RTab>());
            newTeam.getTabs().addAll(checkout.getTeam().getTabs());
            teams.add(newTeam);
        }
    }
    Log.d("RBS", "Created " + teams.size() + " teams");
    /*
         * Unpack images
         */
    for (RCheckout checkout : checkouts) {
        for (RTab tab : checkout.getTeam().getTabs()) {
            for (RMetric metric : tab.getMetrics()) {
                if (metric instanceof RGallery) {
                    for (int i = 0; ((RGallery) metric).getImages() != null && i < ((RGallery) metric).getImages().size(); i++) {
                        int picID = io.savePicture(event.getID(), ((RGallery) metric).getImages().get(i));
                        if (picID != -1) {
                            ((RGallery) metric).setPictureIDs(new ArrayList<Integer>());
                            ((RGallery) metric).getPictureIDs().add(picID);
                        }
                    }
                    if (((RGallery) metric).getImages() != null)
                        ((RGallery) metric).getImages().clear();
                }
            }
        }
    }
    /*
         * Save teams
         * -Teams don't need to be verified since the form has also been pulled from the server
         */
    for (RTeam t : teams) {
        Collections.sort(t.getTabs());
        io.saveTeam(event.getID(), t);
    }
    // Remove all the other synced events
    REvent[] events = io.loadEvents();
    for (int i = 0; events != null && i < events.length; i++) {
        events[i].setCloudEnabled(events[i].getID() == event.getID());
        io.saveEvent(events[i]);
    }
    /*
         * Add default sync ids
         */
    for (RCheckout checkout : checkouts) {
        cloudSettings.getCheckoutSyncIDs().put(checkout.getID(), 0L);
    }
    io.saveCloudSettings(cloudSettings);
    if (listener != null) {
        listener.success(event);
    }
}
Also used : RTab(com.cpjd.roblu.models.RTab) RGallery(com.cpjd.roblu.models.metrics.RGallery) ArrayList(java.util.ArrayList) RMetric(com.cpjd.roblu.models.metrics.RMetric) StrictMode(android.os.StrictMode) RForm(com.cpjd.roblu.models.RForm) CloudTeamRequest(com.cpjd.requests.CloudTeamRequest) REvent(com.cpjd.roblu.models.REvent) CloudTeam(com.cpjd.models.CloudTeam) RCheckout(com.cpjd.roblu.models.RCheckout) RSyncSettings(com.cpjd.roblu.models.RSyncSettings) CloudCheckout(com.cpjd.models.CloudCheckout) RSettings(com.cpjd.roblu.models.RSettings) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) CloudCheckoutRequest(com.cpjd.requests.CloudCheckoutRequest) RTeam(com.cpjd.roblu.models.RTeam) RUI(com.cpjd.roblu.models.RUI) Request(com.cpjd.http.Request) CloudTeamRequest(com.cpjd.requests.CloudTeamRequest) CloudCheckoutRequest(com.cpjd.requests.CloudCheckoutRequest) IOException(java.io.IOException) IOException(java.io.IOException)

Example 2 with CloudTeam

use of com.cpjd.models.CloudTeam in project Roblu by wdavies973.

the class Service method loop.

/**
 * This is the main background service looper, this should perform any necessary
 * Roblu Cloud sync operations
 */
public void loop() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
    StrictMode.setThreadPolicy(policy);
    if (!Utils.hasInternetConnection(getApplicationContext())) {
        Log.d("RBS", "No internet connection detected. Ending loop() early.");
        return;
    }
    /*
         * Create all the utilities we need for this loop
         */
    IO io = new IO(getApplicationContext());
    RSettings settings = io.loadSettings();
    RSyncSettings cloudSettings = io.loadCloudSettings();
    Request r = new Request(settings.getServerIP());
    ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    CloudTeamRequest teamRequest = new CloudTeamRequest(r, settings.getCode());
    CloudCheckoutRequest checkoutRequest = new CloudCheckoutRequest(r, settings.getCode());
    boolean result = r.ping();
    if (result)
        Utils.requestServerHealthRefresh(getApplicationContext(), "online");
    else
        Utils.requestServerHealthRefresh(getApplicationContext(), "offline");
    if (!result) {
        Log.d("RBS", "Roblu server is down. Unable to connect.");
        return;
    }
    // Load the active event
    REvent[] events = io.loadEvents();
    REvent activeEvent = null;
    for (int i = 0; events != null && events.length > 0 && i < events.length; i++) {
        if (events[i].isCloudEnabled()) {
            activeEvent = events[i];
            break;
        }
    }
    if (activeEvent != null && activeEvent.getReadOnlyTeamNumber() != -1) {
        teamRequest.setTeamNumber(activeEvent.getReadOnlyTeamNumber());
        teamRequest.setCode("");
        checkoutRequest.setTeamNumber(activeEvent.getReadOnlyTeamNumber());
        checkoutRequest.setTeamCode("");
    }
    /*
         * Check if a purge is requested
         */
    if (cloudSettings.isPurgeRequested() && checkoutRequest.purge()) {
        cloudSettings.setPurgeRequested(false);
        cloudSettings.setTeamSyncID(0);
        cloudSettings.getCheckoutSyncIDs().clear();
        Log.d("RBS", "Event successfully purged from Roblu Cloud.");
        io.saveCloudSettings(cloudSettings);
        Notify.notifyNoAction(getApplicationContext(), "Event purged", "Active event successfully removed from Roblu Cloud.");
        return;
    }
    if (activeEvent == null)
        return;
    // Create the sync helper
    SyncHelper syncHelper = new SyncHelper(getApplicationContext(), activeEvent, SyncHelper.MODES.NETWORK);
    RForm form = io.loadForm(activeEvent.getID());
    /*
         * Check to see if the form was modified and needs to be uploaded
         */
    if (form.isUploadRequired()) {
        try {
            teamRequest.pushForm(mapper.writeValueAsString(form));
            form.setUploadRequired(false);
            io.saveForm(activeEvent.getID(), form);
            Notify.notifyNoAction(getApplicationContext(), "Form uploaded", "Successfully uploaded RForm to the server.");
            Log.d("RBS-Service", "Successfully uploaded RForm to the server.");
        } catch (Exception e) {
            Log.d("RBS-Service", "Failed to complete an upload required request for RForm.");
        }
    }
    /*
         * Check to see if the UI model should be uploaded
         */
    if (settings.getRui().isUploadRequired()) {
        try {
            teamRequest.pushUI(mapper.writeValueAsString(settings.getRui()));
            settings.getRui().setUploadRequired(false);
            io.saveSettings(settings);
            Log.d("RBS-Service", "Successfully uploaded RUI to the server.");
        } catch (Exception e) {
            Log.d("RBS-Service", "Failed to complete an upload required request for RUI.");
        }
    }
    /*
         * Check for cloud team updates
         */
    try {
        CloudTeam t = teamRequest.getTeam(cloudSettings.getTeamSyncID());
        if (t != null) {
            /*
                 * If a different master app overwrites the cloud app with a different event, run this check to prevent conflicts
                 * from happening.
                 */
            if (t.getActiveEventName() != null && !t.getActiveEventName().equals("") && activeEvent.getName() != null && !t.getActiveEventName().equals(activeEvent.getName())) {
                activeEvent.setCloudEnabled(false);
                cloudSettings.getCheckoutSyncIDs().clear();
                io.saveCloudSettings(cloudSettings);
                io.saveEvent(activeEvent);
                return;
            }
            // Merge RForm
            form = mapper.readValue(t.getForm(), RForm.class);
            form.setUploadRequired(false);
            io.saveForm(activeEvent.getID(), form);
            // Merge RUI
            RUI rui = mapper.readValue(t.getUi(), RUI.class);
            rui.setUploadRequired(false);
            settings.setRui(rui);
            // make sure to refresh this
            settings = io.loadSettings();
            io.saveSettings(settings);
            // Update the sync ID
            cloudSettings.setTeamSyncID((int) t.getSyncID());
            io.saveCloudSettings(cloudSettings);
            Log.d("RBS-Service", "Successfully pulled team data from the server.");
        }
    } catch (Exception e) {
        Log.d("RBS-Service", "Failed to pull team data from the server: " + e.getMessage());
    }
    /*
         *
         * Alright, into the belly of the beast.
         * This code will check for completed checkouts on the server and merge them with the local repository.
         * Shall we begin?
         *
         */
    try {
        CloudCheckout[] checkouts = checkoutRequest.pullCompletedCheckouts(syncHelper.packSyncIDs(cloudSettings.getCheckoutSyncIDs()));
        syncHelper.unpackCheckouts(checkouts, cloudSettings);
        io.saveCloudSettings(cloudSettings);
    } catch (Exception e) {
        Log.d("RBS-Service", "An error occurred while fetching completed checkouts. " + e.getMessage());
    }
    /*
         * Next, uploading everything from /pending/
         */
    try {
        Log.d("RBS-Service", "Checking for any checkouts to upload...");
        ArrayList<RCheckout> checkouts = new ArrayList<>(Arrays.asList(io.loadPendingCheckouts()));
        boolean wasSuccess = checkoutRequest.pushCheckouts(syncHelper.packCheckouts(checkouts));
        if (wasSuccess) {
            for (RCheckout checkout : checkouts) {
                io.deletePendingCheckout(checkout.getID());
            }
            Notify.notifyNoAction(getApplicationContext(), "Uploaded new checkouts", "Uploaded " + checkouts.size() + " new checkout(s).");
        }
        Log.d("RBS-Service", "Uploaded " + checkouts.size() + " checkouts.");
    } catch (Exception e) {
        Log.d("RBS-Service", "An error occurred while attempting to push /pending/ checkouts: " + e.getMessage());
    }
    io.saveCloudSettings(cloudSettings);
    Log.d("RBS-Service", "Sleeping Roblu background service for 10 seconds...");
}
Also used : IO(com.cpjd.roblu.io.IO) RUI(com.cpjd.roblu.models.RUI) Request(com.cpjd.http.Request) CloudTeamRequest(com.cpjd.requests.CloudTeamRequest) CloudCheckoutRequest(com.cpjd.requests.CloudCheckoutRequest) ArrayList(java.util.ArrayList) StrictMode(android.os.StrictMode) RForm(com.cpjd.roblu.models.RForm) CloudTeamRequest(com.cpjd.requests.CloudTeamRequest) REvent(com.cpjd.roblu.models.REvent) SyncHelper(com.cpjd.roblu.sync.SyncHelper) CloudTeam(com.cpjd.models.CloudTeam) RCheckout(com.cpjd.roblu.models.RCheckout) RSyncSettings(com.cpjd.roblu.models.RSyncSettings) CloudCheckout(com.cpjd.models.CloudCheckout) RSettings(com.cpjd.roblu.models.RSettings) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) CloudCheckoutRequest(com.cpjd.requests.CloudCheckoutRequest)

Aggregations

StrictMode (android.os.StrictMode)2 Request (com.cpjd.http.Request)2 CloudCheckout (com.cpjd.models.CloudCheckout)2 CloudTeam (com.cpjd.models.CloudTeam)2 CloudCheckoutRequest (com.cpjd.requests.CloudCheckoutRequest)2 CloudTeamRequest (com.cpjd.requests.CloudTeamRequest)2 RCheckout (com.cpjd.roblu.models.RCheckout)2 REvent (com.cpjd.roblu.models.REvent)2 RForm (com.cpjd.roblu.models.RForm)2 RSettings (com.cpjd.roblu.models.RSettings)2 RSyncSettings (com.cpjd.roblu.models.RSyncSettings)2 RUI (com.cpjd.roblu.models.RUI)2 ArrayList (java.util.ArrayList)2 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)2 IO (com.cpjd.roblu.io.IO)1 RTab (com.cpjd.roblu.models.RTab)1 RTeam (com.cpjd.roblu.models.RTeam)1 RGallery (com.cpjd.roblu.models.metrics.RGallery)1 RMetric (com.cpjd.roblu.models.metrics.RMetric)1 SyncHelper (com.cpjd.roblu.sync.SyncHelper)1