0) {
- Logger.log('Users:');
- for (i = 0; i < users.length; i++) {
- var user = users[i];
- Logger.log('%s (%s)', user.primaryEmail, user.name.fullName);
+ try {
+ const response = AdminDirectory.Users.list(optionalArgs);
+ const users = response.users;
+ if (!users || users.length === 0) {
+ console.log('No users found.');
+ return;
}
- } else {
- Logger.log('No users found.');
+ // Print the list of user's full name and email
+ console.log('Users:');
+ for (const user of users) {
+ console.log('%s (%s)', user.primaryEmail, user.name.fullName);
+ }
+ } catch (err) {
+ // TODO (developer)- Handle exception from the Directory API
+ console.log('Failed with error %s', err.message);
}
}
// [END admin_sdk_directory_quickstart]
diff --git a/adminSDK/reports/quickstart.gs b/adminSDK/reports/quickstart.gs
index a5c7e6d56..5b5778886 100644
--- a/adminSDK/reports/quickstart.gs
+++ b/adminSDK/reports/quickstart.gs
@@ -15,25 +15,31 @@
*/
// [START admin_sdk_reports_quickstart]
/**
- * List login events for a G Suite domain.
+ * List login events for a Google Workspace domain.
+ * @see https://developers.google.com/admin-sdk/reports/reference/rest/v1/activities/list
*/
function listLogins() {
- var userKey = 'all';
- var applicationName = 'login';
- var optionalArgs = {
+ const userKey = 'all';
+ const applicationName = 'login';
+ const optionalArgs = {
maxResults: 10
};
- var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs);
- var activities = response.items;
- if (activities && activities.length > 0) {
- Logger.log('Logins:');
- for (i = 0; i < activities.length; i++) {
- var activity = activities[i];
- Logger.log('%s: %s (%s)', activity.id.time, activity.actor.email,
+ try {
+ const response = AdminReports.Activities.list(userKey, applicationName, optionalArgs);
+ const activities = response.items;
+ if (!activities || activities.length === 0) {
+ console.log('No logins found.');
+ return;
+ }
+ // Print login events
+ console.log('Logins:');
+ for (const activity of activities) {
+ console.log('%s: %s (%s)', activity.id.time, activity.actor.email,
activity.events[0].name);
}
- } else {
- Logger.log('No logins found.');
+ } catch (err) {
+ // TODO (developer)- Handle exception from the Report API
+ console.log('Failed with error %s', err.message);
}
}
// [END admin_sdk_reports_quickstart]
diff --git a/adminSDK/reseller/quickstart.gs b/adminSDK/reseller/quickstart.gs
index dbcff972c..3e7ee0e6b 100644
--- a/adminSDK/reseller/quickstart.gs
+++ b/adminSDK/reseller/quickstart.gs
@@ -15,23 +15,28 @@
*/
// [START admin_sdk_reseller_quickstart]
/**
- * List Admin SDK reseller subscriptions.
+ * List Admin SDK reseller.
+ * @see https://developers.google.com/admin-sdk/reseller/reference/rest/v1/subscriptions/list
*/
function listSubscriptions() {
- var optionalArgs = {
+ const optionalArgs = {
maxResults: 10
};
- var response = AdminReseller.Subscriptions.list(optionalArgs);
- var subscriptions = response.subscriptions;
- if (subscriptions && subscriptions.length > 0) {
- Logger.log('Subscriptions:');
- for (i = 0; i < subscriptions.length; i++) {
- var subscription = subscriptions[i];
- Logger.log('%s (%s, %s)', subscription.customerId, subscription.skuId,
+ try {
+ const response = AdminReseller.Subscriptions.list(optionalArgs);
+ const subscriptions = response.subscriptions;
+ if (!subscriptions || subscriptions.length === 0) {
+ console.log('No subscriptions found.');
+ return;
+ }
+ console.log('Subscriptions:');
+ for (const subscription of subscriptions) {
+ console.log('%s (%s, %s)', subscription.customerId, subscription.skuId,
subscription.plan.planName);
}
- } else {
- Logger.log('No subscriptions found.');
+ } catch (err) {
+ // TODO (developer)- Handle exception from the Reseller API
+ console.log('Failed with error %s', err.message);
}
}
// [END admin_sdk_reseller_quickstart]
diff --git a/advanced/README.md b/advanced/README.md
index 6b891373a..0efa5d004 100644
--- a/advanced/README.md
+++ b/advanced/README.md
@@ -4,4 +4,4 @@ This directory contains samples for using Apps Script Advanced Services.
> Note: These services must be [enabled](https://developers.google.com/apps-script/guides/services/advanced#enabling_advanced_services) before running these samples.
-Learn more: https://developers.google.com/apps-script/guides/services/advanced
+Learn more at [developers.google.com](https://developers.google.com/apps-script/guides/services/advanced).
diff --git a/advanced/adminSDK.gs b/advanced/adminSDK.gs
index 3fcfcdc68..c0aed633d 100644
--- a/advanced/adminSDK.gs
+++ b/advanced/adminSDK.gs
@@ -16,10 +16,11 @@
// [START apps_script_admin_sdk_list_all_users]
/**
* Lists all the users in a domain sorted by first name.
+ * @see https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list
*/
function listAllUsers() {
- var pageToken;
- var page;
+ let pageToken;
+ let page;
do {
page = AdminDirectory.Users.list({
domain: 'example.com',
@@ -27,14 +28,14 @@ function listAllUsers() {
maxResults: 100,
pageToken: pageToken
});
- var users = page.users;
- if (users) {
- for (var i = 0; i < users.length; i++) {
- var user = users[i];
- Logger.log('%s (%s)', user.name.fullName, user.primaryEmail);
- }
- } else {
- Logger.log('No users found.');
+ const users = page.users;
+ if (!users) {
+ console.log('No users found.');
+ return;
+ }
+ // Print the user's full name and email.
+ for (const user of users) {
+ console.log('%s (%s)', user.name.fullName, user.primaryEmail);
}
pageToken = page.nextPageToken;
} while (pageToken);
@@ -43,12 +44,19 @@ function listAllUsers() {
// [START apps_script_admin_sdk_get_users]
/**
-* Get a user by their email address and logs all of their data as a JSON string.
-*/
+ * Get a user by their email address and logs all of their data as a JSON string.
+ * @see https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/get
+ */
function getUser() {
- var userEmail = 'liz@example.com';
- var user = AdminDirectory.Users.get(userEmail);
- Logger.log('User data:\n %s', JSON.stringify(user, null, 2));
+ // TODO (developer) - Replace userEmail value with yours
+ const userEmail = 'liz@example.com';
+ try {
+ const user = AdminDirectory.Users.get(userEmail);
+ console.log('User data:\n %s', JSON.stringify(user, null, 2));
+ } catch (err) {
+ // TODO (developer)- Handle exception from the API
+ console.log('Failed with error %s', err.message);
+ }
}
// [END apps_script_admin_sdk_get_users]
@@ -59,7 +67,8 @@ function getUser() {
* @see https://developers.google.com/admin-sdk/directory/v1/reference/users/insert
*/
function addUser() {
- var user = {
+ let user = {
+ // TODO (developer) - Replace primaryEmail value with yours
primaryEmail: 'liz@example.com',
name: {
givenName: 'Elizabeth',
@@ -68,46 +77,59 @@ function addUser() {
// Generate a random password string.
password: Math.random().toString(36)
};
- user = AdminDirectory.Users.insert(user);
- Logger.log('User %s created with ID %s.', user.primaryEmail, user.id);
+ try {
+ user = AdminDirectory.Users.insert(user);
+ console.log('User %s created with ID %s.', user.primaryEmail, user.id);
+ } catch (err) {
+ // TODO (developer)- Handle exception from the API
+ console.log('Failed with error %s', err.message);
+ }
}
// [END apps_script_admin_sdk_add_user]
// [START apps_script_admin_sdk_create_alias]
/**
* Creates an alias (nickname) for a user.
+ * @see https://developers.google.com/admin-sdk/directory/reference/rest/v1/users.aliases/insert
*/
function createAlias() {
- var userEmail = 'liz@example.com';
- var alias = {
+ // TODO (developer) - Replace userEmail value with yours
+ const userEmail = 'liz@example.com';
+ let alias = {
alias: 'chica@example.com'
};
- alias = AdminDirectory.Users.Aliases.insert(alias, userEmail);
- Logger.log('Created alias %s for user %s.', alias.alias, userEmail);
+ try {
+ alias = AdminDirectory.Users.Aliases.insert(alias, userEmail);
+ console.log('Created alias %s for user %s.', alias.alias, userEmail);
+ } catch (err) {
+ // TODO (developer)- Handle exception from the API
+ console.log('Failed with error %s', err.message);
+ }
}
// [END apps_script_admin_sdk_create_alias]
// [START apps_script_admin_sdk_list_all_groups]
/**
* Lists all the groups in the domain.
+ * @see https://developers.google.com/admin-sdk/directory/reference/rest/v1/groups/list
*/
function listAllGroups() {
- var pageToken;
- var page;
+ let pageToken;
+ let page;
do {
page = AdminDirectory.Groups.list({
domain: 'example.com',
maxResults: 100,
pageToken: pageToken
});
- var groups = page.groups;
- if (groups) {
- for (var i = 0; i < groups.length; i++) {
- var group = groups[i];
- Logger.log('%s (%s)', group.name, group.email);
- }
- } else {
- Logger.log('No groups found.');
+ const groups = page.groups;
+ if (!groups) {
+ console.log('No groups found.');
+ return;
+ }
+ // Print group name and email.
+ for (const group of groups) {
+ console.log('%s (%s)', group.name, group.email);
}
pageToken = page.nextPageToken;
} while (pageToken);
@@ -117,16 +139,24 @@ function listAllGroups() {
// [START apps_script_admin_sdk_add_group_member]
/**
* Adds a user to an existing group in the domain.
+ * @see https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/insert
*/
function addGroupMember() {
- var userEmail = 'liz@example.com';
- var groupEmail = 'bookclub@example.com';
- var member = {
+ // TODO (developer) - Replace userEmail value with yours
+ const userEmail = 'liz@example.com';
+ // TODO (developer) - Replace groupEmail value with yours
+ const groupEmail = 'bookclub@example.com';
+ const member = {
email: userEmail,
role: 'MEMBER'
};
- member = AdminDirectory.Members.insert(member, groupEmail);
- Logger.log('User %s added as a member of group %s.', userEmail, groupEmail);
+ try {
+ AdminDirectory.Members.insert(member, groupEmail);
+ console.log('User %s added as a member of group %s.', userEmail, groupEmail);
+ } catch (err) {
+ // TODO (developer)- Handle exception from the API
+ console.log('Failed with error %s', err.message);
+ }
}
// [END apps_script_admin_sdk_add_group_member]
@@ -137,11 +167,11 @@ function addGroupMember() {
* (including attachments), and inserts it in a Google Group in the domain.
*/
function migrateMessages() {
- var groupId = 'exampleGroup@example.com';
- var messagesToMigrate = getRecentMessagesContent();
- for (var i = 0; i < messagesToMigrate.length; i++) {
- var messageContent = messagesToMigrate[i];
- var contentBlob = Utilities.newBlob(messageContent, 'message/rfc822');
+ // TODO (developer) - Replace groupId value with yours
+ const groupId = 'exampleGroup@example.com';
+ const messagesToMigrate = getRecentMessagesContent();
+ for (const messageContent of messagesToMigrate) {
+ const contentBlob = Utilities.newBlob(messageContent, 'message/rfc822');
AdminGroupsMigration.Archive.insert(groupId, contentBlob);
}
}
@@ -153,14 +183,14 @@ function migrateMessages() {
* @return {Array} the messages' content.
*/
function getRecentMessagesContent() {
- var NUM_THREADS = 3;
- var NUM_MESSAGES = 3;
- var threads = GmailApp.getInboxThreads(0, NUM_THREADS);
- var messages = GmailApp.getMessagesForThreads(threads);
- var messagesContent = [];
- for (var i = 0; i < messages.length; i++) {
- for (var j = 0; j < NUM_MESSAGES; j++) {
- var message = messages[i][j];
+ const NUM_THREADS = 3;
+ const NUM_MESSAGES = 3;
+ const threads = GmailApp.getInboxThreads(0, NUM_THREADS);
+ const messages = GmailApp.getMessagesForThreads(threads);
+ const messagesContent = [];
+ for (let i = 0; i < messages.length; i++) {
+ for (let j = 0; j < NUM_MESSAGES; j++) {
+ const message = messages[i][j];
if (message) {
messagesContent.push(message.getRawContent());
}
@@ -175,9 +205,15 @@ function getRecentMessagesContent() {
* Gets a group's settings and logs them to the console.
*/
function getGroupSettings() {
- var groupId = 'exampleGroup@example.com';
- var group = AdminGroupsSettings.Groups.get(groupId);
- Logger.log(JSON.stringify(group, null, 2));
+ // TODO (developer) - Replace groupId value with yours
+ const groupId = 'exampleGroup@example.com';
+ try {
+ const group = AdminGroupsSettings.Groups.get(groupId);
+ console.log(JSON.stringify(group, null, 2));
+ } catch (err) {
+ // TODO (developer)- Handle exception from the API
+ console.log('Failed with error %s', err.message);
+ }
}
// [END apps_script_admin_sdk_get_group_setting]
@@ -185,12 +221,18 @@ function getGroupSettings() {
/**
* Updates group's settings. Here, the description is modified, but various
* other settings can be changed in the same way.
+ * @see https://developers.google.com/admin-sdk/groups-settings/v1/reference/groups/patch
*/
function updateGroupSettings() {
- var groupId = 'exampleGroup@example.com';
- var group = AdminGroupsSettings.newGroups();
- group.description = 'Newly changed group description';
- AdminGroupsSettings.Groups.patch(group, groupId);
+ const groupId = 'exampleGroup@example.com';
+ try {
+ const group = AdminGroupsSettings.newGroups();
+ group.description = 'Newly changed group description';
+ AdminGroupsSettings.Groups.patch(group, groupId);
+ } catch (err) {
+ // TODO (developer)- Handle exception from the API
+ console.log('Failed with error %s', err.message);
+ }
}
// [END apps_script_admin_sdk_update_group_setting]
@@ -201,20 +243,21 @@ function updateGroupSettings() {
* list of results.
*/
function getLicenseAssignments() {
- var productId = 'Google-Apps';
- var customerId = 'example.com';
- var assignments;
- var pageToken;
+ const productId = 'Google-Apps';
+ const customerId = 'example.com';
+ let assignments = [];
+ let pageToken = null;
do {
- assignments = AdminLicenseManager.LicenseAssignments
- .listForProduct(productId, customerId, {
+ const response = AdminLicenseManager.LicenseAssignments.listForProduct(productId, customerId, {
maxResults: 500,
pageToken: pageToken
});
+ assignments = assignments.concat(response.items);
+ pageToken = response.nextPageToken;
} while (pageToken);
- for (var i = 0; i < assignments.items.length; i++) {
- var assignment = assignments.items[i];
- Logger.log('userId: %s, productId: %s, skuId: %s',
+ // Print the productId and skuId
+ for (const assignment of assignments) {
+ console.log('userId: %s, productId: %s, skuId: %s',
assignment.userId, assignment.productId, assignment.skuId);
}
}
@@ -224,14 +267,21 @@ function getLicenseAssignments() {
/**
* Insert a license assignment for a user, for a given product ID and sku ID
* combination.
+ * For more details follow the link
+ * https://developers.google.com/admin-sdk/licensing/reference/rest/v1/licenseAssignments/insert
*/
function insertLicenseAssignment() {
- var productId = 'Google-Apps';
- var skuId = 'Google-Vault';
- var userId = 'marty@hoverboard.net';
- var results = AdminLicenseManager.LicenseAssignments
- .insert({userId: userId}, productId, skuId);
- Logger.log(results);
+ const productId = 'Google-Apps';
+ const skuId = 'Google-Vault';
+ const userId = 'marty@hoverboard.net';
+ try {
+ const results = AdminLicenseManager.LicenseAssignments
+ .insert({userId: userId}, productId, skuId);
+ console.log(results);
+ } catch (e) {
+ // TODO (developer) - Handle exception.
+ console.log('Failed with an error %s ', e.message);
+ }
}
// [END apps_script_admin_sdk_insert_license_assignment]
@@ -239,16 +289,17 @@ function insertLicenseAssignment() {
/**
* Generates a login activity report for the last week as a spreadsheet. The
* report includes the time, user, and login result.
+ * @see https://developers.google.com/admin-sdk/reports/reference/rest/v1/activities/list
*/
function generateLoginActivityReport() {
- var now = new Date();
- var oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
- var startTime = oneWeekAgo.toISOString();
- var endTime = now.toISOString();
+ const now = new Date();
+ const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
+ const startTime = oneWeekAgo.toISOString();
+ const endTime = now.toISOString();
- var rows = [];
- var pageToken;
- var page;
+ const rows = [];
+ let pageToken;
+ let page;
do {
page = AdminReports.Activities.list('all', 'login', {
startTime: startTime,
@@ -256,11 +307,10 @@ function generateLoginActivityReport() {
maxResults: 500,
pageToken: pageToken
});
- var items = page.items;
+ const items = page.items;
if (items) {
- for (var i = 0; i < items.length; i++) {
- var item = items[i];
- var row = [
+ for (const item of items) {
+ const row = [
new Date(item.id.time),
item.actor.email,
item.events[0].name
@@ -271,21 +321,21 @@ function generateLoginActivityReport() {
pageToken = page.nextPageToken;
} while (pageToken);
- if (rows.length > 0) {
- var spreadsheet = SpreadsheetApp.create('G Suite Login Report');
- var sheet = spreadsheet.getActiveSheet();
+ if (rows.length === 0) {
+ console.log('No results returned.');
+ return;
+ }
+ const spreadsheet = SpreadsheetApp.create('Google Workspace Login Report');
+ const sheet = spreadsheet.getActiveSheet();
- // Append the headers.
- var headers = ['Time', 'User', 'Login Result'];
- sheet.appendRow(headers);
+ // Append the headers.
+ const headers = ['Time', 'User', 'Login Result'];
+ sheet.appendRow(headers);
- // Append the results.
- sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);
+ // Append the results.
+ sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);
- Logger.log('Report spreadsheet created: %s', spreadsheet.getUrl());
- } else {
- Logger.log('No results returned.');
- }
+ console.log('Report spreadsheet created: %s', spreadsheet.getUrl());
}
// [END apps_script_admin_sdk_generate_login_activity_report]
@@ -294,21 +344,22 @@ function generateLoginActivityReport() {
* Generates a user usage report for this day last week as a spreadsheet. The
* report includes the date, user, last login time, number of emails received,
* and number of drive files created.
+ * @see https://developers.google.com/admin-sdk/reports/reference/rest/v1/userUsageReport/get
*/
function generateUserUsageReport() {
- var today = new Date();
- var oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
- var timezone = Session.getScriptTimeZone();
- var date = Utilities.formatDate(oneWeekAgo, timezone, 'yyyy-MM-dd');
+ const today = new Date();
+ const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
+ const timezone = Session.getScriptTimeZone();
+ const date = Utilities.formatDate(oneWeekAgo, timezone, 'yyyy-MM-dd');
- var parameters = [
+ const parameters = [
'accounts:last_login_time',
'gmail:num_emails_received',
'drive:num_items_created'
];
- var rows = [];
- var pageToken;
- var page;
+ const rows = [];
+ let pageToken;
+ let page;
do {
page = AdminReports.UserUsageReport.get('all', date, {
parameters: parameters.join(','),
@@ -316,17 +367,15 @@ function generateUserUsageReport() {
pageToken: pageToken
});
if (page.warnings) {
- for (var i = 0; i < page.warnings.length; i++) {
- var warning = page.warnings[i];
- Logger.log(warning.message);
+ for (const warning of page.warnings) {
+ console.log(warning.message);
}
}
- var reports = page.usageReports;
+ const reports = page.usageReports;
if (reports) {
- for (var i = 0; i < reports.length; i++) {
- var report = reports[i];
- var parameterValues = getParameterValues(report.parameters);
- var row = [
+ for (const report of reports) {
+ const parameterValues = getParameterValues(report.parameters);
+ const row = [
report.date,
report.entity.userEmail,
parameterValues['accounts:last_login_time'],
@@ -339,22 +388,22 @@ function generateUserUsageReport() {
pageToken = page.nextPageToken;
} while (pageToken);
- if (rows.length > 0) {
- var spreadsheet = SpreadsheetApp.create('G Suite User Usage Report');
- var sheet = spreadsheet.getActiveSheet();
+ if (rows.length === 0) {
+ console.log('No results returned.');
+ return;
+ }
+ const spreadsheet = SpreadsheetApp.create('Google Workspace User Usage Report');
+ const sheet = spreadsheet.getActiveSheet();
- // Append the headers.
- var headers = ['Date', 'User', 'Last Login', 'Num Emails Received',
- 'Num Drive Files Created'];
- sheet.appendRow(headers);
+ // Append the headers.
+ const headers = ['Date', 'User', 'Last Login', 'Num Emails Received',
+ 'Num Drive Files Created'];
+ sheet.appendRow(headers);
- // Append the results.
- sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);
+ // Append the results.
+ sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);
- Logger.log('Report spreadsheet created: %s', spreadsheet.getUrl());
- } else {
- Logger.log('No results returned.');
- }
+ console.log('Report spreadsheet created: %s', spreadsheet.getUrl());
}
/**
@@ -363,9 +412,9 @@ function generateUserUsageReport() {
* @return {Object} A map from parameter names to their values.
*/
function getParameterValues(parameters) {
- return parameters.reduce(function(result, parameter) {
- var name = parameter.name;
- var value;
+ return parameters.reduce((result, parameter) => {
+ const name = parameter.name;
+ let value;
if (parameter.intValue !== undefined) {
value = parameter.intValue;
} else if (parameter.stringValue !== undefined) {
@@ -386,20 +435,19 @@ function getParameterValues(parameters) {
* Logs the list of subscriptions, including the customer ID, date created, plan
* name, and the sku ID. Notice the use of page tokens to access the full list
* of results.
+ * @see https://developers.google.com/admin-sdk/reseller/reference/rest/v1/subscriptions/list
*/
function getSubscriptions() {
- var result;
- var subscriptions;
- var pageToken;
+ let result;
+ let pageToken;
do {
result = AdminReseller.Subscriptions.list({
pageToken: pageToken
});
- for (var i = 0; i < result.subscriptions.length; i++) {
- var sub = result.subscriptions[i];
- var creationDate = new Date();
+ for (const sub of result.subscriptions) {
+ const creationDate = new Date();
creationDate.setUTCSeconds(sub.creationTime);
- Logger.log('customer ID: %s, date created: %s, plan name: %s, sku id: %s',
+ console.log('customer ID: %s, date created: %s, plan name: %s, sku id: %s',
sub.customerId, creationDate.toDateString(), sub.plan.planName,
sub.skuId);
}
diff --git a/advanced/adsense.gs b/advanced/adsense.gs
index df7b896b7..33e3488f2 100644
--- a/advanced/adsense.gs
+++ b/advanced/adsense.gs
@@ -17,17 +17,17 @@
/**
* Lists available AdSense accounts.
*/
-function listAccounts () {
+function listAccounts() {
let pageToken;
do {
- const response = AdSense.Accounts.list({ pageToken: pageToken });
- if (response.accounts) {
- for (const account of response.accounts) {
- Logger.log('Found account with resource name "%s" and display name "%s".',
+ const response = AdSense.Accounts.list({pageToken: pageToken});
+ if (!response.accounts) {
+ console.log('No accounts found.');
+ return;
+ }
+ for (const account of response.accounts) {
+ console.log('Found account with resource name "%s" and display name "%s".',
account.name, account.displayName);
- }
- } else {
- Logger.log('No accounts found.');
}
pageToken = response.nextPageToken;
} while (pageToken);
@@ -38,23 +38,24 @@ function listAccounts () {
/**
* Logs available Ad clients for an account.
*
- * @param {string} accountName The resource name of the account that owns the collection of ad clients.
+ * @param {string} accountName The resource name of the account that owns the
+ * collection of ad clients.
*/
-function listAdClients (accountName) {
+function listAdClients(accountName) {
let pageToken;
do {
const response = AdSense.Accounts.Adclients.list(accountName, {
pageToken: pageToken
});
- if (response.adClients) {
- for (const adClient of response.adClients) {
- Logger.log('Found ad client for product "%s" with resource name "%s".',
+ if (!response.adClients) {
+ console.log('No ad clients found for this account.');
+ return;
+ }
+ for (const adClient of response.adClients) {
+ console.log('Found ad client for product "%s" with resource name "%s".',
adClient.productCode, adClient.name);
- Logger.log('Reporting dimension ID: %s',
+ console.log('Reporting dimension ID: %s',
adClient.reportingDimensionId ?? 'None');
- }
- } else {
- Logger.log('No ad clients found for this account.');
}
pageToken = response.nextPageToken;
} while (pageToken);
@@ -64,22 +65,23 @@ function listAdClients (accountName) {
// [START apps_script_adsense_list_ad_units]
/**
* Lists ad units.
- * @param {string} adClientName The resource name of the ad client that owns the collection of ad units.
+ * @param {string} adClientName The resource name of the ad client that owns the collection
+ * of ad units.
*/
-function listAdUnits (adClientName) {
+function listAdUnits(adClientName) {
let pageToken;
do {
const response = AdSense.Accounts.Adclients.Adunits.list(adClientName, {
pageSize: 50,
pageToken: pageToken
});
- if (response.adUnits) {
- for (const adUnit of response.adUnits) {
- Logger.log('Found ad unit with resource name "%s" and display name "%s".',
+ if (!response.adUnits) {
+ console.log('No ad units found for this ad client.');
+ return;
+ }
+ for (const adUnit of response.adUnits) {
+ console.log('Found ad unit with resource name "%s" and display name "%s".',
adUnit.name, adUnit.displayName);
- }
- } else {
- Logger.log('No ad units found for this ad client.');
}
pageToken = response.nextPageToken;
@@ -91,9 +93,10 @@ function listAdUnits (adClientName) {
/**
* Generates a spreadsheet report for a specific ad client in an account.
* @param {string} accountName The resource name of the account.
- * @param {string} adClientName The reporting dimension ID of the ad client.
+ * @param {string} adClientReportingDimensionId The reporting dimension ID
+ * of the ad client.
*/
-function generateReport (accountName, adClientReportingDimensionId) {
+function generateReport(accountName, adClientReportingDimensionId) {
// Prepare report.
const today = new Date();
const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
@@ -111,22 +114,22 @@ function generateReport (accountName, adClientReportingDimensionId) {
orderBy: ['+DATE']
});
- if (report.rows) {
- const spreadsheet = SpreadsheetApp.create('AdSense Report');
- const sheet = spreadsheet.getActiveSheet();
+ if (!report.rows) {
+ console.log('No rows returned.');
+ return;
+ }
+ const spreadsheet = SpreadsheetApp.create('AdSense Report');
+ const sheet = spreadsheet.getActiveSheet();
- // Append the headers.
- sheet.appendRow(report.headers.map(header => header.name));
+ // Append the headers.
+ sheet.appendRow(report.headers.map((header) => header.name));
- // Append the results.
- sheet.getRange(2, 1, report.rows.length, report.headers.length)
- .setValues(report.rows.map(row => row.cells.map(cell => cell.value)));
+ // Append the results.
+ sheet.getRange(2, 1, report.rows.length, report.headers.length)
+ .setValues(report.rows.map((row) => row.cells.map((cell) => cell.value)));
- Logger.log('Report spreadsheet created: %s',
+ console.log('Report spreadsheet created: %s',
spreadsheet.getUrl());
- } else {
- Logger.log('No rows returned.');
- }
}
/**
@@ -134,7 +137,7 @@ function generateReport (accountName, adClientReportingDimensionId) {
* @param {string} parameter The parameter to be escaped.
* @return {string} The escaped parameter.
*/
-function escapeFilterParameter (parameter) {
+function escapeFilterParameter(parameter) {
return parameter.replace('\\', '\\\\').replace(',', '\\,');
}
@@ -143,8 +146,9 @@ function escapeFilterParameter (parameter) {
*
* @param {string} paramName the name of the date parameter
* @param {Date} value the date
+ * @return {object} formatted date
*/
-function dateToJson (paramName, value) {
+function dateToJson(paramName, value) {
return {
[paramName + '.year']: value.getFullYear(),
[paramName + '.month']: value.getMonth() + 1,
diff --git a/advanced/analytics.gs b/advanced/analytics.gs
index a0b8fb64c..a691ce4a2 100644
--- a/advanced/analytics.gs
+++ b/advanced/analytics.gs
@@ -18,17 +18,23 @@
* Lists Analytics accounts.
*/
function listAccounts() {
- var accounts = Analytics.Management.Accounts.list();
- if (accounts.items && accounts.items.length) {
- for (var i = 0; i < accounts.items.length; i++) {
- var account = accounts.items[i];
- Logger.log('Account: name "%s", id "%s".', account.name, account.id);
+ try {
+ const accounts = Analytics.Management.Accounts.list();
+ if (!accounts.items || !accounts.items.length) {
+ console.log('No accounts found.');
+ return;
+ }
+
+ for (let i = 0; i < accounts.items.length; i++) {
+ const account = accounts.items[i];
+ console.log('Account: name "%s", id "%s".', account.name, account.id);
// List web properties in the account.
listWebProperties(account.id);
}
- } else {
- Logger.log('No accounts found.');
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
}
}
@@ -37,18 +43,23 @@ function listAccounts() {
* @param {string} accountId The account ID.
*/
function listWebProperties(accountId) {
- var webProperties = Analytics.Management.Webproperties.list(accountId);
- if (webProperties.items && webProperties.items.length) {
- for (var i = 0; i < webProperties.items.length; i++) {
- var webProperty = webProperties.items[i];
- Logger.log('\tWeb Property: name "%s", id "%s".', webProperty.name,
- webProperty.id);
+ try {
+ const webProperties = Analytics.Management.Webproperties.list(accountId);
+ if (!webProperties.items || !webProperties.items.length) {
+ console.log('\tNo web properties found.');
+ return;
+ }
+ for (let i = 0; i < webProperties.items.length; i++) {
+ const webProperty = webProperties.items[i];
+ console.log('\tWeb Property: name "%s", id "%s".',
+ webProperty.name, webProperty.id);
// List profiles in the web property.
listProfiles(accountId, webProperty.id);
- }
- } else {
- Logger.log('\tNo web properties found.');
+ }
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
}
}
@@ -61,17 +72,22 @@ function listProfiles(accountId, webPropertyId) {
// Note: If you experience "Quota Error: User Rate Limit Exceeded" errors
// due to the number of accounts or profiles you have, you may be able to
// avoid it by adding a Utilities.sleep(1000) statement here.
+ try {
+ const profiles = Analytics.Management.Profiles.list(accountId,
+ webPropertyId);
- var profiles = Analytics.Management.Profiles.list(accountId,
- webPropertyId);
- if (profiles.items && profiles.items.length) {
- for (var i = 0; i < profiles.items.length; i++) {
- var profile = profiles.items[i];
- Logger.log('\t\tProfile: name "%s", id "%s".', profile.name,
+ if (!profiles.items || !profiles.items.length) {
+ console.log('\t\tNo web properties found.');
+ return;
+ }
+ for (let i = 0; i < profiles.items.length; i++) {
+ const profile = profiles.items[i];
+ console.log('\t\tProfile: name "%s", id "%s".', profile.name,
profile.id);
}
- } else {
- Logger.log('\t\tNo web properties found.');
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
}
}
// [END apps_script_analytics_accounts]
@@ -82,43 +98,44 @@ function listProfiles(accountId, webPropertyId) {
* @param {string} profileId The profile ID.
*/
function runReport(profileId) {
- var today = new Date();
- var oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
+ const today = new Date();
+ const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
- var startDate = Utilities.formatDate(oneWeekAgo, Session.getScriptTimeZone(),
+ const startDate = Utilities.formatDate(oneWeekAgo, Session.getScriptTimeZone(),
'yyyy-MM-dd');
- var endDate = Utilities.formatDate(today, Session.getScriptTimeZone(),
+ const endDate = Utilities.formatDate(today, Session.getScriptTimeZone(),
'yyyy-MM-dd');
- var tableId = 'ga:' + profileId;
- var metric = 'ga:visits';
- var options = {
+ const tableId = 'ga:' + profileId;
+ const metric = 'ga:visits';
+ const options = {
'dimensions': 'ga:source,ga:keyword',
'sort': '-ga:visits,ga:source',
'filters': 'ga:medium==organic',
'max-results': 25
};
- var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
+ const report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
- if (report.rows) {
- var spreadsheet = SpreadsheetApp.create('Google Analytics Report');
- var sheet = spreadsheet.getActiveSheet();
+ if (!report.rows) {
+ console.log('No rows returned.');
+ return;
+ }
+
+ const spreadsheet = SpreadsheetApp.create('Google Analytics Report');
+ const sheet = spreadsheet.getActiveSheet();
- // Append the headers.
- var headers = report.columnHeaders.map(function(columnHeader) {
- return columnHeader.name;
- });
- sheet.appendRow(headers);
+ // Append the headers.
+ const headers = report.columnHeaders.map((columnHeader) => {
+ return columnHeader.name;
+ });
+ sheet.appendRow(headers);
- // Append the results.
- sheet.getRange(2, 1, report.rows.length, headers.length)
- .setValues(report.rows);
+ // Append the results.
+ sheet.getRange(2, 1, report.rows.length, headers.length)
+ .setValues(report.rows);
- Logger.log('Report spreadsheet created: %s',
- spreadsheet.getUrl());
- } else {
- Logger.log('No rows returned.');
- }
+ console.log('Report spreadsheet created: %s',
+ spreadsheet.getUrl());
}
// [END apps_script_analytics_reports]
diff --git a/advanced/analyticsAdmin.gs b/advanced/analyticsAdmin.gs
new file mode 100644
index 000000000..973388fd5
--- /dev/null
+++ b/advanced/analyticsAdmin.gs
@@ -0,0 +1,37 @@
+/**
+ * Copyright 2021 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+// [START apps_script_analyticsadmin]
+/**
+ * Logs the Google Analytics accounts accessible by the current user.
+ */
+function listAccounts() {
+ try {
+ accounts = AnalyticsAdmin.Accounts.list();
+ if (!accounts.items || !accounts.items.length) {
+ console.log('No accounts found.');
+ return;
+ }
+
+ for (let i = 0; i < accounts.items.length; i++) {
+ const account = accounts.items[i];
+ console.log('Account: name "%s", displayName "%s".', account.name, account.displayName);
+ }
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
+ }
+}
+// [END apps_script_analyticsadmin]
diff --git a/advanced/analyticsData.gs b/advanced/analyticsData.gs
index bd2212699..b881998d1 100644
--- a/advanced/analyticsData.gs
+++ b/advanced/analyticsData.gs
@@ -25,60 +25,66 @@ function runReport() {
*/
const propertyId = 'YOUR-GA4-PROPERTY-ID';
- var metric = AnalyticsData.newMetric();
- metric.name = 'activeUsers';
+ try {
+ const metric = AnalyticsData.newMetric();
+ metric.name = 'activeUsers';
- var dimension = AnalyticsData.newDimension();
- dimension.name = 'city';
+ const dimension = AnalyticsData.newDimension();
+ dimension.name = 'city';
- var dateRange = AnalyticsData.newDateRange();
- dateRange.startDate = '2020-03-31';
- dateRange.endDate = 'today';
+ const dateRange = AnalyticsData.newDateRange();
+ dateRange.startDate = '2020-03-31';
+ dateRange.endDate = 'today';
- var request = AnalyticsData.newRunReportRequest();
- request.dimensions = [ dimension ];
- request.metrics = [ metric ];
- request.dateRanges = dateRange;
+ const request = AnalyticsData.newRunReportRequest();
+ request.dimensions = [dimension];
+ request.metrics = [metric];
+ request.dateRanges = dateRange;
- var report = AnalyticsData.Properties.runReport(request,
- 'properties/' + propertyId);
- if (report.rows) {
- var spreadsheet = SpreadsheetApp.create('Google Analytics Report');
- var sheet = spreadsheet.getActiveSheet();
+ const report = AnalyticsData.Properties.runReport(request,
+ 'properties/' + propertyId);
+ if (!report.rows) {
+ console.log('No rows returned.');
+ return;
+ }
+
+ const spreadsheet = SpreadsheetApp.create('Google Analytics Report');
+ const sheet = spreadsheet.getActiveSheet();
// Append the headers.
- var dimensionHeaders = report.dimensionHeaders.map(
- function(dimensionHeader) {
- return dimensionHeader.name;
- });
- var metricHeaders = report.metricHeaders.map(
- function(metricHeader) {
- return metricHeader.name;
- });
- var headers = [ ...dimensionHeaders, ...metricHeaders];
+ const dimensionHeaders = report.dimensionHeaders.map(
+ (dimensionHeader) => {
+ return dimensionHeader.name;
+ });
+ const metricHeaders = report.metricHeaders.map(
+ (metricHeader) => {
+ return metricHeader.name;
+ });
+ const headers = [...dimensionHeaders, ...metricHeaders];
sheet.appendRow(headers);
// Append the results.
- var rows = report.rows.map( function(row) {
- var dimensionValues = row.dimensionValues.map(
- function(dimensionValue) {
- return dimensionValue.value;
- });
- var metricValues = row.metricValues.map(
- function(metricValues) {
- return metricValues.value;
- });
- return [ ...dimensionValues, ...metricValues];
+ const rows = report.rows.map((row) => {
+ const dimensionValues = row.dimensionValues.map(
+ (dimensionValue) => {
+ return dimensionValue.value;
+ });
+ const metricValues = row.metricValues.map(
+ (metricValues) => {
+ return metricValues.value;
+ });
+ return [...dimensionValues, ...metricValues];
});
sheet.getRange(2, 1, report.rows.length, headers.length)
.setValues(rows);
- Logger.log('Report spreadsheet created: %s',
+ console.log('Report spreadsheet created: %s',
spreadsheet.getUrl());
- } else {
- Logger.log('No rows returned.');
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
}
}
// [END apps_script_analyticsdata]
diff --git a/advanced/bigquery.gs b/advanced/bigquery.gs
index 0495317f0..a4127aa1b 100644
--- a/advanced/bigquery.gs
+++ b/advanced/bigquery.gs
@@ -20,17 +20,23 @@
function runQuery() {
// Replace this value with the project ID listed in the Google
// Cloud Platform project.
- var projectId = 'XXXXXXXX';
+ const projectId = 'XXXXXXXX';
- var request = {
- query: 'SELECT TOP(word, 300) AS word, COUNT(*) AS word_count ' +
- 'FROM publicdata:samples.shakespeare WHERE LENGTH(word) > 10;'
+ const request = {
+ // TODO (developer) - Replace query with yours
+ query: 'SELECT refresh_date AS Day, term AS Top_Term, rank ' +
+ 'FROM `bigquery-public-data.google_trends.top_terms` ' +
+ 'WHERE rank = 1 ' +
+ 'AND refresh_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 WEEK) ' +
+ 'GROUP BY Day, Top_Term, rank ' +
+ 'ORDER BY Day DESC;',
+ useLegacySql: false
};
- var queryResults = BigQuery.Jobs.query(request, projectId);
- var jobId = queryResults.jobReference.jobId;
+ let queryResults = BigQuery.Jobs.query(request, projectId);
+ const jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
- var sleepTimeMs = 500;
+ let sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
@@ -38,7 +44,7 @@ function runQuery() {
}
// Get all the rows of results.
- var rows = queryResults.rows;
+ let rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
@@ -46,32 +52,31 @@ function runQuery() {
rows = rows.concat(queryResults.rows);
}
- if (rows) {
- var spreadsheet = SpreadsheetApp.create('BiqQuery Results');
- var sheet = spreadsheet.getActiveSheet();
+ if (!rows) {
+ console.log('No rows returned.');
+ return;
+ }
+ const spreadsheet = SpreadsheetApp.create('BigQuery Results');
+ const sheet = spreadsheet.getActiveSheet();
- // Append the headers.
- var headers = queryResults.schema.fields.map(function(field) {
- return field.name;
- });
- sheet.appendRow(headers);
+ // Append the headers.
+ const headers = queryResults.schema.fields.map(function(field) {
+ return field.name;
+ });
+ sheet.appendRow(headers);
- // Append the results.
- var data = new Array(rows.length);
- for (var i = 0; i < rows.length; i++) {
- var cols = rows[i].f;
- data[i] = new Array(cols.length);
- for (var j = 0; j < cols.length; j++) {
- data[i][j] = cols[j].v;
- }
+ // Append the results.
+ const data = new Array(rows.length);
+ for (let i = 0; i < rows.length; i++) {
+ const cols = rows[i].f;
+ data[i] = new Array(cols.length);
+ for (let j = 0; j < cols.length; j++) {
+ data[i][j] = cols[j].v;
}
- sheet.getRange(2, 1, rows.length, headers.length).setValues(data);
-
- Logger.log('Results spreadsheet created: %s',
- spreadsheet.getUrl());
- } else {
- Logger.log('No rows returned.');
}
+ sheet.getRange(2, 1, rows.length, headers.length).setValues(data);
+
+ console.log('Results spreadsheet created: %s', spreadsheet.getUrl());
}
// [END apps_script_bigquery_run_query]
@@ -82,17 +87,17 @@ function runQuery() {
function loadCsv() {
// Replace this value with the project ID listed in the Google
// Cloud Platform project.
- var projectId = 'XXXXXXXX';
+ const projectId = 'XXXXXXXX';
// Create a dataset in the BigQuery UI (https://bigquery.cloud.google.com)
// and enter its ID below.
- var datasetId = 'YYYYYYYY';
+ const datasetId = 'YYYYYYYY';
// Sample CSV file of Google Trends data conforming to the schema below.
// https://docs.google.com/file/d/0BwzA1Orbvy5WMXFLaTR1Z1p2UDg/edit
- var csvFileId = '0BwzA1Orbvy5WMXFLaTR1Z1p2UDg';
+ const csvFileId = '0BwzA1Orbvy5WMXFLaTR1Z1p2UDg';
// Create the table.
- var tableId = 'pets_' + new Date().getTime();
- var table = {
+ const tableId = 'pets_' + new Date().getTime();
+ let table = {
tableReference: {
projectId: projectId,
datasetId: datasetId,
@@ -107,15 +112,18 @@ function loadCsv() {
]
}
};
- table = BigQuery.Tables.insert(table, projectId, datasetId);
- Logger.log('Table created: %s', table.id);
-
+ try {
+ table = BigQuery.Tables.insert(table, projectId, datasetId);
+ console.log('Table created: %s', table.id);
+ } catch (err) {
+ console.log('unable to create table');
+ }
// Load CSV data from Drive and convert to the correct format for upload.
- var file = DriveApp.getFileById(csvFileId);
- var data = file.getBlob().setContentType('application/octet-stream');
+ const file = DriveApp.getFileById(csvFileId);
+ const data = file.getBlob().setContentType('application/octet-stream');
// Create the data upload job.
- var job = {
+ const job = {
configuration: {
load: {
destinationTable: {
@@ -127,8 +135,11 @@ function loadCsv() {
}
}
};
- job = BigQuery.Jobs.insert(job, projectId, data);
- Logger.log('Load job started. Check on the status of it here: ' +
- 'https://bigquery.cloud.google.com/jobs/%s', projectId);
+ try {
+ const jobResult = BigQuery.Jobs.insert(job, projectId, data);
+ console.log(`Load job started. Status: ${jobResult.status.state}`);
+ } catch (err) {
+ console.log('unable to insert job');
+ }
}
// [END apps_script_bigquery_load_csv]
diff --git a/advanced/calendar.gs b/advanced/calendar.gs
index f67e1e41d..28f8116a0 100644
--- a/advanced/calendar.gs
+++ b/advanced/calendar.gs
@@ -13,40 +13,44 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// [START apps_script_calendar_list_calendars]
+// [START calendar_list_calendars]
/**
* Lists the calendars shown in the user's calendar list.
+ * @see https://developers.google.com/calendar/api/v3/reference/calendarList/list
*/
function listCalendars() {
- var calendars;
- var pageToken;
+ let calendars;
+ let pageToken;
do {
calendars = Calendar.CalendarList.list({
maxResults: 100,
pageToken: pageToken
+
});
- if (calendars.items && calendars.items.length > 0) {
- for (var i = 0; i < calendars.items.length; i++) {
- var calendar = calendars.items[i];
- Logger.log('%s (ID: %s)', calendar.summary, calendar.id);
- }
- } else {
- Logger.log('No calendars found.');
+ if (!calendars.items || calendars.items.length === 0) {
+ console.log('No calendars found.');
+ return;
+ }
+ // Print the calendar id and calendar summary
+ for (const calendar of calendars.items) {
+ console.log('%s (ID: %s)', calendar.summary, calendar.id);
}
pageToken = calendars.nextPageToken;
} while (pageToken);
}
-// [END apps_script_calendar_list_calendars]
+// [END calendar_list_calendars]
-// [START apps_script_calendar_create_event]
+// [START calendar_create_event]
/**
* Creates an event in the user's default calendar.
+ * @see https://developers.google.com/calendar/api/v3/reference/events/insert
*/
function createEvent() {
- var calendarId = 'primary';
- var start = getRelativeDate(1, 12);
- var end = getRelativeDate(1, 13);
- var event = {
+ const calendarId = 'primary';
+ const start = getRelativeDate(1, 12);
+ const end = getRelativeDate(1, 13);
+ // event details for creating event.
+ let event = {
summary: 'Lunch Meeting',
location: 'The Deli',
description: 'To discuss our plans for the presentation next week.',
@@ -57,14 +61,19 @@ function createEvent() {
dateTime: end.toISOString()
},
attendees: [
- {email: 'alice@example.com'},
- {email: 'bob@example.com'}
+ {email: 'gduser1@workspacesample.dev'},
+ {email: 'gduser2@workspacesample.dev'}
],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
- event = Calendar.Events.insert(event, calendarId);
- Logger.log('Event ID: ' + event.id);
+ try {
+ // call method to insert/create new event in provided calandar
+ event = Calendar.Events.insert(event, calendarId);
+ console.log('Event ID: ' + event.id);
+ } catch (err) {
+ console.log('Failed with error %s', err.message);
+ }
}
/**
@@ -75,7 +84,7 @@ function createEvent() {
* @return {Date} The new date.
*/
function getRelativeDate(daysOffset, hour) {
- var date = new Date();
+ const date = new Date();
date.setDate(date.getDate() + daysOffset);
date.setHours(hour);
date.setMinutes(0);
@@ -83,40 +92,40 @@ function getRelativeDate(daysOffset, hour) {
date.setMilliseconds(0);
return date;
}
-// [END apps_script_calendar_create_event]
+// [END calendar_create_event]
-// [START apps_script_calendar_list_events]
+// [START calendar_list_events]
/**
* Lists the next 10 upcoming events in the user's default calendar.
+ * @see https://developers.google.com/calendar/api/v3/reference/events/list
*/
function listNext10Events() {
- var calendarId = 'primary';
- var now = new Date();
- var events = Calendar.Events.list(calendarId, {
+ const calendarId = 'primary';
+ const now = new Date();
+ const events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 10
});
- if (events.items && events.items.length > 0) {
- for (var i = 0; i < events.items.length; i++) {
- var event = events.items[i];
- if (event.start.date) {
- // All-day event.
- var start = new Date(event.start.date);
- Logger.log('%s (%s)', event.summary, start.toLocaleDateString());
- } else {
- var start = new Date(event.start.dateTime);
- Logger.log('%s (%s)', event.summary, start.toLocaleString());
- }
+ if (!events.items || events.items.length === 0) {
+ console.log('No events found.');
+ return;
+ }
+ for (const event of events.items) {
+ if (event.start.date) {
+ // All-day event.
+ const start = new Date(event.start.date);
+ console.log('%s (%s)', event.summary, start.toLocaleDateString());
+ return;
}
- } else {
- Logger.log('No events found.');
+ const start = new Date(event.start.dateTime);
+ console.log('%s (%s)', event.summary, start.toLocaleString());
}
}
-// [END apps_script_calendar_list_events]
+// [END calendar_list_events]
-// [START apps_script_calendar_log_synced_events]
+// [START calendar_log_synced_events]
/**
* Retrieve and log events from the given calendar that have been modified
* since the last sync. If the sync token is missing or invalid, log all
@@ -127,21 +136,20 @@ function listNext10Events() {
* perform a full sync; if false, use the existing sync token if possible.
*/
function logSyncedEvents(calendarId, fullSync) {
- var properties = PropertiesService.getUserProperties();
- var options = {
+ const properties = PropertiesService.getUserProperties();
+ const options = {
maxResults: 100
};
- var syncToken = properties.getProperty('syncToken');
+ const syncToken = properties.getProperty('syncToken');
if (syncToken && !fullSync) {
options.syncToken = syncToken;
} else {
// Sync events up to thirty days in the past.
options.timeMin = getRelativeDate(-30, 0).toISOString();
}
-
// Retrieve events one page at a time.
- var events;
- var pageToken;
+ let events;
+ let pageToken;
do {
try {
options.pageToken = pageToken;
@@ -153,38 +161,34 @@ function logSyncedEvents(calendarId, fullSync) {
properties.deleteProperty('syncToken');
logSyncedEvents(calendarId, true);
return;
- } else {
- throw new Error(e.message);
}
+ throw new Error(e.message);
}
-
- if (events.items && events.items.length > 0) {
- for (var i = 0; i < events.items.length; i++) {
- var event = events.items[i];
- if (event.status === 'cancelled') {
- console.log('Event id %s was cancelled.', event.id);
- } else if (event.start.date) {
- // All-day event.
- var start = new Date(event.start.date);
- console.log('%s (%s)', event.summary, start.toLocaleDateString());
- } else {
- // Events that don't last all day; they have defined start times.
- var start = new Date(event.start.dateTime);
- console.log('%s (%s)', event.summary, start.toLocaleString());
- }
- }
- } else {
+ if (events.items && events.items.length === 0) {
console.log('No events found.');
+ return;
+ }
+ for (const event of events.items) {
+ if (event.status === 'cancelled') {
+ console.log('Event id %s was cancelled.', event.id);
+ return;
+ }
+ if (event.start.date) {
+ const start = new Date(event.start.date);
+ console.log('%s (%s)', event.summary, start.toLocaleDateString());
+ return;
+ }
+ // Events that don't last all day; they have defined start times.
+ const start = new Date(event.start.dateTime);
+ console.log('%s (%s)', event.summary, start.toLocaleString());
}
-
pageToken = events.nextPageToken;
} while (pageToken);
-
properties.setProperty('syncToken', events.nextSyncToken);
}
-// [END apps_script_calendar_log_synced_events]
+// [END calendar_log_synced_events]
-// [START apps_script_calendar_conditional_update]
+// [START calendar_conditional_update]
/**
* Creates an event in the user's default calendar, waits 30 seconds, then
* attempts to update the event's location, on the condition that the event
@@ -196,10 +200,10 @@ function logSyncedEvents(calendarId, fullSync) {
* to the etag of the new event when it was created.
*/
function conditionalUpdate() {
- var calendarId = 'primary';
- var start = getRelativeDate(1, 12);
- var end = getRelativeDate(1, 13);
- var event = {
+ const calendarId = 'primary';
+ const start = getRelativeDate(1, 12);
+ const end = getRelativeDate(1, 13);
+ let event = {
summary: 'Lunch Meeting',
location: 'The Deli',
description: 'To discuss our plans for the presentation next week.',
@@ -210,14 +214,14 @@ function conditionalUpdate() {
dateTime: end.toISOString()
},
attendees: [
- {email: 'alice@example.com'},
- {email: 'bob@example.com'}
+ {email: 'gduser1@workspacesample.dev'},
+ {email: 'gduser2@workspacesample.dev'}
],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
event = Calendar.Events.insert(event, calendarId);
- Logger.log('Event ID: ' + event.getId());
+ console.log('Event ID: ' + event.getId());
// Wait 30 seconds to see if the event has been updated outside this script.
Utilities.sleep(30 * 1000);
// Try to update the event, on the condition that the event state has not
@@ -225,20 +229,20 @@ function conditionalUpdate() {
event.location = 'The Coffee Shop';
try {
event = Calendar.Events.update(
- event,
- calendarId,
- event.id,
- {},
- {'If-Match': event.etag}
+ event,
+ calendarId,
+ event.id,
+ {},
+ {'If-Match': event.etag}
);
- Logger.log('Successfully updated event: ' + event.id);
+ console.log('Successfully updated event: ' + event.id);
} catch (e) {
- Logger.log('Fetch threw an exception: ' + e);
+ console.log('Fetch threw an exception: ' + e);
}
}
-// [END apps_script_calendar_conditional_update]
+// [END calendar_conditional_update]
-// [START apps_script_calendar_conditional_fetch]
+// [START calendar_conditional_fetch]
/**
* Creates an event in the user's default calendar, then re-fetches the event
* every second, on the condition that the event has changed since the last
@@ -248,10 +252,10 @@ function conditionalUpdate() {
* to the etag of the last known state of the event.
*/
function conditionalFetch() {
- var calendarId = 'primary';
- var start = getRelativeDate(1, 12);
- var end = getRelativeDate(1, 13);
- var event = {
+ const calendarId = 'primary';
+ const start = getRelativeDate(1, 12);
+ const end = getRelativeDate(1, 13);
+ let event = {
summary: 'Lunch Meeting',
location: 'The Deli',
description: 'To discuss our plans for the presentation next week.',
@@ -262,23 +266,24 @@ function conditionalFetch() {
dateTime: end.toISOString()
},
attendees: [
- {email: 'alice@example.com'},
- {email: 'bob@example.com'}
+ {email: 'gduser1@workspacesample.dev'},
+ {email: 'gduser2@workspacesample.dev'}
],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
- event = Calendar.Events.insert(event, calendarId);
- Logger.log('Event ID: ' + event.getId());
- // Re-fetch the event each second, but only get a result if it has changed.
- for (var i = 0; i < 30; i++) {
- Utilities.sleep(1000);
- try {
+ try {
+ // insert event
+ event = Calendar.Events.insert(event, calendarId);
+ console.log('Event ID: ' + event.getId());
+ // Re-fetch the event each second, but only get a result if it has changed.
+ for (let i = 0; i < 30; i++) {
+ Utilities.sleep(1000);
event = Calendar.Events.get(calendarId, event.id, {}, {'If-None-Match': event.etag});
- Logger.log('New event description: ' + event.description);
- } catch (e) {
- Logger.log('Fetch threw an exception: ' + e);
+ console.log('New event description: ' + event.start.dateTime);
}
+ } catch (e) {
+ console.log('Fetch threw an exception: ' + e);
}
}
-// [END apps_script_calendar_conditional_fetch]
+// [END calendar_conditional_fetch]
diff --git a/advanced/classroom.gs b/advanced/classroom.gs
index cc9b6f3ff..1dc7c8a54 100644
--- a/advanced/classroom.gs
+++ b/advanced/classroom.gs
@@ -18,18 +18,27 @@
* Lists 10 course names and IDs.
*/
function listCourses() {
- var optionalArgs = {
+ /**
+ * @see https://developers.google.com/classroom/reference/rest/v1/courses/list
+ */
+ const optionalArgs = {
pageSize: 10
+ // Use other query parameters here if needed.
};
- var response = Classroom.Courses.list(optionalArgs);
- var courses = response.courses;
- if (courses && courses.length > 0) {
- for (i = 0; i < courses.length; i++) {
- var course = courses[i];
- Logger.log('%s (%s)', course.name, course.id);
+ try {
+ const response = Classroom.Courses.list(optionalArgs);
+ const courses = response.courses;
+ if (!courses || courses.length === 0) {
+ console.log('No courses found.');
+ return;
}
- } else {
- Logger.log('No courses found.');
+ // Print the course names and IDs of the available courses.
+ for (const course in courses) {
+ console.log('%s (%s)', courses[course].name, courses[course].id);
+ }
+ } catch (err) {
+ // TODO (developer)- Handle Courses.list() exception from Classroom API
+ console.log('Failed with error %s', err.message);
}
}
// [END apps_script_classroom_list_courses]
diff --git a/advanced/docs.gs b/advanced/docs.gs
index c2d742a7d..c8721bf5e 100644
--- a/advanced/docs.gs
+++ b/advanced/docs.gs
@@ -14,59 +14,74 @@
* limitations under the License.
*/
-// [START apps_script_docs_create_document]
+// [START docs_create_document]
/**
* Create a new document.
+ * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create
+ * @return {string} documentId
*/
function createDocument() {
- var document = Docs.Documents.create({'title': 'My New Document'});
- Logger.log('Created document with ID: ' + document.documentId);
+ try {
+ // Create document with title
+ const document = Docs.Documents.create({'title': 'My New Document'});
+ console.log('Created document with ID: ' + document.documentId);
+ return document.documentId;
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', e.message);
+ }
}
-// [END apps_script_docs_create_document]
+// [END docs_create_document]
-// [START apps_script_docs_find_and_replace]
+// [START docs_find_and_replace_text]
/**
* Performs "replace all".
- * @param {string} documentId The document to perform the replace text
- * operations on.
- * @param {Object} findTextToReplacementMap A map from the "find text" to the
- * "replace text".
+ * @param {string} documentId The document to perform the replace text operations on.
+ * @param {Object} findTextToReplacementMap A map from the "find text" to the "replace text".
+ * @return {Object} replies
+ * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
*/
function findAndReplace(documentId, findTextToReplacementMap) {
- var requests = [];
- for (var findText in findTextToReplacementMap) {
- var replaceText = findTextToReplacementMap[findText];
- var request = {
+ const requests = [];
+ for (const findText in findTextToReplacementMap) {
+ const replaceText = findTextToReplacementMap[findText];
+ const request = {
replaceAllText: {
containsText: {
text: findText,
- matchCase: true,
+ matchCase: true
},
replaceText: replaceText
}
};
requests.push(request);
}
-
- var response = Docs.Documents.batchUpdate({'requests': requests}, documentId);
- var replies = response.replies;
- for (var i = 0; i < replies.length; i++) {
- var reply = replies[i];
- var numReplacements = reply.replaceAllText.occurrencesChanged || 0;
- Logger.log('Request %s performed %s replacements.', i, numReplacements);
+ try {
+ const response = Docs.Documents.batchUpdate({'requests': requests}, documentId);
+ const replies = response.replies;
+ for (const [index] of replies.entries()) {
+ const numReplacements = replies[index].replaceAllText.occurrencesChanged || 0;
+ console.log('Request %s performed %s replacements.', index, numReplacements);
+ }
+ return replies;
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error : %s', e.message);
}
}
-// [END apps_script_docs_find_and_replace]
+// [END docs_find_and_replace_text]
-// [START apps_script_docs_insert_and_style_text]
+// [START docs_insert_and_style_text]
/**
* Insert text at the beginning of the document and then style the inserted
* text.
* @param {string} documentId The document the text is inserted into.
* @param {string} text The text to insert into the document.
+ * @return {Object} replies
+ * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
*/
function insertAndStyleText(documentId, text) {
- var requests = [{
+ const requests = [{
insertText: {
location: {
index: 1
@@ -80,7 +95,7 @@ function insertAndStyleText(documentId, text) {
startIndex: 1,
endIndex: text.length + 1
},
- text_style: {
+ textStyle: {
fontSize: {
magnitude: 12,
unit: 'PT'
@@ -92,35 +107,48 @@ function insertAndStyleText(documentId, text) {
fields: 'weightedFontFamily, fontSize'
}
}];
- Docs.Documents.batchUpdate({'requests': requests}, documentId);
+ try {
+ const response =Docs.Documents.batchUpdate({'requests': requests}, documentId);
+ return response.replies;
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with an error %s', e.message);
+ }
}
-// [END apps_script_docs_insert_and_style_text]
+// [END docs_insert_and_style_text]
-// [START apps_script_docs_read_first_paragraph]
- /**
+// [START docs_read_first_paragraph]
+/**
* Read the first paragraph of the body of a document.
* @param {string} documentId The ID of the document to read.
+ * @return {Object} paragraphText
+ * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get
*/
function readFirstParagraph(documentId) {
- var document = Docs.Documents.get(documentId);
- var bodyElements = document.body.content;
-
- for (var i = 0; i < bodyElements.length; i++) {
- var structuralElement = bodyElements[i];
- if (structuralElement.paragraph !== null) {
- var paragraphElements = structuralElement.paragraph.elements;
- var paragraphText = '';
+ try {
+ // Get the document using document ID
+ const document = Docs.Documents.get(documentId);
+ const bodyElements = document.body.content;
+ for (let i = 0; i < bodyElements.length; i++) {
+ const structuralElement = bodyElements[i];
+ // Print the first paragraph text present in document
+ if (structuralElement.paragraph) {
+ const paragraphElements = structuralElement.paragraph.elements;
+ let paragraphText = '';
- for (var j = 0; j < paragraphElements.length; j++) {
- var paragraphElement = paragraphElements[j];
- if (paragraphElement.textRun !== null) {
- paragraphText += paragraphElement.textRun.content;
+ for (let j = 0; j < paragraphElements.length; j++) {
+ const paragraphElement = paragraphElements[j];
+ if (paragraphElement.textRun !== null) {
+ paragraphText += paragraphElement.textRun.content;
+ }
}
+ console.log(paragraphText);
+ return paragraphText;
}
-
- Logger.log(paragraphText);
- return;
}
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', e.message);
}
}
-// [END apps_script_docs_read_first_paragraph]
+// [END docs_read_first_paragraph]
diff --git a/advanced/doubleclick.gs b/advanced/doubleclick.gs
index 3659e43fc..1d556465b 100644
--- a/advanced/doubleclick.gs
+++ b/advanced/doubleclick.gs
@@ -19,15 +19,20 @@
*/
function listUserProfiles() {
// Retrieve the list of available user profiles
- var profiles = DoubleClickCampaigns.UserProfiles.list();
+ try {
+ const profiles = DoubleClickCampaigns.UserProfiles.list();
- if (profiles.items) {
- // Print out the user ID and name of each
- for (var i = 0; i < profiles.items.length; i++) {
- var profile = profiles.items[i];
- Logger.log('Found profile with ID %s and name "%s".',
- profile.profileId, profile.userName);
+ if (profiles.items) {
+ // Print out the user ID and name of each
+ for (let i = 0; i < profiles.items.length; i++) {
+ const profile = profiles.items[i];
+ console.log('Found profile with ID %s and name "%s".',
+ profile.profileId, profile.userName);
+ }
}
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
}
}
// [END apps_script_doubleclick_list_user_profiles]
@@ -38,25 +43,30 @@ function listUserProfiles() {
* Note the use of paging tokens to retrieve the whole list.
*/
function listActiveCampaigns() {
- var profileId = '1234567'; // Replace with your profile ID.
- var fields = 'nextPageToken,campaigns(id,name)';
- var result;
- var pageToken;
- do {
- result = DoubleClickCampaigns.Campaigns.list(profileId, {
- 'archived': false,
- 'fields': fields,
- 'pageToken': pageToken
- });
- if (result.campaigns) {
- for (var i = 0; i < result.campaigns.length; i++) {
- var campaign = result.campaigns[i];
- Logger.log('Found campaign with ID %s and name "%s".',
- campaign.id, campaign.name);
+ const profileId = '1234567'; // Replace with your profile ID.
+ const fields = 'nextPageToken,campaigns(id,name)';
+ let result;
+ let pageToken;
+ try {
+ do {
+ result = DoubleClickCampaigns.Campaigns.list(profileId, {
+ 'archived': false,
+ 'fields': fields,
+ 'pageToken': pageToken
+ });
+ if (result.campaigns) {
+ for (let i = 0; i < result.campaigns.length; i++) {
+ const campaign = result.campaigns[i];
+ console.log('Found campaign with ID %s and name "%s".',
+ campaign.id, campaign.name);
+ }
}
- }
- pageToken = result.nextPageToken;
- } while (pageToken);
+ pageToken = result.nextPageToken;
+ } while (pageToken);
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
+ }
}
// [END apps_script_doubleclick_list_active_campaigns]
@@ -66,36 +76,42 @@ function listActiveCampaigns() {
* The campaign is set to last for one month.
*/
function createAdvertiserAndCampaign() {
- var profileId = '1234567'; // Replace with your profile ID.
+ const profileId = '1234567'; // Replace with your profile ID.
- var advertiser = {
+ const advertiser = {
name: 'Example Advertiser',
status: 'APPROVED'
};
- var advertiserId = DoubleClickCampaigns.Advertisers
- .insert(advertiser, profileId).id;
- var landingPage = {
- advertiserId: advertiserId,
- archived: false,
- name: 'Example landing page',
- url: 'https://www.google.com'
- };
- var landingPageId = DoubleClickCampaigns.AdvertiserLandingPages
- .insert(landingPage, profileId).id;
+ try {
+ const advertiserId = DoubleClickCampaigns.Advertisers
+ .insert(advertiser, profileId).id;
- var campaignStart = new Date();
- // End campaign after 1 month.
- var campaignEnd = new Date();
- campaignEnd.setMonth(campaignEnd.getMonth() + 1);
+ const landingPage = {
+ advertiserId: advertiserId,
+ archived: false,
+ name: 'Example landing page',
+ url: 'https://www.google.com'
+ };
+ const landingPageId = DoubleClickCampaigns.AdvertiserLandingPages
+ .insert(landingPage, profileId).id;
- var campaign = {
- advertiserId: advertiserId,
- defaultLandingPageId: landingPageId,
- name: 'Example campaign',
- startDate: Utilities.formatDate(campaignStart, 'GMT', 'yyyy-MM-dd'),
- endDate: Utilities.formatDate(campaignEnd, 'GMT', 'yyyy-MM-dd')
- };
- DoubleClickCampaigns.Campaigns.insert(campaign, profileId);
+ const campaignStart = new Date();
+ // End campaign after 1 month.
+ const campaignEnd = new Date();
+ campaignEnd.setMonth(campaignEnd.getMonth() + 1);
+
+ const campaign = {
+ advertiserId: advertiserId,
+ defaultLandingPageId: landingPageId,
+ name: 'Example campaign',
+ startDate: Utilities.formatDate(campaignStart, 'GMT', 'yyyy-MM-dd'),
+ endDate: Utilities.formatDate(campaignEnd, 'GMT', 'yyyy-MM-dd')
+ };
+ DoubleClickCampaigns.Campaigns.insert(campaign, profileId);
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
+ }
}
// [END apps_script_doubleclick_create_advertiser_and_campaign]
diff --git a/advanced/drive.gs b/advanced/drive.gs
index 8c848eb65..6dcce2256 100644
--- a/advanced/drive.gs
+++ b/advanced/drive.gs
@@ -13,84 +13,110 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// [START apps_script_drive_upload_file]
+
+// [START drive_upload_file]
/**
* Uploads a new file to the user's Drive.
*/
function uploadFile() {
- var image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();
- var file = {
- title: 'google_logo.png',
- mimeType: 'image/png'
- };
- file = Drive.Files.insert(file, image);
- Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
+ try {
+ // Makes a request to fetch a URL.
+ const image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();
+ let file = {
+ title: 'google_logo.png',
+ mimeType: 'image/png'
+ };
+ // Insert new files to user's Drive
+ file = Drive.Files.insert(file, image);
+ console.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed to upload file with error %s', err.message);
+ }
}
-// [END apps_script_drive_upload_file]
+// [END drive_upload_file]
-// [START apps_script_drive_list_root_folders]
+// [START drive_list_root_folders]
/**
* Lists the top-level folders in the user's Drive.
*/
function listRootFolders() {
- var query = '"root" in parents and trashed = false and ' +
- 'mimeType = "application/vnd.google-apps.folder"';
- var folders;
- var pageToken;
+ const query = '"root" in parents and trashed = false and ' +
+ 'mimeType = "application/vnd.google-apps.folder"';
+ let folders;
+ let pageToken = null;
do {
- folders = Drive.Files.list({
- q: query,
- maxResults: 100,
- pageToken: pageToken
- });
- if (folders.items && folders.items.length > 0) {
- for (var i = 0; i < folders.items.length; i++) {
- var folder = folders.items[i];
- Logger.log('%s (ID: %s)', folder.title, folder.id);
+ try {
+ folders = Drive.Files.list({
+ q: query,
+ maxResults: 100,
+ pageToken: pageToken
+ });
+ if (!folders.items || folders.items.length === 0) {
+ console.log('No folders found.');
+ return;
+ }
+ for (let i = 0; i < folders.items.length; i++) {
+ const folder = folders.items[i];
+ console.log('%s (ID: %s)', folder.title, folder.id);
}
- } else {
- Logger.log('No folders found.');
+ pageToken = folders.nextPageToken;
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', err.message);
}
- pageToken = folders.nextPageToken;
} while (pageToken);
}
-// [END apps_script_drive_list_root_folders]
+// [END drive_list_root_folders]
-// [START apps_script_drive_add_custom_property]
+// [START drive_add_custom_property]
/**
* Adds a custom property to a file. Unlike Apps Script's DocumentProperties,
- * Drive's custom file properties can be accessed outside of Apps Script and by
- * other applications (if the visibility is set to PUBLIC).
+ * Drive's custom file properties can be accessed outside of Apps Script and
+ * by other applications (if the visibility is set to PUBLIC).
* @param {string} fileId The ID of the file to add the property to.
*/
function addCustomProperty(fileId) {
- var property = {
- key: 'department',
- value: 'Sales',
- visibility: 'PUBLIC'
- };
- Drive.Properties.insert(property, fileId);
+ try {
+ const property = {
+ key: 'department',
+ value: 'Sales',
+ visibility: 'PUBLIC'
+ };
+ // Adds a property to a file
+ Drive.Properties.insert(property, fileId);
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', err.message);
+ }
}
-// [END apps_script_drive_add_custom_property]
+// [END drive_add_custom_property]
-// [START apps_script_drive_list_revisions]
+// [START drive_list_revisions]
/**
* Lists the revisions of a given file. Note that some properties of revisions
- * are only available for certain file types. For example, G Suite application
- * files do not consume space in Google Drive and thus list a file size of 0.
+ * are only available for certain file types. For example, Google Workspace
+ * application files do not consume space in Google Drive and thus list a file
+ * size of 0.
* @param {string} fileId The ID of the file to list revisions for.
*/
function listRevisions(fileId) {
- var revisions = Drive.Revisions.list(fileId);
- if (revisions.items && revisions.items.length > 0) {
- for (var i = 0; i < revisions.items.length; i++) {
- var revision = revisions.items[i];
- var date = new Date(revision.modifiedDate);
- Logger.log('Date: %s, File size (bytes): %s', date.toLocaleString(),
+ try {
+ const revisions = Drive.Revisions.list(fileId);
+ if (!revisions.items || revisions.items.length === 0) {
+ console.log('No revisions found.');
+ return;
+ }
+ for (let i = 0; i < revisions.items.length; i++) {
+ const revision = revisions.items[i];
+ const date = new Date(revision.modifiedDate);
+ console.log('Date: %s, File size (bytes): %s', date.toLocaleString(),
revision.fileSize);
}
- } else {
- Logger.log('No revisions found.');
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', err.message);
}
}
-// [END apps_script_drive_list_revisions]
+
+// [END drive_list_revisions]
diff --git a/advanced/driveActivity.gs b/advanced/driveActivity.gs
index 3719bc05c..3d5f8bd0f 100644
--- a/advanced/driveActivity.gs
+++ b/advanced/driveActivity.gs
@@ -39,6 +39,6 @@ function getUsersActivity() {
}
pageToken = result.nextPageToken;
} while (pageToken);
- Logger.log(Object.keys(users));
+ console.log(Object.keys(users));
}
// [END apps_script_drive_activity_get_users_activity]
diff --git a/advanced/driveLabels.gs b/advanced/driveLabels.gs
new file mode 100644
index 000000000..1e4ffa447
--- /dev/null
+++ b/advanced/driveLabels.gs
@@ -0,0 +1,124 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// [START apps_script_drive_labels_list_labels]
+/**
+ * List labels available to the user.
+ */
+function listLabels() {
+ let pageToken = null;
+ let labels = [];
+ do {
+ try {
+ const response = DriveLabels.Labels.list({
+ publishedOnly: true,
+ pageToken: pageToken
+ });
+ pageToken = response.nextPageToken;
+ labels = labels.concat(response.labels);
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed to list labels with error %s', err.message);
+ }
+ } while (pageToken != null);
+
+ console.log('Found %d labels', labels.length);
+}
+// [END apps_script_drive_labels_list_labels]
+
+// [START apps_script_drive_labels_get_label]
+/**
+ * Get a label by name.
+ * @param {string} labelName The label name.
+ */
+function getLabel(labelName) {
+ try {
+ const label = DriveLabels.Labels.get(labelName, {view: 'LABEL_VIEW_FULL'});
+ const title = label.properties.title;
+ const fieldsLength = label.fields.length;
+ console.log(`Fetched label with title: '${title}' and ${fieldsLength} fields.`);
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed to get label with error %s', err.message);
+ }
+}
+// [END apps_script_drive_labels_get_label]
+
+// [START apps_script_drive_labels_list_labels_on_drive_item]
+/**
+ * List Labels on a Drive Item
+ * Fetches a Drive Item and prints all applied values along with their to their
+ * human-readable names.
+ *
+ * @param {string} fileId The Drive File ID
+ */
+function listLabelsOnDriveItem(fileId) {
+ try {
+ const appliedLabels = Drive.Files.listLabels(fileId);
+
+ console.log('%d label(s) are applied to this file', appliedLabels.items.length);
+
+ appliedLabels.items.forEach((appliedLabel) => {
+ // Resource name of the label at the applied revision.
+ const labelName = 'labels/' + appliedLabel.id + '@' + appliedLabel.revisionId;
+
+ console.log('Fetching Label: %s', labelName);
+ const label = DriveLabels.Labels.get(labelName, {view: 'LABEL_VIEW_FULL'});
+
+ console.log('Label Title: %s', label.properties.title);
+
+ Object.keys(appliedLabel.fields).forEach((fieldId) => {
+ const fieldValue = appliedLabel.fields[fieldId];
+ const field = label.fields.find((f) => f.id == fieldId);
+
+ console.log(`Field ID: ${field.id}, Display Name: ${field.properties.displayName}`);
+ switch (fieldValue.valueType) {
+ case 'text':
+ console.log('Text: %s', fieldValue.text[0]);
+ break;
+ case 'integer':
+ console.log('Integer: %d', fieldValue.integer[0]);
+ break;
+ case 'dateString':
+ console.log('Date: %s', fieldValue.dateString[0]);
+ break;
+ case 'user':
+ const user = fieldValue.user.map((user) => {
+ return `${user.emailAddress}: ${user.displayName}`;
+ }).join(', ');
+ console.log(`User: ${user}`);
+ break;
+ case 'selection':
+ const choices = fieldValue.selection.map((choiceId) => {
+ return field.selectionOptions.choices.find((choice) => choice.id === choiceId);
+ });
+ const selection = choices.map((choice) => {
+ return `${choice.id}: ${choice.properties.displayName}`;
+ }).join(', ');
+ console.log(`Selection: ${selection}`);
+ break;
+ default:
+ console.log('Unknown: %s', fieldValue.valueType);
+ console.log(fieldValue.value);
+ }
+ });
+ });
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', err.message);
+ }
+}
+// [END apps_script_drive_labels_list_labels_on_drive_item]
diff --git a/advanced/fusionTables.gs b/advanced/fusionTables.gs
deleted file mode 100644
index 98f500e21..000000000
--- a/advanced/fusionTables.gs
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * Copyright Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START apps_script_fusion_tables_list]
-/**
- * This sample lists Fusion Tables that the user has access to.
- */
-function listTables() {
- var tables = FusionTables.Table.list();
- if (tables.items) {
- for (var i = 0; i < tables.items.length; i++) {
- var table = tables.items[i];
- Logger.log('Table with name "%s" and ID "%s" was found.',
- table.name, table.tableId);
- }
- } else {
- Logger.log('No tables found.');
- }
-}
-// [END apps_script_fusion_tables_list]
-
-// [START apps_script_fusion_tables_run_query]
-/**
- * This sample queries for the first 100 rows in the given Fusion Table and
- * saves the results to a new spreadsheet.
- * @param {string} tableId The table ID.
- */
-function runQuery(tableId) {
- var sql = 'SELECT * FROM ' + tableId + ' LIMIT 100';
- var result = FusionTables.Query.sqlGet(sql, {
- hdrs: false
- });
- if (result.rows) {
- var spreadsheet = SpreadsheetApp.create('Fusion Table Query Results');
- var sheet = spreadsheet.getActiveSheet();
-
- // Append the headers.
- sheet.appendRow(result.columns);
-
- // Append the results.
- sheet.getRange(2, 1, result.rows.length, result.columns.length)
- .setValues(result.rows);
-
- Logger.log('Query results spreadsheet created: %s',
- spreadsheet.getUrl());
- } else {
- Logger.log('No rows returned.');
- }
-}
-// [END apps_script_fusion_tables_run_query]
diff --git a/advanced/gmail.gs b/advanced/gmail.gs
index d866e05f6..a1195c6b7 100644
--- a/advanced/gmail.gs
+++ b/advanced/gmail.gs
@@ -13,101 +13,120 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// [START apps_script_gmail_label]
+// [START gmail_label]
/**
* Lists the user's labels, including name, type,
* ID and visibility information.
*/
function listLabelInfo() {
- var response =
- Gmail.Users.Labels.list('me');
- for (var i = 0; i < response.labels.length; i++) {
- var label = response.labels[i];
- Logger.log(JSON.stringify(label));
+ try {
+ const response =
+ Gmail.Users.Labels.list('me');
+ for (let i = 0; i < response.labels.length; i++) {
+ const label = response.labels[i];
+ console.log(JSON.stringify(label));
+ }
+ } catch (err) {
+ console.log(err);
}
}
-// [END apps_script_gmail_label]
+// [END gmail_label]
-// [START apps_script_gmail_inbox_snippets]
+// [START gmail_inbox_snippets]
/**
* Lists, for each thread in the user's Inbox, a
* snippet associated with that thread.
*/
function listInboxSnippets() {
- var pageToken;
- do {
- var threadList = Gmail.Users.Threads.list('me', {
- q: 'label:inbox',
- pageToken: pageToken
- });
- if (threadList.threads && threadList.threads.length > 0) {
- threadList.threads.forEach(function(thread) {
- Logger.log('Snippet: %s', thread.snippet);
+ try {
+ let pageToken;
+ do {
+ const threadList = Gmail.Users.Threads.list('me', {
+ q: 'label:inbox',
+ pageToken: pageToken
});
- }
- pageToken = threadList.nextPageToken;
- } while (pageToken);
+ if (threadList.threads && threadList.threads.length > 0) {
+ threadList.threads.forEach(function(thread) {
+ console.log('Snippet: %s', thread.snippet);
+ });
+ }
+ pageToken = threadList.nextPageToken;
+ } while (pageToken);
+ } catch (err) {
+ console.log(err);
+ }
}
-// [END apps_script_gmail_inbox_snippets]
+// [END gmail_inbox_snippets]
-// [START apps_script_gmail_history]
+// [START gmail_history]
/**
* Gets a history record ID associated with the most
* recently sent message, then logs all the message IDs
* that have changed since that message was sent.
*/
function logRecentHistory() {
- // Get the history ID associated with the most recent
- // sent message.
- var sent = Gmail.Users.Threads.list('me', {
+ try {
+ // Get the history ID associated with the most recent
+ // sent message.
+ const sent = Gmail.Users.Threads.list('me', {
q: 'label:sent',
maxResults: 1
- });
- if (!sent.threads || !sent.threads[0]) {
- Logger.log('No sent threads found.');
- return;
- }
- var historyId = sent.threads[0].historyId;
-
- // Log the ID of each message changed since the most
- // recent message was sent.
- var pageToken;
- var changed = [];
- do {
- var recordList = Gmail.Users.History.list('me', {
- startHistoryId: historyId,
- pageToken: pageToken
});
- var history = recordList.history;
- if (history && history.length > 0) {
- history.forEach(function(record) {
- record.messages.forEach(function(message) {
- if (changed.indexOf(message.id) === -1) {
- changed.push(message.id);
- }
- });
- });
+ if (!sent.threads || !sent.threads[0]) {
+ console.log('No sent threads found.');
+ return;
}
- pageToken = recordList.nextPageToken;
- } while (pageToken);
+ const historyId = sent.threads[0].historyId;
- changed.forEach(function(id) {
- Logger.log('Message Changed: %s', id);
- });
+ // Log the ID of each message changed since the most
+ // recent message was sent.
+ let pageToken;
+ const changed = [];
+ do {
+ const recordList = Gmail.Users.History.list('me', {
+ startHistoryId: historyId,
+ pageToken: pageToken
+ });
+ const history = recordList.history;
+ if (history && history.length > 0) {
+ history.forEach(function(record) {
+ record.messages.forEach(function(message) {
+ if (changed.indexOf(message.id) === -1) {
+ changed.push(message.id);
+ }
+ });
+ });
+ }
+ pageToken = recordList.nextPageToken;
+ } while (pageToken);
+
+ changed.forEach(function(id) {
+ console.log('Message Changed: %s', id);
+ });
+ } catch (err) {
+ console.log(err);
+ }
}
-// [END apps_script_gmail_history]
+// [END gmail_history]
-// [START apps_script_gmail_raw]
+// [START gmail_raw]
+/**
+ * Logs the raw message content for the most recent message in gmail.
+ */
function getRawMessage() {
- var messageId = Gmail.Users.Messages.list('me').messages[0].id;
- console.log(messageId);
- var message = Gmail.Users.Messages.get('me', messageId, {
- 'format': 'raw'
- });
+ try {
+ const messageId = Gmail.Users.Messages.list('me').messages[0].id;
+ console.log(messageId);
+ const message = Gmail.Users.Messages.get('me', messageId, {
+ 'format': 'raw'
+ });
- // Get raw content as base64url encoded string.
- var encodedMessage = Utilities.base64Encode(message.raw);
- console.log(encodedMessage);
+ // Get raw content as base64url encoded string.
+ const encodedMessage = Utilities.base64Encode(message.raw);
+ console.log(encodedMessage);
+ } catch (err) {
+ console.log(err);
+ }
}
-// [END apps_script_gmail_raw]
+// [END gmail_raw]
diff --git a/advanced/googlePlus.gs b/advanced/googlePlus.gs
deleted file mode 100644
index bcafffe06..000000000
--- a/advanced/googlePlus.gs
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Copyright Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START apps_script_plus_people]
-/**
- * The following example demonstrates how to retrieve a list of the people
- * in the user's Google+ circles.
- */
-function getPeople() {
- var userId = 'me';
- var people;
- var pageToken;
- do {
- people = Plus.People.list(userId, 'visible', {
- pageToken: pageToken
- });
- if (people.items) {
- for (var i = 0; i < people.items.length; i++) {
- var person = people.items[i];
- Logger.log(person.displayName);
- }
- } else {
- Logger.log('No people in your visible circles.');
- }
- pageToken = people.nextPageToken;
- } while (pageToken);
-}
-// [END apps_script_plus_people]
-
- // [START apps_script_plus_posts]
-/**
- * The following example demonstrates how to list a user's posts. The returned
- * results contain a brief summary of the posts, including a list of comments
- * made on the post.
- */
-function getPosts() {
- var userId = 'me';
- var posts;
- var pageToken;
- do {
- posts = Plus.Activities.list(userId, 'public', {
- maxResults: 10,
- pageToken: pageToken
- });
- if (posts.items) {
- for (var i = 0; i < posts.items.length; i++) {
- var post = posts.items[i];
- Logger.log(post.title);
- var comments = Plus.Comments.list(post.id);
- if (comments.items) {
- for (var j = 0; j < comments.items.length; j++) {
- var comment = comments.items[j];
- Logger.log(comment.actor.displayName + ': ' +
- comment.object.content);
- }
- }
- }
- } else {
- Logger.log('No posts found.');
- }
- pageToken = posts.pageToken;
- } while (pageToken);
-}
-// [END apps_script_plus_posts]
diff --git a/advanced/googlePlusDomains.gs b/advanced/googlePlusDomains.gs
deleted file mode 100644
index 129b60e68..000000000
--- a/advanced/googlePlusDomains.gs
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * Copyright Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START apps_script_plus_domains_profile]
-/**
- * The following example demonstrates how to retrieve details from a user's
- * Google+ profile.
- */
-function getProfile() {
- var userId = 'me';
- var profile = PlusDomains.People.get(userId);
-
- Logger.log('ID: %s', profile.id);
- Logger.log('Display name: %s', profile.displayName);
- Logger.log('Image URL: %s', profile.image.url);
- Logger.log('Profile URL: %s', profile.url);
-}
-// [END apps_script_plus_domains_profile]
-
- // [START apps_script_plus_domains_circle]
-/**
- * The following example demonstrates how to create an empty circle for a user
- * within your G Suite domain.
- */
-function createCircle() {
- var userId = 'me';
- var circle = PlusDomains.newCircle();
- circle.displayName = 'Tech support';
-
- circle = PlusDomains.Circles.insert(circle, userId);
- Logger.log('Created "Tech support" circle with id: ' + circle.id);
-}
-// [END apps_script_plus_domains_circle]
-
- // [START apps_script_plus_domains_get_posts]
-/**
- * The following example demonstrates how to list a user's posts. The returned
- * results contain a brief summary of the posts, including a title. Use the
- * Activities.get() method to read the full details of a post.
- */
-function getPosts() {
- var userId = 'me';
- var pageToken;
- var posts;
- do {
- posts = PlusDomains.Activities.list(userId, 'user', {
- maxResults: 100,
- pageToken: pageToken
- });
- if (posts.items) {
- for (var i = 0; i < posts.items.length; i++) {
- var post = posts.items[i];
- Logger.log('ID: %s, Content: %s', post.id, post.object.content);
- }
- }
- pageToken = posts.nextPageToken;
- } while (pageToken);
-}
-// [END apps_script_plus_domains_get_posts]
-
-// [START apps_script_plus_domains_create_post]
-/**
- * The following example demonstrates how to create a post that is available
- * to all users within your G Suite domain.
- */
-function createPost() {
- var userId = 'me';
- var post = {
- object: {
- originalContent: 'Happy Monday! #caseofthemondays'
- },
- access: {
- items: [{
- type: 'domain'
- }],
- domainRestricted: true
- }
- };
-
- post = PlusDomains.Activities.insert(post, userId);
- Logger.log('Post created with URL: %s', post.url);
-}
-// [END apps_script_plus_domains_create_post]
diff --git a/advanced/iot.gs b/advanced/iot.gs
index b6b44dcf7..8087fd023 100644
--- a/advanced/iot.gs
+++ b/advanced/iot.gs
@@ -18,17 +18,17 @@
* Lists the registries for the configured project and region.
*/
function listRegistries() {
- Logger.log(response);
+ console.log(response);
var projectId = 'your-project-id';
var cloudRegion = 'us-central1';
var parent = 'projects/' + projectId + '/locations/' + cloudRegion;
var response = CloudIoT.Projects.Locations.Registries.list(parent);
- if (response.deviceRegistries){
+ if (response.deviceRegistries) {
response.deviceRegistries.forEach(
- function(registry){
- Logger.log(registry.id);
- });
+ function(registry) {
+ console.log(registry.id);
+ });
}
}
// [END apps_script_iot_list_registries]
@@ -46,16 +46,16 @@ function createRegistry() {
var pubsubTopic = 'projects/' + projectId + '/topics/' + topic;
var registry = {
- eventNotificationConfigs: [{
+ 'eventNotificationConfigs': [{
// From - https://console.cloud.google.com/cloudpubsub
- pubsubTopicName : pubsubTopic
+ pubsubTopicName: pubsubTopic
}],
'id': name
};
var parent = 'projects/' + projectId + '/locations/' + cloudRegion;
- var response = CloudIoT.Projects.Locations.Registries.create(registry, parent)
- Logger.log('Created registry: ' + response.id);
+ var response = CloudIoT.Projects.Locations.Registries.create(registry, parent);
+ console.log('Created registry: ' + response.id);
}
// [END apps_script_iot_create_registry]
@@ -71,8 +71,8 @@ function getRegistry() {
var parent = 'projects/' + projectId + '/locations/' + cloudRegion;
var registryName = parent + '/registries/' + name;
- var response = CloudIoT.Projects.Locations.Registries.get(registryName)
- Logger.log('Retrieved registry: ' + response.id);
+ var response = CloudIoT.Projects.Locations.Registries.get(registryName);
+ console.log('Retrieved registry: ' + response.id);
}
// [END apps_script_iot_get_registry]
@@ -88,9 +88,9 @@ function deleteRegistry() {
var parent = 'projects/' + projectId + '/locations/' + cloudRegion;
var registryName = parent + '/registries/' + name;
- var response = CloudIoT.Projects.Locations.Registries.remove(registryName)
+ var response = CloudIoT.Projects.Locations.Registries.remove(registryName);
// Successfully removed registry if exception was not thrown.
- Logger.log('Deleted registry: ' + name);
+ console.log('Deleted registry: ' + name);
}
// [END apps_script_iot_delete_registry]
@@ -108,12 +108,12 @@ function listDevicesForRegistry() {
var response = CloudIoT.Projects.Locations.Registries.Devices.list(registryName);
- Logger.log('Registry contains the following devices: ');
+ console.log('Registry contains the following devices: ');
if (response.devices) {
response.devices.forEach(
- function(device){
- Logger.log('\t' + device.id);
- });
+ function(device) {
+ console.log('\t' + device.id);
+ });
}
}
// [END apps_script_iot_list_devices]
@@ -128,7 +128,7 @@ function createDevice() {
var projectId = 'your-project-id';
var registry = 'your-registry-name';
- Logger.log('Creating device: ' + name + ' in Registry: ' + registry);
+ console.log('Creating device: ' + name + ' in Registry: ' + registry);
var parent = 'projects/' + projectId + '/locations/' + cloudRegion + '/registries/' + registry;
var device = {
@@ -139,8 +139,8 @@ function createDevice() {
}
};
- var response = CloudIoT.Projects.Locations.Registries.Devices.create(device, parent)
- Logger.log('Created device:' + response.name);
+ var response = CloudIoT.Projects.Locations.Registries.Devices.create(device, parent);
+ console.log('Created device:' + response.name);
}
// [END apps_script_iot_create_unauth_device]
@@ -178,11 +178,11 @@ function createRsaDevice() {
format: 'RSA_X509_PEM',
key: cert
}
- }],
+ }]
};
var response = CloudIoT.Projects.Locations.Registries.Devices.create(device, parent);
- Logger.log('Created device:' + response.name);
+ console.log('Created device:' + response.name);
}
// [END apps_script_iot_create_rsa_device]
@@ -199,9 +199,9 @@ function deleteDevice() {
var parent = 'projects/' + projectId + '/locations/' + cloudRegion + '/registries/' + registry;
var deviceName = parent + '/devices/' + name;
- var response = CloudIoT.Projects.Locations.Registries.Devices.remove(deviceName)
+ var response = CloudIoT.Projects.Locations.Registries.Devices.remove(deviceName);
// If no exception thrown, device was successfully removed
- Logger.log('Successfully deleted device: ' + deviceName);
+ console.log('Successfully deleted device: ' + deviceName);
}
// [END apps_script_iot_delete_device]
diff --git a/advanced/mirror.gs b/advanced/mirror.gs
deleted file mode 100644
index 7be30550f..000000000
--- a/advanced/mirror.gs
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Copyright Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START apps_script_mirror_timeline]
-/**
- * This sample inserts a new item into the timeline.
- */
-function insertTimelineItem() {
- var timelineItem = Mirror.newTimelineItem();
- timelineItem.text = 'Hello world!';
-
- var notificationConfig = Mirror.newNotificationConfig();
- notificationConfig.level = 'AUDIO_ONLY';
-
- var menuItem = Mirror.newMenuItem();
- menuItem.action = 'REPLY';
-
- timelineItem.notification = notificationConfig;
- timelineItem.menuItems = [menuItem];
-
- Mirror.Timeline.insert(timelineItem);
-}
-// [END apps_script_mirror_timeline]
-
-// [START apps_script_mirror_contact]
-/**
- * This sample inserts a new contact.
- */
-function insertContact() {
- var contact = {
- id: 'harold',
- displayName: 'Harold Penguin',
- imageUrls: ['https://developers.google.com/glass/images/harold.jpg']
- };
-
- Mirror.Contacts.insert(contact);
-}
-// [END apps_script_mirror_contact]
-
-// [START apps_script_mirror_location]
-/**
- * This sample prints the most recent known location of the user's Glass to the
- * script editor's log.
- */
-function printLatestLocation() {
- var location = Mirror.Locations.get('latest');
-
- Logger.log('Location recorded on: ' + location.timestamp);
- Logger.log(' > Latitude: ' + location.latitude);
- Logger.log(' > Longitude: ' + location.longitude);
- Logger.log(' > Accuracy: ' + location.accuracy + ' meters');
-}
-// [END apps_script_mirror_location]
diff --git a/advanced/people.gs b/advanced/people.gs
index 1077ec88c..10cf68d09 100644
--- a/advanced/people.gs
+++ b/advanced/people.gs
@@ -13,40 +13,177 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// [START apps_script_people_get_connections]
+// [START people_get_connections]
/**
* Gets a list of people in the user's contacts.
+ * @see https://developers.google.com/people/api/rest/v1/people.connections/list
*/
function getConnections() {
- var people = People.People.Connections.list('people/me', {
- personFields: 'names,emailAddresses'
- });
- Logger.log('Connections: %s', JSON.stringify(people, null, 2));
+ try {
+ // Get the list of connections/contacts of user's profile
+ const people = People.People.Connections.list('people/me', {
+ personFields: 'names,emailAddresses'
+ });
+ // Print the connections/contacts
+ console.log('Connections: %s', JSON.stringify(people, null, 2));
+ } catch (err) {
+ // TODO (developers) - Handle exception here
+ console.log('Failed to get the connection with an error %s', err.message);
+ }
}
-// [END apps_script_people_get_connections]
+// [END people_get_connections]
-// [START apps_script_people_get_self]
+// [START people_get_self_profile]
/**
* Gets the own user's profile.
+ * @see https://developers.google.com/people/api/rest/v1/people/getBatchGet
*/
function getSelf() {
- var people = People.People.getBatchGet({
- resourceNames: ['people/me'],
- personFields: 'names,emailAddresses'
- });
- Logger.log('Myself: %s', JSON.stringify(people, null, 2));
+ try {
+ // Get own user's profile using People.getBatchGet() method
+ const people = People.People.getBatchGet({
+ resourceNames: ['people/me'],
+ personFields: 'names,emailAddresses'
+ // Use other query parameter here if needed
+ });
+ console.log('Myself: %s', JSON.stringify(people, null, 2));
+ } catch (err) {
+ // TODO (developer) -Handle exception
+ console.log('Failed to get own profile with an error %s', err.message);
+ }
}
-// [END apps_script_people_get_self]
+// [END people_get_self_profile]
-// [START apps_script_people_get_account]
+// [START people_get_account]
/**
* Gets the person information for any Google Account.
* @param {string} accountId The account ID.
+ * @see https://developers.google.com/people/api/rest/v1/people/get
*/
function getAccount(accountId) {
- var people = People.People.get('people/' + accountId, {
- personFields: 'names,emailAddresses'
- });
- Logger.log('Public Profile: %s', JSON.stringify(people, null, 2));
+ try {
+ // Get the Account details using account ID.
+ const people = People.People.get('people/' + accountId, {
+ personFields: 'names,emailAddresses'
+ });
+ // Print the profile details of Account.
+ console.log('Public Profile: %s', JSON.stringify(people, null, 2));
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed to get account with an error %s', err.message);
+ }
}
-// [END apps_script_people_get_account]
+// [END people_get_account]
+
+// [START people_get_group]
+
+/**
+ * Gets a contact group with the given name
+ * @param {string} name The group name.
+ * @see https://developers.google.com/people/api/rest/v1/contactGroups/list
+ */
+function getContactGroup(name) {
+ try {
+ const people = People.ContactGroups.list();
+ // Finds the contact group for the person where the name matches.
+ const group = people['contactGroups'].find((group) => group['name'] === name);
+ // Prints the contact group
+ console.log('Group: %s', JSON.stringify(group, null, 2));
+ } catch (err) {
+ // TODO (developers) - Handle exception
+ console.log('Failed to get the contact group with an error %s', err.message);
+ }
+}
+
+// [END people_get_group]
+
+// [START people_get_contact_by_email]
+
+/**
+ * Gets a contact by the email address.
+ * @param {string} email The email address.
+ * @see https://developers.google.com/people/api/rest/v1/people.connections/list
+ */
+function getContactByEmail(email) {
+ try {
+ // Gets the person with that email address by iterating over all contacts.
+ const people = People.People.Connections.list('people/me', {
+ personFields: 'names,emailAddresses'
+ });
+ const contact = people['connections'].find((connection) => {
+ return connection['emailAddresses'].some((emailAddress) => emailAddress['value'] === email);
+ });
+ // Prints the contact.
+ console.log('Contact: %s', JSON.stringify(contact, null, 2));
+ } catch (err) {
+ // TODO (developers) - Handle exception
+ console.log('Failed to get the connection with an error %s', err.message);
+ }
+}
+
+// [END people_get_contact_by_email]
+
+// [START people_get_full_name]
+/**
+ * Gets the full name (given name and last name) of the contact as a string.
+ * @see https://developers.google.com/people/api/rest/v1/people/get
+ */
+function getFullName() {
+ try {
+ // Gets the person by specifying resource name/account ID
+ // in the first parameter of People.People.get.
+ // This example gets the person for the user running the script.
+ const people = People.People.get('people/me', {personFields: 'names'});
+ // Prints the full name (given name + family name)
+ console.log(`${people['names'][0]['givenName']} ${people['names'][0]['familyName']}`);
+ } catch (err) {
+ // TODO (developers) - Handle exception
+ console.log('Failed to get the connection with an error %s', err.message);
+ }
+}
+
+// [END people_get_full_name]
+
+// [START people_get_phone_numbers]
+/**
+ * Gets all the phone numbers for this contact.
+ * @see https://developers.google.com/people/api/rest/v1/people/get
+ */
+function getPhoneNumbers() {
+ try {
+ // Gets the person by specifying resource name/account ID
+ // in the first parameter of People.People.get.
+ // This example gets the person for the user running the script.
+ const people = People.People.get('people/me', {personFields: 'phoneNumbers'});
+ // Prints the phone numbers.
+ console.log(people['phoneNumbers']);
+ } catch (err) {
+ // TODO (developers) - Handle exception
+ console.log('Failed to get the connection with an error %s', err.message);
+ }
+}
+
+// [END people_get_phone_numbers]
+
+// [START people_get_single_phone_number]
+/**
+ * Gets a phone number by type, such as work or home.
+ * @see https://developers.google.com/people/api/rest/v1/people/get
+ */
+function getPhone() {
+ try {
+ // Gets the person by specifying resource name/account ID
+ // in the first parameter of People.People.get.
+ // This example gets the person for the user running the script.
+ const people = People.People.get('people/me', {personFields: 'phoneNumbers'});
+ // Gets phone number by type, such as home or work.
+ const phoneNumber = people['phoneNumbers'].find((phone) => phone['type'] === 'home')['value'];
+ // Prints the phone numbers.
+ console.log(phoneNumber);
+ } catch (err) {
+ // TODO (developers) - Handle exception
+ console.log('Failed to get the connection with an error %s', err.message);
+ }
+}
+
+// [END people_get_single_phone_number]
diff --git a/advanced/prediction.gs b/advanced/prediction.gs
deleted file mode 100644
index 88ba2817d..000000000
--- a/advanced/prediction.gs
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * Copyright Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START apps_script_prediction_query_hosted_model]
-/**
- * Runs sentiment analysis across a sentence.
- * Prints the sentiment label.
- */
-function queryHostedModel() {
- // When querying hosted models you must always use this
- // specific project number.
- var projectNumber = '414649711441';
- var hostedModelName = 'sample.sentiment';
-
- // Query the hosted model with a positive statement.
- var predictionString = 'Want to go to the park this weekend?';
- var prediction = Prediction.Hostedmodels.predict(
- {
- input: {
- csvInstance: [predictionString]
- }
- },
- projectNumber,
- hostedModelName);
- // Logs Sentiment: positive.
- Logger.log('Sentiment: ' + prediction.outputLabel);
-
- // Now query the hosted model with a negative statement.
- predictionString = 'You are not very nice!';
- prediction = Prediction.Hostedmodels.predict(
- {
- input: {
- csvInstance: [predictionString]
- }
- },
- projectNumber,
- hostedModelName);
- // Logs Sentiment: negative.
- Logger.log('Sentiment: ' + prediction.outputLabel);
-}
-// [END apps_script_prediction_query_hosted_model]
-
-// [START apps_script_prediction_create_new_model]
-/**
- * Creates a new prediction model.
- */
-function createNewModel() {
- // Replace this value with the project number listed in the Google
- // APIs Console project.
- var projectNumber = 'XXXXXXXX';
- var id = 'mylanguageidmodel';
- var storageDataLocation = 'languageidsample/language_id.txt';
-
- // Returns immediately. Training happens asynchronously.
- var result = Prediction.Trainedmodels.insert(
- {
- id: id,
- storageDataLocation: storageDataLocation
- },
- projectNumber);
- Logger.log(result);
-}
-// [END apps_script_prediction_create_new_model]
-
-// [START apps_script_prediction_query_training_status]
-/**
- * Gets the training status from a prediction model.
- * Logs the status.
- */
-function queryTrainingStatus() {
- // Replace this value with the project number listed in the Google
- // APIs Console project.
- var projectNumber = 'XXXXXXXX';
- var id = 'mylanguageidmodel';
-
- var result = Prediction.Trainedmodels.get(projectNumber, id);
- Logger.log(result.trainingStatus);
-}
-// [END apps_script_prediction_query_training_status]
-
-// [START apps_script_prediction_query_trailed_model]
-/**
- * Gets the language from a trained language model.
- * Logs the language of the sentence.
- */
-function queryTrainedModel() {
- // Replace this value with the project number listed in the Google
- // APIs Console project.
- var projectNumber = 'XXXXXXXX';
- var id = 'mylanguageidmodel';
- var query = 'Este es un mensaje de prueba de ejemplo';
-
- var prediction = Prediction.Trainedmodels.predict(
- {
- input:
- {
- csvInstance: [query]
- }
- },
- projectNumber,
- id);
- // Logs Language: Spanish.
- Logger.log('Language: ' + prediction.outputLabel);
-}
-// [END apps_script_prediction_query_trailed_model]
diff --git a/advanced/sheets.gs b/advanced/sheets.gs
index 3875bd5f9..cac5df416 100644
--- a/advanced/sheets.gs
+++ b/advanced/sheets.gs
@@ -13,38 +13,48 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var spreadsheetId = '1LcjJcCdM6OGrJtJEkHegV-rH5bWZ-mCukEMMCKYtUkc';
-var sheetId = 371977894;
-var pivotSourceDataSheetId = 371977894;
-var destinationSheetId = 1428299768;
-
-// [START apps_script_sheets_read_range]
+// TODO (developer)- Replace the spreadsheet ID and sheet ID with yours values.
+const yourspreadsheetId = '1YdrrmXSjpi4Tz-UuQ0eUKtdzQuvpzRLMoPEz3niTTVU';
+const yourpivotSourceDataSheetId = 635809130;
+const yourdestinationSheetId = 83410180;
+// [START sheets_read_range]
/**
* Read a range (A1:D5) of data values. Logs the values.
* @param {string} spreadsheetId The spreadsheet ID to read from.
+ * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
*/
-function readRange(spreadsheetId) {
- var response = Sheets.Spreadsheets.Values.get(spreadsheetId, 'Sheet1!A1:D5');
- Logger.log(response.values);
+function readRange(spreadsheetId = yourspreadsheetId) {
+ try {
+ const response = Sheets.Spreadsheets.Values.get(spreadsheetId, 'Sheet1!A1:D5');
+ if (response.values) {
+ console.log(response.values);
+ return;
+ }
+ console.log('Failed to get range of values from spreadsheet');
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', e.message);
+ }
}
-// [END apps_script_sheets_read_range]
+// [END sheets_read_range]
-// [START apps_script_sheets_write_range]
+// [START sheets_write_range]
/**
* Write to multiple, disjoint data ranges.
* @param {string} spreadsheetId The spreadsheet ID to write to.
+ * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate
*/
-function writeToMultipleRanges(spreadsheetId) {
+function writeToMultipleRanges(spreadsheetId = yourspreadsheetId) {
// Specify some values to write to the sheet.
- var columnAValues = [
+ const columnAValues = [
['Item', 'Wheel', 'Door', 'Engine']
];
- var rowValues = [
+ const rowValues = [
['Cost', 'Stocked', 'Ship Date'],
['$20.50', '4', '3/1/2016']
];
- var request = {
+ const request = {
'valueInputOption': 'USER_ENTERED',
'data': [
{
@@ -59,19 +69,28 @@ function writeToMultipleRanges(spreadsheetId) {
}
]
};
-
- var response = Sheets.Spreadsheets.Values.batchUpdate(request, spreadsheetId);
- Logger.log(response);
+ try {
+ const response = Sheets.Spreadsheets.Values.batchUpdate(request, spreadsheetId);
+ if (response) {
+ console.log(response);
+ return;
+ }
+ console.log('response null');
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', e.message);
+ }
}
-// [END apps_script_sheets_write_range]
+// [END sheets_write_range]
-// [START apps_script_sheets_new_sheet]
+// [START sheets_add_new_sheet]
/**
* Add a new sheet with some properties.
* @param {string} spreadsheetId The spreadsheet ID.
+ * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate
*/
-function addSheet(spreadsheetId) {
- var requests = [{
+function addSheet(spreadsheetId = yourspreadsheetId) {
+ const requests = [{
'addSheet': {
'properties': {
'title': 'Deposits',
@@ -87,24 +106,31 @@ function addSheet(spreadsheetId) {
}
}
}];
-
- var response =
+ try {
+ const response =
Sheets.Spreadsheets.batchUpdate({'requests': requests}, spreadsheetId);
- Logger.log('Created sheet with ID: ' +
+ console.log('Created sheet with ID: ' +
response.replies[0].addSheet.properties.sheetId);
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', e.message);
+ }
}
-// [END apps_script_sheets_new_sheet]
+// [END sheets_add_new_sheet]
-// [START apps_script_sheets_add_pivot_table]
+// [START sheets_add_pivot_table]
/**
* Add a pivot table.
* @param {string} spreadsheetId The spreadsheet ID to add the pivot table to.
* @param {string} pivotSourceDataSheetId The sheet ID to get the data from.
* @param {string} destinationSheetId The sheet ID to add the pivot table to.
+ * @see https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate
*/
function addPivotTable(
- spreadsheetId, pivotSourceDataSheetId, destinationSheetId) {
- var requests = [{
+ spreadsheetId = yourspreadsheetId,
+ pivotSourceDataSheetId= yourpivotSourceDataSheetId,
+ destinationSheetId= yourdestinationSheetId) {
+ const requests = [{
'updateCells': {
'rows': {
'values': [
@@ -164,9 +190,12 @@ function addPivotTable(
'fields': 'pivotTable'
}
}];
-
- var response =
- Sheets.Spreadsheets.batchUpdate({'requests': requests}, spreadsheetId);
- // The Pivot table will appear anchored to cell A50 of the destination sheet.
+ try {
+ const response = Sheets.Spreadsheets.batchUpdate({'requests': requests}, spreadsheetId);
+ // The Pivot table will appear anchored to cell A50 of the destination sheet.
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', e.message);
+ }
}
-// [END apps_script_sheets_add_pivot_table]
+// [END sheets_add_pivot_table]
diff --git a/advanced/shoppingContent.gs b/advanced/shoppingContent.gs
index 69f1ad0d4..22cc7e2c8 100644
--- a/advanced/shoppingContent.gs
+++ b/advanced/shoppingContent.gs
@@ -18,9 +18,9 @@
* Inserts a product into the products list. Logs the API response.
*/
function productInsert() {
- var merchantId = 123456; // Replace this with your Merchant Center ID.
+ const merchantId = 123456; // Replace this with your Merchant Center ID.
// Create a product resource and insert it
- var productResource = {
+ const productResource = {
'offerId': 'book123',
'title': 'A Tale of Two Cities',
'description': 'A classic novel about the French Revolution',
@@ -52,8 +52,14 @@ function productInsert() {
}
};
- response = ShoppingContent.Products.insert(productResource, merchantId);
- Logger.log(response); // RESTful insert returns the JSON object as a response.
+ try {
+ response = ShoppingContent.Products.insert(productResource, merchantId);
+ // RESTful insert returns the JSON object as a response.
+ console.log(response);
+ } catch (e) {
+ // TODO (Developer) - Handle exceptions
+ console.log('Failed with error: $s', e.error);
+ }
}
// [END apps_script_shopping_product_insert]
@@ -62,26 +68,31 @@ function productInsert() {
* Lists the products for a given merchant.
*/
function productList() {
- var merchantId = 123456; // Replace this with your Merchant Center ID.
- var pageToken;
- var pageNum = 1;
- var maxResults = 10;
- do {
- var products = ShoppingContent.Products.list(merchantId, {
- pageToken: pageToken,
- maxResults: maxResults
- });
- Logger.log('Page ' + pageNum);
- if (products.resources) {
- for (var i = 0; i < products.resources.length; i++) {
- Logger.log('Item [' + i + '] ==> ' + products.resources[i]);
+ const merchantId = 123456; // Replace this with your Merchant Center ID.
+ let pageToken;
+ let pageNum = 1;
+ const maxResults = 10;
+ try {
+ do {
+ const products = ShoppingContent.Products.list(merchantId, {
+ pageToken: pageToken,
+ maxResults: maxResults
+ });
+ console.log('Page ' + pageNum);
+ if (products.resources) {
+ for (let i = 0; i < products.resources.length; i++) {
+ console.log('Item [' + i + '] ==> ' + products.resources[i]);
+ }
+ } else {
+ console.log('No more products in account ' + merchantId);
}
- } else {
- Logger.log('No more products in account ' + merchantId);
- }
- pageToken = products.nextPageToken;
- pageNum++;
- } while (pageToken);
+ pageToken = products.nextPageToken;
+ pageNum++;
+ } while (pageToken);
+ } catch (e) {
+ // TODO (Developer) - Handle exceptions
+ console.log('Failed with error: $s', e.error);
+ }
}
// [END apps_script_shopping_product_list]
@@ -93,7 +104,7 @@ function productList() {
* @param {object} productResource3 The third product resource.
*/
function custombatch(productResource1, productResource2, productResource3) {
- var merchantId = 123456; // Replace this with your Merchant Center ID.
+ const merchantId = 123456; // Replace this with your Merchant Center ID.
custombatchResource = {
'entries': [
{
@@ -119,8 +130,13 @@ function custombatch(productResource1, productResource2, productResource3) {
}
]
};
- var response = ShoppingContent.Products.custombatch(custombatchResource);
- Logger.log(response);
+ try {
+ const response = ShoppingContent.Products.custombatch(custombatchResource);
+ console.log(response);
+ } catch (e) {
+ // TODO (Developer) - Handle exceptions
+ console.log('Failed with error: $s', e.error);
+ }
}
// [END apps_script_shopping_product_batch_insert]
@@ -131,37 +147,43 @@ function custombatch(productResource1, productResource2, productResource3) {
*/
function updateAccountTax() {
// Replace this with your Merchant Center ID.
- var merchantId = 123456;
+ const merchantId = 123456;
// Replace this with the account that you are updating taxes for.
- var accountId = 123456;
+ const accountId = 123456;
- var accounttax = ShoppingContent.Accounttax.get(merchantId, accountId);
- Logger.log(accounttax);
+ try {
+ const accounttax = ShoppingContent.Accounttax.get(merchantId, accountId);
+ console.log(accounttax);
- var taxInfo = {
- accountId: accountId,
- rules: [
- {
- 'useGlobalRate': true,
- 'locationId': 21135,
- 'shippingTaxed': true,
- 'country': 'US'
- },
- {
- 'ratePercent': 3,
- 'locationId': 21136,
- 'country': 'US'
- },
- {
- 'ratePercent': 2,
- 'locationId': 21160,
- 'shippingTaxed': true,
- 'country': 'US'
- }
- ]
- };
+ const taxInfo = {
+ accountId: accountId,
+ rules: [
+ {
+ 'useGlobalRate': true,
+ 'locationId': 21135,
+ 'shippingTaxed': true,
+ 'country': 'US'
+ },
+ {
+ 'ratePercent': 3,
+ 'locationId': 21136,
+ 'country': 'US'
+ },
+ {
+ 'ratePercent': 2,
+ 'locationId': 21160,
+ 'shippingTaxed': true,
+ 'country': 'US'
+ }
+ ]
+ };
- Logger.log(ShoppingContent.Accounttax.update(taxInfo, merchantId, accountId));
+ console.log(ShoppingContent.Accounttax
+ .update(taxInfo, merchantId, accountId));
+ } catch (e) {
+ // TODO (Developer) - Handle exceptions
+ console.log('Failed with error: $s', e.error);
+ }
}
// [END apps_script_shopping_account_info]
diff --git a/advanced/slides.gs b/advanced/slides.gs
index 40a9b2227..d8532df0b 100644
--- a/advanced/slides.gs
+++ b/advanced/slides.gs
@@ -13,18 +13,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var presentationId = '1K0Wd9BWgfy1doB0da_vRYmaYTUavEYVKJV_EygSiiMY';
-var pageId = 'p';
-var shapeId = 'MyTextBoxId';
// [START apps_script_slides_create_presentation]
/**
* Create a new presentation.
+ * @return {string} presentation Id.
+ * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/create
*/
function createPresentation() {
- var presentation =
+ try {
+ const presentation =
Slides.Presentations.create({'title': 'MyNewPresentation'});
- Logger.log('Created presentation with ID: ' + presentation.presentationId);
+ console.log('Created presentation with ID: ' + presentation.presentationId);
+ return presentation.presentationId;
+ } catch (e) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', e.message);
+ }
}
// [END apps_script_slides_create_presentation]
@@ -32,12 +37,14 @@ function createPresentation() {
/**
* Create a new slide.
* @param {string} presentationId The presentation to add the slide to.
+ * @return {Object} slide
+ * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/batchUpdate
*/
function createSlide(presentationId) {
// You can specify the ID to use for the slide, as long as it's unique.
- var pageId = Utilities.getUuid();
+ const pageId = Utilities.getUuid();
- var requests = [{
+ const requests = [{
'createSlide': {
'objectId': pageId,
'insertionIndex': 1,
@@ -46,9 +53,15 @@ function createSlide(presentationId) {
}
}
}];
- var slide =
+ try {
+ const slide =
Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
- Logger.log('Created Slide with ID: ' + slide.replies[0].createSlide.objectId);
+ console.log('Created Slide with ID: ' + slide.replies[0].createSlide.objectId);
+ return slide;
+ } catch (e) {
+ // TODO (developer) - Handle Exception
+ console.log('Failed with error %s', e.message);
+ }
}
// [END apps_script_slides_create_slide]
@@ -57,13 +70,21 @@ function createSlide(presentationId) {
* Read page element IDs.
* @param {string} presentationId The presentation to read from.
* @param {string} pageId The page to read from.
+ * @return {Object} response
+ * @see https://developers.google.com/slides/api/reference/rest/v1/presentations.pages/get
*/
function readPageElementIds(presentationId, pageId) {
// You can use a field mask to limit the data the API retrieves
// in a get request, or what fields are updated in an batchUpdate.
- var response = Slides.Presentations.Pages.get(
- presentationId, pageId, {'fields': 'pageElements.objectId'});
- Logger.log(response);
+ try {
+ const response = Slides.Presentations.Pages.get(
+ presentationId, pageId, {'fields': 'pageElements.objectId'});
+ console.log(response);
+ return response;
+ } catch (e) {
+ // TODO (developer) - Handle Exception
+ console.log('Failed with error %s', e.message);
+ }
}
// [END apps_script_slides_read_page]
@@ -72,13 +93,15 @@ function readPageElementIds(presentationId, pageId) {
* Add a new text box with text to a page.
* @param {string} presentationId The presentation ID.
* @param {string} pageId The page ID.
+ * @return {Object} response
+ * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/batchUpdate
*/
function addTextBox(presentationId, pageId) {
// You can specify the ID to use for elements you create,
// as long as the ID is unique.
- var pageElementId = Utilities.getUuid();
+ const pageElementId = Utilities.getUuid();
- var requests = [{
+ const requests = [{
'createShape': {
'objectId': pageElementId,
'shapeType': 'TEXT_BOX',
@@ -110,10 +133,16 @@ function addTextBox(presentationId, pageId) {
'insertionIndex': 0
}
}];
- var response =
+ try {
+ const response =
Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
- Logger.log('Created Textbox with ID: ' +
+ console.log('Created Textbox with ID: ' +
response.replies[0].createShape.objectId);
+ return response;
+ } catch (e) {
+ // TODO (developer) - Handle Exception
+ console.log('Failed with error %s', e.message);
+ }
}
// [END apps_script_slides_add_text_box]
@@ -122,9 +151,11 @@ function addTextBox(presentationId, pageId) {
* Format the text in a shape.
* @param {string} presentationId The presentation ID.
* @param {string} shapeId The shape ID.
+ * @return {Object} replies
+ * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/batchUpdate
*/
function formatShapeText(presentationId, shapeId) {
- var requests = [{
+ const requests = [{
'updateTextStyle': {
'objectId': shapeId,
'fields': 'foregroundColor,bold,italic,fontFamily,fontSize,underline',
@@ -148,25 +179,40 @@ function formatShapeText(presentationId, shapeId) {
}
}
}];
- var response =
+ try {
+ const response =
Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
+ return response.replies;
+ } catch (e) {
+ // TODO (developer) - Handle Exception
+ console.log('Failed with error %s', e.message);
+ }
}
// [END apps_script_slides_format_shape_text]
-// [START apps_script_slides_thumbnail]
+// [START apps_script_slides_save_thumbnail]
/**
* Saves a thumbnail image of the current Google Slide presentation in Google Drive.
* Logs the image URL.
* @param {number} i The zero-based slide index. 0 is the first slide.
* @example saveThumbnailImage(0)
+ * @see https://developers.google.com/slides/api/reference/rest/v1/presentations.pages/getThumbnail
*/
function saveThumbnailImage(i) {
- var presentation = SlidesApp.getActivePresentation();
- var thumbnail = Slides.Presentations.Pages.getThumbnail(
- presentation.getId(), presentation.getSlides()[i].getObjectId());
- var response = UrlFetchApp.fetch(thumbnail.contentUrl);
- var image = response.getBlob();
- var file = DriveApp.createFile(image);
- Logger.log(file.getUrl());
+ try {
+ const presentation = SlidesApp.getActivePresentation();
+ // Get the thumbnail of specified page
+ const thumbnail = Slides.Presentations.Pages.getThumbnail(
+ presentation.getId(), presentation.getSlides()[i].getObjectId());
+ // fetch the URL to the thumbnail image.
+ const response = UrlFetchApp.fetch(thumbnail.contentUrl);
+ const image = response.getBlob();
+ // Creates a file in the root of the user's Drive from a given Blob of arbitrary data.
+ const file = DriveApp.createFile(image);
+ console.log(file.getUrl());
+ } catch (e) {
+ // TODO (developer) - Handle Exception
+ console.log('Failed with error %s', e.message);
+ }
}
-// [END apps_script_slides_thumbnail]
+// [END apps_script_slides_save_thumbnail]
diff --git a/advanced/tagManager.gs b/advanced/tagManager.gs
index 4902a183c..3d15f8d8e 100644
--- a/advanced/tagManager.gs
+++ b/advanced/tagManager.gs
@@ -15,58 +15,64 @@
*/
// [START apps_script_tag_manager_create_version]
/**
- * Creates a container version for a particular account with the input accountPath.
+ * Creates a container version for a particular account
+ * with the input accountPath.
* @param {string} accountPath The account path.
* @return {string} The tag manager container version.
*/
function createContainerVersion(accountPath) {
- var date = new Date();
+ const date = new Date();
// Creates a container in the account, using the current timestamp to make
// sure the container is unique.
- var container = TagManager.Accounts.Containers.create(
- {
- 'name': 'appscript tagmanager container ' + date.getTime(),
- 'usageContext': ['WEB']
- },
- accountPath);
- var containerPath = container.path;
- // Creates a workspace in the container to track entity changes.
- var workspace = TagManager.Accounts.Containers.Workspaces.create(
- {'name': 'appscript workspace', 'description': 'appscript workspace'},
- containerPath);
- var workspacePath = workspace.path;
- // Creates a random value variable.
- var variable = TagManager.Accounts.Containers.Workspaces.Variables.create(
- {'name': 'apps script variable', 'type': 'r'},
- workspacePath);
- // Creates a trigger that fires on any page view.
- var trigger = TagManager.Accounts.Containers.Workspaces.Triggers.create(
- {'name': 'apps script trigger', 'type': 'PAGEVIEW'},
- workspacePath);
- // Creates a arbitary pixel that fires the tag on all page views.
- var tag = TagManager.Accounts.Containers.Workspaces.Tags.create(
- {
- 'name': 'apps script tag',
- 'type': 'img',
- 'liveOnly': false,
- 'parameter': [
- {'type': 'boolean', 'key': 'useCacheBuster', 'value': 'true'}, {
- 'type': 'template',
- 'key': 'cacheBusterQueryParam',
- 'value': 'gtmcb'
- },
- {'type': 'template', 'key': 'url', 'value': '//example.com'}
- ],
- 'firingTriggerId': [trigger.triggerId]
- },
- workspacePath);
- // Creates a container version with the variabe, trigger, and tag.
- var version = TagManager.Accounts.Containers.Workspaces
- .create_version(
- {'name': 'apps script version'}, workspacePath)
- .containerVersion;
- Logger.log(version);
- return version;
+ try {
+ const container = TagManager.Accounts.Containers.create(
+ {
+ 'name': 'appscript tagmanager container ' + date.getTime(),
+ 'usageContext': ['WEB']
+ },
+ accountPath);
+ const containerPath = container.path;
+ // Creates a workspace in the container to track entity changes.
+ const workspace = TagManager.Accounts.Containers.Workspaces.create(
+ {'name': 'appscript workspace', 'description': 'appscript workspace'},
+ containerPath);
+ const workspacePath = workspace.path;
+ // Creates a random value variable.
+ const variable = TagManager.Accounts.Containers.Workspaces.Variables.create(
+ {'name': 'apps script variable', 'type': 'r'},
+ workspacePath);
+ // Creates a trigger that fires on any page view.
+ const trigger = TagManager.Accounts.Containers.Workspaces.Triggers.create(
+ {'name': 'apps script trigger', 'type': 'PAGEVIEW'},
+ workspacePath);
+ // Creates a arbitary pixel that fires the tag on all page views.
+ const tag = TagManager.Accounts.Containers.Workspaces.Tags.create(
+ {
+ 'name': 'apps script tag',
+ 'type': 'img',
+ 'liveOnly': false,
+ 'parameter': [
+ {'type': 'boolean', 'key': 'useCacheBuster', 'value': 'true'}, {
+ 'type': 'template',
+ 'key': 'cacheBusterQueryParam',
+ 'value': 'gtmcb'
+ },
+ {'type': 'template', 'key': 'url', 'value': '//example.com'}
+ ],
+ 'firingTriggerId': [trigger.triggerId]
+ },
+ workspacePath);
+ // Creates a container version with the variabe, trigger, and tag.
+ const version = TagManager.Accounts.Containers.Workspaces
+ .create_version(
+ {'name': 'apps script version'}, workspacePath)
+ .containerVersion;
+ console.log(version);
+ return version;
+ } catch (e) {
+ // TODO (Developer) - Handle exception
+ console.log('Failed with error: %s', e.error);
+ }
}
// [END apps_script_tag_manager_create_version]
@@ -77,7 +83,7 @@ function createContainerVersion(accountPath) {
* @return {string} The container path.
*/
function grabContainerPath(versionPath) {
- var pathParts = versionPath.split('/');
+ const pathParts = versionPath.split('/');
return pathParts.slice(0, 4).join('/');
}
@@ -87,17 +93,22 @@ function grabContainerPath(versionPath) {
* @param {object} version The container version.
*/
function publishVersionAndQuickPreviewDraft(version) {
- var containerPath = grabContainerPath(version.path);
- // Publish the input container version.
- TagManager.Accounts.Containers.Versions.publish(version.path);
- var workspace = TagManager.Accounts.Containers.Workspaces.create(
- {'name': 'appscript workspace', 'description': 'appscript workspace'},
- containerPath);
- var workspaceId = workspace.path;
- // Quick previews the current container draft.
- var quickPreview = TagManager.Accounts.Containers.Workspaces.quick_preview(
- workspace.path);
- Logger.log(quickPreview);
+ try {
+ const containerPath = grabContainerPath(version.path);
+ // Publish the input container version.
+ TagManager.Accounts.Containers.Versions.publish(version.path);
+ const workspace = TagManager.Accounts.Containers.Workspaces.create(
+ {'name': 'appscript workspace', 'description': 'appscript workspace'},
+ containerPath);
+ const workspaceId = workspace.path;
+ // Quick previews the current container draft.
+ const quickPreview = TagManager.Accounts.Containers.Workspaces
+ .quick_preview(workspace.path);
+ console.log(quickPreview);
+ } catch (e) {
+ // TODO (Developer) - Handle exceptions
+ console.log('Failed with error: $s', e.error);
+ }
}
// [END apps_script_tag_manager_publish_version]
@@ -108,7 +119,7 @@ function publishVersionAndQuickPreviewDraft(version) {
* @return {string} The container path.
*/
function grabContainerPath(versionPath) {
- var pathParts = versionPath.split('/');
+ const pathParts = versionPath.split('/');
return pathParts.slice(0, 4).join('/');
}
@@ -118,20 +129,26 @@ function grabContainerPath(versionPath) {
* @param {object} version The container version object.
*/
function createAndReauthorizeUserEnvironment(version) {
- // Creates a container version.
- var containerPath = grabContainerPath(version.path);
- // Creates a user environment that points to a container version.
- var environment = TagManager.Accounts.Containers.Environments.create(
- {
- 'name': 'test_environment',
- 'type': 'user',
- 'containerVersionId': version.containerVersionId
- },
- containerPath);
- Logger.log('Original user environment: ' + environment);
- // Reauthorizes the user environment that points to a container version.
- TagManager.Accounts.Containers.Environments.reauthorize({}, environment.path);
- Logger.log('Reauthorized user environment: ' + environment);
+ try {
+ // Creates a container version.
+ const containerPath = grabContainerPath(version.path);
+ // Creates a user environment that points to a container version.
+ const environment = TagManager.Accounts.Containers.Environments.create(
+ {
+ 'name': 'test_environment',
+ 'type': 'user',
+ 'containerVersionId': version.containerVersionId
+ },
+ containerPath);
+ console.log('Original user environment: ' + environment);
+ // Reauthorizes the user environment that points to a container version.
+ TagManager.Accounts.Containers.Environments.reauthorize(
+ {}, environment.path);
+ console.log('Reauthorized user environment: ' + environment);
+ } catch (e) {
+ // TODO (Developer) - Handle exceptions
+ console.log('Failed with error: $s', e.error);
+ }
}
// [END apps_script_tag_manager_create_user_environment]
@@ -141,20 +158,25 @@ function createAndReauthorizeUserEnvironment(version) {
* @param {string} accountPath The account path.
*/
function logAllAccountUserPermissionsWithContainerAccess(accountPath) {
- var userPermissions =
+ try {
+ const userPermissions =
TagManager.Accounts.User_permissions.list(accountPath).userPermission;
- for (var i = 0; i < userPermissions.length; i++) {
- var userPermission = userPermissions[i];
- if ('emailAddress' in userPermission) {
- var containerAccesses = userPermission.containerAccess;
- for (var j = 0; j < containerAccesses.length; j++) {
- var containerAccess = containerAccesses[j];
- Logger.log(
- 'emailAddress:' + userPermission.emailAddress + ' containerId:' +
- containerAccess.containerId + ' containerAccess:' +
- containerAccess.permission);
+ for (let i = 0; i < userPermissions.length; i++) {
+ const userPermission = userPermissions[i];
+ if ('emailAddress' in userPermission) {
+ const containerAccesses = userPermission.containerAccess;
+ for (let j = 0; j < containerAccesses.length; j++) {
+ const containerAccess = containerAccesses[j];
+ console.log(
+ 'emailAddress:' + userPermission.emailAddress +
+ ' containerId:' + containerAccess.containerId +
+ ' containerAccess:' + containerAccess.permission);
+ }
}
}
+ } catch (e) {
+ // TODO (Developer) - Handle exceptions
+ console.log('Failed with error: $s', e.error);
}
}
// [END apps_script_tag_manager_log]
diff --git a/advanced/tasks.gs b/advanced/tasks.gs
index 29e36dffb..af1e3bd9c 100644
--- a/advanced/tasks.gs
+++ b/advanced/tasks.gs
@@ -13,54 +13,79 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// [START apps_script_tasks_lists_task_lists]
+// [START tasks_lists_task_lists]
/**
- * Lists tasks titles and IDs.
+ * Lists the titles and IDs of tasksList.
+ * @see https://developers.google.com/tasks/reference/rest/v1/tasklists/list
*/
function listTaskLists() {
- var taskLists = Tasks.Tasklists.list();
- if (taskLists.items) {
- for (var i = 0; i < taskLists.items.length; i++) {
- var taskList = taskLists.items[i];
- Logger.log('Task list with title "%s" and ID "%s" was found.',
- taskList.title, taskList.id);
+ try {
+ // Returns all the authenticated user's task lists.
+ const taskLists = Tasks.Tasklists.list();
+ // If taskLists are available then print all tasklists.
+ if (!taskLists.items) {
+ console.log('No task lists found.');
+ return;
}
- } else {
- Logger.log('No task lists found.');
+ // Print the tasklist title and tasklist id.
+ for (let i = 0; i < taskLists.items.length; i++) {
+ const taskList = taskLists.items[i];
+ console.log('Task list with title "%s" and ID "%s" was found.', taskList.title, taskList.id);
+ }
+ } catch (err) {
+ // TODO (developer) - Handle exception from Task API
+ console.log('Failed with an error %s ', err.message);
}
}
-// [END apps_script_tasks_lists_task_lists]
+// [END tasks_lists_task_lists]
-// [START apps_script_tasks_list_tasks]
+// [START tasks_list_tasks]
/**
* Lists task items for a provided tasklist ID.
* @param {string} taskListId The tasklist ID.
+ * @see https://developers.google.com/tasks/reference/rest/v1/tasks/list
*/
function listTasks(taskListId) {
- var tasks = Tasks.Tasks.list(taskListId);
- if (tasks.items) {
- for (var i = 0; i < tasks.items.length; i++) {
- var task = tasks.items[i];
- Logger.log('Task with title "%s" and ID "%s" was found.',
- task.title, task.id);
+ try {
+ // List the task items of specified tasklist using taskList id.
+ const tasks = Tasks.Tasks.list(taskListId);
+ // If tasks are available then print all task of given tasklists.
+ if (!tasks.items) {
+ console.log('No tasks found.');
+ return;
+ }
+ // Print the task title and task id of specified tasklist.
+ for (let i = 0; i < tasks.items.length; i++) {
+ const task = tasks.items[i];
+ console.log('Task with title "%s" and ID "%s" was found.', task.title, task.id);
}
- } else {
- Logger.log('No tasks found.');
+ } catch (err) {
+ // TODO (developer) - Handle exception from Task API
+ console.log('Failed with an error %s', err.message);
}
}
-// [END apps_script_tasks_list_tasks]
+// [END tasks_list_tasks]
-// [START apps_script_tasks_add_task]
+// [START tasks_add_task]
/**
* Adds a task to a tasklist.
* @param {string} taskListId The tasklist to add to.
+ * @see https://developers.google.com/tasks/reference/rest/v1/tasks/insert
*/
function addTask(taskListId) {
- var task = {
+ // Task details with title and notes for inserting new task
+ let task = {
title: 'Pick up dry cleaning',
notes: 'Remember to get this done!'
};
- task = Tasks.Tasks.insert(task, taskListId);
- Logger.log('Task with ID "%s" was created.', task.id);
+ try {
+ // Call insert method with taskDetails and taskListId to insert Task to specified tasklist.
+ task = Tasks.Tasks.insert(task, taskListId);
+ // Print the Task ID of created task.
+ console.log('Task with ID "%s" was created.', task.id);
+ } catch (err) {
+ // TODO (developer) - Handle exception from Tasks.insert() of Task API
+ console.log('Failed with an error %s', err.message);
+ }
}
-// [END apps_script_tasks_add_task]
+// [END tasks_add_task]
diff --git a/advanced/test_adminSDK.gs b/advanced/test_adminSDK.gs
new file mode 100644
index 000000000..fb825fe04
--- /dev/null
+++ b/advanced/test_adminSDK.gs
@@ -0,0 +1,147 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tests listAllUsers function of adminSDK.gs
+ */
+function itShouldListAllUsers() {
+ console.log('> itShouldListAllUsers');
+ listAllUsers();
+}
+
+/**
+ * Tests getUser function of adminSDK.gs
+ */
+function itShouldGetUser() {
+ console.log('> itShouldGetUser');
+ getUser();
+}
+
+/**
+ * Tests addUser function of adminSDK.gs
+ */
+function itShouldAddUser() {
+ console.log('> itShouldAddUser');
+ addUser();
+}
+
+/**
+ * Tests createAlias function of adminSDK.gs
+ */
+function itShouldCreateAlias() {
+ console.log('> itShouldCreateAlias');
+ createAlias();
+}
+
+/**
+ * Tests listAllGroups function of adminSDK.gs
+ */
+function itShouldListAllGroups() {
+ console.log('> itShouldListAllGroups');
+ listAllGroups();
+}
+
+/**
+ * Tests addGroupMember function of adminSDK.gs
+ */
+function itShouldAddGroupMember() {
+ console.log('> itShouldAddGroupMember');
+ addGroupMember();
+}
+
+/**
+ * Tests migrateMessages function of adminSDK.gs
+ */
+function itShouldMigrateMessages() {
+ console.log('> itShouldMigrateMessages');
+ migrateMessages();
+}
+
+/**
+ * Tests getGroupSettings function of adminSDK.gs
+ */
+function itShouldGetGroupSettings() {
+ console.log('> itShouldGetGroupSettings');
+ getGroupSettings();
+}
+
+/**
+ * Tests updateGroupSettings function of adminSDK.gs
+ */
+function itShouldUpdateGroupSettings() {
+ console.log('> itShouldUpdateGroupSettings');
+ updateGroupSettings();
+}
+
+/**
+ * Tests getLicenseAssignments function of adminSDK.gs
+ */
+function itShouldGetLicenseAssignments() {
+ console.log('> itShouldGetLicenseAssignments');
+ getLicenseAssignments();
+}
+
+/**
+ * Tests insertLicenseAssignment function of adminSDK.gs
+ */
+function itShouldInsertLicenseAssignment() {
+ console.log('> itShouldInsertLicenseAssignment');
+ insertLicenseAssignment();
+}
+
+/**
+ * Tests generateLoginActivityReport function of adminSDK.gs
+ */
+function itShouldGenerateLoginActivityReport() {
+ console.log('> itShouldGenerateLoginActivityReport');
+ generateLoginActivityReport();
+}
+
+/**
+ * Tests generateUserUsageReport function of adminSDK.gs
+ */
+function itShouldGenerateUserUsageReport() {
+ console.log('> itShouldGenerateUserUsageReport');
+ generateUserUsageReport();
+}
+
+/**
+ * Tests getSubscriptions function of adminSDK.gs
+ */
+function itShouldGetSubscriptions() {
+ console.log('> itShouldGetSubscriptions');
+ getSubscriptions();
+}
+
+/**
+ * Runs all the tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldListAllUsers();
+ itShouldGetUser();
+ itShouldAddUser();
+ itShouldCreateAlias();
+ itShouldListAllGroups();
+ itShouldAddGroupMember();
+ itShouldMigrateMessages();
+ itShouldGetGroupSettings();
+ itShouldUpdateGroupSettings();
+ itShouldGetLicenseAssignments();
+ itShouldInsertLicenseAssignment();
+ itShouldGenerateLoginActivityReport();
+ itShouldGenerateUserUsageReport();
+ itShouldGetSubscriptions();
+}
diff --git a/advanced/test_adsense.gs b/advanced/test_adsense.gs
new file mode 100644
index 000000000..1b7ef1e24
--- /dev/null
+++ b/advanced/test_adsense.gs
@@ -0,0 +1,52 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Replace with correct values
+const accountName = 'account name';
+const clientName = 'ad client name';
+
+/**
+ * Tests listAccounts function of adsense.gs
+ */
+function itShouldListAccounts() {
+ console.log('> itShouldListAccounts');
+ listAccounts();
+}
+
+/**
+ * Tests listAdClients function of adsense.gs
+ */
+function itShouldListAdClients() {
+ console.log('> itShouldListAdClients');
+ listAdClients(accountName);
+}
+
+/**
+ * Tests listAdUnits function of adsense.gs
+ */
+function itShouldListAdUnits() {
+ console.log('> itShouldListAdUnits');
+ listAdUnits(clientName);
+}
+
+/**
+ * Run all tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldListAccounts();
+ itShouldListAdClients();
+ itShouldListAdUnits();
+}
diff --git a/advanced/test_analytics.gs b/advanced/test_analytics.gs
new file mode 100644
index 000000000..505974c2b
--- /dev/null
+++ b/advanced/test_analytics.gs
@@ -0,0 +1,42 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Replace with the required profileId
+const profileId = 'abcd';
+
+/**
+ * Tests listAccounts function of analytics.gs
+ */
+function itShouldListAccounts() {
+ console.log('> itShouldListAccounts');
+ listAccounts();
+}
+
+/**
+ * Tests runReport function of analytics.gs
+ */
+function itShouldRunReport() {
+ console.log('> itShouldRunReport');
+ runReport(profileId);
+}
+
+/**
+ * Runs all the tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldListAccounts();
+ itShouldRunReport();
+}
diff --git a/advanced/test_bigquery.gs b/advanced/test_bigquery.gs
new file mode 100644
index 000000000..d79373b2f
--- /dev/null
+++ b/advanced/test_bigquery.gs
@@ -0,0 +1,39 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tests runQuery function of adminSDK.gs
+ */
+function itShouldRunQuery() {
+ console.log('> itShouldRunQuery');
+ runQuery();
+}
+
+/**
+ * Tests loadCsv function of adminSDK.gs
+ */
+function itShouldLoadCsv() {
+ console.log('> itShouldLoadCsv');
+ loadCsv();
+}
+
+/**
+ * Runs all the tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldRunQuery();
+ itShouldLoadCsv();
+}
diff --git a/advanced/test_calendar.gs b/advanced/test_calendar.gs
new file mode 100644
index 000000000..ceec9a2a4
--- /dev/null
+++ b/advanced/test_calendar.gs
@@ -0,0 +1,88 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tests listCalendars function of calendar.gs
+ */
+function itShouldListCalendars() {
+ console.log('> itShouldListCalendars');
+ listCalendars();
+}
+
+/**
+ * Tests createEvent function of calendars.gs
+ */
+function itShouldCreateEvent() {
+ console.log('> itShouldCreateEvent');
+ createEvent();
+}
+
+/**
+ * Tests gerRelativeDate function of calendar.gs
+ */
+function itShouldGetRelativeDate() {
+ console.log('> itShouldGetRelativeDate');
+ console.log('no offset: ' + getRelativeDate(0, 0));
+ console.log('4 hour offset: ' + getRelativeDate(0, 4));
+ console.log('1 day offset: ' + getRelativeDate(1, 0));
+ console.log('1 day and 3 hour off set: ' + getRelativeDate(1, 3));
+}
+
+/**
+ * Tests listNext10Events function of calendar.gs
+ */
+function itShouldListNext10Events() {
+ console.log('> itShouldListNext10Events');
+ listNext10Events();
+}
+
+/**
+ * Tests logSyncedEvents function of calendar.gs
+ */
+function itShouldLogSyncedEvents() {
+ console.log('> itShouldLogSyncedEvents');
+ logSyncedEvents('primary', true);
+ logSyncedEvents('primary', false);
+}
+
+/**
+ * Tests conditionalUpdate function of calendar.gs
+ */
+function itShouldConditionalUpdate() {
+ console.log('> itShouldConditionalUpdate (takes 30 seconds)');
+ conditionalUpdate();
+}
+
+/**
+ * Tests conditionalFetch function of calendar.gs
+ */
+function itShouldConditionalFetch() {
+ console.log('> itShouldConditionalFetch');
+ conditionalFetch();
+}
+
+/**
+ * Runs all the tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldListCalendars();
+ itShouldCreateEvent();
+ itShouldGetRelativeDate();
+ itShouldListNext10Events();
+ itShouldLogSyncedEvents();
+ itShouldConditionalUpdate();
+ itShouldConditionalFetch();
+}
diff --git a/advanced/test_classroom.gs b/advanced/test_classroom.gs
new file mode 100644
index 000000000..bbe2d7625
--- /dev/null
+++ b/advanced/test_classroom.gs
@@ -0,0 +1,30 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tests listCourses function of classroom.gs
+ */
+function itShouldListCourses() {
+ console.log('> itShouldListCourses');
+ listCourses();
+}
+
+/**
+ * Runs all the tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldListCourses();
+}
diff --git a/advanced/test_docs.gs b/advanced/test_docs.gs
new file mode 100644
index 000000000..97bbd35ce
--- /dev/null
+++ b/advanced/test_docs.gs
@@ -0,0 +1,106 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+// TODO (developer) - Replace with your documentId
+const documentId='1EaLpBfuo3bMUeP6_P34auuQroh3bCWi6hLDppY6J6us';
+/**
+ * A simple exists assertion check. Expects a value to exist. Errors if DNE.
+ * @param {any} value A value that is expected to exist.
+ */
+function expectToExist(value) {
+ if (!value) {
+ console.log('DNE');
+ return;
+ }
+ console.log('TEST: Exists');
+}
+
+/**
+ * A simple exists assertion check for primatives (no nested objects).
+ * Expects actual to equal expected. Logs the output.
+ * @param {any} expected The actual value.
+ * @param {any} actual The expected value.
+ */
+function expectToEqual(expected, actual) {
+ if (actual !== expected) {
+ console.log('TEST: actual: %s = expected: %s', actual, expected);
+ return;
+ }
+ console.log('TEST: actual: %s = expected: %s', actual, expected);
+}
+
+
+/**
+ * Runs all tests.
+ */
+function RUN_ALL_TESTS() {
+ itShouldCreateDocument();
+ itShouldInsertTextWithStyle();
+ itShouldReplaceText();
+ itShouldReadFirstParagraph();
+}
+
+/**
+ * Creates a presentation.
+ */
+function itShouldCreateDocument() {
+ const documentId = createDocument();
+ expectToExist(documentId);
+ deleteFileOnCleanup(documentId);
+}
+
+
+/**
+ * Insert text with style.
+ */
+function itShouldInsertTextWithStyle() {
+ const documentId = createDocument();
+ expectToExist(documentId);
+ const text='This is the sample document';
+ const replies=insertAndStyleText(documentId, text);
+ expectToEqual(2, replies.length);
+ deleteFileOnCleanup(documentId);
+}
+
+/**
+ * Find and Replace the text.
+ */
+function itShouldReplaceText() {
+ const documentId = createDocument();
+ expectToExist(documentId);
+ const text='This is the sample document';
+ const response=insertAndStyleText(documentId, text);
+ expectToEqual(2, response.replies.length);
+ const findTextToReplacementMap={'sample': 'test', 'document': 'Doc'};
+ const replies=findAndReplace(documentId, findTextToReplacementMap);
+ expectToEqual(2, replies.length);
+ deleteFileOnCleanup(documentId);
+}
+
+/**
+ * Read first paragraph
+ */
+function itShouldReadFirstParagraph() {
+ const paragraphText=readFirstParagraph(documentId);
+ expectToExist(paragraphText);
+ expectToEqual(89, paragraphText.length);
+}
+/**
+ * Delete the file
+ * @param {string} id Document ID
+ */
+function deleteFileOnCleanup(id) {
+ Drive.Files.remove(id);
+}
diff --git a/advanced/test_doubleclick.gs b/advanced/test_doubleclick.gs
new file mode 100644
index 000000000..c0efee4b8
--- /dev/null
+++ b/advanced/test_doubleclick.gs
@@ -0,0 +1,48 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tests listUserProfiles function of doubleclick.gs
+ */
+function itShouldListUserProfiles() {
+ console.log('> itShouldListUserProfiles');
+ listUserProfiles();
+}
+
+/**
+ * Tests listActiveCampaigns function of doubleclick.gs
+ */
+function itShouldListActiveCampaigns() {
+ console.log('> itShouldListActiveCampaigns');
+ listActiveCampaigns();
+}
+
+/**
+ * Tests createAdvertiserAndCampaign function of doubleclick.gs
+ */
+function itShouldCreateAdvertiserAndCampaign() {
+ console.log('> itShouldCreateAdvertiserAndCampaign');
+ createAdvertiserAndCampaign();
+}
+
+/**
+ * Run all tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldListUserProfiles();
+ itShouldListActiveCampaigns();
+ itShouldCreateAdvertiserAndCampaign();
+}
diff --git a/advanced/test_drive.gs b/advanced/test_drive.gs
new file mode 100644
index 000000000..f3ebd5eeb
--- /dev/null
+++ b/advanced/test_drive.gs
@@ -0,0 +1,121 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Helper functions to help test drive.gs expectToExist(...)
+ * @param {string} value
+ * To test drive.gs please add drive services
+ */
+function expectToExist(value) {
+ if (value) {
+ console.log('TEST: Exists');
+ } else {
+ throw new Error('TEST: DNE');
+ }
+}
+
+/**
+ * Helper functions to help test drive.gs expectToEqual
+ * @param {string} actual
+ * @param {string} expected
+ * To test drive.gs please add drive services
+ */
+function expectToEqual(actual, expected) {
+ console.log('TEST: actual: %s = expected: %s', actual, expected);
+ if (actual !== expected) {
+ console.log('TEST: actual: %s expected: %s', actual, expected);
+ }
+}
+
+/**
+ * Helper functions to help test drive.gs createFolder()
+ *
+ * To test drive.gs please add drive services
+ */
+function createTestFolder() {
+ DriveApp.createFolder('test1');
+ DriveApp.createFolder('test2');
+}
+
+/**
+ * Helper functions to help test drive.gs getFilesByName(...)
+ *
+ * To test drive.gs please add drive services
+ */
+function fileCleanUp() {
+ DriveApp.getFilesByName('google_logo.png').next().setTrashed(true);
+}
+
+/**
+ * Helper functions folderCleanUp()
+ *
+ * To test getFoldersByName() please add drive services
+ */
+function folderCleanUp() {
+ DriveApp.getFoldersByName('test1').next().setTrashed(true);
+ DriveApp.getFoldersByName('test2').next().setTrashed(true);
+}
+
+/**
+ * drive.gs test functions below
+ */
+
+/**
+ * tests drive.gs uploadFile
+ * @return {string} fileId The ID of the file
+ */
+function checkUploadFile() {
+ uploadFile();
+ const fileId = DriveApp.getFilesByName('google_logo.png').next().getId();
+ expectToExist(fileId);
+ return fileId;
+}
+
+/**
+ * tests drive.gs listRootFolders
+ */
+function checkListRootFolders() {
+ createTestFolder();
+
+ const folders = DriveApp.getFolders();
+ while (folders.hasNext()) {
+ const folder = folders.next();
+ console.log(folder.getName() + ' ' + folder.getId());
+ }
+ listRootFolders();
+ folderCleanUp();
+}
+
+/**
+ * tests drive.gs addCustomProperty
+ * @param {string} fileId The ID of the file
+ */
+function checkAddCustomProperty(fileId) {
+ addCustomProperty(fileId);
+ expectToEqual(Drive.Properties.get(fileId, 'department',
+ {visibility: 'PUBLIC'}).value, 'Sales');
+}
+
+/**
+ * Run all tests
+ */
+function RUN_ALL_TESTS() {
+ const fileId = checkUploadFile();
+ checkListRootFolders();
+ checkAddCustomProperty(fileId);
+ listRevisions(fileId);
+ fileCleanUp();
+}
diff --git a/advanced/test_gmail.gs b/advanced/test_gmail.gs
new file mode 100644
index 000000000..494871f66
--- /dev/null
+++ b/advanced/test_gmail.gs
@@ -0,0 +1,30 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Run All functions of gmail.gs
+ * Add gmail services to run
+ */
+function RUN_ALL_TESTS() {
+ console.log('> ltShouldListLabelInfo');
+ listLabelInfo();
+ console.log('> ltShouldListInboxSnippets');
+ listInboxSnippets();
+ console.log('> ltShouldLogRecentHistory');
+ logRecentHistory();
+ console.log('> ltShouldGetRawMessage');
+ getRawMessage();
+}
diff --git a/advanced/test_people.gs b/advanced/test_people.gs
new file mode 100644
index 000000000..07e1e09e0
--- /dev/null
+++ b/advanced/test_people.gs
@@ -0,0 +1,29 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Helper functions for sheets.gs testing
+ *
+ * to tests people.gs add people api services
+ */
+function RUN_ALL_TESTS() {
+ console.log('> itShouldGetConnections');
+ getConnections();
+ console.log('> itShouldGetSelf'); // Requires the scope userinfo.profile
+ getSelf();
+ console.log('> itShouldGetAccount');
+ getAccount('me');
+}
diff --git a/advanced/test_sheets.gs b/advanced/test_sheets.gs
new file mode 100644
index 000000000..345214c06
--- /dev/null
+++ b/advanced/test_sheets.gs
@@ -0,0 +1,89 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Helper functions for sheets.gs testing
+ * to tests sheets.gs add sheets services
+ *
+ * create test spreadsheets
+ * @return {string} spreadsheet
+ */
+function createTestSpreadsheet() {
+ const spreadsheet = SpreadsheetApp.create('Test Spreadsheet');
+ for (let i = 0; i < 3; ++i) {
+ spreadsheet.appendRow([1, 2, 3]);
+ }
+ return spreadsheet.getId();
+}
+
+/**
+ * populate the created spreadsheet with values
+ * @param {string} spreadsheetId
+ */
+function populateValues(spreadsheetId) {
+ const batchUpdateRequest = Sheets.newBatchUpdateSpreadsheetRequest();
+ const repeatCellRequest = Sheets.newRepeatCellRequest();
+
+ const values = [];
+ for (let i = 0; i < 10; ++i) {
+ values[i] = [];
+ for (let j = 0; j < 10; ++j) {
+ values[i].push('Hello');
+ }
+ }
+ const range = 'A1:J10';
+ SpreadsheetApp.openById(spreadsheetId).getRange(range).setValues(values);
+ SpreadsheetApp.flush();
+}
+
+/**
+ * Functions to test sheets.gs below this line
+ * tests readRange function of sheets.gs
+ * @return {string} spreadsheet ID
+ */
+function itShouldReadRange() {
+ console.log('> itShouldReadRange');
+ spreadsheetId = createTestSpreadsheet();
+ populateValues(spreadsheetId);
+ readRange(spreadsheetId);
+ return spreadsheetId;
+}
+
+/**
+ * tests the addPivotTable function of sheets.gs
+ * @param {string} spreadsheetId
+ */
+function itShouldAddPivotTable(spreadsheetId) {
+ console.log('> itShouldAddPivotTable');
+ const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
+ const sheets = spreadsheet.getSheets();
+ sheetId = sheets[0].getSheetId();
+ addPivotTable(spreadsheetId, sheetId, sheetId);
+ SpreadsheetApp.flush();
+ console.log('Created pivot table');
+}
+
+/**
+ * runs all the tests
+ */
+function RUN_ALL_TEST() {
+ const spreadsheetId = itShouldReadRange();
+ console.log('> itShouldWriteToMultipleRanges');
+ writeToMultipleRanges(spreadsheetId);
+ console.log('> itShouldAddSheet');
+ addSheet(spreadsheetId);
+ itShouldAddPivotTable(spreadsheetId);
+}
diff --git a/advanced/test_shoppingContent.gs b/advanced/test_shoppingContent.gs
new file mode 100644
index 000000000..14cc296c2
--- /dev/null
+++ b/advanced/test_shoppingContent.gs
@@ -0,0 +1,62 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Before running these tests replace the product resource variables
+const productResource1 = {};
+const productResource2 = {};
+const productResource3 = {};
+
+/**
+ * Tests productInsert function of shoppingContent.gs
+ */
+function itShouldProductInsert() {
+ console.log('> itShouldPproductInsert');
+ productInsert();
+}
+
+/**
+ * Tests productList function of shoppingContent.gs
+ */
+function itShouldProductList() {
+ console.log('> itShouldProductList');
+ productList();
+}
+
+/**
+ * Tests custombatch function of shoppingContent.gs
+ */
+function itShouldCustombatch() {
+ console.log('> itShouldCustombatch');
+ custombatch(productResource1, productResource2, productResource3);
+}
+
+/**
+ * Tests updateAccountTax function of shoppingContent.gs
+ */
+function itShouldUpdateAccountTax() {
+ console.log('> itShouldUpdateAccountTax');
+ updateAccountTax();
+}
+
+/**
+ * Run all tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldProductInsert();
+ itShouldProductList();
+ itShouldCustombatch();
+ itShouldUpdateAccountTax();
+}
diff --git a/advanced/test_slides.gs b/advanced/test_slides.gs
new file mode 100644
index 000000000..156221503
--- /dev/null
+++ b/advanced/test_slides.gs
@@ -0,0 +1,170 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * A simple existance assertion. Logs if the value is falsy.
+ * @param {object} value The value we expect to exist.
+ */
+function expectToExist(value) {
+ if (!value) {
+ console.log('DNE');
+ return;
+ }
+ console.log('TEST: Exists');
+}
+
+/**
+ * A simple equality assertion. Logs if there is a mismatch.
+ * @param {object} expected The expected value.
+ * @param {object} actual The actual value.
+ */
+function expectToEqual(expected, actual) {
+ if (actual !== expected) {
+ console.log('TEST: actual: %s = expected: %s', actual, expected);
+ return;
+ }
+ console.log('TEST: actual: %s = expected: %s', actual, expected);
+}
+/**
+ * Creates a presentation.
+ * @param {string} presentationId The presentation ID.
+ * @param {string} pageId The page ID.
+ * @return {string} objectId
+ */
+function addShape(presentationId, pageId) {
+ // Create a new square textbox, using the supplied element ID.
+ const elementId = 'MyTextBox_01';
+ const pt350 = {
+ magnitude: 350,
+ unit: 'PT'
+ };
+ const requests = [{
+ createShape: {
+ objectId: elementId,
+ shapeType: 'ELLIPSE',
+ elementProperties: {
+ pageObjectId: pageId,
+ size: {
+ height: pt350,
+ width: pt350
+ },
+ transform: {
+ scaleX: 1,
+ scaleY: 1,
+ translateX: 350,
+ translateY: 100,
+ unit: 'PT'
+ }
+ }
+ }
+ },
+
+ // Insert text into the box, using the supplied element ID.
+ {
+ insertText: {
+ objectId: elementId,
+ insertionIndex: 0,
+ text: 'Text Formatted!'
+ }
+ }];
+
+ // Execute the request.
+ const createTextboxWithTextResponse = Slides.Presentations.batchUpdate({
+ requests: requests
+ }, presentationId);
+ const createShapeResponse = createTextboxWithTextResponse.replies[0].createShape;
+ console.log('Created textbox with ID: %s', createShapeResponse.objectId);
+ // [END slides_create_textbox_with_text]
+ return createShapeResponse.objectId;
+}
+
+
+/**
+ * Runs all tests.
+ */
+function RUN_ALL_TESTS() {
+ itShouldCreateAPresentation();
+ itShouldCreateASlide();
+ itShouldCreateATextboxWithText();
+ itShouldFormatShapes();
+ itShouldReadPage();
+}
+
+/**
+ * Creates a presentation.
+ */
+function itShouldCreateAPresentation() {
+ const presentationId = createPresentation();
+ expectToExist(presentationId);
+ deleteFileOnCleanup(presentationId);
+}
+
+
+/**
+ * Creates a new slide.
+ */
+function itShouldCreateASlide() {
+ console.log('> itShouldCreateASlide');
+ const presentationId = createPresentation();
+ const slideId=createSlide(presentationId);
+ expectToExist(slideId);
+ deleteFileOnCleanup(presentationId);
+}
+
+/**
+ * Creates a slide with text.
+ */
+function itShouldCreateATextboxWithText() {
+ const presentationId = createPresentation();
+ const slide=createSlide(presentationId);
+ const pageId = slide.replies[0].createSlide.objectId;
+ const response = addTextBox(presentationId, pageId);
+ expectToEqual(2, response.replies.length);
+ const boxId = response.replies[0].createShape.objectId;
+ expectToExist(boxId);
+ deleteFileOnCleanup(presentationId);
+}
+
+/**
+ * Test for Read Page.
+ */
+function itShouldReadPage() {
+ const presentationId = createPresentation();
+ const slide=createSlide(presentationId);
+ const pageId = slide.replies[0].createSlide.objectId;
+ const response = readPageElementIds(presentationId, pageId);
+ expectToEqual(3, response.pageElements.length);
+ deleteFileOnCleanup(presentationId);
+}
+/**
+ * Test for format shapes
+ */
+function itShouldFormatShapes() {
+ const presentationId = createPresentation();
+ const slide=createSlide(presentationId);
+ const pageId = slide.replies[0].createSlide.objectId;
+ const shapeId=addShape(presentationId, pageId);
+ const replies=formatShapeText(presentationId, shapeId);
+ expectToExist(replies);
+ deleteFileOnCleanup(presentationId);
+}
+/**
+ * Delete the file
+ * @param {string} id presentationId
+ */
+function deleteFileOnCleanup(id) {
+ Drive.Files.remove(id);
+}
diff --git a/advanced/test_tagManager.gs b/advanced/test_tagManager.gs
new file mode 100644
index 000000000..42053dd27
--- /dev/null
+++ b/advanced/test_tagManager.gs
@@ -0,0 +1,65 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+// Before running tagManager tests create a test tagMAnager account
+// and replace the value below with its account path
+const path = 'accounts/6007387289';
+
+/**
+ * Tests createContainerVersion function of tagManager.gs
+ * @param {string} accountPath Tag manager account's path
+ * @return {object} version The container version
+ */
+function itShouldCreateContainerVersion(accountPath) {
+ console.log('> itShouldCreateContainerVersion');
+ const version = createContainerVersion(accountPath);
+ return version;
+}
+
+/**
+ * Tests publishVersionAndQuickPreviewDraft function of tagManager.gs
+ * @param {object} version tag managers container version
+ */
+function itShouldPublishVersionAndQuickPreviewDraft(version) {
+ console.log('> itShouldPublishVersionAndQuickPreviewDraft');
+ publishVersionAndQuickPreviewDraft(version);
+}
+
+/**
+ * Tests createAndReauthorizeUserEnvironment function of tagManager.gs
+ * @param {object} version tag managers container version
+ */
+function itShouldCreateAndReauthorizeUserEnvironment(version) {
+ console.log('> itShouldCreateAndReauthorizeUserEnvironment');
+ createAndReauthorizeUserEnvironment(version);
+}
+
+/**
+ * Tests logAllAccountUserPermissionsWithContainerAccess function of tagManager.gs
+ * @param {string} accountPath Tag manager account's path
+ */
+function itShouldLogAllAccountUserPermissionsWithContainerAccess(accountPath) {
+ console.log('> itShouldLogAllAccountUserPermissionsWithContainerAccess');
+ logAllAccountUserPermissionsWithContainerAccess(accountPath);
+}
+/**
+ * Runs all tests
+ */
+function RUN_ALL_TESTS() {
+ const version = itShouldCreateContainerVersion(path);
+ itShouldPublishVersionAndQuickPreviewDraft(version);
+ itShouldCreateAndReauthorizeUserEnvironment(version);
+ itShouldLogAllAccountUserPermissionsWithContainerAccess(path);
+}
diff --git a/advanced/test_tasks.gs b/advanced/test_tasks.gs
new file mode 100644
index 000000000..b38668fcd
--- /dev/null
+++ b/advanced/test_tasks.gs
@@ -0,0 +1,57 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Test functions for tasks.gs
+ *
+ * Add task API services to test
+ */
+
+/**
+ * tests listTaskLists of tasks.gs
+ */
+function itShouldListTaskLists() {
+ console.log('> itShouldListTaskLists');
+ listTaskLists();
+}
+
+/**
+ * tests listTasks of tasks.gs
+ */
+function itShouldListTasks() {
+ console.log('> itShouldListTasks');
+ const taskId = Tasks.Tasklists.list().items[0].id;
+ listTasks(taskId);
+}
+
+/**
+ * tests addTask of tasks.gs
+ */
+function itShouldAddTask() {
+ console.log('> itShouldAddTask');
+ const taskId = Tasks.Tasklists.list().items[0].id;
+ addTask(taskId);
+}
+
+/**
+ * run all tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldListTaskLists();
+ itShouldListTasks();
+ itShouldAddTask();
+ itShouldListTasks();
+}
diff --git a/advanced/test_youtube.gs b/advanced/test_youtube.gs
new file mode 100644
index 000000000..6afd7454d
--- /dev/null
+++ b/advanced/test_youtube.gs
@@ -0,0 +1,29 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Run all tests
+ */
+function RUN_ALL_TESTS() {
+ console.log('> itShouldSearchByKeyword');
+ searchByKeyword();
+ console.log('> itShouldRetrieveMyUploads');
+ retrieveMyUploads();
+ console.log('> itShouldAddSubscription');
+ addSubscription();
+ console.log('> itShouldCreateSlides');
+ createSlides();
+}
diff --git a/advanced/test_youtubeAnalytics.gs b/advanced/test_youtubeAnalytics.gs
new file mode 100644
index 000000000..5211bfb83
--- /dev/null
+++ b/advanced/test_youtubeAnalytics.gs
@@ -0,0 +1,30 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tests createReport function of youtubeAnalytics.gs
+ */
+function itShouldCreateReport() {
+ console.log('> itShouldCreateReport');
+ createReport();
+}
+
+/**
+ * Run all tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldCreateReport();
+}
diff --git a/advanced/test_youtubeContentId.gs b/advanced/test_youtubeContentId.gs
new file mode 100644
index 000000000..350c88de7
--- /dev/null
+++ b/advanced/test_youtubeContentId.gs
@@ -0,0 +1,48 @@
+/**
+ * Copyright Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Tests claimYourVideoWithMonetizePolicy function of youtubeContentId.gs
+ */
+function itShouldClaimVideoWithMonetizePolicy() {
+ console.log('> itShouldClaimVideoWithMonetizePolicy');
+ claimYourVideoWithMonetizePolicy();
+}
+
+/**
+ * Tests updateAssetOwnership function of youtubeContentId.gs
+ */
+function itShouldUpdateAssetOwnership() {
+ console.log('> itShouldUpdateAssetOwnership');
+ updateAssetOwnership();
+}
+
+/**
+ * Tests releaseClaim function of youtubeContentId.gs
+ */
+function itShouldReleaseClaim() {
+ console.log('> itShouldReleaseClaim');
+ releaseClaim();
+}
+
+/**
+ * Run all tests
+ */
+function RUN_ALL_TESTS() {
+ itShouldClaimVideoWithMonetizePolicy();
+ itShouldUpdateAssetOwnership();
+ itShouldReleaseClaim();
+}
diff --git a/advanced/urlShortener.gs b/advanced/urlShortener.gs
deleted file mode 100644
index e39c85361..000000000
--- a/advanced/urlShortener.gs
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Copyright Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// [START apps_script_url_shortener_shorten]
-/**
- * Shortens a long URL. Logs this URL.
- */
-function shortenUrl() {
- var url = UrlShortener.Url.insert({
- longUrl: 'http://www.example.com'
- });
- Logger.log('Shortened URL is "%s".', url.id);
-}
-// [END apps_script_url_shortener_shorten]
-
-// [START apps_script_url_shortener_get_clicks]
-/**
- * Logs the number of clicks to a short URL over the last week.
- * @param {string} shortUrl The short URL.
- */
-function getClicks(shortUrl) {
- var url = UrlShortener.Url.get(shortUrl, {
- projection: 'ANALYTICS_CLICKS'
- });
- Logger.log('The URL received %s clicks this week.', url.analytics.week.shortUrlClicks);
-}
-// [END apps_script_url_shortener_get_clicks]
diff --git a/advanced/youtube.gs b/advanced/youtube.gs
index 45cf2ceda..87a2f86d8 100644
--- a/advanced/youtube.gs
+++ b/advanced/youtube.gs
@@ -21,14 +21,22 @@
* @see https://developers.google.com/youtube/v3/docs/search/list
*/
function searchByKeyword() {
- var results = YouTube.Search.list('id,snippet', {
- q: 'dogs',
- maxResults: 25
- });
-
- results.items.forEach(function(item) {
- Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
- });
+ try {
+ const results = YouTube.Search.list('id,snippet', {
+ q: 'dogs',
+ maxResults: 25
+ });
+ if (results === null) {
+ console.log('Unable to search videos');
+ return;
+ }
+ results.items.forEach((item)=> {
+ console.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
+ });
+ } catch (err) {
+ // TODO (developer) - Handle exceptions from Youtube API
+ console.log('Failed with an error %s', err.message);
+ }
}
// [END apps_script_youtube_search]
@@ -41,31 +49,45 @@ function searchByKeyword() {
* 4. If there is a next page of resuts, fetching it and returns to step 3.
*/
function retrieveMyUploads() {
- var results = YouTube.Channels.list('contentDetails', {
- mine: true
- });
-
- for (var i = 0; i < results.items.length; i++) {
- var item = results.items[i];
- // Get the channel ID - it's nested in contentDetails, as described in the
- // Channel resource: https://developers.google.com/youtube/v3/docs/channels
- var playlistId = item.contentDetails.relatedPlaylists.uploads;
- var nextPageToken;
- while (nextPageToken !== null) {
- var playlistResponse = YouTube.PlaylistItems.list('snippet', {
- playlistId: playlistId,
- maxResults: 25,
- pageToken: nextPageToken
- });
-
- for (var j = 0; j < playlistResponse.items.length; j++) {
- var playlistItem = playlistResponse.items[j];
- Logger.log('[%s] Title: %s',
- playlistItem.snippet.resourceId.videoId,
- playlistItem.snippet.title);
- }
- nextPageToken = playlistResponse.nextPageToken;
+ try {
+ // @see https://developers.google.com/youtube/v3/docs/channels/list
+ const results = YouTube.Channels.list('contentDetails', {
+ mine: true
+ });
+ if (!results || results.items.length === 0) {
+ console.log('No Channels found.');
+ return;
+ }
+ for (let i = 0; i < results.items.length; i++) {
+ const item = results.items[i];
+ /** Get the channel ID - it's nested in contentDetails, as described in the
+ * Channel resource: https://developers.google.com/youtube/v3/docs/channels.
+ */
+ const playlistId = item.contentDetails.relatedPlaylists.uploads;
+ let nextPageToken = null;
+ do {
+ // @see: https://developers.google.com/youtube/v3/docs/playlistItems/list
+ const playlistResponse = YouTube.PlaylistItems.list('snippet', {
+ playlistId: playlistId,
+ maxResults: 25,
+ pageToken: nextPageToken
+ });
+ if (!playlistResponse || playlistResponse.items.length === 0) {
+ console.log('No Playlist found.');
+ break;
+ }
+ for (let j = 0; j < playlistResponse.items.length; j++) {
+ const playlistItem = playlistResponse.items[j];
+ console.log('[%s] Title: %s',
+ playlistItem.snippet.resourceId.videoId,
+ playlistItem.snippet.title);
+ }
+ nextPageToken = playlistResponse.nextPageToken;
+ } while (nextPageToken);
}
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with err %s', err.message);
}
}
// [END apps_script_youtube_uploads]
@@ -73,11 +95,12 @@ function retrieveMyUploads() {
// [START apps_script_youtube_subscription]
/**
* This sample subscribes the user to the Google Developers channel on YouTube.
+ * @see https://developers.google.com/youtube/v3/docs/subscriptions/insert
*/
function addSubscription() {
// Replace this channel ID with the channel ID you want to subscribe to
- var channelId = 'UC9gFih9rw0zNCK3ZtoKQQyA';
- var resource = {
+ const channelId = 'UC_x5XG1OV2P6uZZ5FSM9Ttw';
+ const resource = {
snippet: {
resourceId: {
kind: 'youtube#channel',
@@ -87,14 +110,15 @@ function addSubscription() {
};
try {
- var response = YouTube.Subscriptions.insert(resource, 'snippet');
- Logger.log(response);
+ const response = YouTube.Subscriptions.insert(resource, 'snippet');
+ console.log('Added subscription for channel title : %s', response.snippet.title);
} catch (e) {
if (e.message.match('subscriptionDuplicate')) {
- Logger.log('Cannot subscribe; already subscribed to channel: ' +
- channelId);
+ console.log('Cannot subscribe; already subscribed to channel: ' +
+ channelId);
} else {
- Logger.log('Error adding subscription: ' + e.message);
+ // TODO (developer) - Handle exception
+ console.log('Error adding subscription: ' + e.message);
}
}
}
@@ -105,23 +129,23 @@ function addSubscription() {
* Creates a slide presentation with 10 videos from the YouTube search `YOUTUBE_QUERY`.
* The YouTube Advanced Service must be enabled before using this sample.
*/
-var PRESENTATION_TITLE = 'San Francisco, CA';
-var YOUTUBE_QUERY = 'San Francisco, CA';
+const PRESENTATION_TITLE = 'San Francisco, CA';
+const YOUTUBE_QUERY = 'San Francisco, CA';
/**
* Gets a list of YouTube videos.
* @param {String} query - The query term to search for.
* @return {object[]} A list of objects with YouTube video data.
- * @ref https://developers.google.com/youtube/v3/docs/search/list
+ * @see https://developers.google.com/youtube/v3/docs/search/list
*/
function getYouTubeVideosJSON(query) {
- var youTubeResults = YouTube.Search.list('id,snippet', {
+ const youTubeResults = YouTube.Search.list('id,snippet', {
q: query,
type: 'video',
maxResults: 10
});
- return youTubeResults.items.map(function(item) {
+ return youTubeResults.items.map((item)=> {
return {
url: 'https://youtu.be/' + item.id.videoId,
title: item.snippet.title,
@@ -135,17 +159,25 @@ function getYouTubeVideosJSON(query) {
* Logs out the URL of the presentation.
*/
function createSlides() {
- var youTubeVideos = getYouTubeVideosJSON(YOUTUBE_QUERY);
- var presentation = SlidesApp.create(PRESENTATION_TITLE);
- presentation.getSlides()[0].getPageElements()[0].asShape()
- .getText().setText(PRESENTATION_TITLE);
-
- // Add slides with videos and log the presentation URL to the user.
- youTubeVideos.forEach(function(video) {
- var slide = presentation.appendSlide();
- slide.insertVideo(video.url,
- 0, 0, presentation.getPageWidth(), presentation.getPageHeight());
- });
- Logger.log(presentation.getUrl());
+ try {
+ const youTubeVideos = getYouTubeVideosJSON(YOUTUBE_QUERY);
+ const presentation = SlidesApp.create(PRESENTATION_TITLE);
+ presentation.getSlides()[0].getPageElements()[0].asShape()
+ .getText().setText(PRESENTATION_TITLE);
+ if (!presentation) {
+ console.log('Unable to create presentation');
+ return;
+ }
+ // Add slides with videos and log the presentation URL to the user.
+ youTubeVideos.forEach((video)=> {
+ const slide = presentation.appendSlide();
+ slide.insertVideo(video.url,
+ 0, 0, presentation.getPageWidth(), presentation.getPageHeight());
+ });
+ console.log(presentation.getUrl());
+ } catch (err) {
+ // TODO (developer) - Handle exception
+ console.log('Failed with error %s', err.message);
+ }
}
// [END apps_script_youtube_slides]
diff --git a/advanced/youtubeAnalytics.gs b/advanced/youtubeAnalytics.gs
index a8a3b30c2..cfb0edda0 100644
--- a/advanced/youtubeAnalytics.gs
+++ b/advanced/youtubeAnalytics.gs
@@ -13,30 +13,30 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
- // [START apps_script_youtube_report]
+// [START apps_script_youtube_report]
/**
* Creates a spreadsheet containing daily view counts, watch-time metrics,
* and new-subscriber counts for a channel's videos.
*/
function createReport() {
// Retrieve info about the user's YouTube channel.
- var channels = YouTube.Channels.list('id,contentDetails', {
+ const channels = YouTube.Channels.list('id,contentDetails', {
mine: true
});
- var channelId = channels.items[0].id;
+ const channelId = channels.items[0].id;
// Retrieve analytics report for the channel.
- var oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
- var today = new Date();
- var lastMonth = new Date(today.getTime() - oneMonthInMillis);
+ const oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
+ const today = new Date();
+ const lastMonth = new Date(today.getTime() - oneMonthInMillis);
- var metrics = [
+ const metrics = [
'views',
'estimatedMinutesWatched',
'averageViewDuration',
'subscribersGained'
];
- var result = YouTubeAnalytics.Reports.query({
+ const result = YouTubeAnalytics.Reports.query({
ids: 'channel==' + channelId,
startDate: formatDateString(lastMonth),
endDate: formatDateString(today),
@@ -45,25 +45,25 @@ function createReport() {
sort: 'day'
});
- if (result.rows) {
- var spreadsheet = SpreadsheetApp.create('YouTube Analytics Report');
- var sheet = spreadsheet.getActiveSheet();
+ if (!result.rows) {
+ console.log('No rows returned.');
+ return;
+ }
+ const spreadsheet = SpreadsheetApp.create('YouTube Analytics Report');
+ const sheet = spreadsheet.getActiveSheet();
- // Append the headers.
- var headers = result.columnHeaders.map(function(columnHeader) {
- return formatColumnName(columnHeader.name);
- });
- sheet.appendRow(headers);
+ // Append the headers.
+ const headers = result.columnHeaders.map((columnHeader)=> {
+ return formatColumnName(columnHeader.name);
+ });
+ sheet.appendRow(headers);
- // Append the results.
- sheet.getRange(2, 1, result.rows.length, headers.length)
- .setValues(result.rows);
+ // Append the results.
+ sheet.getRange(2, 1, result.rows.length, headers.length)
+ .setValues(result.rows);
- Logger.log('Report spreadsheet created: %s',
- spreadsheet.getUrl());
- } else {
- Logger.log('No rows returned.');
- }
+ console.log('Report spreadsheet created: %s',
+ spreadsheet.getUrl());
}
/**
@@ -82,7 +82,7 @@ function formatDateString(date) {
* @example "averageViewPercentage" becomes "Average View Percentage".
*/
function formatColumnName(columnName) {
- var name = columnName.replace(/([a-z])([A-Z])/g, '$1 $2');
+ let name = columnName.replace(/([a-z])([A-Z])/g, '$1 $2');
name = name.slice(0, 1).toUpperCase() + name.slice(1);
return name;
}
diff --git a/advanced/youtubeContentId.gs b/advanced/youtubeContentId.gs
index 9b2b12596..22d37737c 100644
--- a/advanced/youtubeContentId.gs
+++ b/advanced/youtubeContentId.gs
@@ -17,15 +17,16 @@
/**
* This function creates a partner-uploaded claim on a video with the specified
* asset and policy rules.
+ * @see https://developers.google.com/youtube/partner/docs/v1/claims/insert
*/
function claimYourVideoWithMonetizePolicy() {
// The ID of the content owner that you are acting on behalf of.
- var onBehalfOfContentOwner = 'replaceWithYourContentOwnerID';
+ const onBehalfOfContentOwner = 'replaceWithYourContentOwnerID';
// A YouTube video ID to claim. In this example, the video must be uploaded
// to one of your onBehalfOfContentOwner's linked channels.
- var videoId = 'replaceWithYourVideoID';
- var assetId = 'replaceWithYourAssetID';
- var claimToInsert = {
+ const videoId = 'replaceWithYourVideoID';
+ const assetId = 'replaceWithYourAssetID';
+ const claimToInsert = {
'videoId': videoId,
'assetId': assetId,
'contentType': 'audiovisual',
@@ -37,12 +38,12 @@ function claimYourVideoWithMonetizePolicy() {
'policy': {'rules': [{'action': 'monetize'}]}
};
try {
- var claimInserted = YoutubeContentId.Claims.insert(claimToInsert,
+ const claimInserted = YouTubeContentId.Claims.insert(claimToInsert,
{'onBehalfOfContentOwner': onBehalfOfContentOwner});
- Logger.log('Claim created on video %s: %s', videoId, claimInserted);
+ console.log('Claim created on video %s: %s', videoId, claimInserted);
} catch (e) {
- Logger.log('Failed to create claim on video %s, error: %s',
- videoId, e.message);
+ console.log('Failed to create claim on video %s, error: %s',
+ videoId, e.message);
}
}
// [END apps_script_youtube_claim]
@@ -51,12 +52,15 @@ function claimYourVideoWithMonetizePolicy() {
/**
* This function updates your onBehalfOfContentOwner's ownership on an existing
* asset.
+ * @see https://developers.google.com/youtube/partner/docs/v1/ownership/update
*/
function updateAssetOwnership() {
- var onBehalfOfContentOwner = 'replaceWithYourContentOwnerID';
- var assetId = 'replaceWithYourAssetID';
+ // The ID of the content owner that you are acting on behalf of.
+ const onBehalfOfContentOwner = 'replaceWithYourContentOwnerID';
+ // Replace values with your asset id
+ const assetId = 'replaceWithYourAssetID';
// The new ownership here would replace your existing ownership on the asset.
- var myAssetOwnership = {
+ const myAssetOwnership = {
'general': [
{
'ratio': 100,
@@ -70,12 +74,12 @@ function updateAssetOwnership() {
]
};
try {
- var updatedOwnership = YoutubeContentId.Ownership.update(myAssetOwnership,
+ const updatedOwnership = YouTubeContentId.Ownership.update(myAssetOwnership,
assetId, {'onBehalfOfContentOwner': onBehalfOfContentOwner});
- Logger.log('Ownership updated on asset %s: %s', assetId, updatedOwnership);
+ console.log('Ownership updated on asset %s: %s', assetId, updatedOwnership);
} catch (e) {
- Logger.log('Ownership update failed on asset %s, error: %s',
- assetId, e.message);
+ console.log('Ownership update failed on asset %s, error: %s',
+ assetId, e.message);
}
}
// [END apps_script_youtube_update_asset_ownership]
@@ -84,21 +88,23 @@ function updateAssetOwnership() {
/**
* This function releases an existing claim your onBehalfOfContentOwner has
* on a video.
+ * @see https://developers.google.com/youtube/partner/docs/v1/claims/patch
*/
function releaseClaim() {
- var onBehalfOfContentOwner = 'replaceWithYourContentOwnerID';
+ // The ID of the content owner that you are acting on behalf of.
+ const onBehalfOfContentOwner = 'replaceWithYourContentOwnerID';
// The ID of the claim to be released.
- var claimId = 'replaceWithYourClaimID';
+ const claimId = 'replaceWithYourClaimID';
// To release the claim, change the resource's status to inactive.
- var claimToBeReleased = {
+ const claimToBeReleased = {
'status': 'inactive'
};
try {
- var claimReleased = YoutubeContentId.Claims.patch(claimToBeReleased,
+ const claimReleased = YouTubeContentId.Claims.patch(claimToBeReleased,
claimId, {'onBehalfOfContentOwner': onBehalfOfContentOwner});
- Logger.log('Claim %s was released: %s', claimId, claimReleased);
+ console.log('Claim %s was released: %s', claimId, claimReleased);
} catch (e) {
- Logger.log('Failed to release claim %s, error: %s', claimId, e.message);
+ console.log('Failed to release claim %s, error: %s', claimId, e.message);
}
}
// [END apps_script_youtube_release_claim]
diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml
deleted file mode 100644
index 91c1a45dc..000000000
--- a/android/AndroidManifest.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-