Arbeta med Gmail‑kalendrar

Lägga till, redigera och radera en kalender

Aspose.Email låter applikationer hantera Gmail-kalendrar med hjälp av IGmailClient som tillhandahåller funktioner som att lägga till, radera och uppdatera Gmail-kalendrar. Denna klientklass returnerar en lista över ExtendedCalendar-objekt som innehåller information om Gmail-kalenderobjekten. IGmailClient klassen exponerar följande funktioner för kalendrar:

Hämta lista över alla kalendrar för en klient

  • deleteCalendar Den kan användas för att radera en kalender
  • fetchCalendar Den kan användas för att hämta en specifik kalender för en klient
  • updateCalendar Denna funktion används för att återinfoga en modifierad kalender för en klient

För att komma åt kalendrarna initieras GoogleTestUser med Gmail-kontots uppgifter. GoogleOAuthHelper används för att hämta åtkomsttoken för användaren som sedan används för att initiera IGmailClient.

Infoga, hämta och uppdatera

För att infoga en kalender, initiera en Calendar typobjekt och infoga det med hjälp av createCalendar funktion. createCalendar returnerar ID för den nyligen infogade kalendern. Detta ID kan användas för att hämta kalendern från servern. Följande kodsnutt visar hur man infogar, hämtar och uppdaterar en kalender.

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);
}

Radera specifik kalender

För att radera en specifik kalender måste vi hämta listan över alla klientens kalendrar och sedan radera efter behov. listCalendars returnerar listan över ExtendedCalendar som innehåller Gmail-kalendrar. Följande kodsnutt visar hur du raderar en specifik kalender.

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());
    }
}

Arbeta med kalenderåtkomstkontroll

Aspose.Email ger full kontroll över åtkomstkontrollen till kalenderobjekten. listAccessRules funktion exponeras av IGmailClient som returnerar en lista över AccessControlRule. Individuell regelinformation kan hämtas, modifieras och sparas tillbaka för en klients kalender. IGmailClient innehåller följande funktioner för att hantera åtkomstkontrollreglerna.

Följande kodsnutt visar hur funktionerna som används för att hantera åtkomstregler:

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;
    }
}

Arbeta med klientinställningar och färginformation

Aspose.Email stödjer åtkomst till klientinställningarna genom att använda IGmailClient.getSettings. Den returnerar en lista över inställningar som visas nedan:

  1. dateFieldOrder
  2. displayAllTimezones
  3. hideInvitations
  4. format24HourTime
  5. defaultCalendarMode
  6. defaultEventLength
  7. locale
  8. remindOnRespondedEventsOnly
  9. alternateCalendar
  10. userLocation
  11. hideWeekends
  12. showDeclinedEvents
  13. weekStart
  14. weather
  15. customCalendarMode
  16. timezoneLabel
  17. timezone
  18. useKeyboardShortcuts
  19. country

Liknande färginformation för klienter kan också hämtas med IGmailClient.getColors. Detta färginformationsobjekt returnerar listan av förgrundsfärger, bakgrundsfärger samt uppdateringsdatum och tid.

Kom åt klientinställningar

Följande kodsnutt visar hur funktionerna som används för att komma åt klientinställningarna:

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");
        }
    }
}

Kom åt färginformation

Följande kodsnutt visar hur funktionerna som används för att komma åt klientens färginställningar.

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());
}

Arbeta med möten

Aspose.Email erbjuder funktioner för att arbeta med Möten i Google-kalendrar. Följande är en lista över uppgifter som kan utföras på möten i Google Kalender:

  1. Lägg till möten - createAppointment, importAppointment
  2. Hämta lista över möten - listAppointments
  3. Hämta specifikt möte - fetchAppointment, listAppointmentInstances
  4. Uppdatera ett möte - updateAppointment
  5. Flytta möte från en kalender till en annan - moveAppointment
  6. Ta bort möte - deleteAppointment

Lägga till ett möte

Följande kodexempel demonstrerar funktionen att lägga till ett möte i en kalender. I detta exempel följs följande steg:

  1. Skapa och infoga en kalender.
  2. Hämta lista över möten från en ny kalender.
  3. Skapa ett möte.
  4. Infoga möte.
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);
    }
    
}

Hämta och uppdatera möte

Här demonstreras hämtning och uppdatering av kalendern på följande sätt:

  1. Hämta specifikt möte.
  2. Ändra mötet.
  3. Uppdatera mötet i kalendern.

Det antas att en kalender med ID "calendarId" och ett mötes unika ID "AppointmentUniqueId" redan har extraherats. Följande kodexempel visar hur du hämtar och uppdaterar mötet.

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);
}

Flytta och ta bort möte

Appointment kan flyttas genom att ange källkalender, destinationskalender och unikt ID för mötet i källkalendern. Följande kodexempel visar hur du flyttar och tar bort mötet.

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);
}