Retrieving User Activity Reports for a specified set of users within G Suite

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);
  }
}

Answer №1

The issue arises from the incorrect way in which the method AdminReports.UserUsageReport() is being called. The correct syntax is:

AdminReports.UserUsageReport.get(userKey, date, optionalArgs) 

Therefore, you should replace the userkey ‘all’ with userList[a], instead of directly including it in the parameters:

page = AdminReports.UserUsageReport.get(userList[a], date, {
  parameters: parameters.join(','),
  maxResults: 1,
  pageToken: pageToken,
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can JQuery be used to detect text input in real-time in a textarea field?

Currently, I have a button for "post" that becomes active when text is typed into the text area. The issue arises when all text is deleted from the text area, as the button remains active in its coloured state despite being disabled using the following cod ...

Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked? protected void ChangeStatusSevenDays_Click(object sender, EventArgs e) { for (int i = 0; i < grdImoveis2.Rows.Count; i++) { GridViewRow RowVie ...

Guide on implementing react hook form 7 together with Material-UI switch

When utilizing react-hook-form with MUI switch, there is an issue where the initial value does not display on page load despite being set to true. However, upon form submission without any changes, the switches reflect their correct values (true or false). ...

When using jQuery, the .change() function will only be triggered after the user clicks a button or

Looking for assistance with an unusual issue in my JavaScript/jQuery code. The jQuery .change() function on a simple text input element only triggers when I click somewhere on the page, open the Chrome console, or press a key on the keyboard. It doesn&apo ...

Is it possible to dynamically change HTML content by utilizing a JSON file?

Looking to implement a JavaScript loop (using jQuery) that can dynamically populate the HTML file with content from a JSON file based on matching <div> ids to the JSON "id" values. The solution should be scalable and able to handle any number of < ...

Retrieve the attribute value from an HTML element in a JSON response using JavaScript

I received a JSON request result containing a blogger post. // API callback posts( { "version": "1.0", "encoding": "UTF-8", "entry": { "title": { "type": "text", "$t": "Vimeo Embed Video Post" ...

Coordinating Angular to communicate with Node.js to send and receive data

I am currently working on a project using express.js, but I would like to integrate angular into the project to create a single page application. The website currently refreshes the entire content from the server whenever a link is clicked, which seems ine ...

Is there a way to transfer the functionality of openssl_seal from PHP to NodeJS 18?

I'm looking to convert the openssl_seal() function from PHP to NodeJs. The code below is from my PHP SDK and works flawlessly, which is what I want to migrate: $ivLength = openssl_cipher_iv_length('AES-256-CBC') ?: 16; $iv = openssl_random ...

Issue with accessing $index.$parent in function parameter within ng-repeat in AngularJS

Can anyone with more experience please explain to me why this particular code compiles successfully: <li class="btn dropdown top-stack breadcrumb-btn" ng-repeat="nodeName in selectedNodeNames"> <a class="dropdown-toggle btn-anchor"> ...

What is the best way to create a sticky div that reacts to a floating (position: fixed) div?

I have been utilizing Material UI's <Appbar /> component, which is rendered as a div with position: fixed;. The effect of the bar hiding on scroll employs visibility: hidden; and transform: translateY(-59px);. Now, my goal is to include a stick ...

How do I make the YouTube Grid Gallery player show up in a pop-up window?

I have been experimenting with the following code: <head> <script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script> <script type="text/javascript"> function loadVideo(playerUrl, ...

Tips for dynamically updating the value of a variable in Vue by importing a JavaScript file

There is a file for an app that imports ymaps.js where YmapsComponent.vue is declared. import '../js/ymaps.js'; import { createApp } from 'vue'; const app = createApp({}); import YmapsComponent from './components/YmapsComponent.vue ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Using Express, Node, and Angular to transmit audio files to the frontend

I am currently working on serving audio files from a Node/Express backend to an Angular frontend. On the server side, the code looks like this: var file = "/filepath.wav"; res.download(file, 'testAudio.wav'); And here's the client side c ...

Displaying the data from a database on a browser using node.js, MySQL, and Jade

Currently, I am delving into Node.js, Express.js, and Jade while utilizing a MySQL database. As a newcomer to node.js, I decided to start with something simple: presenting data from the database in a table on the browser. Unfortunately, my attempts have no ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

Assigning null values, or initializing values in AngularJS

How can I clear input values to null after clicking on a button? Empty fields: Fields with existing values that I want to reset back to empty fields. HTML: <label class="item item-input"> <input id="tezina" type="number" placeholder ...

Dynamic bullseye displayed on a Vis.js network node

I am currently utilizing Vis.js to create network diagrams. I am interested in adding a notification feature where when an AJAX update is received for a specific node, the canvas will move that node to the center (which Vis.js can already do). Following th ...

Struggling with Ajax issues following a tutorial from Bucky

I previously watched a tutorial by Bucky and I am struggling to make this work, with the error message displayed as index.php:62 Uncaught TypeError: Cannot read property 'documentElement' of undefinedhandleServerResponse @ index.php:62 The Ja ...

What is the best approach to synchronize checkboxes with boolean values in my data model?

I've spent hours searching through similar questions, but haven't found a solution that perfectly matches my issue. What I need is to have a checkbox automatically checked based on a true/false value in my data using data binding. While I can suc ...