I'm trying to build an app using Google photos API, in which given a person's image, I can get all the images of him/her from Google photos - google-photos

I'm a newbie and this is my first project on this topic. Google photos group the images based on faces. I want to fetch, set of all photos associated to a given person or set of photos in which the person is present. Is it possible to do this? How to go about doing this and if you could please specify a good source from where I can get better understanding of the API.
Thanks in advance!

Try This Code
call onAuthPhotoApiLoad function on button click
**also include js of google **
var scopeApi = ['https://www.googleapis.com/auth/photoslibrary', 'https://www.googleapis.com/auth/photoslibrary.readonly', 'https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata'];
function onAuthPhotoApiLoad() {
window.gapi.auth.authorize(
{
'client_id': "Put Client ID Here",
'scope': scopeApi,
'immediate': false
},
handlePhotoApiAuthResult);
}
function handlePhotoApiAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
GetAllPhotoGoogleApi();
}
}
function GetAllPhotoGoogleApi() {
gapi.client.request({
'path': 'https://photoslibrary.googleapis.com/v1/mediaItems:search',
'method': 'POST',
'body': {
"filters": {
"mediaTypeFilter": {
"mediaTypes": ["PHOTO"]
}
}
}
}).then(function (response) {
console.log(response);
}, function (reason) {
console.log(reason);
});
}

Related

Access to fetch at 'API_Gateway_URL' from origin 'S3_host_url' has been blocked by CORS policy

I know this question has been asked previously but I couldn't find any answer that solves my problem, so please forgive me if it is repetitive.
I have created a Lambda function that reads data from a DynamoDB table. I created an API gateway for this Lambda function.
When I directly hit the url in my browser, I get the expected result. But when I fetch the URL in my react app, I'm getting the below error(I have hosted my react app on S3 bucket with static website hosting)
Access to fetch at 'API_gateway_url'
from origin 'S3_static_website_endpoint' has been blocked
by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
On searching the web, I found out that I need to set the 'Access-Control-Allow-Origin' header in my Lambda and I have done it, but still I'm getting the same issue.
PS: I'm posting this question after 1 whole day of trial-error and looking at different answers, so if you know the answer please help me!
Lambda function:
console.log('function starts');
const AWS = require('aws-sdk');
const dynamoDB = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
function formatResponse(data, code) {
return {
statusCode: code,
headers: {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Credentials" : true,
"Access-Control-Allow-Headers":"X-Api-Key"
},
body: JSON.stringify(data)
}
}
let param = {
TableName: 'tableName',
Limit: 100 //maximum result of 100 items
};
//Will scan your entire table in dynamoDB and return results.
dynamoDB.scan(param, function(err,data){
if(err){
return formatResponse(data, 400);
}else{
return formatResponse(data, 200);
}
});
}
React app:
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: {}
};
}
async componentDidMount() {
try {
const response = await fetch('API_gateway_url');
let responseJson = await response.json();
this.setState(
{
isLoading: false,
dataSource: responseJson
},
function () { }
);
} catch (error) {
console.error(error);
}
}
render() {
let { dataSource } = this.state;
if (this.state.isLoading) {
return <div>Loading...</div>;
} else {
return (
<div>
{dataSource.Items.map(item => (
<div key={item.PlayerId}>
<h1>{item.PlayerId}</h1>
<li>{item.PlayerName}</li>
<li>{item.PlayerPosition}</li>
<li>{item.PlayerNationality}</li>
</div>
))}
</div>
);
}
}
}
export default App;
I suspect that your Lambda is not run for OPTIONS requests (i.e. a "preflight"). You can configure CORS in your API Gateway which should resolve the problem. See Enabling CORS for a REST API resource.
This was resolved by using the cors package.
Implementation can be found here:
https://epsagon.com/blog/aws-lambda-express-getting-started-guide/

How to choose the image size when using FB.api(me/friends), into Facebook Graph API?

I'm using that snippet below to get info of my contacts, works fine, I just need to know how to change the size of the picture I get, currently I'm getting a very small pic. I searched through Facebook docs and found nothing.
FB.api('/me/friends', { fields: 'id, name, picture', limit: 3 }, function(response)
{
if (response.error)
{
alert(JSON.stringify(response.error));
}
else
{
alert("Loading friends...");
console.log("fdata: " + response.data);
response.data.forEach(function(item)
{
// feeding my html
});
}
});
Thanks!
Ps.: I'm using a Phonegap plugin to use Facebook API. Probably, the JS methods I'm calling are calling Java methods, so, I don't know which especifically API I'm using, but seems to me the default Graph Api.
I use /user_id/picture?type=large for profile pics.
http://developers.facebook.com/tools/explorer/135669679827333/?method=GET&path=732484576%2Fpicture%3Ftype%3Dlarge
refer to http://developers.facebook.com/docs/reference/api/#pictures
in your case do not call the pictures of the friends, use the id instead
in your html build the image
<image src="https://graph.facebook.com/user_id/picture?type=large&return_ssl_results=1" />
Example:
<div id="friends"></div>
<script>
FB.api('/me/friends', { fields: 'id, name', limit: 3 }, function(response)
{
if (response.error)
{
alert(JSON.stringify(response.error));
}
else
{
alert("Loading friends...");
console.log("fdata: " + response.data);
response.data.forEach(function(item)
{
document.getElementById('friends').innerHTML+='<image src="https://graph.facebook.com/'+item['id']+'/picture?type=large&return_ssl_results=1" />';
document.getElementById('friends').innerHTML+='<br />'+item['name']+'';
});
}
});
</script>
You can go with either of the following 4 based on your needs
FB.api('id?fields=picture&type=large');
or
FB.api('id?fields=picture&type=small');
or
FB.api('id?fields=picture&type=square');
or
FB.api('id?fields=picture&type=normal');

Update / Delete a tab from a facebook page using the Graph API returns "(#210) Subject must be a page."

I am trying to delete an application tab from a facebook page.
According to the documentation, I should issue a DELETE request to "https://graph.facebook.com/PAGE_ID/tabs/TAB_ID" with a PAGE access token, but when I do so I get the error "(#210) Subject must be a page."
The same happens when trying to update a tab.
I have requested the user for "manage_pages" permission and I have the correct access_token (Adding a tab works perfectly).
the exact request is: https://graph.facebook.com/212757048770606/tabs/app_289329597785433 (with an access token)
Does anyone know what am I doing wrong?? or is there an open bug report?
Thanks alot
I don't have a solution for you, but I do know that I had some problems with removing a tab that boiled down to the fact that the tab's ID (returned from a call to get /PAGE_ID/tabs) already includes the page ID and "tabs" path.
Initially I was building my URL by taking the tab ID and sticking it on the end of /PAGE_ID/tabs/, but that didn't work because the URL ended up being something like /12345/tabs/12345/tabs/app_4567. Once I realized that the tab ID was sort of "compound" already, I got the Remove to work.
Add the page access token to the call of Facebook API
var PageAccessToken = 123456789123456789123456789123456789;
FB.api(
"/{page_id}/tabs",
"POST",
{
"object": {
"app_id": "{page_id}"
}
},{
"access_token": PageAccessToken
},
function (response) {
if (response && !response.error) {
console.log(response);
} else {
console.log(response.error);
}
}
);
function DeleteTabPage(){
var pid = page_id;
var at = access_tocken;
debugger;
FB.api(pid + '/tabs/app_{your app id}', 'DELETE', { app_id: your app id, access_token: at }, function (response) {
debugger;
if (!response || response.error) {
debugger;`enter code here`
alert('Facebook add app error ' + response.error);
} else {
console.log(response);
debugger;
// alert('App has been added');
}
}); /* end of page/tabs*/
}

pages.isFan returns incorrect signature

I am working on a Facebook canvas iFrame application, and I`m going insane.
I am trying to check if a user is a fan of the page where the app is located, so that I can allow or disallow voting.
I use the following code:
function CheckFan() {
FB.init({
appId: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
FB.api({ method: 'pages.isFan', page_id: '145116742177104' }
, function(resp) {
if (resp) { $('#main_frame').show(); $('#non_fan').hide(); }
else { $('#main_frame').hide(); $('#non_fan').show(); }
});
}
This JS SDK is driving me up the wall, while calling the documentation "incomplete" is an insult to incompleteness.
Any input will be appriciated.
Thank you!
-Elad
This has been deprecated by Facebook.
A new Graph API alternative will hopfuly be available by the time we need to deploy the app.
For now I use FQL:
FB.api({ method: 'fql.query', query: 'SELECT uid FROM page_fan WHERE uid= ' + user_id + ' AND page_id=145116742177104' },
function(result) {
if (result.length)
{ $('.main_frame').show(); $('#non_fan').hide(); } else { $('.main_frame').hide(); $('#non_fan').show(); }
});

facebook application API check if user is application admin in facebook

i have:
user facebook data (
https://graph.facebook.com/btaylor )
facebook application data (
https://graph.facebook.com/2439131959
)
Is somehow possible to get if user is application administrator in facebook with this in my hands?
To get this kind of information you can use FQL:
protected function authorizeByFb(){
$result = $this->fb->api(array(
'method' => 'fql.query',
'query' => "SELECT developer_id FROM developer WHERE application_id='{$appId}' AND developer_id='{$fbUserId}'",
));
if(count($result)==1){
return true;
}
return false;
}
if your developed application is checking the role of the logged in facebook user or simply your application wants to recognize it's owner or admin,
then
http://developers.facebook.com/tools/explorer/?method=GET&path=me%2Faccounts should have that application id listed
api call:
FB.api('/me/accounts', 'get', {"access_token":access_token}, function(response){
//loop through response to check any application id matches current application id
});
response sample:
{
"name": "app_name",
"access_token": "current_token_here",
"category": "Application",
"id": "your_owned_app_id"
},
{
"name": "app_name1",
"access_token": "current_token_here",
"category": "Application",
"id": "your_owned_app1_id"
},
I just got this to work using the Facebook JS API:
FB.api({ method: 'pages.isAdmin', page_id : fbAppId }, function(response){
if(response){
alert('the user is an admin');
}else{
alert('the user is not an admin')
}
});
It's using the FB.api method to access the old REST API. This assumes that you've already called FB.init, so make sure that this comes after your init code.
Cheers,
Jeremy
You can get the signed_request and then check if page_admin = 1
<?php
$signed_request = $facebook->getSignedRequest();
$page_admin = $signed_request["page"]["admin"];
if ( $page_admin == 1 ){
echo 'Welcome Admin!';
}
?>
I tried to attempted javascript form above and found this method to work as an alternative now that the old restful api is depreciated.
function checkAdmin(fbUID, fbAppID){
FB.api({
method: 'fql.query',
query: 'SELECT role FROM app_role WHERE developer_id ='+fbUID+' AND application_id = '+fbAppID
},
function(response) {
if(response.length){
alert('User is an Admin');
}
else{
alert('User is not an Admin')
}
});
}