I am currently attempting to utilize the Admin SDK Reports Service to retrieve the latest login time and other data for a specific set of 20 users. Due to the large size of the domain, it is not practical to fetch data for the entire domain and then filter it down. Therefore, I am looking to only obtain data for these 20 users, but I am facing difficulty in achieving this. My existing code is throwing an error:
Admin user usage reports get failed with error: GoogleJsonResponseException: API call to reports.userUsageReport.get failed with error: Bad Request
Although I acknowledge that my approach may be incorrect, I am unsure of what alternative steps to take after reviewing the documentation. While using the website interface works fine for one user, it seems odd that the options are limited to either retrieving all users or just one individual. I attempted modifying my code to loop through fetching data for one user at a time, but unfortunately, it results in the aforementioned error. The value of userList
is extracted from a table within the AppMaker user interface. Additionally, I can successfully use the documentation's API explorer without any issues.
Below is the current function I have implemented:
function generateLoginActivityReport(userList) {
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');
userList = JSON.parse(userList);
for (var a = 0; a < userList.length; a++) {
var parameters = [
'accounts:last_login_time',
'drive:num_items_created'
];
var rows = [];
var pageToken;
var page;
do {
page = AdminReports.UserUsageReport.get('all', date, {
parameters: parameters.join(','),
maxResults: 1,
pageToken: pageToken,
userKey: userList[a]
});
var reports = page.usageReports;
if (page.warnings) {
for (var q = 0; q < page.warnings.length; q++) {
var warning = page.warnings[a];
Logger.log(warning.message);
}
}
if (reports) {
for (var i = 0; i < reports.length; i++) {
var report = reports[i];
try {
var parameterValues = getParameterValues(report.parameters);
var row = [
report.date,
report.entity.userEmail,
parameterValues['accounts:last_login_time'],
];
rows.push(row);
var ar = app.models.ActivityReport.newRecord();
ar.LastLogin = parameterValues['accounts:last_login_time'];
ar.DocsAdded = 0;
ar.Email = report.entity.userEmail.toString();
app.saveRecords([ar]);
}
catch(error) {
console.error("Error! Did not write last item to model: \n"+error);
}
}
}
} while (pageToken);
}
}