יצירת אירועים

דמיינו אפליקציה שעוזרת למשתמשים למצוא את מסלולי הטיולים הכי טובים. הוספת תוכנית הטיול כאירוע ביומן עוזרת למשתמשים להתארגן באופן אוטומטי. ביומן Google הם יכולים לשתף את התוכנית ולקבל תזכורות, כדי להתכונן בלי לחץ. בנוסף, בזכות השילוב החלק של מוצרי Google, אפליקציית Google Now שולחת להם התראה על הזמן לצאת, ואפליקציית מפות Google מכוונת אותם למקום הפגישה בזמן.

במאמר הזה מוסבר איך ליצור אירועים ביומן ולהוסיף אותם ליומנים של המשתמשים.

הוספת אירוע

כדי ליצור אירוע, מפעילים את השיטה events.insert() ומספקים לפחות את הפרמטרים הבאים:

  • ‫calendarId הוא המזהה של היומן, ויכול להיות כתובת האימייל של היומן שבו רוצים ליצור את האירוע או מילת המפתח המיוחדת 'primary', שתשתמש ביומן הראשי של המשתמש שמחובר לחשבון. אם אתם לא יודעים מה כתובת האימייל של היומן שבו אתם רוצים להשתמש, אתם יכולים לבדוק אותה בהגדרות היומן בממשק המשתמש של יומן Google באינטרנט (בקטע "כתובת היומן"), או לחפש אותה בתוצאה של הקריאה ל-calendarList.list().
  • ‫event הוא האירוע שרוצים ליצור, עם כל הפרטים הנדרשים כמו שעת ההתחלה ושעת הסיום. שני שדות החובה היחידים הם שעת start ושעת end. לרשימה המלאה של שדות האירועים, עיינו במפרט של event.

כדי ליצור אירועים, צריך:

  • מגדירים את היקף ההרשאות של OAuth ל-https://www.googleapis.com/auth/calendar כדי שתהיה לכם גישת עריכה ליומן של המשתמש.
  • מוודאים שלמשתמש המאומת יש גישת כתיבה ליומן עם ה-calendarId שציינתם (לדוגמה, על ידי קריאה ל-calendarList.get() עבור ה-calendarId ובדיקת ה-accessRole).

הוספת מטא-נתונים של אירועים

כשיוצרים אירוע ביומן, אפשר להוסיף לו מטא-נתונים. אם אתם בוחרים לא להוסיף מטא-נתונים במהלך היצירה, אתם יכולים לעדכן שדות רבים באמצעות events.update(). עם זאת, אפשר להגדיר שדות מסוימים, כמו מזהה האירוע, רק במהלך פעולת events.insert().

מיקום
הוספת כתובת לשדה המיקום מאפשרת להשתמש בתכונות כמו "זמן לצאת" או להציג מפה עם מסלול הגעה.
מזהה אירוע
כשיוצרים אירוע, אפשר ליצור מזהה אירוע משלכם שעומד בדרישות הפורמט שלנו. כך אפשר לסנכרן בין ישויות במסד הנתונים המקומי לבין אירועים ביומן Google. היא גם מונעת יצירת אירועים כפולים אם הפעולה נכשלת בשלב כלשהו אחרי שהיא בוצעה בהצלחה בקצה העורפי של היומן. אם לא מציינים מזהה אירוע, השרת יוצר מזהה בשבילכם. מידע נוסף זמין בחומר העזר בנושא מזהי אירועים.
משתתפים
האירוע שאתם יוצרים מופיע בכל היומנים הראשיים של המשתתפים שכללתם עם אותו מזהה אירוע. כברירת מחדל (sendUpdates="externalOnly"), היומן שולח התראות באימייל רק למשתתפים שלא משתמשים ביומן Google. מגדירים את sendUpdates לערך "all" כדי לשלוח התראה לכל המשתתפים, או לערך "none" כדי לא לשלוח התראות באימייל. מידע נוסף זמין במאמר אירועים עם כמה משתתפים.

בדוגמאות הבאות מוסבר איך ליצור אירוע ולהגדיר את המטא-נתונים שלו:

Go

// Refer to the Go quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/go
// Change the scope to calendar.CalendarScope and delete any stored credentials.

event := &calendar.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: &calendar.EventDateTime{
    DateTime: "2015-05-28T09:00:00-07:00",
    TimeZone: "America/Los_Angeles",
  },
  End: &calendar.EventDateTime{
    DateTime: "2015-05-28T17:00:00-07:00",
    TimeZone: "America/Los_Angeles",
  },
  Recurrence: []string{"RRULE:FREQ=DAILY;COUNT=2"},
  Attendees: []*calendar.EventAttendee{
    &calendar.EventAttendee{Email:"lpage@example.com"},
    &calendar.EventAttendee{Email:"sbrin@example.com"},
  },
}

calendarId := "primary"
event, err = srv.Events.Insert(calendarId, event).Do()
if err != nil {
  log.Fatalf("Unable to create event. %v\n", err)
}
fmt.Printf("Event created: %s\n", event.HtmlLink)

Java

// Refer to the Java quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/java
// Change the scope to CalendarScopes.CALENDAR and delete any stored
// credentials.

Event event = new Event()
    .setSummary("Google I/O 2015")
    .setLocation("800 Howard St., San Francisco, CA 94103")
    .setDescription("A chance to hear more about Google's developer products.");

DateTime startDateTime = new DateTime("2015-05-28T09:00:00-07:00");
EventDateTime start = new EventDateTime()
    .setDateTime(startDateTime)
    .setTimeZone("America/Los_Angeles");
event.setStart(start);

DateTime endDateTime = new DateTime("2015-05-28T17:00:00-07:00");
EventDateTime end = new EventDateTime()
    .setDateTime(endDateTime)
    .setTimeZone("America/Los_Angeles");
event.setEnd(end);

String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));

EventAttendee[] attendees = new EventAttendee[] {
    new EventAttendee().setEmail("lpage@example.com"),
    new EventAttendee().setEmail("sbrin@example.com"),
};
event.setAttendees(Arrays.asList(attendees));

EventReminder[] reminderOverrides = new EventReminder[] {
    new EventReminder().setMethod("email").setMinutes(24 * 60),
    new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
    .setUseDefault(false)
    .setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);

String calendarId = "primary";
event = service.events().insert(calendarId, event).execute();
System.out.printf("Event created: %s\n", event.getHtmlLink());

JavaScript

// Refer to the JavaScript quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/js
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.

const 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': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'end': {
    'dateTime': '2015-05-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}
    ]
  }
};

const request = gapi.client.calendar.events.insert({
  'calendarId': 'primary',
  'resource': event
});

request.execute(function(event) {
  appendPre('Event created: ' + event.htmlLink);
});

Node.js

// Refer to the Node.js quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/node
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.

const 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': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'end': {
    'dateTime': '2015-05-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},
    ],
  },
};

calendar.events.insert({
  auth: auth,
  calendarId: 'primary',
  resource: event,
}, function(err, event) {
  if (err) {
    console.log('There was an error contacting the Calendar service: ' + err);
    return;
  }
  console.log('Event created: %s', event.htmlLink);
});

PHP

$event = new Google_Service_Calendar_Event(array(
  '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' => array(
    'dateTime' => '2015-05-28T09:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'end' => array(
    'dateTime' => '2015-05-28T17:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2'
  ),
  'attendees' => array(
    array('email' => 'lpage@example.com'),
    array('email' => 'sbrin@example.com'),
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);

Python

# Refer to the Python quickstart on how to setup the environment:
# https://developers.google.com/workspace/calendar/quickstart/python
# Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
# stored credentials.

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': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'end': {
    'dateTime': '2015-05-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},
    ],
  },
}

event = service.events().insert(calendarId='primary', body=event).execute()
print 'Event created: %s' % (event.get('htmlLink'))

Ruby

event = Google::Apis::CalendarV3::Event.new(
  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: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T09:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  end: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T17:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  recurrence: [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  attendees: [
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'lpage@example.com'
    ),
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'sbrin@example.com'
    )
  ],
  reminders: Google::Apis::CalendarV3::Event::Reminders.new(
    use_default: false,
    overrides: [
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'email',
        minutes: 24 * 60
      ),
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'popup',
        minutes: 10
      )
    ]
  )
)

result = client.insert_event('primary', event)
puts "Event created: #{result.html_link}"

הוספת קבצים מצורפים מ-Drive לאירועים

אתם יכולים לצרף לאירועים ביומן קבצים מ-Google Drive, כמו סיכומי פגישות ב-Docs, תקציבים ב-Sheets, מצגות ב-Slides או כל קובץ רלוונטי אחר מ-Google Drive. אפשר להוסיף את הקובץ כשיוצרים אירוע באמצעות events.insert() או מאוחר יותר כחלק מעדכון, למשל באמצעות events.patch().

כדי לצרף קובץ מ-Google Drive לאירוע, צריך לבצע שתי פעולות:

  1. משיגים את כתובת ה-URL של הקובץ alternateLink, title ו-mimeType ממשאב הקבצים של Drive API, בדרך כלל באמצעות ה-method‏ files.get().
  2. יוצרים או מעדכנים אירוע כשהשדות של attachments מוגדרים בגוף הבקשה והפרמטר supportsAttachments מוגדר כ-true.

בדוגמת הקוד הבאה אפשר לראות איך מעדכנים אירוע קיים כדי להוסיף קובץ מצורף:

Java

public static void addAttachment(Calendar calendarService, Drive driveService, String calendarId,
    String eventId, String fileId) throws IOException {
  File file = driveService.files().get(fileId).execute();
  Event event = calendarService.events().get(calendarId, eventId).execute();

  List<EventAttachment> attachments = event.getAttachments();
  if (attachments == null) {
    attachments = new ArrayList<EventAttachment>();
  }
  attachments.add(new EventAttachment()
      .setFileUrl(file.getAlternateLink())
      .setMimeType(file.getMimeType())
      .setTitle(file.getTitle()));

  Event changes = new Event()
      .setAttachments(attachments);
  calendarService.events().patch(calendarId, eventId, changes)
      .setSupportsAttachments(true)
      .execute();
}

PHP

function addAttachment($calendarService, $driveService, $calendarId, $eventId, $fileId) {
  $file = $driveService->files->get($fileId);
  $event = $calendarService->events->get($calendarId, $eventId);
  $attachments = $event->attachments;

  $attachments[] = array(
    'fileUrl' => $file->alternateLink,
    'mimeType' => $file->mimeType,
    'title' => $file->title
  );
  $changes = new Google_Service_Calendar_Event(array(
    'attachments' => $attachments
  ));

  $calendarService->events->patch($calendarId, $eventId, $changes, array(
    'supportsAttachments' => TRUE
  ));
}

Python

def add_attachment(calendarService, driveService, calendarId, eventId, fileId):
    file = driveService.files().get(fileId=fileId).execute()
    event = calendarService.events().get(calendarId=calendarId,
                                         eventId=eventId).execute()

    attachments = event.get('attachments', [])
    attachments.append({
        'fileUrl': file['alternateLink'],
        'mimeType': file['mimeType'],
        'title': file['title']
    })

    changes = {
        'attachments': attachments
    }
    calendarService.events().patch(calendarId=calendarId, eventId=eventId,
                                   body=changes,
                                   supportsAttachments=True).execute()

הוספת שיחות ועידה בווידאו ובטלפון לאירועים

אתם יכולים לשייך אירועים לשיחות ועידה ב-Hangouts וב-Google Meet כדי לאפשר למשתמשים להיפגש מרחוק באמצעות שיחת טלפון או שיחת וידאו.

אפשר להשתמש בשדה conferenceData כדי לקרוא, להעתיק ולמחוק פרטים קיימים של שיחות ועידה, וגם כדי לבקש ליצור שיחות ועידה חדשות. כדי לאפשר יצירה ושינוי של פרטי שיחת הוועידה, מגדירים את הפרמטר conferenceDataVersion של הבקשה לערך 1.

יש שלושה סוגים של conferenceData שנתמכים כרגע, כפי שמצוין ב-conferenceData.conferenceSolution.key.type:

  1. ‫Hangouts לצרכנים (eventHangout)
  2. הגרסה הקלאסית של Hangouts למשתמשי Google Workspace (הוצאה משימוש; eventNamedHangout)
  3. ‫Google Meet ‏(hangoutsMeet)

כדי לדעת איזה סוג של שיחת ועידה נתמך ביומן של משתמש מסוים, אפשר לבדוק את conferenceProperties.allowedConferenceSolutionTypes באוספים calendars ו-calendarList. אפשר גם לבדוק אם המשתמש מעדיף ליצור שיחות Hangouts לכל האירועים החדשים שהוא יוצר, על ידי בדיקת ההגדרה autoAddHangouts באוסף settings.

בנוסף ל-type, ה-conferenceSolution מספק גם את השדות name ו-iconUri, שבהם אפשר להשתמש כדי לייצג את הפתרון לשיחות ועידה, כמו שמוצג בהמשך:

JavaScript

const solution = event.conferenceData.conferenceSolution;

const content = document.getElementById("content");
const text = document.createTextNode("Join " + solution.name);
const icon = document.createElement("img");
icon.src = solution.iconUri;

content.appendChild(icon);
content.appendChild(text);

כדי ליצור שיחת ועידה חדשה לאירוע, צריך לספק createRequest עם requestId חדש שנוצר, שיכול להיות string אקראי. השיחות נוצרות באופן אסינכרוני, אבל תמיד אפשר לבדוק את סטטוס הבקשה כדי לעדכן את המשתמשים.

לדוגמה, כדי לבקש יצירת שיחת ועידה לאירוע קיים:

JavaScript

const eventPatch = {
  conferenceData: {
    createRequest: {requestId: "7qxalsvy0e"}
  }
};

gapi.client.calendar.events.patch({
  calendarId: "primary",
  eventId: "7cbh8rpc10lrc0ckih9tafss99",
  resource: eventPatch,
  sendUpdates: "all",
  conferenceDataVersion: 1
}).execute(function(event) {
  console.log("Conference created for event: %s", event.htmlLink);
});

יכול להיות שהתגובה המיידית לקריאה הזו עדיין לא תכיל את conferenceData המלא. זה מצוין על ידי קוד הסטטוס pending בשדה status. קוד הסטטוס משתנה ל-success אחרי שפרטי הוועידה מאוכלסים. השדה entryPoints מכיל מידע על מזהי ה-URI של הווידאו והטלפון שזמינים למשתמשים שלכם כדי להתקשר.

אם רוצים לקבוע כמה אירועים ביומן עם אותם פרטי שיחת ועידה, אפשר להעתיק את כל ה-conferenceData מאירוע אחד לאירוע אחר.

העתקה יכולה להיות שימושית במצבים מסוימים. לדוגמה, נניח שאתם מפתחים אפליקציה לגיוס עובדים שמגדירה אירועים נפרדים למועמד ולמראיין – אתם רוצים להגן על זהות המראיין, אבל גם לוודא שכל המשתתפים מצטרפים לאותה שיחת ועידה.