Google Calendar: Get events list(schedules)
Accesses to Google Calendar and retrieves a list of events (schedules) registered in the specified period. Combining this Task with Workflows will make it possible to get the next week’s schedule, and notify (announce) it by email.
Configs
  • C1: User who connects to Google Calendar *
  • C2: Set CalendarID *#{EL}
  • C3: Select DATE DATA for Start Date *
  • C4: Select DATE DATA for End Date *
  • C5: Set Timezone of Date Data (e.g -07:00) *#{EL}
  • C6: Data Item that will save Events List *
  • C7: Data Item that will save Response
Script (click to open)
/*
Notes(en):
- This request requires authorization with at least one of the following scopes:
    - https://www.googleapis.com/auth/calendar.readonly
    - https://www.googleapis.com/auth/calendar
    - https://www.googleapis.com/auth/calendar.events.readonly
    - https://www.googleapis.com/auth/calendar.events
- Supports both My Calendars and Other Calendars.

Notes(ja):
- カレンダー権限を持つユーザにより、OAuth認可される必要があります。(以下のうち少なくとも1つ)
    - https://www.googleapis.com/auth/calendar.readonly
    - https://www.googleapis.com/auth/calendar
    - https://www.googleapis.com/auth/calendar.events.readonly
    - https://www.googleapis.com/auth/calendar.events
- マイカレンダーと他のカレンダーの両方をサポートします。

Notes:
- See Also
   - https://developers.google.com/calendar/v3/reference/events/list
- To Get "ClientId" and "Secret"
    - Access to https://console.developers.google.com/
- OAuth Setting sample
    - "Authorization Endpoint URL"
        - https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force
    - "Token Endpoint URL"
        - https://accounts.google.com/o/oauth2/token
    - "Scope"
        - https://www.googleapis.com/auth/calendar.events.readonly
- Error Log sample (wrong CalendarID or Scope)
    - AutomatedTask UnexpectedResponseError: 404
        - { "error": {
        - "errors": [ {
        -     "domain": "global",
        -     "reason": "notFound",
        -     "message": "Not Found"
        -    } ],
        -   "code": 404,
        -   "message": "Not Found"
        - } }

*/

//////// START "main()" /////////////////////////////////////////////////////////////////
main();
function main() {

  //// == Config Retrieving / 工程コンフィグの参照 ==
  const quser = configs.getObject( "conf_UserID" ); // com.questetra.bpms.core.event.scripttask.QuserView
  const calendarId = configs.get( "conf_CalendarId" );
  const startDateNum = configs.get( "conf_StartDate" );
  const endDateNum = configs.get( "conf_EndDate" );
  let   timezone = configs.get( "conf_Timezone" );
  const eventsListNum = configs.get( "conf_EventsList" );
  const responseNum = configs.get( "conf_Response" );


  //// == Data Retrieving / ワークフローデータの参照 ==
  const startDate = engine.findDataByNumber(startDateNum); // com.questetra.bpms.util.AddableDate
  const endDate = engine.findDataByNumber(endDateNum); // com.questetra.bpms.util.AddableDate


  //// == Calculating / 演算 ==
  /// Check Required
  if ( calendarId === null || calendarId === "" ) {
    throw "the CalendarID is empty.";
  }
  if ( startDate === null ) {
    throw "the Start Date is empty.";
  }
  if ( endDate === null ) {
    throw "the End Date is empty.";
  }
  if ( timezone === null || timezone === "" ) {
    throw "the Timezone is empty.";
  }

  /// obtain OAuth2 Access Token
  let token;
  try {
    token = httpClient.getGoogleOAuth2Token(quser, "Calendar");
  } catch (e) {
    throw "This User has not connected with Google Calendar.";
  }

  /// Check Start Date / End Date Validity
  if ( startDate.compareTo( endDate ) >= 1 ) {
    // startDate > endDate
    throw "The End Date should be the day after the Start Date.";
  }

  /// Check Timezone Validity
  if ( timezone.match(/^([\+\-]?)([01][0-9]|2[0-3]):([0-5][0-9])$/) == null ) {
    throw "The Timezone format is incorrect.";
  } else if ( timezone.match(/^([01][0-9]|2[0-3]):([0-5][0-9])$/) !== null ) {
    // e.g.)  00:00, 09:00, -08:00  -->  +00:00, +09:00, -08:00
    timezone = "+" + timezone;
  }

  /// Get Events List
  const responseTxt = getEventsList(token, calendarId, startDate, endDate, timezone);

  /// Retrieve StartDate/StartTime/Summary date
  const eventsListTsv = retrieveData( JSON.parse(responseTxt) );


  //// == Data Updating / ワークフローデータへの代入 ==
  engine.setDataByNumber( eventsListNum, eventsListTsv );
  if ( responseNum !== null && responseNum !== "") {
    engine.setDataByNumber( responseNum, responseTxt );
  }

} //////// END "main()" /////////////////////////////////////////////////////////////////


/**
 * Google Calendar からイベントリスト(予定)を取得する
 * @param {String} token OAuth2 Token
 * @param {calendarId} Calendar's ID
 * @param {Date} startDate 参照期間開始日
 * @param {Date} endDate 参照期間終了日
 * @param {String} timezone タイムゾーン
 * @return {String} HTTP-Response (String)
 */
function getEventsList(token, calendarId, startDate, endDate, timezone) {

  const uri = "https://www.googleapis.com/calendar/v3/calendars/" + calendarId + "/events";
  const sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");

  const response = httpClient.begin()
    .bearer( token )
    .queryParam( "timeMax", sdf.format(endDate)   + "T23:59:59" + timezone )
    .queryParam( "timeMin", sdf.format(startDate) + "T00:00:00" + timezone )
    .queryParam( "timeZone", timezone )
    .queryParam( "singleEvents", "True" )
    .queryParam( "orderBy", "startTime" )
    .get( uri );

  const status = response.getStatusCode();
  const responseTxt = response.getResponseAsString();

  if (status >= 300) {
    const error = `Failed to create\nstatus:${status}`;
    engine.log(responseTxt);
    throw error;
  }

  return responseTxt;
}

/**
 * 取得したイベントリスト(予定)から 開始日/開始日時/サマリーを抽出する
 * @param {String} eventsListJson イベントリスト(予定)のJSON
 * @return {String} eventsListTsv イベントリスト(予定)の開始日/開始日時/サマリーのTSV
 */
function retrieveData(eventsListJson) {

  let eventsListTsv = "";

  for( let i = 0; i < eventsListJson.items.length; i++ ) {
  
    if ( "dateTime" in eventsListJson.items[i].start ) {
      // "dateTime": "2021-01-18T13:00:00+09:00"
      eventsListTsv += eventsListJson.items[i].start.dateTime.substring(0, 10);
      eventsListTsv += "\t(" + eventsListJson.items[i].start.dateTime.substring(11, 16) + ") \t";
    } else if ( "date" in eventsListJson.items[i].start ) {
      // "date": "2021-01-18"
      eventsListTsv += eventsListJson.items[i].start.date;
      eventsListTsv += "\t(--:--) \t";
    }
    
    eventsListTsv += eventsListJson.items[i].summary;
    eventsListTsv += "\n";
  }

  return eventsListTsv.slice(0, -1);
}

Download

2021-01-08 (C) Questetra, Inc. (MIT License)
https://support.questetra.com/addons/googlecalendar-eventslist-get/
The Addon-import feature is available with Professional edition.

Notes

  • Refer to the following page for Calendar ID
    • [Calendar Settings] > [Calendar Address]
  • You need to register Project at Google API Manager beforehand (Scope: “https://www.googleapis.com/auth/calendar”)
  • The Start Date C3 ‘ and the End Date C4’ are specified in UTC with the time zone entered in C5

Capture

See also

1 thought on “Google Calendar Get events list (schedules)”

  1. Pingback: Google Calendar Event List – Questetra Support

Comments are closed.

%d bloggers like this: