Google Calendar: Get events list (schedules)

Google Calendar: Get events list (schedules)

Google Calendar イベントリスト(予定)取得

Accesses Google Calendar and retrieves a list of events/schedules registered during the specified time period. Utilizing this Task in a Workflow will make it possible to get the next week’s schedule, and announce it by email.

Auto Step icon
Configs for this Auto Step
conf_UserID
C1: User who connects to Google Calendar *
conf_CalendarId
C2: Set CalendarID *#{EL}
conf_StartDate
C3: Select DATE DATA for Start Date *
conf_EndDate
C4: Select DATE DATA for End Date *
conf_Timezone
C5: Set Timezone of Date Data (e.g -07:00) *#{EL}
conf_EventsList
C6: Data Item that will save Events List *
conf_Response
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.";
  }

  /// 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(quser, 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 {Quser} quser 認証ユーザ
 * @param {calendarId} Calendar's ID
 * @param {Date} startDate 参照期間開始日
 * @param {Date} endDate 参照期間終了日
 * @param {String} timezone タイムゾーン
 * @return {String} HTTP-Response (String)
 */
function getEventsList(quser, 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()
    .googleOAuth2(quser, "Calendar")
    .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

warning Freely modifiable JavaScript (ECMAScript) code. No warranty of any kind.
(Installing Addon Auto-Steps are available only on the Professional edition.)

Notes

  • Users in C1 need to have a configured connection with Google Calendar in [Account Settings] > [Google Connectivity]
    • Google Workspace Connectivity ([System Settings] > [Google Connectivity]) must be enabled on the workflow platform ([System Administrator Authorization] required)
  • Refer to the following page for Calendar ID [Calendar Settings] > [Calendar Address]
  • The Start Date C3‘ and the End Date C4’ are specified in UTC with the time zone entered in C5

Capture

See Also

Scroll to Top

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading