Skip to content

Commit

Permalink
feat: Update space notification sample to use new OAuth API (#965)
Browse files Browse the repository at this point in the history
* feat: Samples for space notification setting APIs

* feat: Update space notification sample to use new OAuth API.

* fix: remove the incorrect client lib reference.
  • Loading branch information
davidjunhuo authored Feb 25, 2025
1 parent 4517e8f commit 45983c4
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 167 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,97 +17,27 @@

// [START chat_get_space_notification_setting_user_cred]

const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {ChatServiceClient} = require('@google-apps/chat');
const {auth} = require('google-auth-library');
import {createClientWithUserCredentials} from './authentication-utils.js';

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/chat.users.spacesettings'];
const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.users.spacesettings'];

// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/**
* Reads previously authorized credentials from the save file.
*
* @return {Promise<OAuth2Client|null>}
*/
async function loadSavedCredentialsIfExist() {
try {
const content = await fs.readFile(TOKEN_PATH);
const credentials = JSON.parse(content);
return auth.fromJSON(credentials);
} catch (err) {
console.log(err);
return null;
}
}

/**
* Serializes credentials to a file compatible with GoogleAuth.fromJSON.
*
* @param {OAuth2Client} client
* @return {Promise<void>}
*/
async function saveCredentials(client) {
const content = await fs.readFile(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id: key.client_id,
client_secret: key.client_secret,
refresh_token: client.credentials.refresh_token,
});
await fs.writeFile(TOKEN_PATH, payload);
}

/**
* Load or request or authorization to call APIs.
*
* @return {Promise<OAuth2Client>}
*/
async function authorize() {
let client = await loadSavedCredentialsIfExist();
if (client) {
return client;
}
client = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
if (client.credentials) {
await saveCredentials(client);
}
return client;
}

/**
* Gets space notification settings with user credential.
* @param {OAuth2Client} authClient An authorized OAuth2 client.
*/
async function getSpaceNotificationSetting(authClient) {
// This sample shows how to get the space notification setting for the calling user
async function main() {
// Create a client
const chatClient = new ChatServiceClient({
authClient: authClient,
scopes: SCOPES,
});
const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

// Initialize request argument(s)
// Initialize request argument(s), replace the SPACE_NAME with an actual space name.
const request = {
name : 'users/me/spaces/AAAA1XmS6pY/spaceNotificationSetting'
name : 'users/me/spaces/SPACE_NAME/spaceNotificationSetting'
};

// Make the request
const result = await chatClient.getSpaceNotificationSetting(request);
const response = await chatClient.getSpaceNotificationSetting(request);

console.log(result)
// Handle the response
console.log(response);
}

authorize().then(getSpaceNotificationSetting).catch(console.error);
main().catch(console.error);

// [END chat_get_space_notification_setting_user_cred]
2 changes: 2 additions & 0 deletions chat/client-libraries/cloud/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,15 @@
"get-message-user-cred.js": "node ./get-message-user-cred.js",
"get-space-app-cred.js": "node ./get-space-app-cred.js",
"get-space-event-user-cred.js": "node ./get-space-event-user-cred.js",
"get-space-notification-setting-user-cred.js": "node ./get-space-notification-setting-user-cred.js",
"get-space-user-cred.js": "node ./get-space-user-cred.js",
"get-space-read-state-user-cred.js": "node ./get-space-read-state-user-cred.js",
"get-thread-read-state-user-cred.js": "node ./get-thread-read-state-user-cred.js",
"set-up-space-user-cred.js": "node ./set-up-space-user-cred.js",
"update-membership-user-cred.js": "node ./update-membership-user-cred.js",
"update-message-app-cred.js": "node ./update-message-app-cred.js",
"update-message-user-cred.js": "node ./update-message-user-cred.js",
"update-space-notification-setting-user-cred.js": "node ./update-space-notification-setting-user-cred.js",
"update-space-read-state-user-cred.js": "node ./update-space-read-state-user-cred.js",
"update-space-user-cred.js": "node ./update-space-user-cred.js",
"list-memberships-app-cred.js": "node ./list-memberships-app-cred.js",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,102 +17,32 @@

// [START chat_update_space_notification_setting_user_cred]

const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {ChatServiceClient} = require('@google-apps/chat');
const {auth} = require('google-auth-library');
import {createClientWithUserCredentials} from './authentication-utils.js';

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/chat.users.spacesettings'];
const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.users.spacesettings'];

// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/**
* Reads previously authorized credentials from the save file.
*
* @return {Promise<OAuth2Client|null>}
*/
async function loadSavedCredentialsIfExist() {
try {
const content = await fs.readFile(TOKEN_PATH);
const credentials = JSON.parse(content);
return auth.fromJSON(credentials);
} catch (err) {
console.log(err);
return null;
}
}

/**
* Serializes credentials to a file compatible with GoogleAuth.fromJSON.
*
* @param {OAuth2Client} client
* @return {Promise<void>}
*/
async function saveCredentials(client) {
const content = await fs.readFile(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id: key.client_id,
client_secret: key.client_secret,
refresh_token: client.credentials.refresh_token,
});
await fs.writeFile(TOKEN_PATH, payload);
}

/**
* Load or request or authorization to call APIs.
*
* @return {Promise<OAuth2Client>}
*/
async function authorize() {
let client = await loadSavedCredentialsIfExist();
if (client) {
return client;
}
client = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
if (client.credentials) {
await saveCredentials(client);
}
return client;
}

/**
* Updates space notification settings with user credential.
* @param {OAuth2Client} authClient An authorized OAuth2 client.
*/
async function updateSpaceNotificationSetting(authClient) {
// This sample shows how to update the space notification setting for the calling user
async function main() {
// Create a client
const chatClient = new ChatServiceClient({
authClient: authClient,
scopes: SCOPES,
});
const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

// Initialize request argument(s)
// Initialize request argument(s), replace the SPACE_NAME with an actual space name.
const request = {
spaceNotificationSetting : {
name : 'users/me/spaces/AAAA1XmS6pY/spaceNotificationSetting',
name : 'users/me/spaces/SPACE_NAME/spaceNotificationSetting',
notificationSetting : 'ALL',
muteSetting : 'UNMUTED'
},
updateMask : { paths: ['notification_setting','mute_setting']}
};

// Make the request
const result = await chatClient.updateSpaceNotificationSetting(request);
const response = await chatClient.updateSpaceNotificationSetting(request);

console.log(result)
// Handle the response
console.log(response);
}

authorize().then(updateSpaceNotificationSetting).catch(console.error);
main().catch(console.error);

// [END chat_update_space_notification_setting_user_cred]

0 comments on commit 45983c4

Please sign in to comment.