Last active
December 5, 2018 10:31
-
-
Save tyrcho/8f9264c104a7ae8e726c5c25bd86d472 to your computer and use it in GitHub Desktop.
set google domain users as choices in a form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// see https://stackoverflow.com/questions/51025018/referenceerror-admindirectory-is-not-defined to activate AdminDirectory | |
// - resources > advanced google services > Admin Directory API > Activate | |
// - https://console.cloud.google.com/apis/api/admin.googleapis.com/overview?project=project-id-123456&authuser=1 | |
function onOpen(e) { | |
FormApp.getUi() | |
.createAddonMenu() | |
.addItem('Update users', 'setUsers') | |
.addToUi(); | |
} | |
function setUsers() { | |
var emails = listActiveUsers("colisweb.com") | |
.map(function(user) { return user.primaryEmail; }); | |
var form = FormApp.getActiveForm(); | |
updateForm(form, emails); | |
return emails.length; | |
} | |
function updateForm(form, usersValues) { | |
var items = form.getItems(); | |
var destination = items[0].asListItem(); | |
var choices = usersValues | |
.filter(function(value) { return value != ""; }) | |
.map(function(value) { return destination.createChoice(value);}) | |
destination.setChoices(choices); | |
} | |
function listActiveUsers(domainName) { | |
var now = new Date(); | |
var twoWeeksAgo = now.setDate(now.getDate() - 14); | |
var users = AdminDirectory.Users.list({ | |
domain: domainName, | |
orderBy: 'givenName', | |
maxResults: 100 | |
}) | |
.users | |
.filter(function(user) { return Date.parse(user.lastLoginTime) > twoWeeksAgo; }); | |
return users; | |
} | |
function logUsers(users) { | |
if (users && users.length > 0) { | |
Logger.log('Users:'); | |
for (i = 0; i < users.length; i++) { | |
var user = users[i]; | |
Logger.log('%s (%s)', user.primaryEmail, user.name.fullName); | |
} | |
} else { | |
Logger.log('No users found.'); | |
} | |
} | |
function transpose(a) { | |
return a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment