Daily Limit for Unauthenticated Use Exceeded Google Api Calendar - javascript

I'm testing a sample code. It has always worked but suddenly i get:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
Again, it has ALWAYS worked. Nothing changed. I know to set console dev stuff and blablabla. I would like to know the cause of this issue.
This is my script:
gapi.client.init({
'apiKey': 'xxxxxxxx',
'discoveryDocs': ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"],
'clientId': 'xxxx.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar',
}).then(function() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime' //from input
}).then(function(response) {
var events = response.result.items;
if (events.length > 0) {
for (var i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
appendPre(event.summary + ' (' + when + ')created at '+ event.created);
}
} else {
appendPre('No upcoming events found.');
}
});
});
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}

Even if you are not authenticating to Calendar as a user, you should create a client project and attach your key to requests so that Google has a project to "bill" the quota usage against. This will prevent these kind of issues in the future. See Google's help article but the general steps would be:
1) Create a Google API Project at https://console.developers.google.com.
2) Enable Calendar API for the project.
3) Get the API key under API Manager > Credentials.
4) Include the key as a parameter for all your Calendar API requests. E.g.
GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events?key={your_key}

Solved with "https://www.googleapis.com/auth/calendar.readonly" scope! It works again without any changes. Maybe it needs some time, but "https://www.googleapis.com/auth/calendar" still not working.

Related

The request cannot be completed because you have exceeded your quota

I tried to use the javascript MediaUploader.js to upload youtube video to my own account, for some reason, I got this error in onError function:
"errors": [
{
"domain": "youtube.quota",
"reason": "quotaExceeded",
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
],
"code": 403,
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
I only tested a few times today, but got this strange error.
var signinCallback = function (tokens, file){
console.log("signinCallback tokens: ",tokens);
if(tokens.accessToken) { //tokens.access_token
console.log("signinCallback tokens.accessToken: ",tokens.accessToken);
var metadata = {
id: "101",
snippet: {
"title": "Test video upload",
"description":"Description of uploaded video",
"categoryId": "22",//22
"tags": ["test tag1", "test tag2"],
},
status: {
"privacyStatus": "private",
"embeddable": true,
"license": "youtube"
}
};
console.log("signinCallback Object.keys(metadata).join(','): ",Object.keys(metadata).join(','));
var options = {
url: 'https://www.googleapis.com/upload/youtube/v3/videos?part=snippet%2Cstatus&key=<my api key>',
file: file,
token: tokens.accessToken,
metadata: metadata,
contentType: 'application/octet-stream',//"video/*",
params: {
part: Object.keys(metadata).join(',')
},
onError: function(data) {
var message = data;
// Assuming the error is raised by the YouTube API, data will be
// a JSON string with error.message set. That may not be the
// only time onError will be raised, though.
try {
console.log("signinCallback onError data: ",data);
if(data!="Not Found"){
var errorResponse = JSON.parse(data);
message = errorResponse.error.message;
console.log("signinCallback onError message: ",message);
console.log("signinCallback onError errorResponse: ",errorResponse);
}else{
}
} finally {
console.log("signinCallback error.... ");
}
}.bind(this),
onProgress: function(data) {
var currentTime = Date.now();
var bytesUploaded = data.loaded;
var totalBytes = data.total;
// The times are in millis, so we need to divide by 1000 to get seconds.
var bytesPerSecond = bytesUploaded / ((currentTime - this.uploadStartTime) / 1000);
var estimatedSecondsRemaining = (totalBytes - bytesUploaded) / bytesPerSecond;
var percentageComplete = (bytesUploaded * 100) / totalBytes;
console.log("signinCallback onProgress bytesUploaded, totalBytes: ",bytesUploaded, totalBytes);
console.log("signinCallback onProgress percentageComplete: ",percentageComplete);
}.bind(this),
onComplete: function(data) {
console.log("signinCallback onComplete data: ",data);
var uploadResponse = JSON.parse(data);
this.videoId = uploadResponse.id;
//this.pollForVideoStatus();
}.bind(this)
}
MediaUpload.videoUploader(options);
}
};
I checked the developer console of my quota, my quota limit is so big, there is no way I exceeded my quota, ex, I have total of 89 queries today, and my quota limit is 10,000 queries/day.
Expected: upload my video to my youtube account successfully.
Actual results: quotaExceeded
Corrupt Google Developer Project - create a new one
I am disappointed in Google that this was the case for me.
I had the same issue, no usage at all but "quota exceeded" response. My solution was to create a new project. I guess it's because something changed internally over time and wasn't applied correctly to (at least my) already existing project...
I had stopped using AWS for several reasons and thought Google Cloud would be a refreshing experience but this shows me Google treats existing projects as badly as new products that it kills off. Strike one against Google.
https://github.com/googleapis/google-api-nodejs-client/issues/2263#issuecomment-741892605
Youtube does not give you 10,000 Queries a day, they give you 10,000 units a day; a query can be multiple units, depending on what you're doing:
A simple read operation that only retrieves the ID of each returned
resource has a cost of approximately 1 unit.
A write operation has a cost of approximately 50 units.
A video upload has a cost of approximately 1600 units.
If your 89 queries contain video uploads or write operations, then that would explain your issue
More Information:
https://developers.google.com/youtube/v3/getting-started#quota

X-cross origin error on Javascript oauth2 Google calendar api

I have a website and I'm trying to create a button to add an event to Google Calendar. The button triggers this function which loads the calendar apis, loads the api, initialises it and then proceed with the oauth2 login
$.getScript("https://apis.google.com/js/api.js").done(function(script, textStatus){
gapi.load('client:auth2', function(){
gapi.client.init({
apiKey: "xxxxx",
clientId: "xxxxx",
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"],
scope: "https://www.googleapis.com/auth/calendar"
}).then(function(){
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(function(){
if(gapi.auth2.getAuthInstance().isSignedIn.get())
{
var event = {
'summary': "title",
'location': "location",
'description': "",
'start': {
'dateTime': startTime,
},
'end': {
'dateTime': endTime,
}
};
// set event
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
request.execute(function(event){
// success
});
}
else
{
// error
}
});
gapi.auth2.getAuthInstance().signIn();
});
});
}).fail(function(jqxhr, settings, exception) {
// error
});
As soon as my code executes this line:
gapi.auth2.getAuthInstance().signIn();
I get an error which looks like an x-cross origin problem
This is the error I get in the developer error console:
InAppBrowserProxy.js:42 Uncaught DOMException: Blocked a frame with
origin "xxxxxxx" from accessing a cross-origin frame.
where "xxxxxxx" is my website. I couldn't find any resource online to address the issue, the example provided by Google works fine on the same server where I tested the code above
Please note that I've already added my server domain into the Google developer console

AWS SDK can't add Lambda as target to Cloudwatch event

I am developing an application where I need to schedule a task, so I am using AWS Lambda for it.However, the scheduled time is dynamic, since it depends on the user request, it can't be scheduled using AWS Console, so I use AWS Javascript SDK to schedule it.
This is the flow:
Create a CloudWatch Rule (this is successful, I can see the rule being created in the console
Add permission to the policy of lambda, so that cloudwatch event can invoke it (Lambda function code is same for all request, so I created a lambda function in AWS Console instead of using SDK)
Add target to the rule created in Step 1 (this step fails). The error i get is RoleArn is not supported for target arn:aws:lambda:eu-west-1:629429065286:function:prebook.
Below is the Node.js code I wrote
schedule_aws_lambda: function(booking_id, cronTimeIST, callback){
var event = new AWS.CloudWatchEvents({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: 'eu-west-1'
});
var lambda = new AWS.Lambda({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: 'eu-west-1'
});
var year = cronTimeIST.utc().year();
var month = cronTimeIST.utc().month() + 1;
var date = cronTimeIST.utc().date();
var hour = cronTimeIST.utc().hour();
var minute = cronTimeIST.utc().minute();
var cronExpression = "cron(" + minute + " "+ hour + " " + date + " " + month + " ? " + year +")";
var hour_minute = cronTimeIST.format("HH_mm");
var ruleParams = {
Name: 'brodcast_' + booking_id + '_' + hour_minute,
Description: 'prebook brodcast for ' + booking_id + '_' + hour_minute,
ScheduleExpression: cronExpression,
RoleArn: 'arn:aws:iam::629429065286:role/service-role/prebook_lambda_role',
State: 'ENABLED',
};
event.putRule(ruleParams).promise()
.then(data => {
var lambdaPermission = {
FunctionName: 'arn:aws:lambda:eu-west-1:629429065286:function:prebook',
StatementId: 'brodcast_' + booking_id + '_' + hour_minute,
Action: 'lambda:*',
Principal: 'events.amazonaws.com',
};
return lambda.addPermission(lambdaPermission).promise();
})
.then(data => {
var targetParams = {
Rule: ruleParams.Name,
Targets: [
{
Id: 'default',
Arn: 'arn:aws:lambda:eu-west-1:629429065286:function:prebook',
RoleArn: ruleParams.RoleArn,
Input: JSON.stringify({booking_id: booking_id})
}
]
};
return event.putTargets(targetParams).promise();
})
.then(data => {
callback(null, data);
})
.catch(err => {
callback(err)
});
}
I know it has to do something with the Role which doesn't have some permission, I can't figure out the exact cause, I have given the following access for the role
And this is the policy document
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Basically, I want to attach many triggers(the trigger time is not known to me it depends on user request) to the lambda function, however, lambda function code is same for all.
Try removing the RoleArn property. If you are adding permissions to the Lambda function to allow CloudWatch events to invoke it, you don't need it.
In the function policy, make sure you add the SourceArn of the event.
Here's the reference from the docs that explains the error. You must use a resource policy (= Lambda permission), not an identity policy (= role) to invoke Lambda from EventBridge:
Docs: Amazon SQS, Amazon SNS, Lambda, CloudWatch Logs, and EventBridge bus targets do not use roles, and permissions to EventBridge must be granted via a resource policy. API Gateway targets can use either resource policies or IAM roles.
The Lambda AddPermission API creates the resource policy.

Events created with Calendar API not showing up in the calendar

I'm experimenting with Google Calendar API in an attempt to set reminders for users. I think setting a calendar event and setting a reminder to it could do what I need.
I'm using this sample code from google to try the API, I'm getting Back the description of the event I created. But if I sign in to my Google calendar I can't see the event there.
<!DOCTYPE html>
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<p>Google Calendar API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID ='781531190408-u3gh34li8b0um74r11m8hsbcofbpj4jf.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listUpcomingEvents();
// Refer to the JavaScript quickstart on how to setup the environment:
// https://developers.google.com/google-apps/calendar/quickstart/js
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.
var event = /*{
'summary': 'Google I/O 2015',
'location': '800 Howard St., San Francisco, CA 94103',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
'dateTime': '2017-07-28T09:00:00-07:00',
'timeZone': 'America/Los_Angeles'
},
'end': {
'dateTime': '2017-07-28T17:00:00-07:00',
'timeZone': 'America/Los_Angeles'
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees': [
{'email': 'lpage#example.com'},
{'email': 'sbrin#example.com'}
],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10}
]
}
};*/{
"reminders": {
"useDefault": false,
"overrides": [
{
"method": "email",
"minutes": 15
},
{
"method": "popup",
"minutes": 15
},
{
"method": "popup",
"minutes": 5
}
]
},
"start": {
"dateTime": "2017-07-12T10:30:00.0z"
},
"end": {
"dateTime": "2017-07-12T11:30:00.0z"
},
"description": "Just a test description "
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
request.execute(function(event) {
appendPre('Event created: ' + event.description);
});
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function(response) {
var events = response.result.items;
appendPre('Upcoming events:');
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
appendPre(event.description + ' (' + when + ')')
}
} else {
appendPre('No upcoming events found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Am I doing something wrong? Thanks.
I've tried the JavaScript Quickstart and insert an event using this sample code and I got a successful response. Maybe the problem is how you handle your authorization. You may check this tutorial.
Some additional references:
Need good example: Google Calendar API in Javascript
Events added through Google API PHP client not showing in Calendar
Google Calendar Api is not showing event list

#me called by anonymous error when using google plus api inside a gwt project

I'm using the google api javascript client to get information about the user profile inside a gwt project hosted in google app engine.
In localhost, the data is being retrieved correctly. I get a json with the google plus profile. When I deploy to appengine, the response is 401, "#me called by anonymous".
Here is my Code:
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
$(function() {
auth();
});
var API_KEY = "***************************************";
var CLIENT_ID = "************.apps.googleusercontent.com";
var scopes = 'https://www.googleapis.com/auth/plus.me';
function auth() {
var config = {
'client_id' : CLIENT_ID,
'scope' : scopes,
'key' : API_KEY,
};
gapi.client.load('plus', 'v1', function() {
api.client.setApiKey(API_KEY);
gapi.auth.authorize(config, function() {
var request = gapi.client.plus.people.get({
'userId' : 'me',
});
request.execute(function(resp) {
console.log(resp);
});
});
});
}
</script>
What i tried:
call to api.client.setApiKey at the begining.
create a new google api access with the google api console
update:
This is the complete response error message:
{
"error": {
"code": 401,
"message": "me called by anonymous",
"data": [
{
"domain": "global",
"reason": "authError",
"message": "me called by anonymous",
"locationType": "header",
"location": "Authorization"
}
]
},
"id": "gapiRpc"
}
There are other messages that may be related:
This is one of them:
Skipping duplicate osapi method definition chili.people.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition pos.plusones.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition chili.activities.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition googleapis.newHttpRequest on transport googleapis; others may exist, but suppressing warnings
this is the other:
Invalid auth token. 1025***** vs 140186****
I could finally resolve the issue with the following settings or steps:
1) In the google apis console, I left the Redirect URIs section empty and completed the JavaScript origins section with the url of my site, repeating it with the https protocol:
JavaScript origins:
http://example.com
https://example.com
I put the script that loads the api before the end body tag:
<script src="https://apis.google.com/js/client.js"></script>
This script comes inside the body, before the api script:
<script type="text/javascript">
var API_KEY = "***************************************";
var CLIENT_ID = "************.apps.googleusercontent.com";
var scopes = 'https://www.googleapis.com/auth/plus.me';
function auth() {
var scopes = 'https://www.googleapis.com/auth/plus.me';
gapi.client.setApiKey(API_KEY);
window.setTimeout(checkAuth, 1000);
function checkAuth() {
gapi.auth.authorize({
client_id : CLIENT_ID,
scope : scopes,
immediate : false
}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
makeApiCall();
} else {
checkAuth();
}
}
function makeApiCall() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
$("#image").attr("src", resp.image.url);
});
});
}
}
</script>
Then I call the function auth() when the user clicks to see his picture.

Categories

Resources