Search in sources :

Example 6 with GraphObject

use of com.facebook.model.GraphObject in project phonegap-facebook-plugin by Wizcorp.

the class Session method handlePermissionResponse.

/**
     * This parses a server response to a call to me/permissions.  It will return the list of granted permissions.
     * It will optionally update a session with the requested permissions.  It also handles the distinction between
     * 1.0 and 2.0 calls to the endpoint.
     *
     * @param response The server response
     * @return A list of granted permissions or null if an error
     */
static PermissionsPair handlePermissionResponse(Response response) {
    if (response.getError() != null) {
        return null;
    }
    GraphMultiResult result = response.getGraphObjectAs(GraphMultiResult.class);
    if (result == null) {
        return null;
    }
    GraphObjectList<GraphObject> data = result.getData();
    if (data == null || data.size() == 0) {
        return null;
    }
    List<String> grantedPermissions = new ArrayList<String>(data.size());
    List<String> declinedPermissions = new ArrayList<String>(data.size());
    // Check if we are dealing with v2.0 or v1.0 behavior until the server is updated
    GraphObject firstObject = data.get(0);
    if (firstObject.getProperty("permission") != null) {
        // v2.0
        for (GraphObject graphObject : data) {
            String permission = (String) graphObject.getProperty("permission");
            if (permission.equals("installed")) {
                continue;
            }
            String status = (String) graphObject.getProperty("status");
            if (status.equals("granted")) {
                grantedPermissions.add(permission);
            } else if (status.equals("declined")) {
                declinedPermissions.add(permission);
            }
        }
    } else {
        // v1.0
        Map<String, Object> permissionsMap = firstObject.asMap();
        for (Map.Entry<String, Object> entry : permissionsMap.entrySet()) {
            if (entry.getKey().equals("installed")) {
                continue;
            }
            if ((Integer) entry.getValue() == 1) {
                grantedPermissions.add(entry.getKey());
            }
        }
    }
    return new PermissionsPair(grantedPermissions, declinedPermissions);
}
Also used : GraphObject(com.facebook.model.GraphObject) JSONObject(org.json.JSONObject) GraphMultiResult(com.facebook.model.GraphMultiResult) GraphObject(com.facebook.model.GraphObject)

Example 7 with GraphObject

use of com.facebook.model.GraphObject in project phonegap-facebook-plugin by Wizcorp.

the class TestSession method deleteTestAccount.

private void deleteTestAccount(String testAccountId, String appAccessToken) {
    Bundle parameters = new Bundle();
    parameters.putString("access_token", appAccessToken);
    Request request = new Request(null, testAccountId, parameters, HttpMethod.DELETE);
    Response response = request.executeAndWait();
    FacebookRequestError error = response.getError();
    GraphObject graphObject = response.getGraphObject();
    if (error != null) {
        Log.w(LOG_TAG, String.format("Could not delete test account %s: %s", testAccountId, error.getException().toString()));
    } else if (graphObject.getProperty(Response.NON_JSON_RESPONSE_PROPERTY) == (Boolean) false || graphObject.getProperty(Response.SUCCESS_KEY) == (Boolean) false) {
        Log.w(LOG_TAG, String.format("Could not delete test account %s: unknown reason", testAccountId));
    }
}
Also used : Bundle(android.os.Bundle) GraphObject(com.facebook.model.GraphObject)

Example 8 with GraphObject

use of com.facebook.model.GraphObject in project phonegap-facebook-plugin by Wizcorp.

the class TestSession method retrieveTestAccountsForAppIfNeeded.

private static synchronized void retrieveTestAccountsForAppIfNeeded() {
    if (appTestAccounts != null) {
        return;
    }
    appTestAccounts = new HashMap<String, TestAccount>();
    // The data we need is split across two different graph API queries. We construct two queries, submit them
    // together (the second one refers to the first one), then cross-reference the results.
    Request.setDefaultBatchApplicationId(testApplicationId);
    Bundle parameters = new Bundle();
    parameters.putString("access_token", getAppAccessToken());
    Request requestTestUsers = new Request(null, "app/accounts/test-users", parameters, null);
    requestTestUsers.setBatchEntryName("testUsers");
    requestTestUsers.setBatchEntryOmitResultOnSuccess(false);
    Bundle testUserNamesParam = new Bundle();
    testUserNamesParam.putString("access_token", getAppAccessToken());
    testUserNamesParam.putString("ids", "{result=testUsers:$.data.*.id}");
    testUserNamesParam.putString("fields", "name");
    Request requestTestUserNames = new Request(null, "", testUserNamesParam, null);
    requestTestUserNames.setBatchEntryDependsOn("testUsers");
    List<Response> responses = Request.executeBatchAndWait(requestTestUsers, requestTestUserNames);
    if (responses == null || responses.size() != 2) {
        throw new FacebookException("Unexpected number of results from TestUsers batch query");
    }
    TestAccountsResponse testAccountsResponse = responses.get(0).getGraphObjectAs(TestAccountsResponse.class);
    GraphObjectList<TestAccount> testAccounts = testAccountsResponse.getData();
    // Response should contain a map of test accounts: { id's => { GraphUser } }
    GraphObject userAccountsMap = responses.get(1).getGraphObject();
    populateTestAccounts(testAccounts, userAccountsMap);
    return;
}
Also used : Bundle(android.os.Bundle) GraphObject(com.facebook.model.GraphObject)

Example 9 with GraphObject

use of com.facebook.model.GraphObject in project phonegap-facebook-plugin by Wizcorp.

the class FacebookAppLinkResolver method getAppLinkFromUrlsInBackground.

/**
     * Asynchronously resolves App Link data for multiple Urls
     *
     * @param uris A list of Uri objects to resolve into App Links
     * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was successfully
     * resolved into an App Link. Uris that could not be resolved into App Links will not be present in the Map.
     * In the case of general server errors, the task will be completed with the corresponding error.
     */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();
    for (Uri uri : uris) {
        AppLink appLink = null;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }
        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }
    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }
    final Task<Map<Uri, AppLink>>.TaskCompletionSource<Map<Uri, AppLink>> taskCompletionSource = Task.create();
    Bundle appLinkRequestParameters = new Bundle();
    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY, APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    Request appLinkRequest = new Request(null, /* Session */
    "", /* Graph path */
    appLinkRequestParameters, /* Query parameters */
    null, /* HttpMethod */
    new Request.Callback() {

        /* Callback */
        @Override
        public void onCompleted(Response response) {
            FacebookRequestError error = response.getError();
            if (error != null) {
                taskCompletionSource.setError(error.getException());
                return;
            }
            GraphObject responseObject = response.getGraphObject();
            JSONObject responseJson = responseObject != null ? responseObject.getInnerJSONObject() : null;
            if (responseJson == null) {
                taskCompletionSource.setResult(appLinkResults);
                return;
            }
            for (Uri uri : urisToRequest) {
                String uriString = uri.toString();
                if (!responseJson.has(uriString)) {
                    continue;
                }
                JSONObject urlData = null;
                try {
                    urlData = responseJson.getJSONObject(uri.toString());
                    JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);
                    JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);
                    int targetsCount = rawTargets.length();
                    List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);
                    for (int i = 0; i < targetsCount; i++) {
                        AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                        if (target != null) {
                            targets.add(target);
                        }
                    }
                    Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                    AppLink appLink = new AppLink(uri, targets, webFallbackUrl);
                    appLinkResults.put(uri, appLink);
                    synchronized (cachedAppLinks) {
                        cachedAppLinks.put(uri, appLink);
                    }
                } catch (JSONException e) {
                    // The data for this uri was missing or badly formed.
                    continue;
                }
            }
            taskCompletionSource.setResult(appLinkResults);
        }
    });
    appLinkRequest.executeAsync();
    return taskCompletionSource.getTask();
}
Also used : Task(bolts.Task) Bundle(android.os.Bundle) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) GraphObject(com.facebook.model.GraphObject) Uri(android.net.Uri) JSONObject(org.json.JSONObject) AppLink(bolts.AppLink)

Example 10 with GraphObject

use of com.facebook.model.GraphObject in project phonegap-facebook-plugin by Wizcorp.

the class ConnectPlugin method onSessionStateChange.

/*
     * Handles session state changes
     */
private void onSessionStateChange(SessionState state, Exception exception) {
    Log.d(TAG, "onSessionStateChange:" + state.toString());
    if (exception != null && exception instanceof FacebookOperationCanceledException) {
        // only handle FacebookOperationCanceledException to support
        // SDK recovery behavior triggered by getUserInfo
        Log.e(TAG, "exception:" + exception.toString());
        handleError(exception, loginContext);
    } else {
        final Session session = Session.getActiveSession();
        // Check if the session is open
        if (state.isOpened()) {
            if (loginContext != null) {
                // Get user info
                getUserInfo(session, new Request.GraphUserCallback() {

                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        // Create a new result with response data
                        if (loginContext != null) {
                            if (response.getError() != null) {
                                loginContext.error(getFacebookRequestErrorResponse(response.getError()));
                            } else {
                                GraphObject graphObject = response.getGraphObject();
                                Log.d(TAG, "returning login object " + graphObject.getInnerJSONObject().toString());
                                userID = user.getId();
                                loginContext.success(getResponse());
                                loginContext = null;
                            }
                        } else {
                            // Just update the userID in case we force quit the application before
                            userID = user.getId();
                        }
                    }
                });
            } else if (graphContext != null) {
                // Make the graph call
                makeGraphCall();
            }
        } else if (state == SessionState.CLOSED_LOGIN_FAILED && loginContext != null) {
            handleError(new FacebookAuthorizationException("Session was closed and was not closed normally"), loginContext);
        }
    }
}
Also used : Response(com.facebook.Response) FacebookAuthorizationException(com.facebook.FacebookAuthorizationException) FacebookOperationCanceledException(com.facebook.FacebookOperationCanceledException) GraphUser(com.facebook.model.GraphUser) GraphUserCallback(com.facebook.Request.GraphUserCallback) Request(com.facebook.Request) GraphObject(com.facebook.model.GraphObject) Session(com.facebook.Session)

Aggregations

GraphObject (com.facebook.model.GraphObject)42 JSONObject (org.json.JSONObject)23 Bundle (android.os.Bundle)13 JSONException (org.json.JSONException)11 JSONArray (org.json.JSONArray)10 GraphObjectList (com.facebook.model.GraphObjectList)6 SharedPreferences (android.content.SharedPreferences)5 Request (com.facebook.Request)4 GraphMultiResult (com.facebook.model.GraphMultiResult)4 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 Collator (java.text.Collator)4 JSONTokener (org.json.JSONTokener)4 GraphUser (com.facebook.model.GraphUser)3 ActivityNotFoundException (android.content.ActivityNotFoundException)2 Uri (android.net.Uri)2 AppLink (bolts.AppLink)2 Task (bolts.Task)2 FacebookException (com.facebook.FacebookException)2 GraphUserCallback (com.facebook.Request.GraphUserCallback)2