MarkEdmondson1234 / googleAuthR

Google API Client Library for R. Easy authentication and help to build Google API R libraries with OAuth2. Shiny compatible.
https://code.markedmondson.me/googleAuthR
Other
175 stars 54 forks source link

Can't use app online, bug with gar_set_client() #170

Open arth-prin opened 4 years ago

arth-prin commented 4 years ago

What goes wrong

I deployed my application on shinyapps.io. It works properly locally, but it doesn't work online, it seems like I have a bug with gar_set_client()

Steps to reproduce the problem

#global.R
library(shiny)
library(googleAuthR)
library(searchConsoleR)
library(googleAnalyticsR)
library(ggplot2)
library(urltools)
library(dplyr)

#options(googleAuthR.redirect = "https://campels.shinyapps.io/")

options(
  googleAuthR.scopes.selected = c(
    "https://www.googleapis.com/auth/webmasters",
    "https://www.googleapis.com/auth/analytics",
    "https://www.googleapis.com/auth/analytics.readonly"
  )
)

#options(googleAuthR.webapp.client_id = "XXX")
#options(googleAuthR.webapp.client_secret = "XXX")

gar_set_client(web_json = "gcp_client.json")

#server.R
source("global.R")

Server <- function(input, output, session) {

  ## Create access token and render login button
  access_token <- callModule(googleAuth_js, "js_token")

  ## Create access token and render login button
  #connect_api <- callModule(googleAuth, "loginButton")

  ##################### Position_ctr #######################

  Position_ctr <- function(){

    site <- input$url
    gAid <- input$ga_id

    ## date range to fetch
    plage = input$sdl
    start <- as.character(Sys.Date() - plage)
    end <- as.character(Sys.Date() - 3)

    ## Using new GA v4 API
    ## GAv4 filters
    google_seo <- filter_clause_ga4(list(
      dim_filter("medium",
                 "EXACT",
                 "organic"),
      dim_filter("source",
                 "EXACT",
                 "google")
    ),
    operator = "AND")

    max_results <- input$results

    ## Getting the GA data
    gadata <- google_analytics(
      gAid,
      date_range = c(start, end),
      metrics = c("sessions",
                  "pageviews"),
      dimensions = c("landingPagePath"),
      dim_filters = google_seo,
      max = max_results
    )

    ## Getting the Search Console data
    scdata <- search_analytics(
      siteURL = site,
      startDate = start,
      endDate = end,
      dimensions = c("page", "query"),
      rowLimit = max_results,
      aggregationType = "byPage",
      walk_data = "byBatch"
    )

    ## get urls in same format
    ## gadata has urls www.example.com/pagePath
    ## scdata has urls in http://www.example.com/pagePath
    domainparse <- url_parse(scdata[1, ]$page)
    domainname <-
      paste0(domainparse["scheme"], "://", domainparse["domain"])
    scdata$page <- gsub(domainname, "", scdata$page)

    ## % of SEO traffic to each page per keyword
    scdata <- scdata %>%

      group_by(page) %>%
      mutate(clickPage = clicks / sum(clicks)) %>%
      ungroup()

    ## join data on page
    joined_data <- gadata %>%
      left_join(scdata, by = c(landingPagePath = "page")) %>%
      mutate(sessionEst = clickPage * sessions,
             accuracyEst = ((sessionEst / clicks) - 1))

    ## we only want clicks over 0, and get rid of a few columns.
    tidy_data <- joined_data %>%
      filter(clicks > 0) #%>%
    #select(-sessions)

    tidy_data$position <- round(tidy_data$position)

    click_curve <- tidy_data %>%
      group_by(position) %>%
      summarise(
        CTRmean = mean(ctr),
        n = n(),
        click.sum = sum(clicks),
        impressions.sum = sum(impressions),
        sd = sd(ctr),
        E = poisson.test(click.sum)$conf.int[2] / poisson.test(impressions.sum)$conf.int[1],
        lower = CTRmean - E / 2,
        upper = CTRmean + E / 2
      ) %>% ungroup()

    ## add % increase to position 1
    ## could also include other positions
    click_curve <- click_curve %>%
      mutate(
        CTR1 = CTRmean[1] / CTRmean,
        CTR1.upper = upper[1] / upper,
        CTR1.lower = lower[1] / lower
      )

    sitename <- paste("Mon Site (", nrow(scdata), " requêtes )")

    hh <-
      ggplot(click_curve, aes(position, CTRmean)) + theme_minimal()

    hh <-
      hh + geom_line(linetype = 2) + coord_cartesian(xlim = c(1, 10), ylim = c(0, 1))
    hh <-
      hh + geom_ribbon(aes(position, ymin = lower, ymax = upper),
                       alpha = 0.2,
                       fill = "orange")
    hh <- hh + scale_y_continuous(labels = scales::percent)
    hh <-
      hh + geom_point() + geom_label(aes(label = scales::percent(CTRmean)))
    hh <- hh + labs(title = sitename)
    hh <- hh + labs(x = "position", y = "ctr moyen")

    return(hh)

    print(hh)
  }

  Position_ctr_output <- eventReactive(input$submit1, {
    ## wrap existing function with_shiny
    ## pass the reactive token in shiny_access_token
    ## pass other named arguments
    with_shiny(f = Position_ctr, 
               shiny_access_token = access_token())

  })

  output$Position_ctr <- renderPlot({

    Position_ctr_output()

  })
}

Code has been cut, to give you an overview

Actual output

2019-11-27T09:13:39.680648+00:00 shinyapps[1528437]: 2019-11-27 09:13:39> Default Google Project for googleAnalyticsR is set.  
2019-11-27T09:13:39.680651+00:00 shinyapps[1528437]:  If making a lot of API calls, please: 
2019-11-27T09:13:39.680651+00:00 shinyapps[1528437]:  visit: https://bit.ly/2Evk6hn 
2019-11-27T09:13:39.680652+00:00 shinyapps[1528437]:  for instructions on setting your own Google Project 
2019-11-27T09:13:39.680650+00:00 shinyapps[1528437]:  This is shared with all googleAnalyticsR users. 
2019-11-27T09:13:39.680652+00:00 shinyapps[1528437]: 
2019-11-27T09:13:39.688585+00:00 shinyapps[1528437]: Warning: Error in : The default Google Cloud Project for googleAnalyticsR is intended 
2019-11-27T09:13:39.688588+00:00 shinyapps[1528437]: Please set your own client.id and client.secret via googleAuthR::gar_set_client()
2019-11-27T09:13:39.688586+00:00 shinyapps[1528437]:            
2019-11-27T09:13:39.688587+00:00 shinyapps[1528437]: for evalutation only, not production scripts.  
2019-11-27T09:13:39.688588+00:00 shinyapps[1528437]:            
2019-11-27T09:13:39.688588+00:00 shinyapps[1528437]: or otherwise as suggested on the website.
2019-11-27T09:13:39.688588+00:00 shinyapps[1528437]:            
2019-11-27T09:13:39.697250+00:00 shinyapps[1528437]:   227: google_analytics
2019-11-27T09:13:39.697249+00:00 shinyapps[1528437]:   228: stop
2019-11-27T09:13:39.697266+00:00 shinyapps[1528437]:   196: hybrid_chain
2019-11-27T09:13:39.697250+00:00 shinyapps[1528437]:   226: f [/srv/connect/apps/test3/server.R#81]
2019-11-27T09:13:39.697275+00:00 shinyapps[1528437]:   194: .func
2019-11-27T09:13:39.697251+00:00 shinyapps[1528437]:   225: with_shiny
2019-11-27T09:13:39.697275+00:00 shinyapps[1528437]:   191: contextFunc
2019-11-27T09:13:39.697251+00:00 shinyapps[1528437]:   224: eventReactiveHandler [/srv/connect/apps/test3/server.R#183]
2019-11-27T09:13:39.697276+00:00 shinyapps[1528437]:   190: env$runWith
2019-11-27T09:13:39.697251+00:00 shinyapps[1528437]:   222: handlerFunc
2019-11-27T09:13:39.697276+00:00 shinyapps[1528437]:   183: ctx$run
2019-11-27T09:13:39.697252+00:00 shinyapps[1528437]:   209: func
2019-11-27T09:13:39.697276+00:00 shinyapps[1528437]:   182: self$.updateValue
2019-11-27T09:13:39.697274+00:00 shinyapps[1528437]:   195: <reactive:eventReactive(input$submit1)>
2019-11-27T09:13:39.697278+00:00 shinyapps[1528437]:   123: <reactive:plotObj>
2019-11-27T09:13:39.697278+00:00 shinyapps[1528437]:   137: drawPlot
2019-11-27T09:13:39.697278+00:00 shinyapps[1528437]:   107: drawReactive
2019-11-27T09:13:39.697278+00:00 shinyapps[1528437]:    94: origRenderFunc
2019-11-27T09:13:39.697252+00:00 shinyapps[1528437]:   207: f
2019-11-27T09:13:39.697276+00:00 shinyapps[1528437]:   180: Position_ctr_output
2019-11-27T09:13:39.697265+00:00 shinyapps[1528437]:   206: Reduce
2019-11-27T09:13:39.697277+00:00 shinyapps[1528437]:   179: renderPlot [/srv/connect/apps/test3/server.R#190]
2019-11-27T09:13:39.697265+00:00 shinyapps[1528437]:   197: do
2019-11-27T09:13:39.697277+00:00 shinyapps[1528437]:   177: func
2019-11-27T09:13:39.697279+00:00 shinyapps[1528437]:    93: output$Position_ctr
2019-11-27T09:13:39.697283+00:00 shinyapps[1528437]:    13: runApp
2019-11-27T09:13:39.697284+00:00 shinyapps[1528437]:    12: fn
2019-11-27T09:13:39.697291+00:00 shinyapps[1528437]:     5: eval
2019-11-27T09:13:39.697284+00:00 shinyapps[1528437]:     7: connect$retry
2019-11-27T09:13:39.697284+00:00 shinyapps[1528437]:     6: eval

He tells me to use gar_set_client (), but that's what I already do, I don't understand anymore

Session Info

Please run sessionInfo() so we can check what versions of packages you have installed

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale:
[1] LC_COLLATE=French_France.1252  LC_CTYPE=French_France.1252    LC_MONETARY=French_France.1252 LC_NUMERIC=C                   LC_TIME=French_France.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dplyr_0.8.3            urltools_1.7.3         ggplot2_3.2.1          googleAnalyticsR_0.7.1 searchConsoleR_0.4.0   googleAuthR_1.1.1      shiny_1.4.0           

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.2       compiler_3.6.1   pillar_1.4.2     later_1.0.0      tools_3.6.1      zeallot_0.1.0    digest_0.6.23    packrat_0.5.0    gtable_0.3.0     jsonlite_1.6    
[11] memoise_1.1.0    gargle_0.4.0     tibble_2.1.3     lifecycle_0.1.0  pkgconfig_2.0.3  rlang_0.4.1      rstudioapi_0.10  curl_4.2         fastmap_1.0.1    withr_2.1.2     
[21] httr_1.4.1       askpass_1.1      fs_1.3.1         vctrs_0.2.0      triebeard_0.3.0  grid_3.6.1       tidyselect_0.2.5 glue_1.3.1       R6_2.4.1         purrr_0.3.3     
[31] tidyr_1.0.0      magrittr_1.5     scales_1.0.0     backports_1.1.5  promises_1.1.0   htmltools_0.4.0  rsconnect_0.8.15 assertthat_0.2.1 colorspace_1.4-1 mime_0.7        
[41] xtable_1.8-4     httpuv_1.5.2     openssl_1.4.1    lazyeval_0.2.2   munsell_0.5.0    crayon_1.3.4 
MarkEdmondson1234 commented 4 years ago

Is your "gcp_client.json" file also uploaded to the Shiny server?