How to get image url from tweets using the Twitter API - image

I'm using this code:
require_once ("twitteroauth.php");
define('CONSUMER_KEY', 'XXX');
define('CONSUMER_SECRET', 'XXX');
define('ACCESS_TOKEN', 'XXX');
define('ACCESS_TOKEN_SECRET', 'XXX');
$toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$query = array(
"q" => "#Misiones",
"result_type" => "recent",
"include_entities" => "true"
);
results = $toa->get('search/tweets', $query);
foreach ($results->statuses as $result) {
$user = $result->user->screen_name;
$text = $result->text;
To get tweets whit the hashtag #Misiones(the name of the place where i'm live). Works fine but i'm trying to get the image url (if the tweet have some).
I tryed with $result->media and $result->media->media_url and other convinations without succcess.

Tweet Entities are what you are looking for to access the pictures. Entities provide structured data from Tweets including expanded URLs and media URLs. They are located under the entities attribute in all Tweet objects from both Twitter REST and Streaming APIs.
As a result, to answer your question, if a Tweet contains one picture, its URL will be located here:
$media_url = $result->entities->media[0]->media_url;
Below is a PHP snippet you can add to your existing foreach loop, it is a bit more elaborate to handle whether or not the Tweet contains media URLs:
if (isset($result->entities->media)) {
foreach ($result->entities->media as $media) {
$media_url = $media->media_url; // Or $media->media_url_https for the SSL version.
}
}

To get the media_url back to twitter search pass tweet_mode=extended. Works across multiple endpoints (eg. /statuses/show, /statuses/user_timeline ..)
Example: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=aneon&tweet_mode=extended
More here: https://developer.twitter.com/en/docs/tweets/tweet-updates.html

To get the image url of a Tweet with the new v2 api you must append expansions=attachments.media_keys&media.fields=url at your url.
For example to open a stream that returns tweets with their images(if any) create a get request like this
https://api.twitter.com/2/tweets/search/stream?tweet.fields=created_at&expansions=attachments.media_keys&media.fields=url

To get an image url of a tweet, you need a tweet object and a media object. The media object can be obtained with a tweet id.
https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/media

Related

Can get a few image's path from my database but asking more than 9 give me an internal server error

I'm in a web developpement internship, i have to work on a project under symfony 3.2 but i wasn't train on symfony, anyway, i discovered it on my own during the last two weeks (cause the persons who were supposed to help me don't know symfony and haven't work on the project) and here i'm facing a problem that i don't understand, the website is a nearly social network, and i have to work on the showings of user's posts by criteria's, if i get only a few post, no problems, i have the data the image's and evrything i asked, if i don't set a limit (with setMaxResults() ) i get an internal server error.
So i want to get the profile's image from posts's authors, i get the posts that i want within all related informations (like author), i get them with a function in my postRepository. Then, in my controller, when i try to extract some information (like author's image's path), with the method: $author->getImage()->getSrc(); here, if i'd setted less than 9 results in my postRepository query, it work perfectly, but if i don't want to set a limit, or if i want to set a bigger limit than 9 i got an:"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
in my postRepository
public function getLastFiveCommunityPosts($community) {
return $this->createQueryBuilder('post')
->join('post.communities', 'comm')
->where('comm.id = :commu')
->setParameter('commu', $community)
->orderBy('post.createdAt', 'DESC')
//->setMaxResults(9) work perfectly
//->setMaxResults(25) don't work
->getQuery()
->getResult();
in my controller
foreach ($posts as $post) {
$author = $post->getAuthor();
$img = $author->getImage();//->getSrc();!!!!!HERE IS MY PROBLEM!!!!!
$test = (null !== $img)? true : false;//what i just tried to test if getImage() return a null object, and no, on all post it returns true.
$reTest = (null !== $img->getSrc())? true : false;// and this make me have an internal server error(if i don't set a maxResult between 1 and 9)
$data[] = [
'community' => $community->getName(),
'postContent' => $post->getContent(),
'postDate' => $post->getCreatedAt(),
'authorFstName' => $author->getFirstName(),
'authorLstName' => $author->getLastName(),
'authorJob' => $author->getJob(),
'authorImg'=> $img
];
}
return new JsonResponse($data);
}
the project is using sw3 bucket and i think images that i want are hosted in this bucket. maybe there is a correct method to get them massively?
Okay so the problem was that all of my image object wasn't the same (due to old version's remaining profile) i found this method to test the image object:
$test = property_exists($img, 'src'); //return true if it's an old object with src relate on him, return false if it's an object with the ->getSrc() method
so if it returns true, i send $img, and if it's returning false, i send $img->getSrc()!!! thanks a lot to JessGabriel you send me on the right way!

How to retrieve respons status from Street View Image Metadata using guzzle

I am using guzzle to call to Street View Image API from my laravel application. I want to be able to retrieve the status code from my request as explained in the end of the docs.
I specifically want to catch the:
{
"status" : "ZERO_RESULTS"
}
here is my Guzzle code from my controller (am including guzzle correctly in namespace). The address in the get call is generating a "Sorry we have no imagery here":
$client = new Client();
$res = $client->get('https://maps.googleapis.com/maps/api/streetview?size=800x600&location=78.648401,14.194336&key=my-API-key&fov=120&heading=90');
$res->getStatusCode();
dd($res->getBody());
BUT. As u can see in the pic the meta-data is empty. When I dd the $res->getStatusCode(); it gives me a 200.
How do I catch the ZERO_RESULT ?
Sir, please note that there are two different endpoints; one for metadata and one for image retrieval. You only used the image retrieval. Here is an example method checking if a given coordinate has an image
private function coordinateHasImage($coordinate)
{
$client = new Client();
$res = $client->get( 'https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=' . $coordinate . '&fov=90&heading=235&pitch=10&key=YOUR_KEY_HERE');
return json_decode($res->getBody()->getContents())->status == "OK";
}

How to include an association with a user

I need to return a json object to my view. I see my subscriptions in tinker:
\App\User::find(1)->with('subscriptions')->where('id', 1)->get();
In my view, I get my user data but the subscriptions array is emply (length: 0)
Issue one, why I could not just \App\User::find(1)->with('subscriptions')->get() This returns all users in my database.
How can I return, as json, the current user with subscriptions? The long way is to make two api calls.
Im using Cashier for the subscriptions
Try to check the query log by running
\DB::enableQueryLog();
$data = \App\User::with('subscriptions')->find(1);
$query = \DB::getQueryLog();
dd($query);
It will show you what queries running behind the seens.
then for the json format try to decode into json and then pass to view.
$json_format = json_encode($data);
return view('user.index')->withJsonFormat($json_format);
Don't know why you want to pass the data with json format. but if you want to pass this into javascript, jquery or angular please create saperate API and call with AJAX.
The correct query is:
App\User::with('subscriptions')->find(1)
It will return User object with this user's subscriptions.

Merge URL parameters and generate a encrypted URL - Laravel 5.3

I have a URL like http://localhost:8000/assessment/3/199
Where 3 represents assignment id and 199 represents assessor id, in short they both represents two models.
I'm sending such URL into email. I want to first encrypt the URL and then send it to the email.
I want URL like http://localhost:8000/assessment/{some-long-random-string}
So, I want to merge both the parameters, make an encrypted string, send into email, upon accessing the URL decrypt it and get both actual parameters.
I would like a solution which uses Laravel to implement that.
May be using these:
https://laravel.com/docs/5.3/encryption
https://laravel.com/docs/5.3/hashing
The way I would tackle this, is by manually implementing it in a controller.
Generate the URL like this:
$url = URL::action('AssessmentController#decrypt', json_encode([
'assessment' => $assessment_id,
'assessor' => $assessor_id
]);
//now, use $url in your email
Create a route like:
Route::get('/assessment/{ciphertext}', 'AssessmentController#decrypt');
In the controller:
public function decrypt($ciphertext){
$params = json_decode(decrypt($ciphertext));
return $this->getAssessment($params['assessment'], $params['assessor']);
}
Of course, you will need more integrity-checks and some error handling, but you probably get the idea.

Google Contacts API - getting image

I'm having a simple problem while retrieving user's contact's images. So I make a request to
$url = 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=9999&oauth_token=' . $accessToken;
And then I get huge JSON from which I have extracted full name and email. Then I tried getting contact's image, and haven't had any success.
I get with all contacts, and everyone has following structure:
entry [id, updated, category, title, link, gd$email].
In the link section, I got four links, of which first two are some kind of link to an image content but I cannot retrieve it.
Any body had any success in doing this kind of work !?
Tnx alot!
BTW: If some data from my case is missing, please report and I'll add it too!
EDIT: I have also tried to reach the image with URL
http://profiles.google.com/s2/photos/profile/" + userid + "?sz=" + size;
but the problem is I cannot get userId from contacts JSON.
You must call the photo endpoint and append to it a valid access token as a query parameter.
Example:
https://www.google.com/m8/feeds/photos/media/name.surname%40gmail.com/0?access_token=ACCESS_TOKEN
Docs:
https://developers.google.com/google-apps/contacts/v3/#contact_photo_management
Make a request again if the mentioned tags are available as given below.
$add = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full?alt=json&v=3.0&max-results=500&access_token='.$token->access_token");
$add->setRequestMethod("GET");
$add->setRequestHeaders(array('GData-Version' => '3.0', 'content-type' => 'application/atom+xml; charset=UTF-8; type=feed'));
$submit = $client->getIo()->authenticatedRequest($add);
$sub_response = $submit->getResponseBody();
$temp = json_decode($sub_response, true);
foreach ($temp['feed']['entry'] as $image) {
$google_contact_id = $image['link'][2]['href'];
if (isset($image['link'][0]['href'])) {
$photo = new Google_HttpRequest($image['link'][0]['href']);
$photo_val = $client->getIo()->authenticatedRequest($photo);
$photo_return = $photo_val->getResponseBody();
$imgData = base64_encode($photo_return);
$pro_image = 'data:image/jpeg;base64, ' . $imgData . '';
}
}

Resources