private static boolean resetStateFromJSON( JSONObject state, String targetListName, IItemStateApplier stateApplier) { if (!state.has(targetListName)) { return true; } SoomlaUtils.LogDebug(TAG, "Resetting state for " + targetListName); try { JSONObject itemsJSON = state.getJSONObject(targetListName); Iterator keysIter = itemsJSON.keys(); while (keysIter.hasNext()) { String itemId = (String) keysIter.next(); JSONObject itemValuesJSON = itemsJSON.getJSONObject(itemId); if (!stateApplier.applyState(itemId, itemValuesJSON)) { return false; } } } catch (JSONException e) { SoomlaUtils.LogError( TAG, "Unable to set state for " + targetListName + ". error: " + e.getLocalizedMessage()); return false; } return true; }
public static boolean resetLevelUpState(JSONObject state) { if (state == null) { return false; } SoomlaUtils.LogDebug(TAG, "Resetting state with: " + state.toString()); clearCurrentState(); SoomlaUtils.LogDebug(TAG, "Current state was cleared"); return resetGatesStateFromJSON(state) && resetWorldsStateFromJSON(state) && resetMissionsStateFromJSON(state) && resetScoresStateFromJSON(state); }
/** {@inheritDoc} */ @Override public void updateStory( String message, String name, String caption, String description, String link, String picture, final SocialCallbacks.SocialActionListener socialActionListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "updateStory"); RefProvider = getProvider(); RefSocialActionListener = socialActionListener; preformingAction = ACTION_PUBLISH_STORY; try { twitter.updateStatus(message + " " + link); } catch (Exception e) { failListener(ACTION_PUBLISH_STORY, e.getMessage()); } }
/** {@inheritDoc} */ @Override public void like(final Activity parentActivity, String pageId) { SoomlaUtils.LogDebug(TAG, "like"); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.twitter.com/" + pageId)); parentActivity.startActivity(browserIntent); }
/** * Called when a user's information has arrived from twitter * * @param user The user's details */ @Override public void gotUserDetail(User user) { SoomlaUtils.LogDebug(TAG, "getUserProfile/onComplete"); UserProfile userProfile = createUserProfile(user, true); RefUserProfileListener.success(userProfile); clearListener(ACTION_GET_USER_PROFILE); }
private static void clearListener(int requestedAction) { SoomlaUtils.LogDebug(TAG, "Clearing Listeners " + requestedAction); switch (requestedAction) { case ACTION_LOGIN: { RefLoginListener = null; break; } case ACTION_PUBLISH_STATUS: { RefSocialActionListener = null; break; } case ACTION_PUBLISH_STATUS_DIALOG: { RefSocialActionListener = null; break; } case ACTION_PUBLISH_STORY: { RefSocialActionListener = null; break; } case ACTION_PUBLISH_STORY_DIALOG: { RefSocialActionListener = null; break; } case ACTION_UPLOAD_IMAGE: { RefSocialActionListener = null; break; } case ACTION_GET_FEED: { RefFeedListener = null; break; } case ACTION_GET_CONTACTS: { RefContactsListener = null; break; } case ACTION_GET_USER_PROFILE: { RefUserProfileListener = null; break; } default: { SoomlaUtils.LogWarning(TAG, "action unknown clear listener:" + requestedAction); break; } } }
/** {@inheritDoc} */ @Override public void updateStatusDialog( String link, SocialCallbacks.SocialActionListener socialActionListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "updateStatusDialog"); socialActionListener.fail("Dialogs are not available in Twitter"); }
/** {@inheritDoc} */ @Override public boolean isLoggedIn() { SoomlaUtils.LogDebug(TAG, "isLoggedIn"); try { return isInitialized && (twitter.getOAuthAccessToken() != null); } catch (Exception e) { return false; } }
/** {@inheritDoc} */ @Override protected void onDestroy() { super.onDestroy(); if (!mFinishedVerifying) { cancelLogin(); } SoomlaUtils.LogDebug(TAG, "onDestroy"); }
private static void applyGatesStateToJSON(JSONObject modelJSON, JSONObject stateJSON) { JSONObject gatesStateJSON = new JSONObject(); HashMap<String, JSONObject> gates = getGates(modelJSON); for (JSONObject gateJSON : gates.values()) { JSONObject gateValuesJSON = new JSONObject(); try { String gateId = gateJSON.getString("itemId"); gateValuesJSON.put("open", GateStorage.isOpen(gateId)); gatesStateJSON.put(gateId, gateValuesJSON); } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to get Gates state: " + e.getLocalizedMessage()); } } try { stateJSON.put("gates", gatesStateJSON); } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to set Gates state: " + e.getLocalizedMessage()); } }
private static void applyMissionsStateToJSON(JSONObject modelJSON, JSONObject stateJSON) { JSONObject missionsStateJSON = new JSONObject(); HashMap<String, JSONObject> missions = getMissions(modelJSON); for (JSONObject missionJSON : missions.values()) { JSONObject missionValuesJSON = new JSONObject(); try { String missionId = missionJSON.getString("itemId"); missionValuesJSON.put("timesCompleted", MissionStorage.getTimesCompleted(missionId)); missionsStateJSON.put(missionId, missionValuesJSON); } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to get Missions state: " + e.getLocalizedMessage()); } } try { stateJSON.put("missions", missionsStateJSON); } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to set Missions state: " + e.getLocalizedMessage()); } }
private static void applyWorldsStateToJSON(JSONObject modelJSON, JSONObject stateJSON) { JSONObject worldsStateJSON = new JSONObject(); JSONObject levelsStateJSON = new JSONObject(); HashMap<String, JSONObject> worlds = getWorlds(modelJSON); for (JSONObject worldJSON : worlds.values()) { JSONObject worldValuesJSON = new JSONObject(); try { String worldId = worldJSON.getString("itemId"); worldValuesJSON.put("completed", WorldStorage.isCompleted(worldId)); worldValuesJSON.put("assignedReward", WorldStorage.getAssignedReward(worldId)); worldValuesJSON.put( "lastCompletedInnerWorld", WorldStorage.getLastCompletedInnerWorld(worldId)); worldsStateJSON.put(worldId, worldValuesJSON); if (worldJSON.getString("className").equals("Level")) { JSONObject levelValuesJSON = new JSONObject(); levelValuesJSON.put("started", LevelStorage.getTimesStarted(worldId)); levelValuesJSON.put("played", LevelStorage.getTimesPlayed(worldId)); levelValuesJSON.put("timesCompleted", LevelStorage.getTimesCompleted(worldId)); levelValuesJSON.put("last", LevelStorage.getLastDurationMillis(worldId)); levelValuesJSON.put("slowest", LevelStorage.getSlowestDurationMillis(worldId)); levelValuesJSON.put("fastest", LevelStorage.getFastestDurationMillis(worldId)); levelsStateJSON.put(worldId, levelValuesJSON); } } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to get Worlds state: " + e.getLocalizedMessage()); } } try { stateJSON.put("worlds", worldsStateJSON); stateJSON.put("levels", levelsStateJSON); } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to set Worlds state: " + e.getLocalizedMessage()); } }
private static void applyScoresStateToJSON(JSONObject modelJSON, JSONObject stateJSON) { JSONObject scoresStateJSON = new JSONObject(); HashMap<String, JSONObject> scores = getScores(modelJSON); for (JSONObject scoreJSON : scores.values()) { JSONObject scoreValuesJSON = new JSONObject(); try { String scoreId = scoreJSON.getString("itemId"); scoreValuesJSON.put("latest", ScoreStorage.getLatestScore(scoreId)); scoreValuesJSON.put("record", ScoreStorage.getRecordScore(scoreId)); scoresStateJSON.put(scoreId, scoreValuesJSON); } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to get Scores state: " + e.getLocalizedMessage()); } } try { stateJSON.put("scores", scoresStateJSON); } catch (JSONException e) { SoomlaUtils.LogDebug(TAG, "Unable to set Scores state: " + e.getLocalizedMessage()); } }
/** {@inheritDoc} */ @Override public void logout(final AuthCallbacks.LogoutListener logoutListener) { SoomlaUtils.LogDebug(TAG, "logout"); KeyValueStorage.deleteKeyValue(getTwitterStorageKey(TWITTER_OAUTH_TOKEN)); KeyValueStorage.deleteKeyValue(getTwitterStorageKey(TWITTER_OAUTH_SECRET)); mainRequestToken = null; twitter.setOAuthAccessToken(null); twitter.shutdown(); logoutListener.success(); }
/** * Called when the user's friends list has arrived * * @param users The user's friends (by Twitter definition) */ @Override public void gotFriendsList(PagableResponseList<User> users) { SoomlaUtils.LogDebug(TAG, "getContacts/onComplete " + users.size()); List<UserProfile> userProfiles = new ArrayList<UserProfile>(); for (User profile : users) { userProfiles.add(createUserProfile(profile)); } if (users.hasNext()) { lastContactCursor = users.getNextCursor(); } RefContactsListener.success(userProfiles, users.hasNext()); clearListener(ACTION_GET_CONTACTS); }
public static JSONObject getLevelUpModel() { JSONObject modelJSON = null; String model = KeyValueStorage.getValue(DB_KEY_PREFIX + "model"); SoomlaUtils.LogDebug(TAG, "model: " + model); if (model == null) { return null; } try { modelJSON = new JSONObject(model); } catch (JSONException e) { SoomlaUtils.LogError(TAG, "Unable to parse LevelUp model into JSON"); } return modelJSON; }
/** {@inheritDoc} */ @Override public void getUserProfile(final AuthCallbacks.UserProfileListener userProfileListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "getUserProfile"); RefProvider = getProvider(); RefUserProfileListener = userProfileListener; preformingAction = ACTION_GET_USER_PROFILE; try { twitter.showUser(twitterScreenName); } catch (Exception e) { failListener(ACTION_GET_USER_PROFILE, e.getMessage()); } }
private void completeVerify(Uri uri) { SoomlaUtils.LogDebug(TAG, "Verification complete"); /** Handle OAuth Callback */ if (uri != null && uri.toString().startsWith(oauthCallbackURL)) { String verifier = uri.getQueryParameter(OAUTH_VERIFIER); if (!TextUtils.isEmpty(verifier)) { twitter.getOAuthAccessTokenAsync(mainRequestToken, verifier); } else { // Without a verifier an Access Token cannot be received // happens when a user clicks "cancel" cancelLogin(); } } webView.hide(); finish(); mFinishedVerifying = true; }
/** * Called when the user's timeline has arrived * * @param statuses The user's latest statuses */ @Override public void gotUserTimeline(ResponseList<Status> statuses) { SoomlaUtils.LogDebug(TAG, "getFeed/onComplete"); List<String> feeds = new ArrayList<String>(); for (Status post : statuses) { feeds.add(post.getText()); } boolean hasMore; if (feeds.size() >= PAGE_SIZE) { lastFeedCursor++; hasMore = true; } else { lastFeedCursor = 1; hasMore = false; } RefFeedListener.success(feeds, hasMore); clearListener(ACTION_GET_FEED); }
/** {@inheritDoc} */ @Override public void updateStatus( String status, final SocialCallbacks.SocialActionListener socialActionListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "updateStatus"); RefProvider = getProvider(); RefSocialActionListener = socialActionListener; preformingAction = ACTION_PUBLISH_STATUS; try { twitter.updateStatus(status); } catch (Exception e) { failListener(ACTION_PUBLISH_STATUS, e.getMessage()); } }
/** {@inheritDoc} */ @Override public void configure(Map<String, String> providerParams) { autoLogin = false; if (providerParams != null) { twitterConsumerKey = providerParams.get("consumerKey"); twitterConsumerSecret = providerParams.get("consumerSecret"); // extract autoLogin String autoLoginStr = providerParams.get("autoLogin"); autoLogin = autoLoginStr != null && Boolean.parseBoolean(autoLoginStr); } SoomlaUtils.LogDebug( TAG, String.format( "ConsumerKey:%s ConsumerSecret:%s", twitterConsumerKey, twitterConsumerSecret)); if (TextUtils.isEmpty(twitterConsumerKey) || TextUtils.isEmpty(twitterConsumerSecret)) { SoomlaUtils.LogError( TAG, "You must provide the Consumer Key and Secret in the SoomlaProfile initialization parameters"); isInitialized = false; } else { isInitialized = true; } oauthCallbackURL = "oauth://soomla_twitter" + twitterConsumerKey; ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(twitterConsumerKey); configurationBuilder.setOAuthConsumerSecret(twitterConsumerSecret); Configuration configuration = configurationBuilder.build(); twitter = new AsyncTwitterFactory(configuration).getInstance(); if (!actionsListenerAdded) { SoomlaUtils.LogWarning(TAG, "added action listener"); twitter.addListener(actionsListener); actionsListenerAdded = true; } }
/** {@inheritDoc} */ @Override public void getContacts( boolean fromStart, final SocialCallbacks.ContactsListener contactsListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "getContacts"); RefProvider = getProvider(); RefContactsListener = contactsListener; preformingAction = ACTION_GET_USER_PROFILE; try { twitter.getFriendsList(twitterScreenName, fromStart ? -1 : this.lastContactCursor); this.lastContactCursor = -1; } catch (Exception e) { failListener(ACTION_GET_USER_PROFILE, e.getMessage()); } }
/** {@inheritDoc} */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Edge case - start activity without twitter if (twitter == null) { finish(); return; } SoomlaUtils.LogDebug(TAG, "onCreate"); if (webView == null) { webView = new SoomlaTwitterWebView(this); webView.setWebViewClient( new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // See if the URL should be handled by the provider // only if it's a callback which was passed by the // provider if (url.startsWith(oauthCallbackURL)) { Uri uri = Uri.parse(url); completeVerify(uri); return true; } return false; } }); } // we should append additional param forcing login/pass request, otherwise app will be loaded // with previous account // decision based on https://dev.twitter.com/oauth/reference/get/oauth/authorize String url = getIntent().getStringExtra("url") + "&force_login=true"; webView.loadUrlOnUiThread(url); webView.show(this); }
/** * Called when OAuth authentication has been finalized and an Access Token and Access Token * Secret have been provided * * @param accessToken The access token to use to do REST calls */ @Override public void gotOAuthAccessToken(AccessToken accessToken) { SoomlaUtils.LogDebug(TAG, "login/onComplete"); twitter.setOAuthAccessToken(accessToken); // Keep in storage for logging in without web-authentication KeyValueStorage.setValue( getTwitterStorageKey(TWITTER_OAUTH_TOKEN), accessToken.getToken()); KeyValueStorage.setValue( getTwitterStorageKey(TWITTER_OAUTH_SECRET), accessToken.getTokenSecret()); // Keep screen name since Twitter4J does not have it when // logging in using authenticated tokens KeyValueStorage.setValue( getTwitterStorageKey(TWITTER_SCREEN_NAME), accessToken.getScreenName()); twitterScreenName = accessToken.getScreenName(); RefLoginListener.success(RefProvider); clearListener(ACTION_LOGIN); }
/** {@inheritDoc} */ @Override public void login( final Activity parentActivity, final AuthCallbacks.LoginListener loginListener) { if (!isInitialized) { SoomlaUtils.LogError( TAG, "Consumer key and secret were not defined, please provide them in initialization"); return; } SoomlaUtils.LogDebug(TAG, "login"); WeakRefParentActivity = new WeakReference<Activity>(parentActivity); RefProvider = getProvider(); RefLoginListener = loginListener; preformingAction = ACTION_LOGIN; mainRequestToken = null; twitter.setOAuthAccessToken(null); // Try logging in using store credentials String oauthToken = KeyValueStorage.getValue(getTwitterStorageKey(TWITTER_OAUTH_TOKEN)); String oauthTokenSecret = KeyValueStorage.getValue(getTwitterStorageKey(TWITTER_OAUTH_SECRET)); if (!TextUtils.isEmpty(oauthToken) && !TextUtils.isEmpty(oauthTokenSecret)) { twitter.setOAuthAccessToken(new AccessToken(oauthToken, oauthTokenSecret)); twitterScreenName = KeyValueStorage.getValue(getTwitterStorageKey(TWITTER_SCREEN_NAME)); loginListener.success(RefProvider); clearListener(ACTION_LOGIN); } else { // If no stored credentials start login process by requesting // a request token twitter.getOAuthRequestTokenAsync(oauthCallbackURL); } }
/** {@inheritDoc} */ @Override public void uploadImage( String message, String filePath, final SocialCallbacks.SocialActionListener socialActionListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "uploadImage"); RefProvider = getProvider(); RefSocialActionListener = socialActionListener; preformingAction = ACTION_UPLOAD_IMAGE; try { StatusUpdate updateImage = new StatusUpdate(message); updateImage.media(new File(filePath)); twitter.updateStatus(updateImage); } catch (Exception e) { failListener(ACTION_UPLOAD_IMAGE, e.getMessage()); } }
/** {@inheritDoc} */ @Override public void getFeed(Boolean fromStart, final SocialCallbacks.FeedListener feedListener) { if (!isInitialized) { return; } SoomlaUtils.LogDebug(TAG, "getFeed"); RefProvider = getProvider(); RefFeedListener = feedListener; preformingAction = ACTION_GET_FEED; try { if (fromStart) { this.lastFeedCursor = 1; } Paging paging = new Paging(this.lastFeedCursor, PAGE_SIZE); twitter.getUserTimeline(paging); } catch (Exception e) { failListener(ACTION_GET_FEED, e.getMessage()); } }
/** {@inheritDoc} */ @Override protected void onResume() { super.onResume(); SoomlaUtils.LogDebug(TAG, "onResume"); }
/** {@inheritDoc} */ @Override protected void onStop() { super.onStop(); SoomlaUtils.LogDebug(TAG, "onStop"); }
public static void initialize() { SoomlaUtils.LogDebug("SOOMLA Unity SoomlaEventHandler", "Initializing SoomlaEventHandler ..."); mLocalEventHandler = new SoomlaEventHandler(); }