|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google Inc. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +// [START drive_activity_v2_quickstart] |
| 18 | +const fs = require('fs'); |
| 19 | +const readline = require('readline'); |
| 20 | +const {google} = require('googleapis'); |
| 21 | + |
| 22 | +// If modifying these scopes, delete token.json. |
| 23 | +const SCOPES = ['https://www.googleapis.com/auth/drive.activity.readonly']; |
| 24 | +// The file token.json stores the user's access and refresh tokens, and is |
| 25 | +// created automatically when the authorization flow completes for the first |
| 26 | +// time. |
| 27 | +const TOKEN_PATH = 'token.json'; |
| 28 | + |
| 29 | +// Load client secrets from a local file. |
| 30 | +fs.readFile('credentials.json', (err, content) => { |
| 31 | + if (err) return console.log('Error loading client secret file:', err); |
| 32 | + // Authorize a client with credentials, then call the Google Drive Activity |
| 33 | + // API. |
| 34 | + authorize(JSON.parse(content), listDriveActivity); |
| 35 | +}); |
| 36 | + |
| 37 | +/** |
| 38 | + * Create an OAuth2 client with the given credentials, and then execute the |
| 39 | + * given callback function. |
| 40 | + * @param {Object} credentials The authorization client credentials. |
| 41 | + * @param {function} callback The callback to call with the authorized client. |
| 42 | + */ |
| 43 | +function authorize(credentials, callback) { |
| 44 | + const {client_secret, client_id, redirect_uris} = credentials.installed; |
| 45 | + const oAuth2Client = new google.auth.OAuth2( |
| 46 | + client_id, client_secret, redirect_uris[0]); |
| 47 | + |
| 48 | + // Check if we have previously stored a token. |
| 49 | + fs.readFile(TOKEN_PATH, (err, token) => { |
| 50 | + if (err) return getNewToken(oAuth2Client, callback); |
| 51 | + oAuth2Client.setCredentials(JSON.parse(token)); |
| 52 | + callback(oAuth2Client); |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Get and store new token after prompting for user authorization, and then |
| 58 | + * execute the given callback with the authorized OAuth2 client. |
| 59 | + * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for. |
| 60 | + * @param {getEventsCallback} callback The callback for the authorized client. |
| 61 | + */ |
| 62 | +function getNewToken(oAuth2Client, callback) { |
| 63 | + const authUrl = oAuth2Client.generateAuthUrl({ |
| 64 | + access_type: 'offline', |
| 65 | + scope: SCOPES, |
| 66 | + }); |
| 67 | + console.log('Authorize this app by visiting this url:', authUrl); |
| 68 | + const rl = readline.createInterface({ |
| 69 | + input: process.stdin, |
| 70 | + output: process.stdout, |
| 71 | + }); |
| 72 | + rl.question('Enter the code from that page here: ', (code) => { |
| 73 | + rl.close(); |
| 74 | + oAuth2Client.getToken(code, (err, token) => { |
| 75 | + if (err) return console.error('Error retrieving access token', err); |
| 76 | + oAuth2Client.setCredentials(token); |
| 77 | + // Store the token to disk for later program executions |
| 78 | + fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { |
| 79 | + if (err) console.error(err); |
| 80 | + console.log('Token stored to', TOKEN_PATH); |
| 81 | + }); |
| 82 | + callback(oAuth2Client); |
| 83 | + }); |
| 84 | + }); |
| 85 | +} |
| 86 | + |
| 87 | +/** |
| 88 | + * Lists the recent activity in your Google Drive. |
| 89 | + * |
| 90 | + * @param {google.auth.OAuth2} auth An authorized OAuth2 client. |
| 91 | + */ |
| 92 | +function listDriveActivity(auth) { |
| 93 | + const service = google.driveactivity({version: 'v2', auth}); |
| 94 | + const params = { |
| 95 | + 'pageSize': 10, |
| 96 | + }; |
| 97 | + service.activity.query({requestBody: params}, (err, res) => { |
| 98 | + if (err) return console.error('The API returned an error: ' + err); |
| 99 | + const activities = res.data.activities; |
| 100 | + if (activities) { |
| 101 | + console.log('Recent activity:'); |
| 102 | + activities.forEach((activity) => { |
| 103 | + const time = getTimeInfo(activity); |
| 104 | + const action = getActionInfo(activity['primaryActionDetail']); |
| 105 | + const actors = activity.actors.map(getActorInfo); |
| 106 | + const targets = activity.targets.map(getTargetInfo); |
| 107 | + console.log(`${time}: ${truncated(actors)}, ${action}, ` + |
| 108 | + `${truncated(targets)}`); |
| 109 | + }); |
| 110 | + } else { |
| 111 | + console.log('No activity.'); |
| 112 | + } |
| 113 | + }); |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * Returns a string representation of the first elements in a list. |
| 118 | + * |
| 119 | + * @param {Array<Object>} array The array to convert to a short string. |
| 120 | + * @param {number} limit The number of elements to show before truncating. |
| 121 | + * @return {string} |
| 122 | + */ |
| 123 | +function truncated(array, limit = 2) { |
| 124 | + const contents = array.slice(0, limit).join(', '); |
| 125 | + const more = array.length > limit ? ', ...' : ''; |
| 126 | + return `[${contents}${more}]`; |
| 127 | +} |
| 128 | + |
| 129 | +/** |
| 130 | + * Returns the name of a set property in an object, or else "unknown". |
| 131 | + * |
| 132 | + * @param {Object} object The object in which to find the set property. |
| 133 | + * @return {string} |
| 134 | + */ |
| 135 | +function getOneOf(object) { |
| 136 | + for (const key in object) { |
| 137 | + if (object.hasOwnProperty(key)) { |
| 138 | + return key; |
| 139 | + } |
| 140 | + } |
| 141 | + return 'unknown'; |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Returns a time associated with an activity. |
| 146 | + * |
| 147 | + * @param {Object} activity The DriveActivity from which to extract a time. |
| 148 | + * @return {string} |
| 149 | + */ |
| 150 | +function getTimeInfo(activity) { |
| 151 | + if ('timestamp' in activity) { |
| 152 | + return activity.timestamp; |
| 153 | + } |
| 154 | + if ('timeRange' in activity) { |
| 155 | + return activity.timeRange.endTime; |
| 156 | + } |
| 157 | + return 'unknown'; |
| 158 | +} |
| 159 | + |
| 160 | +/** |
| 161 | + * Returns the type of action. |
| 162 | + * |
| 163 | + * @param {Object} actionDetail The ActionDetail to summarize. |
| 164 | + * @return {string} |
| 165 | + */ |
| 166 | +function getActionInfo(actionDetail) { |
| 167 | + return getOneOf(actionDetail); |
| 168 | +} |
| 169 | + |
| 170 | +/** |
| 171 | + * Returns user information, or the type of user if not a known user. |
| 172 | + * |
| 173 | + * @param {Object} user The User to summarize. |
| 174 | + * @return {string} |
| 175 | + */ |
| 176 | +function getUserInfo(user) { |
| 177 | + if ('knownUser' in user) { |
| 178 | + const knownUser = user['knownUser']; |
| 179 | + const isMe = knownUser['isCurrentUser'] || false; |
| 180 | + return isMe ? 'people/me' : knownUser['personName']; |
| 181 | + } |
| 182 | + return getOneOf(user); |
| 183 | +} |
| 184 | + |
| 185 | +/** |
| 186 | + * Returns actor information, or the type of actor if not a user. |
| 187 | + * |
| 188 | + * @param {Object} actor The Actor to summarize. |
| 189 | + * @return {string} |
| 190 | + */ |
| 191 | +function getActorInfo(actor) { |
| 192 | + if ('user' in actor) { |
| 193 | + return getUserInfo(actor['user']); |
| 194 | + } |
| 195 | + return getOneOf(actor); |
| 196 | +} |
| 197 | + |
| 198 | +/** |
| 199 | + * Returns the type of a target and an associated title. |
| 200 | + * |
| 201 | + * @param {Object} target The Target to summarize. |
| 202 | + * @return {string} |
| 203 | + */ |
| 204 | +function getTargetInfo(target) { |
| 205 | + if ('driveItem' in target) { |
| 206 | + const title = target.driveItem.title || 'unknown'; |
| 207 | + return `driveItem:"${title}"`; |
| 208 | + } |
| 209 | + if ('teamDrive' in target) { |
| 210 | + const title = target.teamDrive.title || 'unknown'; |
| 211 | + return `teamDrive:"${title}"`; |
| 212 | + } |
| 213 | + if ('fileComment' in target) { |
| 214 | + const parent = target.fileComment.parent || {}; |
| 215 | + const title = parent.title || 'unknown'; |
| 216 | + return `fileComment:"${title}"`; |
| 217 | + } |
| 218 | + return `${getOneOf(target)}:unknown`; |
| 219 | +} |
| 220 | +// [END drive_activity_v2_quickstart] |
0 commit comments