Повторяющиеся события

В этом документе описывается, как работать с повторяющимися событиями и их экземплярами.

Создавайте повторяющиеся события

Создание повторяющихся событий аналогично созданию обычного (одиночного) события с установленным полем recurrence ресурса event .

Протокол

POST /calendar/v3/calendars/primary/events
...

{
  "summary": "Appointment",
  "location": "Somewhere",
  "start": {
    "dateTime": "2011-06-03T10:00:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "end": {
    "dateTime": "2011-06-03T10:25:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "recurrence": [
    "RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z",
  ],
  "attendees": [
    {
      "email": "attendeeEmail",
      # Other attendee's data...
    },
    # ...
  ],
}

Джава

Event event = new Event();

event.setSummary("Appointment");
event.setLocation("Somewhere");

ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
attendees.add(new EventAttendee().setEmail("attendeeEmail"));
// ...
event.setAttendees(attendees);

DateTime start = DateTime.parseRfc3339("2011-06-03T10:00:00.000-07:00");
DateTime end = DateTime.parseRfc3339("2011-06-03T10:25:00.000-07:00");
event.setStart(new EventDateTime().setDateTime(start).setTimeZone("America/Los_Angeles"));
event.setEnd(new EventDateTime().setDateTime(end).setTimeZone("America/Los_Angeles"));
event.setRecurrence(Arrays.asList("RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z"));

Event recurringEvent = service.events().insert("primary", event).execute();

System.out.println(createdEvent.getId());

.СЕТЬ

Event event = new Event()
    {
      Summary = "Appointment",
      Location = "Somewhere",
      Start = new EventDateTime() {
          DateTime = new DateTime("2011-06-03T10:00:00.000:-07:00")
          TimeZone = "America/Los_Angeles"
      },
      End = new EventDateTime() {
          DateTime = new DateTime("2011-06-03T10:25:00.000:-07:00")
          TimeZone = "America/Los_Angeles"
      },
      Recurrence = new String[] {
          "RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z"
      },
      Attendees = new List<EventAttendee>()
          {
            new EventAttendee() { Email: "attendeeEmail" },
            // ...
          }
    };

Event recurringEvent = service.Events.Insert(event, "primary").Fetch();

Console.WriteLine(recurringEvent.Id);

Питон

event = {
  'summary': 'Appointment',
  'location': 'Somewhere',
  'start': {
    'dateTime': '2011-06-03T10:00:00.000-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'end': {
    'dateTime': '2011-06-03T10:25:00.000-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'recurrence': [
    'RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z',
  ],
  'attendees': [
    {
      'email': 'attendeeEmail',
      # Other attendee's data...
    },
    # ...
  ],
}

recurring_event = service.events().insert(calendarId='primary', body=event).execute()

print recurring_event['id']

PHP

$event = new Google_Service_Calendar_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2011-06-03T10:00:00.000-07:00');
$start->setTimeZone('America/Los_Angeles');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2011-06-03T10:25:00.000-07:00');
$end->setTimeZone('America/Los_Angeles');
$event->setEnd($end);
$event->setRecurrence(array('RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z'));
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('attendeeEmail');
// ...
$attendees = array($attendee1,
                   // ...
                   );
$event->attendees = $attendees;
$recurringEvent = $service->events->insert('primary', $event);

echo $recurringEvent->getId();

Рубин

event = Google::Apis::CalendarV3::Event.new(
  summary: 'Appointment',
  location: 'Somewhere',
  start: {
    date_time: '2011-06-03T10:00:00.000-07:00',
    time_zone:  'America/Los_Angeles'
  },
  end: {
    date_time: '2011-06-03T10:25:00.000-07:00',
    time_zone: 'America/Los_Angeles'
  },
  recurrence: ['RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z']
  attendees: [
    {
      email: 'attendeeEmail'
    },
    #...
  ]
)
response = client.insert_event('primary', event)
print response.id

Доступ к экземплярам

Чтобы просмотреть все экземпляры данного повторяющегося события, вы можете использовать запрос event.instances() .

Запрос events.list() по умолчанию возвращает только отдельные события, повторяющиеся события и исключения ; экземпляры, не являющиеся исключениями, не возвращаются. Если для параметра singleEvents установлено значение true , то в результате отображаются все отдельные экземпляры, но не базовые повторяющиеся события. Когда пользователь, у которого есть разрешения на занятость, запрашивает events.list() , он ведет себя так, как если бы singleEvent имел значение true . Дополнительные сведения о правилах списков управления доступом см. в разделе Acl .

Отдельные случаи подобны единичным событиям. В отличие от родительских повторяющихся событий, у экземпляров не установлено поле recurrence .

Следующие поля событий относятся к экземплярам:

  • recurringEventId — идентификатор родительского повторяющегося события, которому принадлежит этот экземпляр.
  • originalStartTime — время запуска этого экземпляра согласно данным повторения в родительском повторяющемся событии. Это время может отличаться от фактического времени start , если экземпляр был перенесен. Он однозначно идентифицирует экземпляр в серии повторяющихся событий, даже если экземпляр был перемещен.

Изменить или удалить экземпляры

Чтобы изменить один экземпляр (создав исключение), клиентские приложения должны сначала получить экземпляр, а затем обновить его, отправив авторизованный запрос PUT на URL-адрес редактирования экземпляра с обновленными данными в теле. URL-адрес имеет форму:

https://www.googleapis.com/calendar/v3/calendars/calendarId/events/instanceId

Используйте соответствующие значения вместо calendarId и instanceId .

Примечание. Специальное значение calendarId primary можно использовать для ссылки на основной календарь пользователя, прошедшего проверку подлинности.

В случае успеха сервер отвечает кодом состояния HTTP 200 OK с обновленным экземпляром. В следующем примере показано, как отменить экземпляр повторяющегося события.

Протокол

PUT /calendar/v3/calendars/primary/events/instanceId
...

{
  "kind": "calendar#event",
  "id": "instanceId",
  "etag": "instanceEtag",
  "status": "cancelled",
  "htmlLink": "https://www.google.com/calendar/event?eid=instanceEid",
  "created": "2011-05-23T22:27:01.000Z",
  "updated": "2011-05-23T22:27:01.000Z",
  "summary": "Recurring event",
  "location": "Somewhere",
  "creator": {
    "email": "userEmail"
  },
  "recurringEventId": "recurringEventId",
  "originalStartTime": "2011-06-03T10:00:00.000-07:00",
  "organizer": {
    "email": "userEmail",
    "displayName": "userDisplayName"
  },
  "start": {
    "dateTime": "2011-06-03T10:00:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "end": {
    "dateTime": "2011-06-03T10:25:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "iCalUID": "eventUID",
  "sequence": 0,
  "attendees": [
    {
      "email": "attendeeEmail",
      "displayName": "attendeeDisplayName",
      "responseStatus": "needsAction"
    },
    # ...
    {
      "email": "userEmail",
      "displayName": "userDisplayName",
      "responseStatus": "accepted",
      "organizer": true,
      "self": true
    }
  ],
  "guestsCanInviteOthers": false,
  "guestsCanSeeOtherGuests": false,
  "reminders": {
    "useDefault": true
  }
}

Джава

// First retrieve the instances from the API.
Events instances = service.events().instances("primary", "recurringEventId").execute();

// Select the instance to cancel.
Event instance = instances.getItems().get(0);
instance.setStatus("cancelled");

Event updatedInstance = service.events().update("primary", instance.getId(), instance).execute();

// Print the updated date.
System.out.println(updatedInstance.getUpdated());

.СЕТЬ

// First retrieve the instances from the API.
Events instances = service.Events.Instances("primary", "recurringEventId").Fetch();

// Select the instance to cancel.
Event instance = instances.Items[0];
instance.Status = "cancelled";

Event updatedInstance = service.Events.Update(instance, "primary", instance.Id).Fetch();

// Print the updated date.
Console.WriteLine(updatedInstance.Updated);

Питон

# First retrieve the instances from the API.
instances = service.events().instances(calendarId='primary', eventId='recurringEventId').execute()

# Select the instance to cancel.
instance = instances['items'][0]
instance['status'] = 'cancelled'

updated_instance = service.events().update(calendarId='primary', eventId=instance['id'], body=instance).execute()

# Print the updated date.
print updated_instance['updated']

PHP

$events = $service->events->instances("primary", "eventId");

// Select the instance to cancel.
$instance = $events->getItems()[0];
$instance->setStatus('cancelled');

$updatedInstance = $service->events->update('primary', $instance->getId(), $instance);

// Print the updated date.
echo $updatedInstance->getUpdated();

Рубин

# First retrieve the instances from the API.
instances = client.list_event_instances('primary', 'recurringEventId')

# Select the instance to cancel.
instance = instances.items[0]
instance.status = 'cancelled'

response = client.update_event('primary', instance.id, instance)
print response.updated

Измените все следующие экземпляры

Чтобы изменить все экземпляры повторяющегося события в заданном (целевом) экземпляре или после него, необходимо сделать два отдельных запроса API. Эти запросы разделяют исходное повторяющееся событие на два: исходное, в котором сохраняются экземпляры без изменений, и новое повторяющееся событие, имеющее экземпляры, к которым применяется изменение:
  1. Вызовите events.update() , чтобы обрезать исходное повторяющееся событие экземпляров, которые необходимо обновить. Для этого установите компонент UNTIL в RRULE так, чтобы он указывал до времени начала первого целевого экземпляра. Альтернативно вы можете установить компонент COUNT вместо UNTIL .
  2. Вызовите events.insert() , чтобы создать новое повторяющееся событие со всеми теми же данными, что и исходное, за исключением изменения, которое вы пытаетесь внести. Новое повторяющееся событие должно иметь время начала целевого экземпляра.

В этом примере показано, как изменить местоположение на «Где-то еще», начиная с третьего экземпляра повторяющегося события из предыдущих примеров.

Протокол

# Updating the original recurring event to trim the instance list:

PUT /calendar/v3/calendars/primary/events/recurringEventId
...

{
  "summary": "Appointment",
  "location": "Somewhere",
  "start": {
    "dateTime": "2011-06-03T10:00:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "end": {
    "dateTime": "2011-06-03T10:25:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "recurrence": [
    "RRULE:FREQ=WEEKLY;UNTIL=20110617T065959Z",
  ],
  "attendees": [
    {
      "email": "attendeeEmail",
      # Other attendee's data...
    },
    # ...
  ],
}


# Creating a new recurring event with the change applied:

POST /calendar/v3/calendars/primary/events
...

{
  "summary": "Appointment",
  "location": "Somewhere else",
  "start": {
    "dateTime": "2011-06-17T10:00:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "end": {
    "dateTime": "2011-06-17T10:25:00.000-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "recurrence": [
    "RRULE:FREQ=WEEKLY;UNTIL=20110617T065959Z",
  ],
  "attendees": [
    {
      "email": "attendeeEmail",
      # Other attendee's data...
    },
    # ...
  ],
}