Ejemplo n.º 1
0
  private void makeMeRequest(final Session session) {

    // Make an API call to get user data and define a
    // new callback to handle the response.
    Request request =
        Request.newMeRequest(
            session,
            new Request.GraphUserCallback() {
              @Override
              public void onCompleted(GraphUser user, Response response) {
                // If the response is successful
                if (session == Session.getActiveSession()) {
                  if (user != null) {
                    ((OmniDriveApplication) getActivity().getApplication()).setCurrentFBUser(user);
                    // Set the id for the ProfilePictureView
                    // view that in turn displays the profile picture.
                    profilePictureView.setProfileId(user.getId());
                    // Set the Textview's text to the user's name.
                    userNameView.setText(user.getName());
                  }
                }
                if (response.getError() != null) {
                  // Handle errors, will do so later.
                }
              }
            });
    request.executeAsync();

    getAllFriends(session);
  }
  // Note that this method makes a synchronous Graph API call, so should not be called from the main
  // thread.
  public static FetchedAppSettings queryAppSettings(
      final String applicationId, final boolean forceRequery) {

    // Cache the last app checked results.
    if (!forceRequery && fetchedAppSettings.containsKey(applicationId)) {
      return fetchedAppSettings.get(applicationId);
    }

    Bundle appSettingsParams = new Bundle();
    appSettingsParams.putString(APPLICATION_FIELDS, TextUtils.join(",", APP_SETTING_FIELDS));

    Request request = Request.newGraphPathRequest(null, applicationId, null);
    request.setParameters(appSettingsParams);

    GraphObject supportResponse = request.executeAndWait().getGraphObject();
    FetchedAppSettings result =
        new FetchedAppSettings(
            safeGetBooleanFromResponse(supportResponse, SUPPORTS_ATTRIBUTION),
            safeGetBooleanFromResponse(supportResponse, SUPPORTS_IMPLICIT_SDK_LOGGING),
            safeGetStringFromResponse(supportResponse, NUX_CONTENT),
            safeGetBooleanFromResponse(supportResponse, NUX_ENABLED));

    fetchedAppSettings.put(applicationId, result);

    return result;
  }
 private void fetchUserInfo() {
   if (fetchUserInfo) {
     final Session currentSession = sessionTracker.getOpenSession();
     if (currentSession != null) {
       if (currentSession != userInfoSession) {
         Request request =
             Request.newMeRequest(
                 currentSession,
                 new Request.GraphUserCallback() {
                   @Override
                   public void onCompleted(GraphUser me, Response response) {
                     if (currentSession == sessionTracker.getOpenSession()) {
                       user = me;
                       if (userInfoChangedCallback != null) {
                         userInfoChangedCallback.onUserInfoFetched(user);
                       }
                     }
                     if (response.getError() != null) {
                       handleError(response.getError().getException());
                     }
                   }
                 });
         Request.executeBatchAsync(request);
         userInfoSession = currentSession;
       }
     } else {
       user = null;
       if (userInfoChangedCallback != null) {
         userInfoChangedCallback.onUserInfoFetched(user);
       }
     }
   }
 }
Ejemplo n.º 4
0
 private void fetchUserInfo() {
   final Session currentSession = getSession();
   if (currentSession != null && currentSession.isOpened()) {
     if (currentSession != userInfoSession) {
       Request request =
           Request.newMeRequest(
               currentSession,
               new Request.GraphUserCallback() {
                 @Override
                 public void onCompleted(GraphUser me, Response response) {
                   if (currentSession == getSession()) {
                     user = me;
                     updateUI();
                   }
                   if (response.getError() != null) {
                     loginButton.handleError(response.getError().getException());
                   }
                 }
               });
       Bundle parameters = new Bundle();
       parameters.putString(FIELDS, REQUEST_FIELDS);
       request.setParameters(parameters);
       Request.executeBatchAsync(request);
       userInfoSession = currentSession;
     }
   } else {
     user = null;
   }
 }
Ejemplo n.º 5
0
 private void makeMeRequest(final Session session) {
   // Make an API call to get user data and define a
   // new callback to handle the response.
   Request request =
       Request.newMeRequest(
           session,
           new Request.GraphUserCallback() {
             @Override
             public void onCompleted(GraphUser user, Response response) {
               // If the response is successful
               if (session == Session.getActiveSession()) {
                 if (user != null) {
                   /*Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
                   List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
                   if (addresses.size() > 0)
                       System.out.println(addresses.get(0).getLocality());*/
                   if (!registered)
                     RegisterUser(user.getId(), user.getName(), user_location, user.getUsername());
                   else initiateLoading();
                   fb_user = user;
                   // LoadData();
                 }
               }
               if (response.getError() != null) {
                 // Handle errors, will do so later.
               }
             }
           });
   request.executeAsync();
 }
  private Request createRequest(
      Location location,
      int radiusInMeters,
      int resultsLimit,
      String searchText,
      Set<String> extraFields,
      Session session) {
    Request request =
        Request.newPlacesSearchRequest(
            session, location, radiusInMeters, resultsLimit, searchText, null);

    Set<String> fields = new HashSet<String>(extraFields);
    String[] requiredFields = new String[] {ID, NAME, LOCATION, CATEGORY, WERE_HERE_COUNT};
    fields.addAll(Arrays.asList(requiredFields));

    String pictureField = adapter.getPictureFieldSpecifier();
    if (pictureField != null) {
      fields.add(pictureField);
    }

    Bundle parameters = request.getParameters();
    parameters.putString("fields", TextUtils.join(",", fields));
    request.setParameters(parameters);

    return request;
  }
Ejemplo n.º 7
0
  /** Get the current user profile info */
  private void makeMeRequest() {
    final Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
      Request request =
          Request.newMeRequest(
              session,
              new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                  isMakeMeRequestStarted = false;
                  dismissProgressDialog();

                  if (session == Session.getActiveSession() && user != null) {
                    mUser = user;
                    updateUI();
                  }
                  if (response != null && response.getError() != null) {
                    Utils.handleError(
                        getActivity(), response.getError(), Utils.getProfileReadPermission());
                  }
                }
              });
      request.executeAsync();
    }
  }
Ejemplo n.º 8
0
 /**
  * Will make a request to the facebook API and return with the some information about the user. It
  * will then set some layout text fields with the user image and username. It will also make a
  * request to the server for saving the username into the server's database.
  *
  * @param session is the current state or session for the user
  */
 private void makeMeRequest(final Session session) {
   // Make an API call to get user data and define a
   // new callback to handle the response.
   Request request =
       Request.newMeRequest(
           session,
           new Request.GraphUserCallback() {
             @Override
             public void onCompleted(GraphUser user, Response response) {
               // If the response is successful
               if (session == Session.getActiveSession()) {
                 if (user != null) {
                   // Set the id for the ProfilePictureView
                   // view that in turn displays the profile
                   // picture.
                   profilePictureView.setProfileId(user.getId());
                 }
               }
               if (response.getError() != null) {
                 // Handle errors, will do so later.
               }
             }
           });
   request.executeAsync();
 }
Ejemplo n.º 9
0
        @Override
        public void call(Session session, SessionState state, Exception exception) {

          if (state.isOpened()) {

            if (getCount() > 0) return;

            Request friendRequest =
                Request.newMyFriendsRequest(
                    Session.getActiveSession(),
                    new GraphUserListCallback() {
                      @Override
                      public void onCompleted(List<GraphUser> users, Response response) {

                        if (getCount() > 0) return;

                        if (users != null) {

                          for (GraphUser graphUser : users) {

                            ContentValues values = new ContentValues();
                            JSONObject userJson = graphUser.getInnerJSONObject();
                            if (userJson != null) {

                              JSONObject pictureJson = userJson.optJSONObject("picture");
                              if (pictureJson != null) {

                                JSONObject dataPictureJson = pictureJson.optJSONObject("data");
                                if (dataPictureJson != null)
                                  values.put(
                                      DBHelper.KEY_COLUMN_PICTURE,
                                      dataPictureJson.optString("url"));
                              }
                            }
                            values.put(DBHelper.KEY_COLUMN_ID, graphUser.getId());
                            values.put(
                                DBHelper.KEY_COLUMN_NAME,
                                graphUser.getFirstName() + " " + graphUser.getLastName());
                            getActivity()
                                .getContentResolver()
                                .insert(DBProvider.CONTENT_DATA_URI, values);
                          }
                        }
                      }
                    });
            Bundle params = new Bundle();
            params.putString("fields", "id, first_name, last_name, picture.type(large)");
            friendRequest.setParameters(params);
            friendRequest.executeAsync();
          } else if (state.isClosed()) {

          }
        }
Ejemplo n.º 10
0
  private void query(JSONArray args, CallbackContext callbackContext) throws JSONException {
    Log.d(TAG, "executing query: " + args.getString(0));

    Request request = new Request(Session.getActiveSession(), args.getString(0));

    Response response = request.executeAndWait();

    if (response.getError() != null) {
      callbackContext.error(response.getError().toString());
    } else {
      callbackContext.success(response.getGraphObject().getInnerJSONObject());
    }
  }
  private void startLoading(Request request, boolean skipRoundtripIfCached, long afterDelay) {
    this.skipRoundtripIfCached = skipRoundtripIfCached;
    appendResults = false;
    nextRequest = null;
    currentRequest = request;
    currentRequest.setCallback(
        new Request.Callback() {
          @Override
          public void onCompleted(Response response) {
            requestCompleted(response);
          }
        });

    // We are considered loading even if we have a delay.
    loading = true;

    final RequestBatch batch = putRequestIntoBatch(request, skipRoundtripIfCached);
    Runnable r =
        new Runnable() {
          @Override
          public void run() {
            Request.executeBatchAsync(batch);
          }
        };
    if (afterDelay == 0) {
      r.run();
    } else {
      Handler handler = new Handler();
      handler.postDelayed(r, afterDelay);
    }
  }
  private void initUI() {
    aQuery
        .id(R.id.logout_button)
        .clicked(
            new OnClickListener() {

              @Override
              public void onClick(View v) {
                Session session = Session.getActiveSession();
                if (!session.isClosed()) {
                  session.closeAndClearTokenInformation();
                  Intent mainIntent = new Intent(getActivity(), LoginActivity.class);
                  mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  pref.edit().remove(Common.USER_ID).commit();
                  startActivity(mainIntent);
                }
              }
            });

    Session session = Session.getActiveSession();
    if (session.isOpened()) {
      Request.executeMeRequestAsync(
          session,
          new GraphUserCallback() {

            @Override
            public void onCompleted(GraphUser user, Response response) {
              mProfilePictureView.setProfileId(user.getId());
              aQuery.id(R.id.profile_username_textview).text(user.getName());
            }
          });
    }

    initList();
  }
Ejemplo n.º 13
0
  @SuppressWarnings("deprecation")
  private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (session != currentSession) {
      return;
    }

    if (state.isOpened()) {
      // Log in just happened.
      // Toast.makeText(getApplicationContext(), "session opened",
      // Toast.LENGTH_SHORT).show();

      System.out.println("Token=" + session.getAccessToken());
      Request.executeMeRequestAsync(
          session,
          new GraphUserCallback() {
            @Override
            public void onCompleted(GraphUser user, Response response) {
              if (user != null) {

                String[] separated;
                separated = user.toString().split("=");
                String json = separated[2];
                Log.e("dfxfdsfsdf", user.toString());
                Log.e("dfxfdsfsdf", json.toString());

                try {
                  // Facebook Profile JSON data
                  JSONObject profile = new JSONObject(json);

                  // getting name of the user
                  fb_id = profile.getString("id");
                  Log.e("dfxfdsfsdf", fb_id.toString());

                  if (fb_id != null) {

                    GlobalClaass.savePrefrencesfor(context, PreferenceConnector.Facebook_ID, fb_id);

                    Log.e("First", "First");
                    login_type = "facebook";

                    CallFacebookLogin(login_type, fb_id, fb_id);
                  }
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
              if (response != null) {
                /*System.out.println("Response=" + response);
                                Toast.makeText(context, response.toString(),
                Toast.LENGTH_LONG).show();*/
              }
            }
          });

    } else if (state.isClosed()) {
      // Log out just happened. Update the UI.
      /*Toast.makeText(getApplicationContext(), "session closed",
      Toast.LENGTH_SHORT).show();*/
    }
  }
Ejemplo n.º 14
0
  private static void finalizeLogin(
      Session session,
      SessionState state,
      Exception exception,
      final UnityMessage unityMessage,
      final Activity activityToClose) {
    if (activityToClose != null) {
      activityToClose.finish();
    }

    if (!session.isOpened() && state != SessionState.CLOSED_LOGIN_FAILED) {
      unityMessage.sendError("Unknown error while opening session. Check logcat for details.");
      return;
    }

    if (session.isOpened()) {
      unityMessage.put("opened", true);
    } else if (state == SessionState.CLOSED_LOGIN_FAILED) {
      unityMessage.putCancelled();
    }

    if (session.getAccessToken() == null || session.getAccessToken().equals("")) {
      unityMessage.send();
      return;
    }

    // there's a chance a subset of the permissions were allowed even if the login was cancelled
    // if the access token is there, try to get it anyways

    // add a callback to update the access token when it changes
    session.addCallback(
        new StatusCallback() {
          @Override
          public void call(Session session, SessionState state, Exception exception) {
            if (session == null || session.getAccessToken() == null) {
              return;
            }
            final UnityMessage unityMessage = new UnityMessage("OnAccessTokenUpdate");
            unityMessage.put("access_token", session.getAccessToken());
            unityMessage.put(
                "expiration_timestamp", "" + session.getExpirationDate().getTime() / 1000);
            unityMessage.send();
          }
        });
    unityMessage.put("access_token", session.getAccessToken());
    unityMessage.put("expiration_timestamp", "" + session.getExpirationDate().getTime() / 1000);
    Request.newMeRequest(
            session,
            new Request.GraphUserCallback() {
              @Override
              public void onCompleted(GraphUser user, Response response) {
                if (user != null) {
                  unityMessage.put("user_id", user.getId());
                }
                unityMessage.send();
              }
            })
        .executeAsync();
  }
 @Override
 public void handleMessage(Message msg) {
   switch (msg.what) {
     case EXECUTE_REQUEST:
       {
         Request request = (Request) msg.obj;
         request.executeAsync();
         break;
       }
     case EXECUTE_WEBDIALOG:
       {
         mFacebookPlugin._ui((String) (msg.obj), msg.arg1);
         break;
       }
     default:
       break;
   }
 }
Ejemplo n.º 16
0
 void runRequest(Request request) {
   OnActionListener<T> actionListener = getActionListener();
   request.setCallback(mCallback);
   RequestAsyncTask task = new RequestAsyncTask(request);
   task.execute();
   if (actionListener != null) {
     actionListener.onThinking();
   }
 }
  public void followNextLink() {
    if (nextRequest != null) {
      appendResults = true;
      currentRequest = nextRequest;

      currentRequest.setCallback(
          new Request.Callback() {
            @Override
            public void onCompleted(Response response) {
              requestCompleted(response);
            }
          });

      loading = true;
      CacheableRequestBatch batch = putRequestIntoBatch(currentRequest, skipRoundtripIfCached);
      Request.executeBatchAsync(batch);
    }
  }
Ejemplo n.º 18
0
  private void getUserAllAlubum() {
    SessionManager mSessionManager = new SessionManager(this);

    String[] params = {mSessionManager.getFacebookId()};

    logDebug("getUserAllAlubum params " + params);

    // String fqlQuery=
    // "{\"query2\":\"select aid,photo_count,cover_pid, name from album where owner
    // ="+params[0]+"ORDER BY cover_pid\", \"query1\":\"select pid, src from photo where pid in
    // (SELECT cover_pid from album where owner ="+params[0]+") ORDER BY pid\"}";

    String fqlQuery =
        "{\"query2\":\"select aid,photo_count,cover_pid, name from album where owner = "
            + params[0]
            + " and type != 'wall' ORDER BY cover_pid\", \"query1\":\"select pid, src from photo where pid in (SELECT cover_pid from album where owner ="
            + params[0]
            + " ORDER BY cover_pid) ORDER BY pid\"}";

    // String fqlQuery =
    // "select src_big from photo  where album_object_id IN (SELECT  object_id   FROM album WHERE
    // owner="+"'"+params[0]+"'"+" and name='Profile Pictures') LIMIT 5";
    // String fqlQuery =
    // "select uid1, uid2 FROM friend WHERE uid1 = '100003056725155'";
    // String fqlQuery =
    // "select src from photo  where album_object_id IN (SELECT  object_id   FROM album WHERE
    // owner='params[0]' and name='Profile Pictures'";

    logDebug("getUserAllAlubum fqlQuery " + fqlQuery);
    // Log.i(TAG, "Result: " + fqlQuery);
    Bundle param = new Bundle();
    param.putString("q", fqlQuery);
    Session session = Session.getActiveSession();
    Request request =
        new Request(
            session,
            "/fql",
            param,
            HttpMethod.GET,
            new Request.Callback() {
              public void onCompleted(Response response) {
                try {
                  logDebug("getUserAllAlubum    Result  " + response.toString());

                  String[] pramas = {response.toString()};
                  new BackGroundTaskForGetAlubumData().execute(pramas);
                } catch (Exception e) {
                  logError("Request onCompleted Exception " + e);
                }
                // Log.i(TAG, "Result: " + response.toString());

              }
            });

    Request.executeBatchAsync(request);
  }
  @Override
  protected Void doInBackground(Void... voids) {
    final VKRequest vkRequest = Requests.vkFriendsRequest(Requests.LOCALE_RUS);

    vkRequest.executeWithListener(
        new VKRequest.VKRequestListener() {
          @Override
          public void onComplete(VKResponse response) {
            super.onComplete(response);
            vkTask = new ParseVkResponseTask(vkFriends, listener, response);
            vkTask.setShowResults(false);
            vkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
          }
        });

    while (vkTask == null) {}

    try {
      vkTask.get();
      Request fbRequest = Requests.fbFriendsRequest();
      Response response = fbRequest.executeAndWait();
      fbTask = new ParseFbResponseTask(fbFriends, listener, response);
      fbTask.setShowResults(false);
      Handler mainHandler = new Handler(Looper.getMainLooper());
      mainHandler.post(
          new Runnable() {
            @Override
            public void run() {
              fbTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
          });
      fbTask.get();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    fillSyncContactsList();
    storeSyncContacts();

    return null;
  }
Ejemplo n.º 20
0
  private void getFacebookInfos() {
    showLoadingDialog(LOADING_NO_MSG, LOADING_NO_MSG, false);
    Request.executeMeRequestAsync(
        Session.getActiveSession(),
        new GraphUserCallback() {

          @Override
          public void onCompleted(GraphUser user, Response response) {
            // TODO Auto-generated method stub\
            if (user == null) {
              facebookRequestError();
              return;
            }
            hasUserInfoLoaed = true;
            mUser = user;
            if (hasFriendsLoaded) {
              onFacebookInfoLoaded(mUser, mFriends);
            }
          }
        });
    Request request =
        Request.newMyFriendsRequest(
            Session.getActiveSession(),
            new GraphUserListCallback() {

              @Override
              public void onCompleted(List<GraphUser> users, Response response) {
                // TODO Auto-generated method
                if (users == null) {
                  facebookRequestError();
                  return;
                }
                mFriends = FacebookUtil.buildFriends(users);
                hasFriendsLoaded = true;
                if (hasUserInfoLoaed) {
                  onFacebookInfoLoaded(mUser, mFriends);
                }
              }
            });
    request.executeAsync();
  }
Ejemplo n.º 21
0
  private void getAllFriends(final Session session) {
    Request friendsRequest =
        Request.newMyFriendsRequest(
            session,
            new Request.GraphUserListCallback() {

              @Override
              public void onCompleted(List<GraphUser> users, Response response) {
                FacebookRequestError error = response.getError();
                if (error != null) {
                  Log.e(OmniDriveApplication.TAG, error.toString());
                } else if (session == Session.getActiveSession()) {
                  // Set the friends attribute
                  ((OmniDriveApplication) getActivity().getApplication()).setFriends(users);
                }
              }
            });
    Bundle params = new Bundle();
    params.putString("fields", "name,first_name,last_name");
    friendsRequest.setParameters(params);
    friendsRequest.executeAsync();
  }
Ejemplo n.º 22
0
  /**
   * set next and prev pages requests
   *
   * @param response
   */
  private void updateCursor(Response response) {
    if (mOnActionListener == null) {
      return;
    }

    if (mCursor == null) {
      mCursor = new Cursor<T>(GetAction.this);
    }

    Request requestNextPage = response.getRequestForPagedResults(PagingDirection.NEXT);
    if (requestNextPage != null) {
      requestNextPage.setCallback(mCallback);
    }
    mCursor.setNextPage(requestNextPage);

    Request requestPrevPage = response.getRequestForPagedResults(PagingDirection.PREVIOUS);
    if (requestPrevPage != null) {
      requestPrevPage.setCallback(mCallback);
    }
    mCursor.setPrevPage(requestPrevPage);
    mOnActionListener.setCursor(mCursor);
  }
Ejemplo n.º 23
0
  private void Poimg(Bitmap b) {

    Session session = Session.getActiveSession();
    if (session != null) {

      // Part 1: create callback to get URL of uploaded photo
      Request.Callback uploadPhotoRequestCallback =
          new Request.Callback() {
            @Override
            public void onCompleted(Response response) {
              // safety check
              if (isFinishing()) {
                return;
              }
              if (response.getError() != null) { // [IF Failed Posting]
                Log.d("", "photo upload problem. Error=" + response.getError());
                System.out.println(response.getError());
              } //  [ENDIF Failed Posting]
              Object graphResponse = response.getGraphObject().getProperty("id");
              if (graphResponse == null
                  || !(graphResponse instanceof String)
                  || TextUtils.isEmpty((String) graphResponse)) { // [IF Failed upload/no results]
                Log.d("", "failed photo upload/no response");
              } else { // [ELSEIF successful upload]
                fbPhotoAddress = "https://www.facebook.com/photo.php?fbid=" + graphResponse;

                System.out.println(fbPhotoAddress + "/////");
              } // [ENDIF successful posting or not]
            } // [END onCompleted]
          };

      // Part 2: upload the photo
      Request request = Request.newUploadPhotoRequest(session, b, uploadPhotoRequestCallback);
      Bundle bundle = request.getParameters();
      bundle.putString(
          "message",
          "受測者:"
              + UserName
              + "\n拍攝日期:"
              + Data[0]
              + "\n酒測值:"
              + Data[1]
              + "/L"
              + "\n位置:"
              + returnAddress);
      request.setParameters(bundle);
      /*紫陽科技酒測即時群組*/
      request.setGraphPath("615097428532040/photos");
      /*
       * 	測試群組
       * request.setGraphPath("612077312161579/photos");
       */
      /*	個人塗鴉牆
       * request.setGraphPath("me/photos");
       */
      request.executeAsync();
    }
  }
Ejemplo n.º 24
0
  private void sendRequests() {
    textViewResults.setText("");

    String requestIdsText = editRequests.getText().toString();
    String[] requestIds = requestIdsText.split(",");

    List<Request> requests = new ArrayList<Request>();
    for (final String requestId : requestIds) {
      requests.add(
          new Request(
              session,
              requestId,
              null,
              null,
              new Request.Callback() {
                public void onCompleted(Response response) {
                  GraphObject graphObject = response.getGraphObject();
                  FacebookRequestError error = response.getError();
                  String s = textViewResults.getText().toString();
                  if (graphObject != null) {
                    if (graphObject.getProperty("id") != null) {
                      s =
                          s
                              + String.format(
                                  "%s: %s\n",
                                  graphObject.getProperty("id"), graphObject.getProperty("name"));
                    } else {
                      s = s + String.format("%s: <no such id>\n", requestId);
                    }
                  } else if (error != null) {
                    s = s + String.format("Error: %s", error.getErrorMessage());
                  }
                  textViewResults.setText(s);
                }
              }));
    }
    pendingRequest = false;
    Request.executeBatchAndWait(requests);
  }
Ejemplo n.º 25
0
 private void onSessionStateChange(Session session, SessionState state, Exception exception) {
   if (state.isOpened() && !mIsGettingUserInfo) {
     mIsGettingUserInfo = true;
     Request.newMeRequest(
             session,
             new Request.GraphUserCallback() {
               @Override
               public void onCompleted(GraphUser graphUser, Response response) {
                 User user = new User();
                 user.id = graphUser.getId();
                 user.fullName = graphUser.getName();
                 user.persist(getActivity());
                 BusProvider.getInstance().post(new LoginCompleteEvent());
                 Logger.l("Logged in...");
                 mIsGettingUserInfo = false;
               }
             })
         .executeAsync();
   } else if (state.isClosed()) {
     Logger.l("Logged out...");
   }
 }
Ejemplo n.º 26
0
  public void requestUserData(Session session) {
    // Request user data and show the results
    Request.newMeRequest(
            session,
            new Request.GraphUserCallback() {

              @Override
              public void onCompleted(GraphUser user, Response response) {
                if (user != null) {
                  User currentUser = new User();
                  currentUser.setUserId(user.getId());
                  currentUser.setUserName(user.getUsername());
                  currentUser.setUserName(user.getFirstName());
                  currentUser.setLastName(user.getLastName());
                  FbLoginFlowHelper.this.mUserHelper.setCurrentUser(currentUser);
                  if (mStatusCallback != null) {
                    mStatusCallback.onFacebookSessionOpened();
                  }
                }
              }
            })
        .executeAsync();
  }
Ejemplo n.º 27
0
  // <editor-fold desc="Facebook Methods">
  private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (isResumed) {

      // check for the OPENED state instead of session.isOpened() since for the
      // OPENED_TOKEN_UPDATED state, the selection fragment should already be showing.
      if (state.equals(SessionState.OPENED)) {

        if (registered) sendAccessTokenToBackend(session.getAccessToken());

        Request.executeMeRequestAsync(
            session,
            new Request.GraphUserCallback() {
              @Override
              public void onCompleted(GraphUser user, Response response) {
                if (user != null) {
                  Log.i("FB User Id ", user.getId());
                  PreferenceManager.getDefaultSharedPreferences(a)
                      .edit()
                      .putInt("login_method", FACEBOOK_LOGIN)
                      .commit();
                  setContentView(R.layout.activity_start);
                  // LoadData();
                  Session session = Session.getActiveSession();
                  if (session != null && session.isOpened()) makeMeRequest(session);
                }
              }
            });
      } else if (state.isClosed()) {
        PreferenceManager.getDefaultSharedPreferences(a)
            .edit()
            .putInt("login_method", NO_METHOD_DEFINED)
            .commit();
        setContentView(R.layout.activity_login_only_facebook);
      }
    }
  }
Ejemplo n.º 28
0
  private void makeMeRequest(final Session session) {
    // Make an API call to get user data and define a
    // new callback to handle the response.
    Request request =
        Request.newMeRequest(
            session,
            new Request.GraphUserCallback() {
              public void onCompleted(GraphUser user, Response response) {
                // If the response is successful
                if (session == Session.getActiveSession()) {
                  if (user != null) {
                    fb_uid = user.getId();

                    first_name = user.getFirstName();
                    last_name = user.getLastName();

                    if (user.getBirthday() != null) {
                      birthdate = formatDate(user.getBirthday());
                      // Log.i ("facebook info birthday: ", birthdate);
                    }

                    gender = "M";
                    if (user.getProperty("gender").toString().contentEquals("male")) {
                      gender = "M";
                    } else if (user.getProperty("gender").toString().contentEquals("female")) {
                      gender = "F";
                    }
                    // Log.i ("facebook info gender: ", gender);

                    /*
                    email_is_verified = 1;
                    if ((Boolean) user.getProperty("verified")){
                    	email_is_verified = 1;
                    } else {
                    	email_is_verified = 0;
                    }
                    */
                    // Log.i ("facebook info verified: ", String.valueOf(email_is_verified));

                    mHandler.post(
                        new Runnable() {
                          public void run() {
                            RestClient result = null;
                            try {
                              result =
                                  new Rest.requestBody()
                                      .execute(
                                          Rest.USER,
                                          Rest.OTOKE + Rest.accessCode2,
                                          Rest.POST,
                                          "7",
                                          "email",
                                          email,
                                          "firstname",
                                          first_name,
                                          "lastname",
                                          last_name,
                                          "date_of_birth",
                                          birthdate,
                                          "gender",
                                          gender,
                                          "school_id",
                                          String.valueOf(schoolid),
                                          "facebook_uid",
                                          fb_uid)
                                      .get();
                            } catch (InterruptedException e1) {
                              // TODO Auto-generated catch block
                              e1.printStackTrace();
                            } catch (ExecutionException e1) {
                              // TODO Auto-generated catch block
                              e1.printStackTrace();
                            }
                            Log.i("create account facebook result", result.getResponse());

                            if (result.getResponseCode() == 201) {
                              setUserPW(fb_uid);
                              showAlertDialog();
                            } else if (result.getResponseCode() == 403
                                && result.getResponse().contains("age")) {
                              onClickLogout();
                              showErrorAlertDialog(
                                  getString(
                                      R.string
                                          .Registration_failed_The_user_does_not_satisfy_the_age_requirements_of_the_app));
                            } else if (result.getResponseCode() == 409
                                && result.getResponse().contains("email")) {
                              onClickLogout();
                              showErrorAlertDialog(
                                  getString(
                                      R.string
                                          .Registration_failed_The_email_has_been_used_in_another_account));
                            } else if (result.getResponseCode() == 409
                                && result.getResponse().contains("facebook_uid")) {
                              onClickLogout();
                              showErrorAlertDialog(
                                  getString(
                                      R.string
                                          .Registration_failed_Facebook_account_already_has_an_account_on_OOHLALA));
                            }
                          }
                        });
                  }
                }
                if (response.getError() != null) {
                  // Handle errors, will do so later.
                  Log.i("facebook response errorMessage: ", response.getError().getErrorMessage());
                  makeMeRequest(session);
                }
              }
            });
    request.executeAsync();
  }
Ejemplo n.º 29
0
  private void publish(JSONArray args, CallbackContext callbackContext) throws JSONException {
    JSONObject actionParams = args.getJSONObject(0);

    if (actionParams.has("object")) {
      RequestBatch requestBatch = new RequestBatch();

      OpenGraphObject object = buildOpenGraphObject(actionParams);

      Request objectRequest =
          Request.newPostOpenGraphObjectRequest(Session.getActiveSession(), object, null);
      objectRequest.setBatchEntryName("objectCreate");

      OpenGraphAction action =
          OpenGraphAction.Factory.createForPost(actionParams.getString("action"));

      action.setMessage(actionParams.getString("message"));
      action.setProperty("place", actionParams.getLong("place"));
      action.setExplicitlyShared(actionParams.getBoolean("explicitlyShared"));
      action.setProperty(actionParams.getString("objectType"), "{result=objectCreate:$.id}");

      Request request =
          Request.newPostOpenGraphActionRequest(Session.getActiveSession(), action, null);
      request.setBatchEntryDependsOn("objectCreate");

      requestBatch.add(objectRequest);
      requestBatch.add(request);

      List<Response> responses = requestBatch.executeAndWait();
      Response lastResponse = null;

      for (Response response : responses) {

        if (response.getError() != null) {
          callbackContext.error(response.getError().toString());
          return;
        }

        lastResponse = response;
      }

      callbackContext.success(lastResponse.getGraphObject().getInnerJSONObject());
    } else {
      OpenGraphAction action =
          OpenGraphAction.Factory.createForPost(actionParams.getString("action"));

      action.setMessage(actionParams.getString("message"));
      action.setProperty("place", actionParams.getLong("place"));
      action.setExplicitlyShared(actionParams.getBoolean("explicitlyShared"));
      action.setProperty(actionParams.getString("objectType"), actionParams.getString("objectId"));

      Request request =
          Request.newPostOpenGraphActionRequest(Session.getActiveSession(), action, null);

      Response response = request.executeAndWait();

      if (response.getError() != null) {
        callbackContext.error(response.getError().toString());
      } else {
        callbackContext.success(response.getGraphObject().getInnerJSONObject());
      }
    }
  }
Ejemplo n.º 30
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_rest, container, false);
    Intent data = getActivity().getIntent();
    eid = data.getStringExtra("eid");
    event_name = data.getStringExtra("name");
    et_name = (EditText) view.findViewById(R.id.et_name);
    btnChat = (Button) view.findViewById(R.id.buttonChat);
    btnChat.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            if (btnChat.getText().equals("Chat!")) {
              Intent intent = new Intent(getActivity().getApplicationContext(), ChatActivity.class);
              name = et_name.getText().toString();
              if (name.trim().length() > 0) {
                intent.putExtra("name", name);
                intent.putExtra("event_name", event_name);
                intent.putExtra("eid", eid);
                startActivity(intent);
              } else {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
                alertDialogBuilder
                    .setTitle("Error")
                    .setMessage("Please fill in your name.")
                    .setCancelable(false)
                    .setNegativeButton(
                        "Ok",
                        new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                          }
                        });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
              }
            }
          }
        });

    String fqlQuery = "SELECT name FROM user where uid = me()";
    Bundle params = new Bundle();
    params.putString("q", fqlQuery);
    NetworkTracker ntrack = new NetworkTracker(getActivity());
    if (ntrack.getNetwork()) {
      Session session = Session.getActiveSession();
      params.putString("t", session.getAccessToken());
      Request request =
          new Request(session, "/fql?q=QUERY&access_token=t", params, HttpMethod.GET, callback);
      request.executeAsync();

    } else {
      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
      alertDialogBuilder
          .setTitle("Error")
          .setMessage("No internet connection available.")
          .setCancelable(false)
          .setNegativeButton(
              "Ok",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                  dialog.cancel();
                }
              });
      AlertDialog alertDialog = alertDialogBuilder.create();
      alertDialog.show();
    }

    return view;
  }