-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathauthentication.R
More file actions
556 lines (457 loc) · 18 KB
/
Copy pathauthentication.R
File metadata and controls
556 lines (457 loc) · 18 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
#' Create a data frame of datasets that your log in can download
#'
#' DHS datasets that can be downloaded
#' @param config Object of class `rdhs_config` as produced by `read_rdhs_config`
#' that must contain a valid `email`, `project` and `password`.
#' @param datasets_api_results Data.table for the api results for the datasets
#' endpoint. Default = NULL and
#' generated by default if not declared.
#' @param surveys_api_results Data.table for the api results for the surveys
#' endpoint. Default = NULL and
#' generated by default if not declared.
#'
#' @note Inspiration for function to
#' \url{https://github.com/ajdamico/lodown/blob/master/R/dhs.R}
#'
#' @return Returns \code{"data.frame"} of length 14:
#' \itemize{
#' \item{"FileFormat"}
#' \item{"FileSize"}
#' \item{"DatasetType"}
#' \item{"SurveyNum"}
#' \item{"SurveyId"}
#' \item{"FileType"}
#' \item{"FileDateLastModified"}
#' \item{"SurveyYearLabel"}
#' \item{"SurveyType"}
#' \item{"SurveyYear"}
#' \item{"DHS_CountryCode"}
#' \item{"FileName"}
#' \item{"CountryName"}
#' \item{"URLS"}
#' }
#'
available_datasets <- function(config,
datasets_api_results = NULL,
surveys_api_results = NULL) {
# fetch all the datasets meta from the api if to already passed
if (is.null(datasets_api_results) || is.null(surveys_api_results)) {
datasets_api_results <- dhs_datasets()
surveys_api_results <- dhs_surveys()
}
# set up temp file for unpacking bins
tf <- tempfile(fileext = ".txt")
values <- authenticate_dhs(config)
# grab project number here
project_number <- values$proj_id
# re-access the download-datasets page
z <- httr::POST(
"https://dhsprogram.com/data/dataset_admin/download-datasets.cfm",
body = list(proj_id = project_number)
)
# write the information from the `countries` page to a local file
writeBin(z$content, tf)
# load the text
y <- brio::read_lines(tf)
# DHS Website has changed and the POST request data requires two steps here
# Create post request for the download manager
values <- list(
Proj_ID = project_number,
action = "getdatasets"
)
# Head to download page
z <- httr::POST("https://dhsprogram.com/data/dataset_admin/index.cfm",
body = values)
# Create post request for the download manager
values <- list(
Proj_ID = project_number,
action = "downloadmanager"
)
# Head to download page
z <- httr::POST("https://dhsprogram.com/data/dataset_admin/index.cfm",
body = values)
# Grab the content from that and start creation for last post request
writeBin(z$content, tf)
# load the text
y <- brio::read_lines(tf)
# Donqwload manager post creation
ctrycodelist_lines <- grep("name=\"ctrycodelist\" value=", y, value = TRUE)
ctrycodelist <- qdapRegex::rm_between(
ctrycodelist_lines, 'value=\"', '\"', extract = TRUE
)
names(ctrycodelist) <- rep("ctrycodelist", length(ctrycodelist))
class(ctrycodelist) <- "list"
filedatatypelist_DHS_line <- grep("name=\"filedatatypelist_", y, value = TRUE)
filedatatypelist_DHS <- qdapRegex::rm_between(
filedatatypelist_DHS_line, 'value=\"', '\"', extract = TRUE
)
names(filedatatypelist_DHS) <- paste0(
"filedatatypelist_",
qdapRegex::rm_between(filedatatypelist_DHS_line,
"filedatatypelist_", "\" value", extract = TRUE)
)
class(filedatatypelist_DHS) <- "list"
formatlist <- grep("fformatlist", y, value = TRUE)
formatlist <- qdapRegex::rm_between(
formatlist, 'value=\"', '\"', extract = TRUE
)
names(formatlist) <- rep("fformatlist", length(formatlist))
class(formatlist) <- "list"
values <- list(
surveymode = "all",
Proj_ID = project_number,
action = "downloadmanager",
subaction = "Build URL File List",
sub = "submit",
submit = "Build URL File List",
FileDataTypeCode = "",
ctrycode = ""
)
values <- append(values,
values = c(ctrycodelist, filedatatypelist_DHS, formatlist))
# submit request for all the possible datasets
message("Creating Download url list from DHS website...")
z <- httr::POST(
"https://dhsprogram.com/data/dataset_admin/index.cfm",
body = values
)
link.urls <- xml2::xml_find_all(httr::content(z), "//a")
# pull all links download and read in
url_link <- paste0("https://dhsprogram.com", grep(
pattern = "/data/download/urlslist",
xml2::xml_attr(link.urls, "href"), value = TRUE
))
httr::GET(
url_link, httr::user_agent("https://github.com/ropensci/rdhs"),
destfile = tf, httr::write_disk(tf, overwrite = TRUE)
)
urls <- brio::read_lines(tf)
urls <- urls[-which(!nzchar(urls))]
# start filling in the end result data frame of all available datasets
res <- matrix(data = "", nrow = length(urls),
ncol = dim(datasets_api_results)[2] + 1)
colnames(res) <- c(names(datasets_api_results), "URLS")
res <- as.data.frame(res, stringsAsFactors = FALSE)
res$URLS <- urls
res$FileName <- qdapRegex::rm_between(urls, "Filename=", "&Tp",
extract = TRUE) %>% unlist()
res$DHS_CountryCode <- qdapRegex::rm_between(urls, "Ctry_Code=", "&surv_id",
extract = TRUE) %>% unlist()
# match meta using filenames and countrycodes
# (India has subnational datasets that clash)
fileName_matches <- match(
paste0(toupper(res$FileName),
toupper(res$DHS_CountryCode)),
paste0(toupper(datasets_api_results$FileName),
toupper(datasets_api_results$DHS_CountryCode))
)
res_matches <- which(!is.na(fileName_matches))
# remove any missing matches (shouldn't happen if API up to date)
if (sum(is.na(fileName_matches)) > 0) {
message("\nSome of your available datasets are not found in the DHS API. \n",
"This is likely due to the DHS API being out of date and as such \n",
"some of the meta information about your available datasets \n",
"may not be available.")
fileName_matches <- fileName_matches[-which(is.na(fileName_matches))]
}
s <- seq_len(length(datasets_api_results))
res[res_matches, s] <- datasets_api_results[fileName_matches, ]
return(res)
}
#' Create a data frame of datasets that your log in can download
#'
#' Download datasets specified using output of \code{available_datasets}.
#' @param config Object of class `rdhs_config` as produced by `read_rdhs_config`
#' that must contain a valid `email`, `project` and `password`.
#' @param desired_dataset Row from \code{available_datasets}
#' @param download_option Character dictating how the survey is stored when
#' downloaded. Must be one of:
#' \itemize{
#' \item{"zip"} - Just the zip. "z", "i", "p" or "zip" will match
#' \item{"rds"} - Just the read in and saved rds. "r", "d", "s" or "rdhs"
#' will match
#' \item{"both"} - Both the rds and extract. "b", "o", "t", "h" or "both"
#' will match
#' }
#' @param reformat Boolean detailing whether dataset rds should be
#' reformatted for ease of use later. Default = TRUE
#' @param all_lower Logical indicating whether all value labels should be
#' lower case. Default to `TRUE`.
#' @param output_dir_root Directory where files are to be downloaded to
#' @param ... Any other arguments to be passed to
#' \code{\link{read_dhs_dataset}}
#'
download_datasets <- function(config,
desired_dataset,
download_option = "both",
reformat=TRUE,
all_lower=TRUE,
output_dir_root=NULL,
...) {
# possible download options:
download_possibilities <- c("zip", "rds", "both")
download_option <- grep(
paste0(strsplit(download_option, "") %>% unlist(), collapse = "|"),
download_possibilities)
if (!is.element(download_option, 1:3)) {
stop("Download option specified not one of zip,rds,both")
}
# handle output dir
dataset_dir <- file.path(output_dir_root)
if (reformat) {
dataset_dir <- paste0(dataset_dir, "_reformatted")
}
# make sure the folder exists and create the zip path
dir.create(dataset_dir, showWarnings = FALSE, recursive = TRUE)
zip_path <- file.path(dataset_dir, desired_dataset$FileName)
# download our zip and parse the response for any errors
message("Downloading: \n", paste0(desired_dataset$CountryName, " ",
desired_dataset$SurveyYear, " ",
desired_dataset$SurveyType, " ",
desired_dataset$FileType, " ",
desired_dataset$FileFormat, " ",
"[", desired_dataset$FileName, "]",
collapse = ", "))
# set up temp file for unpacking bins
# annoyingly we have to do this because some zips have
# been zipped with the same name several times
# so they can not be unzipped to the same directory.
# Thus we bounce unzips between these two dirs.
tf <- tempfile()
tdir <- tempfile()
on.exit(unlink(c(tf, tdir), recursive = TRUE, force = TRUE))
# create a simple while loop on file size check and carry this
# out three times befoe stopping
file_size_check <- TRUE
attempts <- 3
# if the downloaded file is not the size we expect
# then re log in the first time
while (file_size_check & attempts > 0) {
# download zip to our tempfile
if (Sys.getenv("rdhs_LOUD_DOWNLOAD") == TRUE) {
resp <- httr::GET(desired_dataset$URLS[1],
destfile = tf,
httr::user_agent("https://github.com/ropensci/rdhs"),
httr::write_disk(tf, overwrite = TRUE),
httr::progress()
) %>% handle_api_response(to_json = FALSE)
} else {
resp <- httr::GET(desired_dataset$URLS[1],
destfile = tf,
httr::user_agent("https://github.com/ropensci/rdhs"),
httr::write_disk(tf, overwrite = TRUE)
) %>% handle_api_response(to_json = FALSE)
}
# if it's not the right size and first time we've tried then log in
if (file.size(tf) != desired_dataset$FileSize[1] & attempts == 3) {
# do updated authentication procedure
auth_downloads(config)
} else if (file.size(tf) == desired_dataset$FileSize[1]) {
file_size_check <- FALSE
attempts <- 0
}
attempts <- attempts - 1
}
## If the zip contains a nested zip file of the same name as the desired file,
## unzip and replace the file with the nested zip.
nest_zf <- grep(desired_dataset$FileName,
unzip(tf, list = TRUE)$Name,
ignore.case = TRUE,
value = TRUE)
while (length(nest_zf)){
tf <- unzip(tf, nest_zf[1], exdir = tdir)
nest_zf <- grep(desired_dataset$FileName,
unzip(tf, list = TRUE)$Name,
ignore.case = TRUE,
value = TRUE)
}
## DOWNLOAD OPTIONS HANDLING:
# 1. Just the zip - we'll always do this and then if it's 2 remove it later
# if it's just the zip then we copy it to the
# directory return the file path for this
res <- file.copy(tf, to = zip_path, overwrite = TRUE)
res <- if (res) {
zip_path
} else {
stop("Failed to download zip to where client root is")
}
# 2/3. rds or both
if (download_option >= 2) {
# now read the dataset in with the requested reformat options
res <- read_dhs_dataset(zip_path,
dataset = desired_dataset,
reformat, all_lower, ...
)
# handle results. If it's character it's because we
# haven't yet got a parser we are happy with
if (!is.character(res)) {
# let's assign the file name attribute to the res
attr(res$dataset, which = "filename") <- desired_dataset$file
# set up the rds_path to save the dataset
rds_path <- file.path(dataset_dir, paste0(desired_dataset$file, ".rds"))
# save the dataset out
saveRDS(res$dataset, rds_path)
# if the class of the object is from a geo or geo_covariates file then we
# will just return the rds path
if (inherits(res$dataset, "sf") ||
desired_dataset$FileType == "Geographic Data" ||
desired_dataset$FileType == "Geospatial Covariates") {
res <- rds_path
} else {
# if its a dataset then we return the path and the
# code_descriptions as these are useful to have cached
res$dataset <- rds_path
}
}
# 3. If not both then delete the zip
if (download_option != 3) {
file.remove(zip_path)
}
}
message("Dataset download finished")
return(res)
}
#' Authenticate Users for DHS website
#'
#' @title DHS Website Authentication
#' @param config Object of class `rdhs_config` as produced by `read_rdhs_config`
#' that must contain a valid `email`, `project` and `password`.
#'
#' @details If the user has more than one project that contains the first
#' 30 characters of the provided project they will be prompted to choose
#' which project they want. This choice will be saved so they do
#' not have to enter it again in this R session.
#'
#' @note Credit for some of the function to
#' \url{https://github.com/ajdamico/lodown/blob/master/R/dhs.R}
#'
#' @return Returns list of length 3:
#' \itemize{
#' \item user_name: your email usually
#' \item user_pass: your password you provided
#' \item proj_id: your project number
#' }
#'
#'
#'
authenticate_dhs <- function(config) {
your_email <- config$email
your_project <- config$project
your_password <- config$password
# Argument Checking
if (!is.character(your_email)) stop("your_email is not a string")
if (!is.character(your_project)) stop("your_project is not a string")
if (!is.character(your_password)) stop("your_password is not a string")
# authentication page
terms <- "https://dhsprogram.com/data/dataset_admin/login_main.cfm"
# create a temporary file
tf <- tempfile(fileext = ".txt")
# set the username and password
values <- list(
UserName = your_email,
UserPass = your_password,
Submitted = 1,
UserType = 2
)
# log in.
message("Logging into DHS website...")
z <- httr::POST(terms, body = values) %>% handle_api_response(to_json = FALSE)
# extract the available countries from the projects page
# write the information from the `projects` page to a local file
writeBin(z$content, tf)
# load the text
y <- brio::read_lines(tf)
# figure out the project number - only use first 30 chars due to ellipsis
# formation if it is longer than 30
if (nchar(your_project) > 30) {
project_lines <- unique(
y[grepl("option value", y) &
grepl(paste0(strsplit(your_project, "")[[1]][1:30], collapse = ""),
y, fixed = TRUE)
])
} else {
project_lines <- unique(
y[grepl("option value", y) &
grepl(paste0(strsplit(your_project, "")[[1]], collapse = ""),
y, fixed = TRUE)
])
}
# confirm only one project and handle if more than
if (length(project_lines) == 1) {
} else {
if (length(project_lines) > 1) {
# if they have more than one project that is similar
# then have they encoutnereed this before:
pl <- config$project_choice
# if nothing is set then ask them which one:
if (is.null(pl)) {
# get the names of the projects
projs <- unlist(qdapRegex::ex_between(project_lines, ">", "<"))
nums <- unlist(qdapRegex::ex_between(project_lines, "value=\"", "\">"))
nums <- as.numeric(nums)
oldest <- sort.int(nums, index.return = TRUE)$ix
# prompt for an option until they give is a good one
valid_prompt <- FALSE
while (!valid_prompt) {
pl <- readline(
prompt = cat(
"You have multiple projects that have similar names. Which one",
"did you want to use? The oldest project is number 1.",
"(Enter the correct number for your project)\n",
paste(seq_len(length(project_lines)), projs[oldest], sep = ": "),
"\nYour choice will be remembered within this R session,",
"but will need to be entered each time you load a new R session.",
sep = "\n"
)) %>% as.integer()
if (is.element(pl, seq_len(length(project_lines)))) {
valid_prompt <- TRUE
}
}
# set the option for the future
pl <- as.numeric(pl)
config$project_choice <- nums[oldest][pl]
update_rdhs_config(project_choice = nums[oldest][pl])
}
project_lines <- project_lines[oldest[pl]]
} else {
stop(
"Your log in credentials were not recognised by the DHS website.\n",
"Please check your email, password, and project name are correct (?get_rdhs_config),\n",
"and your internet connection for possible error."
)
}
}
# extract the project number from the line above
project_number <- gsub("(.*)<option value=\"([0-9]*)\">(.*)",
"\\2",
project_lines)
# remove the tf
suppressWarnings(file.remove(tf))
# return these credentials to be used for downloading datasets
res <- list(
user_name = your_email,
user_pass = your_password,
proj_id = project_number
)
return(res)
}
#' @noRd
auth_downloads <- function(config){
# authenticate
values <- authenticate_dhs(config)
# grab project number here
project_number <- values$proj_id
# Create post request for the download manager
values <- list(
Proj_ID = project_number,
action = "getdatasets"
)
# re-access the download-datasets page
z <- httr::POST(
"https://dhsprogram.com/data/dataset_admin/download-datasets.cfm",
body = list(proj_id = project_number)
)
# Head to download page
z <- httr::POST("https://dhsprogram.com/data/dataset_admin/index.cfm",
body = values)
}