Delete / Clear all events that created by Google Calendar API - calendar

I have an application using Google Calendar API.
private function getClient() {
$client = new \Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes('primary');
return $client;
}
Credential is a service_account.
I created and inserted about 65000 events by the above client.
Now, I want to deleted all events (65000 events).
I want to use /clear (
https://developers.google.com/google-apps/calendar/v3/reference/calendars/clear) API to do that but I am not sure it will delete all events from my application without clear other events on my calendar.
I mean on my calendar there are 2 type of events:
Personal Event, created by Rakumo calendar
Event from my application.
I just want to delete all events created from 2.
Anybody can confirm when use /clear API
$service->calendars->clear('primary');
will it delete only all events created from my application ?

Related

Firestore Security rules with payment form

I'm creating a raffle website. The user connects his wallet and pays for a raffle ticket. After the blockchain transaction confirmation, I add his raffle ticket in a collection in firestore.
It causes a security issue because if I allow the user to write to the raffle ticket collection in my firebase security rules, he could create his own tickets without paying.
I need tickets to be added to the database only if payment has been successfully made.
I don't know how websites that have means of payment do it. Maybe firebase isn't a good solution ?
My project is in react/typescript.
You say you do the payment over the blockchain and I assume you use solidity as your smart contract language?
Why don't you emit an event in your smart contract?
You then listen for these events on a (seperate) server.
That updates your (firebase) database whenever an event was emitted.
(Untested) Sample Code:
How do you emit events in solidity? (raffle.sol)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Raffle {
event PaymentCompletion(address buyer, uint256 amountOfTickets);
function buyTickets() external payable {
emit PaymentCompletion(msg.sender, msg.value)
}
}
How do you listen to these events?
when using web3js:
const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
const lastBlock = await web3.eth.getBlockNumber()
// paymentEvents is an array containing the payments of the last 500 blocks.
const paymentEvents = await contract.getPastEvents(
'PaymentCompletion', // change if your looking for a different event
{ fromBlock: latestBlock - 500, toBlock: 'latest' }
);
now iterate through these events and put them into your database. You can also set up a subscription which notifies you whenever a new block was created, so you can check if new events were inside of the current block.
This is what it would look like if you add the first blockchain event to the firebase realtime database.
var db = admin.database();
var ref = db.ref("/payments");
// ...
ref.child("path/to/transaction").set({
buyer: paymentEvents[0].buyer,
amountOfTickets: paymentEvents[0].amountOfTickets,
// put the rest of your data here
}, (err) => {
if (err) {
console.error(err)
}
})
Alternatively (if you don't want to handle the payment on the blockchain) you could also take a look at stripe, it also has a firebase plugin for easy integration. (but I've never tried it out). However, imo using the blockchain for handling the payment would be the cleanest solution. (+ you don't have the handling fees stripe uses).
I hope I could give you some good clues! Firebase should be definitely suitable for this.

How to create an event in a user's Google Calendar that can not be modified?

I want to create an event in a user's Google Calendar that can't be modified by that user.
In the following example, the API belongs to a#gmail.com, and is used to put an event in the calendar of b#occsn.com. To create an event that might be locked, I use the import interface from Google's API
start:
datetime: <date + time>
end:
datetime: <date + time>
summary: My Awesome Event
i_cal_uid: <random UUID>
organizer:
email: noreply#example.com # Non-existent address
display_name: MyAwesomeCompany
attendees:
-
email: <target calendar ID, e.g. user.com_q23rlj3we#group.calendar.google.com>
response_status: accepted
This creates an event on the user's calendar. If the user sees it in his calendar app (I use Fantastical), it can't be moved, but if user goes to Google Calendar's web site directly, the event can be moved, and it warns – only once – about "only moving it in Target Calendar" or something.
My question: Is it possible to create an event in the user's calendar that the user can not modify or move at all?

Log changes detected to domaincontext based on haschanges and getchanges

I have a Silverlight application that is using Entity Framework 4. In the app, it is possible for the user to add/remove string representations of Active Directory group names into the configuration - changes are not saved in the backend until the 'save' button is clicked.
When 'save' is clicked, Entity Framework updates the backend with the changes to the DomainContext. This is working as expected. But I want to log the changes being made and send them out in an email each time before context.SubmitChanges() fires. What is the easiest way to log the changes? I already have code that I can reuse to email the changes to be logged.
I am looking at context.ADGroupRules.EntityContainer.GetChanges() and can see AddedEntities and RemovedEntities properties in there but I'm not sure how to 'get at' the highlighted string in the included snip in order to log it.
if (command == "Save")
{
if (_context.HasChanges)
{
var changeSet = _context.ADGroupRules.EntityContainer.GetChanges();
//log and email changes here
_context.SubmitChanges(OnSubmitCompleted, null);
}
}
I have figured it out.
if (command == "Save")
{
if (_context.HasChanges)
{
var changeSet = _context.ADGroupRules.EntityContainer.GetChanges();
foreach (var entity in changeSet.AddedEntities.OfType<ADGroupRule>())
{
ADGroupRule rule = (ADGroupRule)entity;
Console.WriteLine(rule.ADGroupName);//simulate logging-emailing
}

Gmail API Watch not filtering by Label

I am using Gmail Push Notifications with Google PubSub and have a custom label that I want to monitor for any changes. I use the following code to register a watch for the label (Id of the label is Label_1)
WatchRequest wr = new WatchRequest();
wr.TopicName = "projects/" + primaryLink.ggProjectId + "/topics/iLink" + segmentId;
if (labels != null && labels.Count > 0)
{
wr.LabelIds = new List<string>();
wr.LabelIds.Add("Label_1");
wr.LabelFilterAction = "include";
}
WatchResponse wrr = gs.Users.Watch(wr, emailAccount).Execute();
return "HistoryId " + wrr.HistoryId.ToString();
}
The watch registers OK. The issue is that I get push notifications for any Gmail change not just those under the label.
Are custom labels supported?
I noticed the same issue but later on found out that its because of the way API works. You can filter the emails via LabelIds but you will receive notifications only if emails are directly being filtered to selected custom label. I guess its design rather than a flaw in the API.
To test this, create a custom filter in Gmail which would directly apply your custom label to a set of emails and you should be receiving notifications for those emails.
Edited (June 11, 2015):
Push notification send you HistoryID and user's mailbox name. In response your endpoint should call userhistory.list() with HistoryID and LabelId you want to monitor for changes.
$opt_param = array();
$opt_param['startHistoryId'] = $historyID;
$opt_param['labelId'] = $labelID;
$opt_param['fields'] = 'nextPageToken,historyId,history/messagesAdded';
$service->users_history->listUsersHistory($userID, $opt_param);
Above is a PHP code snippet to filter the history list with historyID and labelID.

EWS API calendar - Impersonating to update raise an error "Access is denied. Check credentials and try again."

I am new to using EWS managed APIs.
Following is the issue I am facing with EWS APIs:
EWS API - Impersonating to update a calendar item created by any other user than a service account, raise an error "Access is denied. Check credentials and try again."
Details:
1. I am using a service account e.g. abc#xyz.onmicrosoft.com. This user is a global administrator and also has ApplicationImpersonation role assigned. (Sign into Online Office 365 account -> Admin -> select "Exchange" tab- > select Permissions on the left panel -> create an impersonation role -> assign ApplicationImpersonation in Roles: and abc#xyz.onmicrosoft.com in Members: -> Click on save)
Create a calendar item by other user for e.g. pqr#xyz.onmicrosoft.com, and invite an attendee - abc#xyz.onmicrosoft.com.
In a c# program, I connect to EWS service using a service account - abc#xyz.onmicrosoft.com, fetch its calendar events. If organizer of an event is some other user - pqr#xyz.onmicrosoft.com then I use impersonation in the following way to update the calendar event/item properties- subject, body text etc.
private static void Impersonate(string organizer)
{
string impersonatedUserSMTPAddress = organizer;
ImpersonatedUserId impersonatedUserId =
new ImpersonatedUserId(ConnectingIdType.SmtpAddress, impersonatedUserSMTPAddress);
service.ImpersonatedUserId = impersonatedUserId;
}
It was working fine till yesterday afternoon. Suddenly, it started throwing an exception "Access is denied. Check credentials and try again." Whenever I try to update that event.
private static void FindAndUpdate(ExchangeService service)
{
CalendarView cv = new CalendarView(DateTime.Now, DateTime.Now.AddDays(30));
cv.MaxItemsReturned = 25;
try
{
FindItemsResults masterResults = service.FindItems(WellKnownFolderName.Calendar, cv);
foreach (Appointment item in masterResults.Items)
{
if (item is Appointment)
{
Appointment masterItem = item as Appointment;
if (!masterRecurEventIDs.Contains(masterItem.ICalUid.ToString()))
{
masterItem.Load();
if (!masterItem.Subject.Contains(" (Updated content)"))
{
//impersonate organizer to update and save for further use
Impersonate(masterItem.Organizer.Address.ToString());
// Update the subject and body
masterItem.Subject = masterItem.Subject + " (Updated content)";
string currentBodyType = masterItem.Body.BodyType.ToString();
masterItem.Body = masterItem.Body.Text + "\nUpdated Body Info: xxxxxxxxxxxx";
// This results in an UpdateItem operation call to EWS.
masterItem.Update(ConflictResolutionMode.AutoResolve);
// Send updated notification to organizer of an appointment
CreateAndSendEmail(masterItem.Organizer.Address.ToString(), masterItem.Subject);
masterRecurEventIDs.Add(masterItem.ICalUid.ToString());
}
else
{
Console.WriteLine("Event is already updated. No need to update again.:\r\n");
Console.WriteLine("Subject: " + masterItem.Subject);
Console.WriteLine("Description: " + masterItem.Body.Text);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
What could be an issue here? Initially I thought may be its a throttling policy which is stopping same user after making certain API call limits for the day, but I am still seeing this issue today.
Any help is appreciated.
Thanks
Found the solution:
Only adding impersonated ID to the existing service instance doesn't work. You also need to re-validate the auto-discover url.
I was investigating an Impersonation + Calendar issue, and found this forum post.
I am sure your problem lies in the way you are trying to get and then update the calendar item (appointment).
You are getting the calendar item using a credentials (mailbox A). Then later on, on following line
Impersonate(masterItem.Organizer.Address.ToString());
you are instructing the Ews Service object to work as the Impersonated Identity (credentials of Mailbox B).
Since you already had grabbed the appointment from Mailbox A, and now trying to update that appointment in Mailbox A, using the credentials of Mailbox B, that should not work IMHO if Mailbox B doesn't have permission on Mailbox A calendar.
So here, actually, you are trying to update the calendar item of Mailbox A, using the impersonated credentials of Mailbox B, and as Mailbox B doesn't have permission on Mailbox A credentials, so the Access Denied error is occurring.
Hope this help someone else too.
Thanks

Resources