-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail_new_users.Rmd
122 lines (106 loc) · 2.66 KB
/
email_new_users.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
---
title: "Report for New Users"
output:
html_document:
df_print: paged
params:
days_back:
input: slider
label: "Days Back"
min: 0
max: 1000
step: 1
value: 1
---
```{r preflight_check, results='asis', include=TRUE}
if (
nchar(Sys.getenv("RSTUDIO_CONNECT_SERVER")) == 0 ||
nchar(Sys.getenv("RSTUDIO_CONNECT_API_KEY")) == 0
) {
print(htmltools::h4("ERROR: Variables Not Defined"))
print(htmltools::div(
"The RSTUDIO_CONNECT_SERVER and RSTUDIO_CONNECT_API_KEY",
"environment variables are required in order for this report",
"to manage users. The API_KEY should represent an administrator",
htmltools::br(),
htmltools::br(),
"Please define these variables",
"and then re-run the report.",
htmltools::br(),
htmltools::br(),
style = "max-width: 600px"
))
knitr::knit_exit("Terminating the report early.")
}
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(connectapi)
get_all_users <- function(connect){
more <- TRUE
page <- 1
users <- tibble::tibble()
while(more){
more <- FALSE
message(paste("Fetching page", page))
tmp_users <- connect$get_users(page)
if (length(tmp_users$results)) {
more <- TRUE
page <- page + 1
}
users <- dplyr::bind_rows(
users,
dplyr::bind_rows(
lapply(tmp_users$results, as_tibble)
)
)
}
return(users)
}
conn <- Connect$new(
host = Sys.getenv("RSTUDIO_CONNECT_SERVER"),
api_key = Sys.getenv("RSTUDIO_CONNECT_API_KEY")
)
```
## Gather New Users from the Past `r params$days_back` Day(s)
```{r data_prep}
users <- get_all_users(conn)
users <- users %>% mutate(
created_date_ts = lubridate::ymd_hms(created_time)
)
new_users <- users %>%
filter(
created_date_ts > lubridate::as_date(
Sys.time() - lubridate::ddays(params$days_back)
)
)
new_users
```
## Generate the Custom Email Body
```{r email}
if (nrow(new_users) > 0) {
to_print <- purrr::map_chr(
1:nrow(new_users),
~sprintf(
"%25s %25s %25s",
new_users$username[.x],
new_users$email[.x],
new_users$created_time[.x])
)
to_print <- c(sprintf("%25s %25s %25s", "Username", "Email", "Created Time"), to_print)
body <- glue::glue(
"New users as of {Sys.Date()} for the past {params$days_back} day(s):\n",
"{paste0(to_print, collapse='\n')}"
)
rmarkdown::output_metadata$set(
rsc_email_subject = "New RStudio Connect Users",
rsc_email_body_text = body,
rsc_email_suppress_scheduled = FALSE
)
cat(body)
} else {
cat("No new users. Not sending email")
rmarkdown::output_metadata$set(rsc_email_suppress_scheduled = TRUE)
}
```