Exemple #1
0
  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;
  }
  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;
        }
    }
  }
  @Subscribe
  public void onCustom(CustomEvent customEvent) {
    if (customEvent.Sender == this) {
      return;
    }
    try {
      JSONObject eventJSON = new JSONObject();

      eventJSON.put("name", customEvent.getName());

      JSONObject extraJSON = new JSONObject();
      if (customEvent.getExtra() != null) {
        for (String ex : customEvent.getExtra().keySet()) {
          extraJSON.put(ex, customEvent.getExtra().get(ex));
        }
      }

      eventJSON.put("extra", extraJSON);

      UnityPlayer.UnitySendMessage("CoreEvents", "onCustomEvent", eventJSON.toString());
    } catch (JSONException e) {
      SoomlaUtils.LogError(
          "SOOMLA SoomlaEventHandler",
          "This is BAD! couldn't create JSON for onMarketItemsRefreshFinished event.");
    }
  }
Exemple #4
0
  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);
  }
Exemple #7
0
  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;
  }
        /**
         * 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 failListener(int requestedAction, String message) {
    switch (requestedAction) {
      case ACTION_LOGIN:
        {
          RefLoginListener.fail("Login failed: " + message);
          break;
        }
      case ACTION_PUBLISH_STATUS:
        {
          RefSocialActionListener.fail("Publish status failed: " + message);
          break;
        }
      case ACTION_PUBLISH_STATUS_DIALOG:
        {
          RefSocialActionListener.fail("Publish status dialog failed: " + message);
          break;
        }
      case ACTION_PUBLISH_STORY:
        {
          RefSocialActionListener.fail("Publish story failed: " + message);
          break;
        }
      case ACTION_PUBLISH_STORY_DIALOG:
        {
          RefSocialActionListener.fail("Publish story dialog failed: " + message);
          break;
        }
      case ACTION_UPLOAD_IMAGE:
        {
          RefSocialActionListener.fail("Upload Image failed: " + message);
          break;
        }
      case ACTION_GET_FEED:
        {
          RefFeedListener.fail("Get feed failed: " + message);
          break;
        }
      case ACTION_GET_CONTACTS:
        {
          RefContactsListener.fail("Get contacts failed: " + message);
          break;
        }
      case ACTION_GET_USER_PROFILE:
        {
          RefUserProfileListener.fail("Get user profile failed: " + message);
          break;
        }
      default:
        {
          SoomlaUtils.LogWarning(TAG, "action unknown fail listener:" + requestedAction);
          break;
        }
    }

    clearListener(requestedAction);
  }
  /** {@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");
    }
  /** {@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;
    }
  }
Exemple #14
0
  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());
    }
  }
 @Subscribe
 public void onRewardTaken(RewardTakenEvent rewardTakenEvent) {
   try {
     JSONObject eventJSON = new JSONObject();
     eventJSON.put("rewardId", rewardTakenEvent.RewardId);
     UnityPlayer.UnitySendMessage("CoreEvents", "onRewardTaken", eventJSON.toString());
   } catch (JSONException e) {
     SoomlaUtils.LogError(
         "SOOMLA SoomlaEventHandler",
         "This is BAD! couldn't create JSON for onRewardGiven event.");
   }
 }
Exemple #16
0
  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());
    }
  }
Exemple #17
0
  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());
    }
  }
Exemple #18
0
  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());
    }
  }
Exemple #19
0
  public static HashMap<String, JSONObject> getWorlds(JSONObject model) {
    HashMap<String, JSONObject> worlds = new HashMap<String, JSONObject>();

    try {
      JSONObject mainWorld = model.getJSONObject("mainWorld");
      addWorldObjectToWorlds(worlds, mainWorld);
    } catch (JSONException e) {
      SoomlaUtils.LogError(
          TAG, "couldn't get something from model. error: " + e.getLocalizedMessage());
    }

    return worlds;
  }
  /** {@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();
  }
  private UserProfile createUserProfile(User user, boolean withExtraFields) {
    String fullName = user.getName();
    String firstName = "";
    String lastName = "";

    if (!TextUtils.isEmpty(fullName)) {
      String[] splitName = fullName.split(" ");
      if (splitName.length > 0) {
        firstName = splitName[0];
        if (splitName.length > 1) {
          lastName = splitName[1];
        }
      }
    }
    Map<String, Object> extraDict = Collections.<String, Object>emptyMap();
    if (withExtraFields) {
      extraDict = new HashMap<String, Object>();
      // TwitterException will throws when Twitter service or network is unavailable, or the user
      // has not authorized
      try {
        extraDict.put("access_token", twitter.getOAuthAccessToken().getToken());
      } catch (TwitterException twitterExc) {
        SoomlaUtils.LogError(TAG, twitterExc.getErrorMessage());
      }
    }
    // Twitter does not supply email access: https://dev.twitter.com/faq#26
    UserProfile result =
        new UserProfile(
            RefProvider,
            String.valueOf(user.getId()),
            user.getScreenName(),
            "",
            firstName,
            lastName,
            extraDict);

    // No gender information on Twitter:
    // https://twittercommunity.com/t/how-to-find-male-female-accounts-in-following-list/7367
    result.setGender("");

    // No birthday on Twitter:
    // https://twittercommunity.com/t/how-can-i-get-email-of-user-if-i-use-api/7019/16
    result.setBirthday("");

    result.setLanguage(user.getLang());
    result.setLocation(user.getLocation());
    result.setAvatarLink(user.getBiggerProfileImageURL());

    return result;
  }
        /**
         * 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);
        }
  /** {@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);
    }
  }
Exemple #24
0
  private static void findInternalLists(
      HashMap<String, JSONObject> objects, String[] listClasses, String listName) {
    try {

      List<String> classes = Arrays.asList(listClasses);
      Set<JSONObject> valuesSet = new HashSet<JSONObject>(objects.values());
      for (JSONObject objectJSON : valuesSet) {
        findInternalLists(objects, classes, listName, objectJSON);
      }
    } catch (JSONException e) {
      SoomlaUtils.LogError(
          TAG,
          "couldn't get internal lists for " + listName + ". error: " + e.getLocalizedMessage());
    }
  }
    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;
    }
  /** {@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());
    }
  }
        /**
         * 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 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);
    }