Google Calendar イベントリスト(予定)取得 (Google Calendar: Get events list(schedules))
Google Calendar にアクセスし、指定された期間に登録されているイベントリスト(予定)の一覧を取得します。
Configs
  • C1: Google カレンダー に接続するユーザ *
  • C2: CalendarIdをセットしてください *#{EL}
  • C3: 参照期間の開始日が格納されている日付型データを選択してください *
  • C4: 参照期間の終了日が格納されている日付型データを選択してください *
  • C5: UTCとの時差をセットしてください (例 +09:00) *#{EL}
  • C6: イベントリスト を保存するデータ項目 *
  • C7: 応答 を保存するデータ項目
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/ja/addons/googlecalendar-eventslist-get/
Addonファイルのインポートは Professional でのみご利用いただけます

Notes

  • カレンダーIDは次のページを参照します
    • [カレンダー設定](Calendar Settings)>[カレンダーのアドレス](Calendar Address)
  • 事前に Google API Manager にてProject登録をしておく必要があります(Scope: “https://www.googleapis.com/auth/calendar”)
  • 開始日(C3’)・終了日(C4’)は、C5に入力されたUTCとの時差(タイムゾーン)で指定されます

Capture

See also

%d