Factual crosswalk api, can I get a place's foursquare venue id with its corresponding facebook page id in 1 request? - factual

I have a database full of places with the facebook page id's. I'd like to map them to the corresponding foursquare venue id with the factual api.
The problem is when I try to issue a request and set the namespace id to the facebook id all I get back is the entry that factual has with the factual_id and facebook id but not any other third party places with the same factual id.
What I'm doing now is saving the factual id, and then sending another request given the factual_id which returns all the crosswalk entries then I can look for the foursquare one. Is there anyway to do this request in 1 step?
Using php here is the code.
The place variable is a object that is basically mapped to a facebook page
$place = Model_Place::find(42);
$factual = new \Factual(\Config::get('factual_oauth_key'), \Config::get('factual_oauth_secret'));
$query = new \FactualQuery;
$query->limit(1);
$query->field("namespace")->equal("facebook");
$query->field("namespace_id")->equal($place->page_id);
$res = $factual->fetch("crosswalk", $query);
$data = $res->getData();
echo "<pre>";
print_r($data);
echo "</pre>";

Related

Twitter - Upload Image Using API and Get URL

I am creating a twitter share button that a user can click but I also want to attach an image to the tweet.
I am uploading the image to Twitter using the API so have the media ID available.
Is there a way to get the URL from this ID so I can attatch it to a Twitter Intent link?
Or can I only use this Media ID with the API to post a tweet for an authenticated user?
I am trying to attatch a Twitter hosted Image to a Share button so that anybody can post it to their Twitter feed
Before you can attach the image to a tweet, you would need to upload the image to twitter first. I think you are already doing this using the endpoint media/upload
Reference:
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
Once this is done issue another POST request to the endpoint statuses/update with parameters 'status' and 'media_ids'. Twitter expects a comma separated list of media_ids. You already have this in the object returned by media/upload endpoint.
Reference:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
The object returned in the above call has the url for each media uploaded under the property entities.
This is an excerpt from how I did using PHP and abrahamoauth library. $connection is the twitter connection object.
$media = $connection->upload('media/upload', array('media' => $_FILES["tweet_image_file"]["tmp_name"]));
$parameters = array(
'status' => '',
'media_ids' => implode(',', array($media->media_id_string)),
);
$result = $connection->post('statuses/update', $parameters);
//$image_url = $result->entities->media[0]->media_url; //stopped working from July 2015
$image_url = $result->entities->media[0]->url;

Get a guest user by userPrincipalName with Microsoft Graph

I am playing with Microsoft Graph to access Azure Active Directory from my application, using the REST API directly (without an SDK).
According to the documentation, I should be able to retrieve a user from their id or userPrincipalName using /users/{id | userPrincipalName}.
This is indeed working, but not for Guest users. With Guest users the userPrincipalName is something like name_originaldomain#EXT##mydomain.onmicrosoft.com, and trying to get the user results in a 404 Not Found.
This is the code I am currently using:
graphClient = new HttpClient();
graphClient.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/");
graphClient.DefaultRequestHeaders.Add("Authorization", $"{token.TokenType} {token.AccessToken}");
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get,
$"users/{Uri.EscapeUriString(username)}"
);
HttpResponseMessage response = await graphClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<UserResult>();
}
// I am here with a 404
Am I missing something or doing something wrong?
An alternative is to create a bigger query that also queries on the mail property with the guest user's email address (or in your case what you have as "name#originaldomain"). For guest users, we set the mail property to the guest's email address.
../users?$filter=mail eq 'name#originaldomain'
Hope this helps,
You need to URL Encode the userPrincipalName. Otherwise you're effectively passing name_originaldomain since the # designates everything beyond that point as a URI Fragment.
Try using name_originaldomain%23EXT%23%40mydomain.onmicrosoft.com

How to make batch request using fb_graph?

when a user login using facebook then i need collect all the movies list liked by the user and his/her friends.
user = FbGraph::User.fetch('me', :access_token => "access_token")
userFrnd = user.friends
movies=[]
userFrnd.each do | uf |
frnd = FbGraph::User.fetch(uf.raw_attributes['id'], :access_token => "access_token")
movies << frnd.movies
end
final_movie_list = movies.flatten.uniq_by {|track| track.raw_attributes["id"]}
this is my fb_graph function and it's working fine.but i need to make it as batch request since the i have 360 friend it take 360 request to process the above function correctly.but help me out to optimize this and reduce the time it takes to calculate this function.
I came to know that batch request may help me but,i don't know how to do that in fb_graph.
Please help me
I'm using FbGraph from ( github.com/nov/fb_graph ) Version: 2.7.8 and I'm able to make a batch request for 100 users, at a time and get following information about them by default.
I'm not using any access token. So you might be able to get more information including movies.
id
name
first_name
last_name
link
username
gender
locale
Here's the demonstration code where ids is an array of Facebook User Ids:
r = FbGraph::User.fetch("?ids=#{ids.join(",")}")
r.raw_attributes #information about the users hashed by their id (String)

Using Twitter OAuth to authenticate API calls for trends

I am working on a website that allows the user to search for the top ten twitter trends in a city or country. At first I was only relying on Twitter's Rest API, but I was having a lot of rate limit issues (at school my rate limit disappears faster than I have a chance to use it). I know that authenticating my API calls will help me to better deal with this issue (Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment).
I implemented #abraham's PHP library (https://github.com/abraham/twitteroauth), unfortunately my API calls aren't being authenticated. I know I have implemented #abraham's PHP library, because it prints out my user information at the end like it should. I have my twitter trend search underneath it but the API call isn't being authenticated. I am not sure how to fix this, and any help would really be appreciated!
This is what I use to get the top ten trends by country:
function showContent(){
// we're going to point to Yahoo's APIs
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// the following code should only run if we've submitted a form
if(isset($_REQUEST['location']))
{
// set a variable named "location" to whatever we passed from the form
$location = $_REQUEST['location'];
// Form YQL query and build URI to YQL Web service in two steps:
// first, we show the query
$yql_query = "select woeid from geo.places where text='$location'";
// then we combine the $BASE_URL and query (urlencoded) together
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
//var_dump($location);
// show what we're calling
// echo $yql_query_url;
// Make call with cURL (curl pulls webpages - it's very common)
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results as $result){
//var_dump($result);
$woeid = $result[0]->woeid;
if (is_numeric ($location))
{
echo "<span style='color:red; padding-left: 245px;'>Please enter a city or a country</span>";
}
else if(empty($result)){
echo "No results found";
}
else {
/* echo "The woeid of $location is $woeid <br />"; */
}
}
}
$jsontrends=file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json");
$phpObj2 = json_decode($jsontrends, true);
echo "<h3 style='margin-top:20px'>TRENDS: ".$phpObj2[0]['locations'][0]['name']."</h3> \r\n";
$data = $phpObj2[0]['trends'];
foreach ($data as $item) {
echo "<br />".$item['name']."\r\n";
echo "<br /> \r\n";
}
if(empty($item)){
echo "No results found";
}
}
}
I then add it to #abraham's html.inc file (along with some php to see the rate limit status) and html.inc is included in the index.php:
<h1>Top Twitter Trends</h1>
<form name='mainForm' method="get">
<input name='location' id='location' type='text'/><br/>
<button id='lookUpTrends'>Submit</button>
</form>
<?php showContent();
$ratelimit = file_get_contents("http://api.twitter.com/1/account/rate_limit_status.json");
echo $ratelimit;
?>
</div>
#abraham's index.php file has some example calls, and since my call doesn't look like this I think that is probably why it isn't being authenticated.
/* Some example calls */
//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
//$connection->post('statuses/destroy', array('id' => 5437877770));
//$connection->post('friendships/create', array('id' => 9436992));
//$connection->post('friendships/destroy', array('id' => 9436992));
Please help me find what I need to fix so that my API calls are authenticated.
update 10-21
I think in order to make an authenticated API call I need to include something like this is my code:
$connection->get('trends/place', array('id' => $woeid));
It didn't fix my problem, but maybe it is on the right track?
First off, you'll find that keeping your PHP and HTML separate will really help streamline your code and keep logical concerns separate (aggregating the data and displaying it are two different concerns)(many PHPers like MVC).
The code you have shared appears to be correct. My guess is that the issue lies in the creation of the OAuth connection, which should look something like:
<?php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token,$secret);
Where CONSUMER_KEY and CONSUMER_SECRET are from your Trends Test app and $token and $secret are from the user signing in to twitter and allowing your app permission. Are all these values showing up when you create the TwitterOAuth object?
Also, be sure you update the config items in the twitteroauth.php file (specifically line 21 should be set to use the 1.1 API and line 29 should be set to 'json').

Twitter: Twitter4j User's Country

I'm using twitter4j to get the location of a Twitter user:
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
long id = accessToken.getUserId();
User user = twitter.showUser(id);
System.out.print("LOCATION: " +user.getLocation());
user.getLocation() does not include the country. How to get the user's country using twitter4j?
There's no separate field for a user's country. Whatever information is set in the Location field on your Twitter Profile page should be returned by the getLocation() method.
One thing I noticed about your code is that you're not showing how the accessToken variable is initialized. Try the following:
Twitter twitter = new TwitterFactory().getInstance();
long id = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET).getUserId();
User user = twitter.showUser(id);
System.out.print("LOCATION: " + user.getLocation());
Where ACCESS_TOKEN and ACCESS_TOKEN_SECRET are the values you get after granting your application permission to access your Twitter account on your Twitter Developers page. When I run the code above I get the expected: "LOCATION: Charlotte, NC USA"

Resources