本頁說明如何透過 Google Cloud Pub/Sub 接收 Google 雲端硬碟事件。
雲端硬碟事件代表雲端硬碟資源的活動或變更,例如資料夾中的新檔案。您可以透過事件瞭解發生了什麼事,然後採取行動,或以有意義的方式回應使用者。
以下列舉幾個事件用途:
觀察及回應檔案、資料夾或共用雲端硬碟的變更,例如檔案遭到編輯或上傳新修訂版本。
監控檔案變更,提升應用程式效能。
稽核檔案共用、移動和刪除等活動,有助於偵測潛在的資料外洩和未經授權存取。
深入瞭解使用者管理檔案的方式,找出可改善內容管理作業的領域。
追蹤檔案變更,確認是否符合法規要求或安全政策。
使用其他 Google Cloud 產品 (例如 Eventarc、Workflows 和 BigQuery) 分析雲端硬碟活動。
活動的運作方式
每當雲端硬碟發生事件時,系統就會建立、更新或刪除 Google 雲端硬碟 API 資源。雲端硬碟會使用事件,將發生的活動類型和受影響的雲端硬碟 API 資源等資訊傳送至應用程式。
Google 雲端硬碟會依類型分類事件。事件類型可協助您篩選並只接收需要的資訊類型,並以相同方式處理類似活動。
下表說明雲端硬碟中的活動如何影響相關的 Drive API 資源,以及 Drive 應用程式收到的事件類型:
活動 | Drive API 資源 | 事件類型 |
---|---|---|
使用者在資料夾或共用雲端硬碟中新增檔案。 | 已建立 File 資源。 |
新增檔案 |
使用者對檔案建立存取權提案。 | 已建立 AccessProposal 資源。 |
新的存取權提議 |
接收 Google 雲端硬碟的事件
傳統上,您的雲端硬碟應用程式可以透過 Drive API 或 Google Drive Activity API 找出事件。Google Workspace Events API 新增雲端硬碟事件後,現在有第三種接收事件的方法:
開發人員預覽版:使用 Google Workspace Events API 訂閱事件,即可在事件發生時收到通知。詳情請參閱「訂閱 Google 雲端硬碟事件」。
使用 Drive API 訂閱事件。使用
changes.watch
方法取得使用者變更事件,或使用files.watch
方法取得檔案變更事件。呼叫 Google Drive Activity API,查詢近期事件。
下表說明訂閱事件與查詢事件的差異和原因:
訂閱 Google Workspace 事件 | 訂閱雲端硬碟 API 監控事件 | 查詢 Drive Activity API 事件 | |
---|---|---|---|
用途 |
|
|
|
API | Google Workspace Events API | Drive API | Drive Activity API |
事件來源 | 檔案、資料夾和共用雲端硬碟 |
changes.watch 和files.watch
|
DriveActivity
|
支援的事件 |
|
Channel
如需支援的事件類型清單,請參閱 Drive API 說明文件中的「 瞭解 Google 雲端硬碟 API 通知事件」。 |
Action
如要查看支援的欄位清單,請參閱 Drive Activity API 參考文件中的 Action 資源。
|
事件格式 | Pub/Sub 訊息,格式符合 CloudEvent 規格。詳情請參閱「Google Workspace 事件結構」。 |
Drive API 資源 (Channel )
|
Drive Activity API 資源 (Action )
|
事件資料 | Base64 編碼字串,可包含或不包含資源資料。如需範例酬載,請參閱「事件資料」。 |
包含資源資料的 JSON 酬載。如需有效負載範例,請參閱參考說明文件中的Channel 資源
。 |
包含資源資料的 JSON 酬載。如需酬載範例,請參閱參考說明文件中的activity.query 回應本文
。 |
開始使用雲端硬碟事件
本指南說明如何建立及管理雲端硬碟資源的 Google Workspace 事件訂閱項目。這樣一來,應用程式就能透過 Google Cloud Pub/Sub 接收事件。
建立 Google Cloud 專案
如要產生 Google Cloud 專案,請參閱「建立 Google Cloud 專案」。
啟用 Google Workspace Events API、Google Cloud Pub/Sub API 和 Google Drive API
使用 Google API 前,請先在 Google Cloud 專案中啟用這些 API。您可以在單一 Google Cloud 專案中啟用一或多個 API。Google Cloud 控制台
在 Google Cloud 控制台中,開啟應用程式的 Google Cloud 專案,並啟用 Google Workspace Events API、Pub/Sub API 和 Drive API:
確認您要在正確的 Cloud 專案中啟用 API,然後按一下「下一步」。
確認要啟用的 API 正確無誤,然後按一下「啟用」。
gcloud
在工作目錄中登入 Google 帳戶:
gcloud auth login
將專案設為應用程式的 Cloud 專案:
gcloud config set project PROJECT_ID
將
PROJECT_ID
替換為應用程式的 Cloud 專案專案 ID。啟用 Google Workspace Events API、Pub/Sub API 和 Drive API:
gcloud services enable workspaceevents.googleapis.com \ pubsub.googleapis.com \ drive.googleapis.com
設定用戶端 ID
如要產生 OAuth 2.0 用戶端 ID,請參閱「建立 OAuth 用戶端 ID 憑證」。
建立 Pub/Sub 主題
建立訂閱項目前,您必須先建立 Google Cloud Pub/Sub 主題,接收應用程式感興趣的相關事件。如要建立 Pub/Sub 主題,請參閱「建立及訂閱 Pub/Sub 主題」。
請務必在要求中參照雲端硬碟服務帳戶 (drive-api-event-push@system.gserviceaccount.com
)。
建立雲端硬碟訂閱項目
當訂閱主體 (或主體階層下方的任何其他檔案) 變更時,系統會調度雲端事件。舉例來說,如果您在共用雲端硬碟中建立訂閱項目,而該共用雲端硬碟中某個檔案 (位於多個子資料夾內) 發生變更,系統就會產生事件。如要瞭解支援的資源和 Google 雲端硬碟事件類型,請參閱「建立訂閱項目的事件類型」。
下列 Node.js 應用程式會在檔案或資料夾上建立雲端硬碟事件訂閱項目,以監聽內容變更事件。詳情請參閱「建立 Google Workspace 訂閱方案」。
如要執行這個範例,請確認已安裝 Node.js 和 npm。 此外,您也必須確認已安裝執行這個範例所需的依附元件。
# Install needed dependencies
$ npm install googleapis @google-cloud/local-auth axios
如要建立雲端硬碟訂閱項目,請使用 Google Workspace Events API 的 subscriptions.create()
方法建立 Subscription
資源:
// app.js
const fs = require('fs').promises;
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const axios = require('axios');
// Scopes for Google Drive API access.
const SCOPES = ['SCOPES'];
/**
* Authenticates the user running the script.
* @return {Promise<OAuth2Client>} The authorized client.
*/
async function authorize() {
const client = await authenticate({
scopes: SCOPES,
keyfilePath: 'credentials.json',
});
if (client.credentials) {
const content = await fs.readFile('credentials.json');
const keys = JSON.parse(content);
const {client_id, client_secret} = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id,
client_secret,
refresh_token: client.credentials.refresh_token,
});
await fs.writeFile('token.json', payload);
return client;
} else {
throw new Exception(
'credentials.json did not have the Oauth client secret or it was not properly formatted');
}
}
/**
* Creates a subscription to Google Drive events.
* @param {OAuth2Client} authClient An authorized OAuth2 client.
*/
async function createSubscription(authClient) {
const url = 'https://workspaceevents.googleapis.com/v1beta/subscriptions';
const data = {
targetResource: 'TARGET_RESOURCE',
eventTypes: ['EVENT_TYPES'],
payload_options: {
include_resource: {
{
'<var>RESOURCE_DATA</var>'
}
}
},
drive_options: {
include_descendants: {
{
'<var>INCLUDE_DESCENDANTS</var>'
}
}
},
notification_endpoint: {pubsub_topic: 'TOPIC_NAME'}
};
try {
const {token} = await authClient.getAccessToken();
const response = await axios.post(
url, data, {headers: {'Authorization': `Bearer ${token}`}});
console.log('Subscription created:', response.data);
} catch (error) {
const message = error.response ? error.response.data : error.message;
console.error('Error creating subscription:', message);
}
}
authorize().then(createSubscription).catch(console.error);
更改下列內容:
SCOPES
:一或多個 OAuth 範圍,支援訂閱項目的每個事件類型。格式為字串陣列。如要列出多個範圍,請以半形逗號分隔。最佳做法是使用限制最多的範圍,但仍允許應用程式運作。例如:'https://www.googleapis.com/auth/drive.file'
TARGET_RESOURCE
:您訂閱的 Google Workspace 資源,格式為完整資源名稱。舉例來說,如要訂閱雲端硬碟檔案或資料夾,請使用//drive.googleapis.com/files/FileID
。EVENT_TYPES
:要在目標資源中訂閱的一或多個事件類型。格式為字串陣列,例如'google.workspace.drive.file.v3.contentChanged'
。RESOURCE_DATA
:布林值,用於指定訂閱項目是否在事件酬載中包含資源資料。這項屬性會影響訂閱方案的有效時間。詳情請參閱「事件資料」。True
:包含所有資源資料。如要限制要納入哪些欄位,請新增fieldMask
,並為變更的資源指定至少一個欄位。僅支援訂閱 Chat 和雲端硬碟資源,包括資源資料。False
:排除資源資料。
INCLUDE_DESCENDANTS
:屬於DriveOptions
的布林值欄位。只有在targetResource
是雲端硬碟檔案或共用雲端硬碟,且 MIME 類型設為application/vnd.google-apps.folder
時,才能使用這項功能。無法在「我的雲端硬碟」或共用雲端硬碟的根資料夾中設定。True
:訂閱項目包含事件清單中的所有子項雲端硬碟檔案。False
:系統會為指定為targetResource
的單一檔案或共用雲端硬碟建立訂閱項目。
TOPIC_NAME
:您在 Cloud 專案中建立的 Pub/Sub 主題完整名稱。這個 Pub/Sub 主題會接收訂閱項目的事件。格式為projects/PROJECT_ID/topics/TOPIC_ID
。notificationEndpoint
欄位用於指定 Pub/Sub 主題,訂閱項目會將事件傳送至該主題。
測試 Google 雲端硬碟訂閱方案
如要測試是否能接收雲端硬碟事件,您可以觸發事件,然後將訊息提取至 Pub/Sub 訂閱項目。詳情請參閱「測試 Google Workspace 訂閱方案」。
使用 Cloud Functions 處理 Google 雲端硬碟事件
系統會將雲端硬碟事件傳送至您建立的訂閱項目中的 Pub/Sub 主題。建立觸發條件時,請確認觸發條件的 Pub/Sub 主題與事件訂閱項目的 Pub/Sub 主題相符。接著部署 Cloud Run 函式,並編輯檔案,即可在記錄檔中查看事件變更。
建立函式前,請先更新依附元件的 package.json
:
{
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0",
"cloudevents": "^8.0.0"
}
}
接著,建立函式的原始碼:
const functions = require('@google-cloud/functions-framework');
const { HTTP } = require("cloudevents");
/**
* A Cloud Function triggered by Pub/Sub messages containing Google Drive activity events.
* This function processes different types of Drive events.
*
* @param {object} cloudEvent The CloudEvent object.
* @param {object} cloudEvent.data The data payload from the event source.
*/
functions.cloudEvent('helloFromDrive', async (cloudEvent) => {
try {
// Verify the Pub/Sub message exists
if (!cloudEvent.data || !cloudEvent.data.message) {
console.warn("Event is missing the Pub/Sub message payload.");
return;
}
// Extract the Pub/Sub message details
const { message } = cloudEvent.data;
const { attributes, data } = message;
// The original Drive CloudEvent is reconstructed from the Pub/Sub message attributes
const driveEvent = HTTP.toEvent({ headers: attributes });
const { type } = driveEvent;
// The Drive event's payload is a base64 encoded JSON string
const payload = JSON.parse(Buffer.from(data, "base64").toString());
console.log(`Processing Drive event type: ${type}`);
// Use a switch statement to handle different event types
switch (type) {
case 'google.workspace.drive.file.v3.contentChanged':
console.log('File Content Changed:', payload);
break;
case 'google.workspace.drive.accessproposal.v3.created':
console.log('Access Proposal Created:', payload);
break;
default:
console.log(`Received unhandled event type: ${type}`);
break;
}
} catch (error) {
console.error("An error occurred while processing the Drive event:", error);
}
});
限制
- 當
DriveOptions
中的includeDescendants
布林欄位為true
時,即使觸發事件的檔案位於雲端硬碟訂閱項目所用資料夾的許多層級下方,共用雲端硬碟和資料夾上的雲端硬碟訂閱項目仍會一律傳送事件。 - 即使您已為資料夾建立訂閱項目,您可能仍無法接收檔案階層中的所有事件,因為使用者或應用程式可能未獲授權存取這些事件。在這種情況下,訂閱項目仍有效,但您無法存取資源,因此不會收到任何事件。
- 系統支援訂閱所有檔案和資料夾的事件,但不支援訂閱共用雲端硬碟的根資料夾。訂閱功能僅支援共用雲端硬碟內的檔案和資料夾。直接對共用雲端硬碟的根資料夾所做的變更不會觸發事件。
- 授權訂閱的使用者必須擁有與訂閱事件相應的檔案權限。
- 訂閱項目只會接收使用者透過 Google Workspace 帳戶或 Google 帳戶存取資源的事件。