Get tagged photo without access token - api

I have some problem on this. Can I get public tagged photo from Instagram api without getting any code or access token?
Please share any link for reading because I cannot found any. I feel it is less knowledge about Instagram api on web.
Thanks!

You can pull public media by tag without authentication.
Take a look at the API documentation for the get /tags/tag-name/media/recent endpoint. Here's the URL: http://instagram.com/developer/endpoints/tags/#get_tags_media_recent
The documentation can be confusing, it shows using an access_token for this endpoint in the example, but it is not required. You will need to register an application and get a client ID.

I use MeteorJS and call a method server side that returns essentially the 'view source' of the instagram page. So if you can run a server side scrape on the tag url you will be able to handle the response with what i have below and it will push all the images into an array.
//server side method
Meteor.methods({
'scrapeInst':function(tag){
return Scrape.url('https://www.instagram.com/explore/tags/'+tag+'/')
}})
//client side logic
Meteor.call('scrapeInst',Session.get('params').tag,function(err,resp){
var theInstResp = resp;
cleanOne = resp.replace(/>|window._sharedData = |;</|;|#47;|<|/g,'').split('script')
var splitter = cleanOne[22].split(',');
var theArr = [];
_.each(splitter,function(e){
var theFinal = {};
var theS = e.split(":");
if(theS[0].replace(/"| |/g,'') === "display_src"){
theFinal[theS[0].replace(/"| |/g,'')] = theS[2].replace(/%22/g,'');
theArr.push(theFinal)
}
});
Session.set('photos',theArr);
setTimeout(function(){
Session.set('loading',false)
},1000)
})

Related

How to update the snippet.description on Youtube from Google Apps Script API using only the videoId?

I want to update my snippet.description on my Youtube channel using the API exposed through Google Apps Script. I know the videoId already so there is no need to create and loop through a search list like they show in the example here.
I expect to see my script complete with the new description on my Youtube video. But I get the following error message instead.
API call to youtube.videos.update failed with error: Forbidden (line 90, file "Youtube")
Code.gs
function updateVideo( data ) {
var videoId = 'foo';
var title = 'bar';
var description = 'baz';
var resource = {
id: videoId,
snippet: {
title: title,
description: description,
categoryId: '22'
}
};
YouTube.Videos.update(resource, 'id,snippet'); // this is line 90
}
What am I doing wrong?
Note
To clarify: By "only the videoId", I mean without creating a list of channels to find it like they do here.
var myChannels = YouTube.Channels.list('contentDetails', {mine: true});
Edit
This question is different because the other asks specifically about HTML. This question is not about using HTML in the description. It's about making any changes whatsoever to the description.
Summary from comments:
This is an authorization error. The account making the API request was not the same account as the owner of the YouTube video.

How to open popup with dropbox-api dropbox-js V2

I'm trying to migrate to dropbox-api v2 in my web application.
Currently I have implementation of opening popup window where user connects to his/her dropbox and I get token. Which I use to get access to files user selected in Dropbox.chooser in later steps.
But I'm having hard time to find the solution for this. I have link to all migration documents dropbox has, but there is not any word about what is the equivalent of client.authenticate() and Dropbox.AuthDriver.Popup() ?
Common Dropbox!!! I just found this issue posted in GitHub for dropbox-sdk-js, and the answer that they don't have this functionality in V2 :( it is really disappointing, i need to implement all staff myself:
https://github.com/dropbox/dropbox-sdk-js/issues/73#issuecomment-247382634
Updated
I have implemented my solution and would like to share if someone will need.
To open a popup window I use following code:
window.open(dropbox.getAuthenticationUrl("MY REDIRECT URL"), 'DropboxAuthPopup', 'dialog=yes,dependent=yes,scrollbars=yes,location=yes')
window.addEventListener('message',function(e) {
if (window.location.origin !== e.origin) {
// Throw error
} else {
// e.data Is what was sent from redirectUrl
// e.data.access_token is the token I needed from dropbox
}
},false);
Then on my page, which I specify dropbox to redirect, i put:
window.addEventListener('load', function() {
var message = parseQueryString(window.location.hash)
window.location.hash = '';
opener = window.opener
if (window.parent != window.top) {
opener = opener || window.parent
}
opener.postMessage(message, window.location.origin);
window.close();
})
Example of parseQueryString can be found from dropbox-sdk-js examples

Google place Api PlaceDetails Photo Reference

I am using Google Place Api where is on some results "photo_reference" (similar to "reference") value. I cannot find any mention about that how to use it to get that photo. I know how to use "reference" to get PlaceDetail and I am sure that usage of photo_reference will be similar, but I cannot find JSON/XML URL for this photo_reference request. Thank you for any help. Pavel
Please take a look at documentation here: https://developers.google.com/places/documentation/photos
They've just announced this new Place Photos feature
In short this is how you should use this new feature:
https://maps.googleapis.com/maps/api/place/photo?photoreference=PHOTO_REFERENCE&sensor=false&maxheight=MAX_HEIGHT&maxwidth=MAX_WIDTH&key=YOUR_API_KEY
just substitute your own values in place of:
PHOTO_REFERENCE
MAX_HEIGHT - int value from 1 to 1600
MAX_WIDTH - int value from 1 to 1600
YOUR_API_KEY
and you are done
The Places API now supports the return of one place photo if available for a Place Search request and up to ten place photos for a Place Details request.
If a photos array is returned with your request, you can pass the photo_reference from a contained photo object to a Place Photo request with the maxheight and/or maxwidth, sensor and key parameters:
https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRvAAAAwMpdHeWlXl-lH0vp7lez4znKPIWSWvgvZFISdKx45AwJVP1Qp37YOrH7sqHMJ8C-vBDC546decipPHchJhHZL94RcTUfPa1jWzo-rSHaTlbNtjh-N68RkcToUCuY9v2HNpo5mziqkir37WU8FJEqVBIQ4k938TI3e7bf8xq-uwDZcxoUbO_ZJzPxremiQurAYzCTwRhE_V0&sensor=false&key=AddYourOwnKeyHere
Please see the documentation for more details.
please bear in mind that there are no free photo requests anymore.
At this moment (November 2020), it is $7.0 for 1000 requests (if your volume is up to 100,000). Check the photo below.
Read more on Google Places billing info page.
Step 1: The URL you should use to call Google Place Photos is :
String url = https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=PHOTOREF&key=YOUR_API_KEY
Refer: https://developers.google.com/places/web-service/photos
Step 2: Since the above URL redirects to another URL, use HTTPClient, as it automatically handles redirect stuff.
Code:
DefaultHttpClient hc = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpContext context = new BasicHttpContext();
hc.setRedirectHandler(new DefaultRedirectHandler() {
#Override
public URI getLocationURI(HttpResponse response,
HttpContext context) throws org.apache.http.ProtocolException {
//Capture the Location header here - This is your redirected URL
System.out.println(Arrays.toString(response.getHeaders("Location")));
return super.getLocationURI(response,context);
}
});
// Response contains the image you want. If you test the redirect URL in a browser or REST CLIENT you can see it's data
HttpResponse response = hc.execute(httpget, context);
if(response.getStatusLine().getStatusCode() == 200) {
// Todo: use the Image response
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
Bitmap bmp = BitmapFactory.decodeStream(instream);
ImageView imageView = new ImageView(context);
imageView.setImageBitmap(bmp);
images.add(imageView);
instream.close();
}
}
else {
System.out.println(response.getStatusLine().getStatusCode()+"");
}
Hope this helps everyone.
After initiating map you can get place details with it's images
const service = new window.google.maps.places.PlacesService(map);
service.getDetails(
{
placeId: "some_place_id_here"
},
(data, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
data.photos &&
data.photos.forEach(photo => {
console.log(photo.getUrl({ maxWidth: 500, maxHeight: 500 }));
});
}
}
);
Solving the PhotoReference issue for Javascript
User #R.K solved this issue in java, however in js you need to use fetch(). Here's the code I used:
await fetch(proxyUrl+url).then(async(ref)=>{
await ref.blob()}).then((image)=>{
// do what you need to do
console.log(image)
}).catch((err)=>{
console.log(err);
})
In this, I used a heroku link for the proxyUrl and the url shown in #Chriss Green's post for url. Hope this helps anyone confused using js!

Getting LinkedIn Profile Picture

Is there an easy way to grab a users LinkedIn profile photo?
Ideally similar to how you would with Facebook - http://graph.facebook.com/userid/picture
You can retrieve the original photo size with this call:
http://api.linkedin.com/v1/people/~/picture-urls::(original)
Note that this could be any size, so you'll need to do scaling on your side, but the image is the original one uploaded by the user.
Not as easy... You need to go through OAuth, then on behalf of the member, you ask for:
http://api.linkedin.com/v1/people/{user-id}/picture-url
If you use the 2.0 version of the API (all developers need to migrate by March 1, 2019), you should use projections to expand the profilePicture.displayImage. If you do this, you will have a full JSON element displayImage~ (the '~' is not a typo) inside profilePicture with all the info you may need.
https://api.linkedin.com/v2/me?projection=(id,profilePicture(displayImage~:playableStreams))
You can see more at the Profile Picture API doc to look at the JSON response or the Profile API doc.
Once the Linkedin user authentication using OAuth 2.x is done, make a request to the people URL.
https://api.linkedin.com/v1/people/~:(id,email-address,first-name,last-name,formatted-name,picture-url)?format=json
Where ~ stands for current authenticated user. The response will be something like this ...
{
"id": "KPxRFxLxuX",
"emailAddress": "johndoe#example.com",
"firstName": "John",
"lastName": "Doe",
"formattedName": "John Doe",
"pictureUrl": "https://media.licdn.com/mpr/mprx/0_0QblxThAqcTCt8rrncxxO5JAr...cjSsn6gRQ2b"
}
Hope this helps!
I'm using OWIN in my solution so after the user allows your application to use LinkedIn credentials a simple and plain GET request to URL https://api.linkedin.com/v1/people/~:(picture-URL)?format=json, as explained before with a Bearer authorization in request headers, solved my problems.
My Startup.Auth.cs file
var linkedInOptions = new LinkedInAuthenticationOptions()
{
ClientId = [ClientID],
ClientSecret = [ClientSecret],
Provider = new LinkedInAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
// This is the access token received by your application after user allows use LinkedIn credentials
context.Identity.AddClaim(new Claim(
"urn:linkedin:accesstoken", context.AccessToken));
context.Identity.AddClaim(new Claim(
"urn:linkedin:name", context.Name));
context.Identity.AddClaim(new Claim(
"urn:linkedin:username", context.UserName));
context.Identity.AddClaim(new Claim(
"urn:linkedin:email", context.Email));
context.Identity.AddClaim(new Claim(
"urn:linkedin:id", context.Id));
return Task.FromResult(0);
}
}
};
app.UseLinkedInAuthentication(linkedInOptions);
My method to get the user's profile picture in LinkedIn:
public string GetUserPhotoUrl(string accessToken)
{
string result = string.Empty;
var apiRequestUri = new Uri("https://api.linkedin.com/v1/people/~:(picture-url)?format=json");
using (var webClient = new WebClient())
{
webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + accessToken);
var json = webClient.DownloadString(apiRequestUri);
dynamic x = JsonConvert.DeserializeObject(json);
string userPicture = x.pictureUrl;
result = userPicture;
}
return result;
}
And finally a snippet of my action that consumes the method above:
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
...
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
string accessToken =
externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:linkedin:accesstoken").Value;
model.PhotoUrl = GetUserPhotoUrl(accessToken);
...
}
I hope it could help.
Best regards
This works well for me!
Explained -
This is for a thumbnail with all other data-
https://api.linkedin.com/v1/people/~:(id,location,picture-urls::(original),specialties,public-profile-url,email-address,formatted-name)?format=json
This is for original image with all other data -
https://api.linkedin.com/v1/people/~:(id,location,picture-url,specialties,public-profile-url,email-address,formatted-name)?format=json
Just use picture-urls::(original)instead of picture-url !
This is currently being used in Gradbee
When you login to linkedin, you will get accesstoken. Use that access token and you can retrieve users data
LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
com.google.code.linkedinapi.schema.Person person = client.getProfileForCurrentUser(EnumSet.of(
ProfileField.ID, ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.HEADLINE,
ProfileField.INDUSTRY, ProfileField.PICTURE_URL, ProfileField.DATE_OF_BIRTH,
ProfileField.LOCATION_NAME, ProfileField.MAIN_ADDRESS, ProfileField.LOCATION_COUNTRY));
String imgageUrl=person.getPictureUrl();
If your goal is simply to display the photo on your site then the LinkedIn Member Profile Plugin may work out for you. It will display the photo, some additional info, along with LinkedIn branding.
Since the LinkedIn API is designed to be used only on behalf of the current logged in user it does not offer similar functionality as the facebook graph api.
This is my solution and it works very very well:
def callback(self):
self.validate_oauth2callback()
oauth_session = self.service.get_auth_session(
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()},
decoder=jsondecoder
)
me = oauth_session.get('people/~:(id,first-name,last-name,public-profile-url,email-address,picture-url,picture-urls::(original))?format=json&oauth2_access_token='+str(oauth_session.access_token), data={'x-li-format': 'json'}, bearer_auth=False).json()
social_id = me['id']
name = me['firstName']
surname = me['lastName']
email = me['emailAddress']
url = me['publicProfileUrl']
image_small = me.get('pictureUrl', None)
image_large = me.get('pictureUrls', {}).get('values', [])[0]
return social_id, name, surname, email, url, image_small, image_large, me
This may not be quite what you're asking for, but it's useful for individual investigations.
Call up the page in Firefox, left-click the menu over the background image.
Select Inspect Element(Q).
search for -target-image"
That will be the end of of id attribute in an img element.
The src attribute of that img element, will be the URL of the background image.
For me this works
image= auth.extra.raw_info.pictureUrls.values.last.first
with omniauth-linkedin gem

How do I get data from a background page to the content script in google chrome extensions

I've been trying to send data from my background page to a content script in my chrome extension. i can't seem to get it to work. I've read a few posts online but they're not really clear and seem quite high level. I've got managed to get the oauth working using the Oauth contacts example on the Chrome samples. The authentication works, i can get the data and display it in an html page by opening a new tab.
I want to send this data to a content script.
i'm having a lot of trouble with this and would really appreciate if someone could outline the explicit steps you need to follow to send data from a bg page to a content script or even better some code. Any takers?
the code for my background page is below (i've excluded the oauth paramaeters and other )
` function onContacts(text, xhr) {
contacts = [];
var data = JSON.parse(text);
var realdata = data.contacts;
for (var i = 0, person; person = realdata.person[i]; i++) {
var contact = {
'name' : person['name'],
'emails' : person['email']
};
contacts.push(contact); //this array "contacts" is read by the
contacts.html page when opened in a new tab
}
chrome.tabs.create({ 'url' : 'contacts.html'}); sending data to new tab
//chrome.tabs.executeScript(null,{file: "contentscript.js"});
may be this may work?
};
function getContacts() {
oauth.authorize(function() {
console.log("on authorize");
setIcon();
var url = "http://mydataurl/";
oauth.sendSignedRequest(url, onContacts);
});
};
chrome.browserAction.onClicked.addListener(getContacts);`
As i'm not quite sure how to get the data into the content script i wont bother posting the multiple versions of my failed content scripts. if I could just get a sample on how to request the "contacts" array from my content script, and how to send the data from the bg page, that would be great!
You have two options getting the data into the content script:
Using Tab API:
http://code.google.com/chrome/extensions/tabs.html#method-executeScript
Using Messaging:
http://code.google.com/chrome/extensions/messaging.html
Using Tab API
I usually use this approach when my extension will just be used once in a while, for example, setting the image as my desktop wallpaper. People don't set a wallpaper every second, or every minute. They usually do it once a week or even day. So I just inject a content script to that page. It is pretty easy to do so, you can either do it by file or code as explained in the documentation:
chrome.tabs.executeScript(tab.id, {file: 'inject_this.js'}, function() {
console.log('Successfully injected script into the page');
});
Using Messaging
If you are constantly need information from your websites, it would be better to use messaging. There are two types of messaging, Long-lived and Single-requests. Your content script (that you define in the manifest) can listen for extension requests:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == 'ping')
sendResponse({ data: 'pong' });
else
sendResponse({});
});
And your background page could send a message to that content script through messaging. As shown below, it will get the currently selected tab and send a request to that page.
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: 'ping'}, function(response) {
console.log(response.data);
});
});
Depends on your extension which method to use. I have used both. For an extension that will be used like every second, every time, I use Messaging (Long-Lived). For an extension that will not be used every time, then you don't need the content script in every single page, you can just use the Tab API executeScript because it will just inject a content script whenever you need to.
Hope that helps! Do a search on Stackoverflow, there are many answers to content scripts and background pages.
To follow on Mohamed's point.
If you want to pass data from the background script to the content script at initialisation, you can generate another simple script that contains only JSON and execute it beforehand.
Is that what you are looking for?
Otherwise, you will need to use the message passing interface
In the background page:
// Subscribe to onVisited event, so that injectSite() is called once at every pageload.
chrome.history.onVisited.addListener(injectSite);
function injectSite(data) {
// get custom configuration for this URL in the background page.
var site_conf = getSiteConfiguration(data.url);
if (site_conf)
{
chrome.tabs.executeScript({ code: 'PARAMS = ' + JSON.stringify(site_conf) + ';' });
chrome.tabs.executeScript({ file: 'site_injection.js' });
}
}
In the content script page (site_injection.js)
// read config directly from background
console.log(PARAM.whatever);
I thought I'd update this answer for current and future readers.
According to the Chrome API, chrome.extension.onRequest is "[d]eprecated since Chrome 33. Please use runtime.onMessage."
See this tutorial from the Chrome API for code examples on the messaging API.
Also, there are similar (newer) SO posts, such as this one, which are more relevant for the time being.