Работа с Google Calendar
Добавяне, редактиране и изтриване на календар
Aspose.Email позволява на приложенията да управляват Gmail календарите, използвайки IGmailClient който предоставя функции като добавяне, изтриване и актуализиране на Gmail календари. Този клиентски клас връща списък от обекти от тип ExtendedCalendar, които съдържат информация за елементите на Gmail календара. IGmailClient класът излага следните функции за календари:
- createCalendar За вмъкване на нов календар
- listCalendars
Получете списък с всички календари на клиент
- deleteCalendar Може да се използва за изтриване на календар
- fetchCalendar Може да се използва за извличане на конкретен календар на клиент
- updateCalendar Тази функция се използва за връщане на модифициран календар на клиент
За достъп до календарите, GoogleTestUser се инициализира с данни за вход в Gmail акаунт. GoogleOAuthHelper се използва за получаване на токен за достъп за потребителя, който след това се използва за инициализиране IGmailClient.
Вмъкване, извличане и актуализиране
За вмъкване на календар, инициализирайте Calendar тип обект и да го вмъкнете, като използвате createCalendar функция. createCalendar връща идентификатора на нововъведения календар. Този идентификатор може да се използва за извличане на календара от сървъра. Следният кодов фрагмент показва как да вмъкнете, извлечете и актуализирате календар.
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
// Insert, get and update calendar
Calendar calendar = new Calendar("Summary", "Description", "Location", "America/Los_Angeles");
// Insert calendar and Retrieve same calendar using id
String id = client.createCalendar(calendar);
Calendar cal = client.fetchCalendar(id);
// Change information in the fetched calendar and Update calendar
cal.setDescription("New Description");
cal.setLocation("New Location");
client.updateCalendar(cal);
}
Изтриване на конкретен календар
За изтриване на конкретен календар, трябва да получим списъка с всички календари на клиент и след това да изтрием според нуждите. listCalendars връща списъка с ExtendedCalendar което съдържа Gmail календари. Следният кодов фрагмент показва как да изтриете конкретен календар.
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
// Access and delete calendar with summary starting from "Calendar summary"
String summary = "Calendar summary";
// Get calendars list
ExtendedCalendar[] lst = client.listCalendars();
for (ExtendedCalendar extCal : lst) {
// Delete selected calendars
if (extCal.getSummary().startsWith(summary))
client.deleteCalendar(extCal.getId());
}
}
Работа с контрол на достъпа до календара
Aspose.Email предоставя пълен контрол върху контрола на достъпа до елементите на календара. listAccessRules функцията е предоставена от IGmailClient която връща списък с AccessControlRule. Индивидуална информация за правило може да бъде извлечена, модифицирана и запазена обратно за календара на клиент. IGmailClient съдържа следните функции за управление на правилата за контрол на достъпа.
- listAccessRules Тази функция предоставя списък с AccessControlRule
- createAccessRule Тази функция създава ново правило за достъп за календар.
- updateAccessRule Тази функция се използва за актуализиране на правило за достъп.
- fetchAccessRule Може да се използва за извличане на конкретно правило за достъп за календар на клиент
- deleteAccessRule Тази функция се използва за изтриване на правило за достъп.
Следният кодов фрагмент показва как се използват функциите за управление на правилата за достъп:
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
// Retrieve list of calendars for the current client
ExtendedCalendar[] calendarList = client.listCalendars();
// Get first calendar id and retrieve list of AccessControlRule for the first calendar
String calendarId = calendarList[0].getId();
AccessControlRule[] roles1 = client.listAccessRules(calendarId);
// Create a local access control rule and Set rule properties
AccessControlRule rule = new AccessControlRule();
rule.setRole(AccessRole.reader);
rule.setScope(new AclScope(AclScopeType.user, email2));
// Insert new rule for the calendar. It returns the newly created rule
AccessControlRule createdRule = client.createAccessRule(calendarId, rule);
// Get list of rules
AccessControlRule[] roles2 = client.listAccessRules(calendarId);
// Current list length should be 1 more than the earlier one
if (roles1.length + 1 == roles2.length) {
System.out.println("List lengths are ok");
} else {
System.out.println("List lengths are not ok");
return;
}
// Change rule and Update the rule for the selected calendar
createdRule.setRole(AccessRole.writer);
AccessControlRule updatedRule = client.updateAccessRule(calendarId, createdRule);
// Retrieve individaul rule against a calendar
AccessControlRule fetchedRule = client.fetchAccessRule(calendarId, createdRule.getId());
// Delete particular rule against a given calendar and Retrieve the all rules list for the same calendar
client.deleteAccessRule(calendarId, createdRule.getId());
AccessControlRule[] roles3 = client.listAccessRules(calendarId);
// Check that current rules list length should be equal to the original list length before adding and deleting the rule
if (roles1.length == roles3.length) {
System.out.println("List lengths are same");
} else {
System.out.println("List lengths are not equal");
return;
}
}
Работа с клиентски настройки и информация за цвят
Aspose.Email поддържа достъп до клиентските настройки чрез използване на IGmailClient.getSettings. Тя връща списък с настройки, както е дадено по-долу:
- ред на полетата за дата
- показване на всички часови зони
- hideInvitations
- форматиране на 24-часово време
- defaultCalendarMode
- стандартна продължителност на събитие
- локализация
- remindOnRespondedEventsOnly
- alternateCalendar
- местоположение на потребителя
- hideWeekends
- showDeclinedEvents
- начало на седмицата
- време
- customCalendarMode
- етикет за часова зона
- часова зона
- useKeyboardShortcuts
- страна
Подобно, информация за цвят за клиентите може да се извлече чрез IGmailClient.getColors. Този обект за информация за цвят връща списъка с предни цветове, фонови цветове и дата и час на актуализиране.
Достъп до клиентски настройки
Следният кодов фрагмент показва как се използват функциите за достъп до настройките на клиента:
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
// Retrieve client settings
Dictionary<String, String> settings = client.getSettings();
if (settings.size() < 1) {
System.out.println("No settings are available.");
return;
}
// Traverse the settings list
for (KeyValuePair<String, String> pair : settings) {
// Get the setting value and test if settings are ok
String value = client.getSetting(pair.getKey());
if (pair.getValue().equals(value)) {
System.out.println("Key = " + pair.getKey() + ", Value = " + pair.getValue());
} else {
System.out.println("Settings could not be retrieved");
}
}
}
Достъп до информация за цвят
Следният кодов фрагмент показва как се използват функциите за достъп до настройките за цвят на клиента.
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
ColorsInfo colors = client.getColors();
Dictionary<String, Colors> palettes = colors.getCalendar();
// Traverse the settings list
for (KeyValuePair<String, Colors> pair : palettes) {
System.out.println("Key = " + pair.getKey() + ", Color = " + pair.getValue());
}
System.out.println("Update Date = " + colors.getUpdated());
}
Работа със срещи
Aspose.Email предоставя функции за работа с Срещи в Google календари. По-долу е списъкът със задачи, които могат да се извършват със срещи в Google календар:
- Добавяне на срещи - createAppointment, importAppointment
- Извличане на списък със срещи - listAppointments
- Извличане на конкретна среща - fetchAppointment, listAppointmentInstances
- Актуализиране на среща - updateAppointment
- Преместване на среща от един календар в друг - moveAppointment
- Изтриване на среща - deleteAppointment
Добавяне на среща
Следният примерен код демонстрира функцията за добавяне на среща в календар. В този пример се следват следните стъпки:
- Създаване и вмъкване на календар.
- Извличане на списък със срещи от нов календар.
- Създаване на среща.
- Вмъкване на среща.
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
// Create local calendar
Calendar calendar1 = new Calendar("Summary", null, null, "Europe/Kiev");
// Insert calendar and get id of inserted calendar and Get back calendar using an id
String id = client.createCalendar(calendar1);
Calendar cal1 = client.fetchCalendar(id);
String calendarId1 = cal1.getId();
try {
// Retrieve list of appointments from the first calendar
Appointment[] appointments = client.listAppointments(calendarId1);
if (appointments.length > 0) {
System.out.println("Wrong number of appointments");
return;
}
// Get current time and Calculate time after an hour from now
java.util.Calendar c = java.util.Calendar.getInstance();
Date startDate = c.getTime();
c.add(java.util.Calendar.HOUR_OF_DAY, 1);
Date endDate = c.getTime();
// Initialize a mail address collection and set attendees mail address
MailAddressCollection attendees = new MailAddressCollection();
attendees.add("User1.EMail@domain.com");
attendees.add("User3.EMail@domain.com");
// Create an appointment with above attendees
Appointment app1 = new Appointment("Location", startDate, endDate, MailAddress.to_MailAddress(email2), attendees);
// Set appointment summary, description, start/end time zone
app1.setSummary("New Summary");
app1.setDescription("New Description");
app1.setStartTimeZone("Europe/Kiev");
app1.setEndTimeZone("Europe/Kiev");
// Insert appointment in the first calendar inserted above and get back inserted appointment
Appointment app2 = client.createAppointment(calendarId1, app1);
// Retrieve appointment using unique id
Appointment app3 = client.fetchAppointment(calendarId1, app2.getUniqueId());
} catch (Exception ex) {
System.err.println(ex);
}
}
Извличане и актуализиране на среща
Тук се демнстрира извличането и актуализирането на календар както следва:
- Извличане на конкретна среща.
- Промяна на срещата.
- Актуализиране на срещата в календара.
Приема се, че календар с идентификатор "calendarId" и уникален идентификатор на среща "AppointmentUniqueId" вече са извлечени. Следният кодов фрагмент показва как да извлечете и актуализирате среща.
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
String calendarId = client.listCalendars()[0].getId();
String AppointmentUniqueId = client.listAppointments(calendarId)[0].getUniqueId();
// Retrieve Appointment
Appointment app3 = client.fetchAppointment(calendarId, AppointmentUniqueId);
// Change the appointment information
app3.setSummary("New Summary");
app3.setDescription("New Description");
app3.setLocation("New Location");
app3.setFlags(AppointmentFlags.AllDayEvent);
java.util.Calendar c = java.util.Calendar.getInstance();
c.add(java.util.Calendar.HOUR_OF_DAY, 2);
app3.setStartDate(c.getTime());
c.add(java.util.Calendar.HOUR_OF_DAY, 1);
app3.setEndDate(c.getTime());
app3.setStartTimeZone("Europe/Kiev");
app3.setEndTimeZone("Europe/Kiev");
// Update the appointment and get back updated appointment
Appointment app4 = client.updateAppointment(calendarId, app3);
}
Преместване и изтриване на среща
Appointment може да се премести, като се посочат изходния календар, целевият календар и уникалният идентификатор на срещата в изходния календар. Следният кодов фрагмент показва как да преместите и изтриете среща.
try (IGmailClient client = GmailClient.getInstance(accessToken, email)) {
String SourceCalendarId = client.listCalendars()[0].getId();
String DestinationCalendarId = client.listCalendars()[1].getId();
String TargetAppUniqueId = client.listAppointments(SourceCalendarId)[0].getUniqueId();
// Retrieve the list of appointments in the destination calendar before moving the appointment
Appointment[] appointments = client.listAppointments(DestinationCalendarId);
System.out.println("Before moving count = " + appointments.length);
Appointment Movedapp = client.moveAppointment(SourceCalendarId, DestinationCalendarId, TargetAppUniqueId);
// Retrieve the list of appointments in the destination calendar after moving the appointment
appointments = client.listAppointments(DestinationCalendarId);
System.out.println("After moving count = " + appointments.length);
// Delete particular appointment from a calendar using unique id
client.deleteAppointment(DestinationCalendarId, Movedapp.getUniqueId());
// Retrieve the list of appointments. It should be one less than the earlier appointments in the destination calendar
appointments = client.listAppointments(DestinationCalendarId);
System.out.println("After deleting count = " + appointments.length);
}