use of com.cpjd.requests.CloudCheckoutRequest 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);
}
}
use of com.cpjd.requests.CloudCheckoutRequest 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...");
}
use of com.cpjd.requests.CloudCheckoutRequest in project Roblu by wdavies973.
the class InitPacker method doInBackground.
@Override
protected Boolean doInBackground(Void... params) {
/*
* Make sure this thread has network permissions
*/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
Log.d("RBS", "Executing InitPacker task...");
IO io = ioWeakReference.get();
RSettings settings = io.loadSettings();
RSyncSettings cloudSettings = io.loadCloudSettings();
cloudSettings.setPurgeRequested(false);
io.saveCloudSettings(cloudSettings);
io.saveSettings(settings);
Request r = new Request(settings.getServerIP());
if (!r.ping()) {
listener.statusUpdate("It appears as though the server is offline. Try again later.");
return false;
}
/*
* Load all teams from the event, also make sure that that the teams are verified
*/
REvent event = io.loadEvent(eventID);
event.setReadOnlyTeamNumber(-1);
RForm form = io.loadForm(eventID);
RTeam[] teams = io.loadTeams(eventID);
if (event == null || form == null || teams == null || teams.length == 0) {
Log.d("RBS", "Not enough data to warrant an event upload.");
listener.statusUpdate("This event doesn't contain any teams or sufficient data to upload to the server. Create some teams!");
return false;
}
// Generate the checkouts
SyncHelper syncHelper = new SyncHelper(io, event, SyncHelper.MODES.NETWORK);
ArrayList<RCheckout> checkouts = syncHelper.generateCheckoutsFromEvent(teams, -1);
// Remove field data
try {
for (RCheckout checkout : checkouts) {
for (RTab tab : checkout.getTeam().getTabs()) {
for (RMetric metric : tab.getMetrics()) {
if (metric instanceof RFieldData) {
((RFieldData) metric).setData(null);
}
}
}
}
} catch (Exception e) {
// Doesn't matter
}
/*
* Convert into JSON and upload
*/
ObjectMapper mapper = new ObjectMapper();
try {
// serialization all the checkouts and pack them in an json array, this will be processed by the server
String serializedCheckouts = syncHelper.packCheckouts(checkouts);
String serializedForm = mapper.writeValueAsString(form);
String serializedUI = mapper.writeValueAsString(settings.getRui());
String eventName = event.getName();
if (eventName == null)
eventName = "";
if (event.getKey() == null)
event.setKey("");
CloudCheckoutRequest ccr = new CloudCheckoutRequest(r, settings.getCode());
Log.d("RBS", "Initializing init packer upload...");
boolean success = ccr.init(settings.getTeamNumber(), eventName, serializedForm, serializedUI, serializedCheckouts, event.getKey());
/*
* Disable all other events with cloud syncing enabled
*/
if (success) {
REvent[] events = io.loadEvents();
for (int i = 0; events != null && i < events.length; i++) {
events[i].setCloudEnabled(events[i].getID() == eventID);
io.saveEvent(events[i]);
}
cloudSettings.getCheckoutSyncIDs().clear();
/*
* Add default sync ids
*/
for (RCheckout checkout : checkouts) {
cloudSettings.getCheckoutSyncIDs().put(checkout.getID(), 0L);
}
io.saveCloudSettings(cloudSettings);
io.saveSettings(settings);
} else
listener.statusUpdate("An error occurred. Event was not uploaded.");
return success;
} catch (Exception e) {
Log.d("RBS", "An error occurred in InitPacker: " + e.getMessage());
listener.statusUpdate("An error occurred. Event was not uploaded.");
return false;
} finally {
/*
* Set all images to null to return memory to normal
*/
for (RCheckout checkout : checkouts) {
for (RTab tab : checkout.getTeam().getTabs()) {
for (RMetric metric : tab.getMetrics()) {
if (metric instanceof RGallery) {
((RGallery) metric).setImages(null);
}
}
}
}
}
}
Aggregations