access event by Facebook API - java

I'm trying to get information about event, to which I am invited.
I created access token in Open Graph page with all available permission and I use it.
I can fetch one event, but I can't see another, which I care. I noticed that event is "invite only", but it's settings are beyond my control.
It doesn't show in my events/maybe (when I clicked "maybe"), and when I try to access it by ID (graph.facebook.com/id), I get error message "Unsupported get request.".
I tried:
RestFB (Java) - this is my purpose
PHP SDK
JavaScript SDK
Can I do something more except using FQL?
I read about it and I want to use simple request to get event, as mentioned on this page: https://developers.facebook.com/docs/graph-api/reference/event/.
I can attach code if if this helps.
Thank You very much to look at this.
EDIT:
Java code:
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN);
String attending = facebookClient.fetchObject("{event-id}/attending", String.class);
System.out.println("Attending: " + attending);
It works like a charm with one event, but fails (return empty array of data) on another event (I was invited to both).
JavaScript code:
FB.api(
'https://graph.facebook.com/{event-id}',
'get',
null,
function(response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
alert('test');
response['data'].forEach(function(entry) {
alert(entry['object']['name']) ;
});
}
}
);
Doesn't return error, but response['data'] array is empty, while in another case contains properly data.
EDIT 2:
Furthermore, I tried FQL with restFB. It similary doesn't work - following code returns only one event, such as http requests.
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN);
String query = "SELECT name, eid FROM event where eid = {event1-id} OR eid = {event2-id}";
List<FqlUser> event = facebookClient.executeFqlQuery(query, FqlUser.class);
System.out.println("Events: " + event);

You can write a FQL query for all events you gave a (non-declining) rsvp feedback for:
select eid, uid, rsvp_status from event_member where uid=me()
If you want to see the according event data, use this:
select eid, name, description, start_time, venue, location, creator, host from event where eid in (select eid from event_member where uid=me())
Please note what is written about permissions to the event table in the docs: https://developers.facebook.com/docs/reference/fql/event/#permissions
You should be able to request FQL via the JS SDK like this:
FB.api(
'https://graph.facebook.com/fql?q=' + encodeURIComponent("select eid, name, description, start_time, venue, location, creator, host from event where eid in (select eid from event_member where uid=me())"),
'get',
...);

Seems to works as expected now. I think that was a bug in facebook itself.

Related

How to open a page dynamically in android when user clicks on pushNotification message sent through php

I have a PHP code for sending pushNotifications to registered mobiles. The notification includes fields of database like "Collection Title", "Community" and a "Collection handle (unique ID)". After the message is received on mobile, when the user clicks on that message, I want a webview of that particular collection handle in android app.
I have searched through various posts, however I am unable to get the desired code.
Any help in this regard would be highly appreciated.
Excerpts of "sendnotification.php" file
$sql1 = "SELECT community.name as inst, collection.name as coll,
handle.handle as handle FROM community2collection, collection2item, handle, community, collection WHERE community2collection.collection_id = collection2item.collection_id AND community.community_id = community2collection.community_id AND collection.collection_id = collection2item.collection_id AND collection2item.item_id = handle.resource_id
ORDER BY handle.handle_id desc limit 2";
$result1 = pg_exec($cnn, $sql1);
$numrows1 = pg_numrows($result1);
echo "numrows1=" . $numrows1;
for($ri = 0; $ri < $numrows1; $ri++) {
$row = pg_fetch_array($result1, $ri);
echo "row=" . $ri;
$pushMessage = $row[1]. " submitted by " .$row[0];
if(isset($gcmRegIds) && isset($pushMessage)) {
$message = array('message' => $pushMessage);
echo $pushMessage;
$pushStatus = sendPushNotification($gcmRegIds, $message);
echo $pushStatus;
echo "row2field=" .$row[2];
Here I want to create the URL dynamically for specific handle in the notification in android app i.e. based on field $row(2) in the code above. I am using GCM service for sending notifications.

Restfb - Using the Batch Request API

This is my FQL. What it does is it receives the post based on post_id, and also returns if post was made by user or page. User or page is returned based on id of the one who posted the post, which is returned by first FQLQuery.
StringBuilder fqlQuery = new StringBuilder();
fqlQuery.append("SELECT "
+ FacebookGraphApi.FQL_STREAM_SELECT
+ " FROM stream WHERE post_id=\"");
fqlQuery.append(rmtId);
fqlQuery.append("\"");
HashMap<String, String> querys = new HashMap<String, String>();
querys.put("messages", fqlQuery.toString());
querys.put(
"users",
"SELECT "
+ FacebookGraphApi.FQL_USER_SELECT
+ " FROM user WHERE uid IN (SELECT actor_id FROM #messages)");
querys.put(
"pages",
"SELECT "
+ FacebookGraphApi.FQL_PAGE_SELECT
+ " FROM page WHERE page_id IN (SELECT actor_id FROM #messages)");
Now what i would like to do is the same using RESTFB Batch Request API
BatchRequest firstRequest = new BatchRequestBuilder(rmtId)).build();
BatchRequest secondRequest = new BatchRequestBuilder(poster_id).build();
List<BatchResponse> batchResponses =
facebookClient.executeBatch(firstRequest,secondRequest);
These are 2 batches that executes, first one returns the post, and it contains "from", that contains poster_id of the one who posted, but i dont know how to put that poster_id from first batch to second batch so it would return poster information.
Any help would be appreciated, thanks.
Just to post the answer,
first request should contain a name method on which u depend on the other request, and search on second request that depends on first ids like this.
?ids={result=name-of-method:$.data.id}

Push Notification condition

Good day,
I am using Parse Push Notification, and below are my difficulties:
In brief, I would like to "merge" these two conditions:
query.whereEqualTo("Gender", userLookingGender);
pushQuery.whereEqualTo("the gender column of the ParseQuery", the user gender of the ParseQuery column);
In other words, I would like to send out a message to the user that falls within that gender. The gender column along with the genders are found in the parse query called "User".
Update:
userLookingGender is the following:
String userLookingGender = ParseUser.getCurrentUser().getString(
"Looking_Gender");
If you need any clarification let me know.
Update 2:
I use one condition, gender, to make easier to understand. Now Imagine if I had multiple condition, and is trying to send a push message only the recipient who fulfill all of the below criteria, and where upon button click it would take them to particular activity page.
ParseQuery<ParseObject> query = ParseQuery.getQuery("User");
query.whereNotEqualTo("objectId", ParseUser.getCurrentUser()
.getObjectId());
// users with Gender = currentUser.Looking_Gender
query.whereEqualTo("Gender", userLookingGender);
// users with Looking_Gender = currentUser.Gender
query.whereEqualTo("Looking_Gender", userGender);
query.setLimit(1) ;
ParseGeoPoint point = ParseUser.getCurrentUser().getParseGeoPoint("location");
query.whereWithinKilometers("location", point, mMax_Distance.doubleValue());
query.whereEqualTo("ActivityName", activityName);
query.whereGreaterThanOrEqualTo("UserAge", minimumAge);
query.whereLessThanOrEqualTo("UserAge", maximumAge);
Update 3:
Android Code
ParseCloud.callFunctionInBackground("sendPushToNearbyAndMatching", new HashMap<String, Object>(), new FunctionCallback<String>() {
public void done(String result, ParseException e) {
if (e == null) {
// success
}
}
});
Parse Cloud JavaScript code (found in cloud/main.js)
The owner column in this case is users
// Use Parse.Cloud.define to define as many cloud functions as you want.
// For example:
Parse.Cloud.define("hello", function(request, response) {
response.success("Hello world!");
});
Parse.Cloud.define("sendPushToNearbyAndMatching", function(request, response) {
Parse.Cloud.useMasterKey();
// the authenticated user on the device calling this function
var user = request.user;
// the complex query matching users
var query = new Parse.Query(Parse.User);
query.whereNotEqualTo("objectId", user.id);
// users with Gender = currentUser.Looking_Gender
query.equalTo("Gender", user.get("Gender"));
// users with Looking_Gender = currentUser.Gender
query.equalTo("Looking_Gender", user.get("Looking_Gender"));
query.equalTo("ActivityName", user.get("ActivityName"));
query.greaterThanOrEqualTo("UserAge", user.get("Minimum_Age"));
query.lessThanOrEqualTo("UserAge", user.get("Maximum_Age"));
query.limit(1);
query.each(function(user) {
// sendPushNotification is added in next code section
return sendPushNotification(user);
}).then(function() {
response.success("success!");
}, function(err) {
response.error(err);
});
});
var sendPushNotification = function(user) {
var query = new Parse.Query(Parse.Installation);
query.equalTo('users', user);
return Parse.Push.send({
where : query, // send to installations matching query
expiration_interval : 600, // optional - expires after 10 minutes
data : {
alert: "App says hello!",
}
})
}
Now that I have a bit more insight I think I'm ready with an answer:
I do Push from Cloud Code, and there the query matches against Installation objects, which is why having the values there as well would be useful.
It looks like you are sending directly from the app, so I would suggest creating a channel for each gender: https://parse.com/docs/push_guide#sending-channels/Android
Then you just need to:
String userLookingGender = ParseUser.getCurrentUser().getString(
"Looking_Gender");
ParsePush push = new ParsePush();
push.setChannel(userLookingGender);
push.setMessage("Your message");
push.sendInBackground();
Update:
Ok. the multiple queries indeed make matters more complicated.
I think you would have to move on to Cloud Code to perform such an advanced query push (which is by the way recommended for security reasons).
Cloud Code guide: https://parse.com/docs/cloud_code_guide
Embrasing the fact that users can have multiple devices, you need to be able to fetch all the installations associated with a user. To do this I would suggest saving a pointer to User on each installation. You can do this as part of the first login of your app.
Assuming you have a, say, owner column in your installation pointing to the respective User owning the device, then you can do something like this in Cloud Code:
Parse.Cloud.define("sendPushToNearbyAndMatching", function(request, response) {
Parse.Cloud.useMasterKey();
// the authenticated user on the device calling this function
var user = request.user;
// the complex query matching users
var query = new Parse.Query(Parse.User);
query.whereNotEqualTo("objectId", user.id);
// users with Gender = currentUser.Looking_Gender
query.equalTo("Gender", user.get("Gender"));
// users with Looking_Gender = currentUser.Gender
query.equalTo("Looking_Gender", user.get("Looking_Gender"));
query.limit(1);
... etc
// execute the query
// i am using each just to show an convenient way to iterate the results
// instead of setting limit(1) consider executing the query using first() instead
// android SDK has a getFirstInBackground() as well
query.each(function(user) {
// sendPushNotification is added in next code section
return sendPushNotification(user);
}).then(function() {
response.success("success!");
}, function(err) {
response.error(err);
});
});
About querying User in javascript: https://parse.com/docs/js_guide#users-querying
How to call this Cloud function from Android: https://parse.com/docs/android_guide#cloudfunctions
Now it is time to send out the notifications to the devices owned by the user:
var sendPushNotification = function(user) {
var promise = new Parse.Promise();
var query = new Parse.Query(Parse.Installation);
query.equalTo('owner', user);
query.count().then(function(count) {
console.log("sending push to " + count + " devices");
Parse.Push.send({
where : query, // send to installations matching query
expiration_interval : 600, // optional - expires after 10 minutes
data : {
alert: "App says hello!",
}
}).then(function() {
// success
console.log("push success");
promise.resolve();
}, function(error) {
console.error(error.message);
promise.reject(error);
});
});
return promise;
}
For more advanced pushes (if you for instance want to receive a broadcast to handle some data) see: https://parse.com/docs/push_guide#sending-queries/JavaScript
Also, if you decide to fiddle with Cloud Code and thereby javascript, I would highly recommend having a look at how promises work. This makes your life so much easier when handling asynchronous calls, for instance when issuing queries: https://parse.com/docs/js_guide#promises
This is all a lot of information and probably a lot to take in all at once if it is new to you, but I think it will be all worth it, I know it was for me.

Get an array of user photos using FQL

I'm to get a list of the users photos (one's they've been tagged in) using FQL.
Basically I've go an array object like so: _imageAddressArray.
I can retrieve the users' photos using graphApi so I know it works, problem with graphAPi is that it's too slow (+15 seconds min for 100 photos).
So far I've got:
//New Stuff
FQL fql = new FQL(facebook);
String FQLResult = null;
try
{
_userGallery = graphApi.getPhotosMy(_noOfPhotos);
FQLResult = fql.fqlQuery("SELECT object_id, src_small FROM photo");
}
catch (EasyFacebookError e)
{
e.printStackTrace();
}
System.out.println("FQL Result" + FQLResult);
This returns the error: 601, any ideas anyone?
Of course ideally FQLResult will be a string[] (string array)
You're getting an error because you don't have a WHERE clause in your FQL statement that references one of the indexed columns -- shown with a "*" here
To get the photos using FQL that your user has been tagged in, try this:
SELECT object_id, src_small FROM photo WHERE object_id IN
(SELECT object_id FROM photo_tag WHERE subject = me())

Facebook FQL: uid of friends

I'm using restfb 1.6.5 (the same problem in 1.6.4) and have problems getting the uids of my friends. This works fine (me-query):
User fbUserMe = fbClient.fetchObject("me", com.restfb.types.User.class);
logger.debug(fbUserMe.getId());
The response body contains something like: {"id":"1234","name":"ME" ...} and fbUserMe.getId() returns my uid. With the next code snipped I want to get the uids of my friends (friends-query):
StringBuffer sb = new StringBuffer();
sb.append("SELECT uid, first_name, last_name FROM user");
sb.append(" WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
List<User> users = fbClient.executeQuery(sb.toString(), User.class);
for(User fbUser : users)
{
logger.debug(fbUser.getId());
}
But this always outputs null, although the response body contains this: [{"uid":5678,"first_name":"Peter" ...} ...].
The obvious difference in the response by is id=1234 for the me-query and uid=5678 for the friends-query. If I use a custom class FqlUser like described in RestFB I'm able to get the uid. Now I'm uncertain of the uid. Do I really get same same id (the same my friend would get in a me-Query) or do I get something like the third_party_id described in Facebook: FQL-user?
You're getting the uid. The same id your friend would get in a "me query".

Categories