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

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

Google Calendar: Get events list(schedules)

Google Calendar にアクセスし、指定された期間に登録されているイベントリスト(予定)の一覧を取得します。

Auto Step icon
Configs for this Auto Step
conf_UserID
C1: Google カレンダー に接続するユーザ *
conf_CalendarId
C2: CalendarIdをセットしてください *#{EL}
conf_StartDate
C3: 参照期間の開始日が格納されている日付型データを選択してください *
conf_EndDate
C4: 参照期間の終了日が格納されている日付型データを選択してください *
conf_Timezone
C5: UTCとの時差をセットしてください (例 +09:00) *#{EL}
conf_EventsList
C6: イベントリスト を保存するデータ項目 *
conf_Response
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.";
  }

  /// 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 自由改変可能な JavaScript (ECMAScript) コードです。いかなる保証もありません。
(アドオン自動工程のインストールは Professional editionでのみ可能です)

Notes

  • C1 のユーザは、[アカウント設定]>[Google 連携]にて、Google カレンダーと連携済みである必要があります
    • ワークフロー基盤にて、Google 連携設定([システム設定]>[Google 連携])が必要です(要[システム管理権限])
  • カレンダーIDは次のページを参照します。[カレンダー設定](Calendar Settings)>[カレンダーのアドレス](Calendar Address)
  • 開始日(C3’)・終了日(C4’)は、C5に入力されたUTCとの時差(タイムゾーン)で指定されます

Capture

See Also

上部へスクロール

Questetra Supportをもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む