In the previous article, we have already seen how to email activity of all users using Graph API.
In our organization, we have this requirement to get the synced file count of all OneDrive users, shared externally file count, and shared internally file count for the last 30 days. We have used Microsoft Graph API to achieve this. Here, I’m sharing the steps involved to get the OneDrive activities and how to check the Graph API results in O365 portal reports.
We can get the 7, 30, 90, 180 days activity details using the below API.
API URL: https://graph.microsoft.com/v1.0/reports/getOneDriveActivityUserDetail(period='D7')
Version 1.0 provides the results in CSV format.
Using the beta version, we can get the JSON results. Here is the URL for the beta version.
Here are the available column details from the OneDrive Activity Graph API.
From Microsoft documentation
“Microsoft Graph is the gateway to data and intelligence in Microsoft 365. Microsoft Graph provides a unified programmability model that you can use to take advantage of the tremendous amount of data in Office 365, Enterprise Mobility + Security, and Windows 10.
You can use Microsoft Graph API to build apps for organizations and consumers that interact with the data of millions of users. With Microsoft Graph, you can connect to a wealth of resources, relationships, and intelligence, all through a single endpoint: https://graph.microsoft.com”
Reference URL - https://developer.microsoft.com/en-us/graph/docs/concepts/overview
Here is the Microsoft Documentation URL.
https://developer.microsoft.com/en-us/graph/docs/concepts/overview
Steps to retrieve OneDrive user activity details using node.js
Let us look at the code part first. Follow the below-listed steps and code.
End-point URL - https://graph.microsoft.com/v1.0/reports/getOneDriveActivityUserDetail(period='D30')
Graph Token URL - https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token
Graph Token body - client_id=" + configValues.clientId + "&scope=" + configValues.scope + "&client_secret=" + configValues.clientSecretId + "&grant_type=client_credentials
Step 1
Register the app in Azure AD using client ID, Tenant ID, and secret key.
Follow the below URL to register the app in Azure.
Make sure to check that your registered Azure app has permissions to read the directory data.
Step 2
In your node.js solution, just create the config file and provide the below values. We have created a config file to avoid the hard-coded things. Provide your tenantId, clientId, and secret key. Please don't use the below mentioned one; it is just a sample (it won't work).
- {
- "scope": "https%3A%2F%2Fgraph.microsoft.com%2F.default",
- "tenantId": "7aa111ae-1ab6-4256-af4c-a0c1cdb4575d",
- "clientId": "bff7fae8-c253-37e5-9b6a-e096bed54f11",
- "clientSecretId": "XgfrmWfX0K/N7SRouCdAskTKrz0cnKN2rS12IkJ9SJk="
- }
Step 3
Refer to the config file in your JS file, as shown below.
- var request = require('sync-request');
- var fs = require('fs');
- var configValues = JSON.parse(fs.readFileSync('emailactivityconfig.json'));
Step 4
Then, frame the Graph Token URL and Graph Token Body to get the authorized token.
- var graphAccessUrl = "https://login.microsoftonline.com/" + configValues.tenantId + "/oauth2/v2.0/token";
- var graphTokenBody = "client_id=" + configValues.clientId + "&scope=" + configValues.scope + "&client_secret=" + configValues.clientSecretId + "&grant_type=client_credentials"
Step 5
Get the Authorized Token using the below method.
- varcontentType = "application/x-www-form-urlencoded; charset=utf-8";
- vargraphTokenError = "Failed to get graph token";
- vargraphToken = "";
-
- getToken(graphAccessUrl, contentType, graphTokenBody, graphTokenError);
-
- functiongetToken(url, type, content, errorMessage, callback) {
- var options = {
- 'headers': {
- 'Content-Type': type
- },
- 'body': content
- };
-
- var tokenResponse = httpPost(url, options);
- if (tokenResponse.statusCode === 200) {
- error = errorMessage;
- if (errorMessage === graphTokenError) {
- vartoken = JSON.parse(tokenResponse.body.toString('utf-8'));
- graphToken = token.access_token;
- }
- if (callback) {
- returncallback();
- }
- } else {
- log(errorMessage);
- }
- }
Step 6
Once you receive the token, make the HTTP call using endpoint and get the results.
Step 7
OneDrive Activity Report in Graph API v1.0 provides the results as CSV format not in JSON format, so we have no need to use the top. In a single API call, we can retrieve all the user results.
- var reqUrl = "https://graph.microsoft.com/v1.0/reports/getOneDriveActivityUserDetail(period='D30')";
- var usersCount = 0;
-
- function getOneDriveActivityReportData(reqUrl) {
- try {
- console.log("Inside get user last logon data method!!!");
- var emailActivityRes = httpGet(encodeURI(reqUrl), GRAPH_TOKEN);
- if (emailActivityRes.statusCode == 200) {
- failIndex = 0;
- var parsedJson = convertCSVToJSON(emailActivityRes.body.toString('utf-8'));
-
- var parsJson = JSON.parse(parsedJson);
- if (parsJson) {
- usersCount = usersCount + parsJson.length;
- for (var i = 0; i < parsJson.length; i++) {
- var currItem = parsJson[i];
- if (currItem) {
-
- }
- }
- }
- console.log("OneDrive users count : " + usersCount);
- } else {
- console.log("One Drive user activity api received failed response: " + emailActivityRes.statusCode)
- }
- }
- } catch (ex) {
- console.log(ex);
- }
- }
-
- function convertCSVToJSON(csv) {
-
-
-
- try {
- var lines = csv.split("\n");
- var result = [];
- var headers = lines[0].split(",");
- for (var i = 1; i < lines.length; i++) {
- var obj = {};
- if (lines[i]) {
- var currentline = lines[i].split(",");
- for (var j = 0; j < headers.length; j++) {
- obj[headers[j]] = currentline[j];
- }
- result.push(obj);
- }
- }
- return JSON.stringify(result);
- } catch (ex) {
- console.log(ex + " in csvToJSON method...");
- }
- }
Step 8
Then, bind the results based on your requirement. You will receive the below object when you call the OneDrive Users Activity API.
Steps to check the OneDrive user activity details from O365 portal
Once you get the results, you can verify the results from O365 and also, follow the below-listed steps to verify the output.
Step 1
Log into Microsoft 365 Admin Center. Learn more here.
https://admin.microsoft.com/AdminPortal
Step 2
Provide a valid username and password to log into your account.
Step 3
From the Microsoft 365 Admin Center main menu, click the "Reports" >> "Usage" option.
Step 4
On the Usage pane, click "Select a report" drop-down list, expand OneDrive, and click the "Activity" option.
Step 5
Click on the "Export" option; you will get the last 30-days report for SharePoint Site collection with the relevant data.
Reference Link
https://docs.microsoft.com/en-us/graph/api/reportroot-getonedriveactivityuserdetail?view=graph-rest-1.0
Summary
In this article, we have explored how to get the activity details of OneDrive users from Office365 portal, using Graph API. I hope this article will come in handy for you. Please share your feedback in the comments section.