R/helper_functions.R

Defines functions tag_id_url trigger_id_url token_status variable_type_fix wspace_picker containerver_unwrap builtinvar_unwrap api_styling easy_call verbose_calls usage_context_fix gtm_manage_auth

Documented in api_styling builtinvar_unwrap containerver_unwrap easy_call gtm_manage_auth tag_id_url token_status trigger_id_url usage_context_fix variable_type_fix verbose_calls wspace_picker

#' gtm_manage_auth
#'
#' A tool for managing your authorizations
#' @param client_id Your Google client ID
#' @param client_secret Your Google client client
#' @param scope The scope that you need (defaults to 'read'); can be one of the following:
#'    * 'delete containers'
#'    * 'edit containers'
#'    * 'edit container versions'
#'    * 'manage accounts'
#'    * 'manage users'
#'    * 'publish'
#'    * 'read'
#' @export

gtm_manage_auth <- function(json_file,client_id=NULL,client_secret=NULL) {

  require(httr)
  require(tidyverse)
  require(purrr)
  require(jsonlite)

  if (purrr::is_empty(json_file) == FALSE) {

    j <- fromJSON(json_file)

    client_id <- j$installed$client_id
    client_secret <- j$installed$client_secret

  }

  myapp <- oauth_app("google", client_id,
                     client_secret)

  scopes <- c('https://www.googleapis.com/auth/tagmanager.delete.containers',
                'https://www.googleapis.com/auth/tagmanager.edit.containers',
                'https://www.googleapis.com/auth/tagmanager.edit.containerversions',
                'https://www.googleapis.com/auth/tagmanager.manage.accounts',
                'https://www.googleapis.com/auth/tagmanager.manage.users',
                'https://www.googleapis.com/auth/tagmanager.publish',
                'https://www.googleapis.com/auth/tagmanager.readonly')

  google_token <- oauth2.0_token(oauth_endpoints("google"), myapp,
                                                    scope = scopes)

  google_token$init_credentials()

  return(google_token)
}

#' usage_context_fix
#'
#' Fix the usage context field to make it look nicer
#' @param x The data frame
#' @export

usage_context_fix <- function(x) {

  require(tidyverse)

  new_df <- x %>%
    mutate(usage_context = str_to_title(usage_context),
          usage_context = gsub('sdk',' SDK ',usage_context),
           usage_context = gsub('Ios','iOS',usage_context))

    return(new_df)

}

#' verbose_calls
#'
#' Reporting call results based on what the API reports
#' @param call The API call results
#' @param call_content The results of parsing the API call content
#' @param verbose The verbose status
#' @export

verbose_calls <- function(call,call_content,verbose) {

  if (call$status_code >= 400) {

    print('Error!')

    print(call_content)

    stop('Terminating process')

  } else if (verbose == TRUE) {

    print(paste('Status code:',call$status_code))

  }

}

#' easy_call
#'
#' An easy way to write a call to a Google API
#' @param call_type One of 'post', 'put', 'get', 'delete'
#' @param url The URL you are sending the call to
#' @param token An OAuth token object
#' @param call_body The request body. Optional
#' @export

easy_call <- function(call_type,url,token,call_body=NULL) {

  require(httr)
  require(tidyverse)

    if(str_to_lower(call_type) == 'post') {

      call <- POST(url,
                   add_headers(Authorization = paste("Bearer", token$credentials$access_token)),
                   encode = 'json',
                   body = call_body)

    } else if (str_to_lower(call_type) == 'get') {

      call <- GET(url,
                   add_headers(Authorization = paste("Bearer", token$credentials$access_token)),
                   encode = 'json',
                   body = call_body)

    } else if (str_to_lower(call_type) == 'put') {

      call <- PUT(url,
                   add_headers(Authorization = paste("Bearer", token$credentials$access_token)),
                   encode = 'json',
                   body = call_body)

    } else if (str_to_lower(call_type) == 'delete') {

      call <- DELETE(url,
                   add_headers(Authorization = paste("Bearer", token$credentials$access_token)),
                   encode = 'json',
                   body = call_body)

    }

    return(call)
  }


#' api_styling
#'
#' An easy way to fix values to be passed to the Google API
#' @param x The value you want to update
#' @export

api_styling <- function(x) {

    x <- gsub('&','and',x)
    x <- str_to_upper(gsub(' ','_',x))

    return(x)
  }

#' builtinvar_unwrap
#'
#' Quickly unwrap a Built-In Variable resource
#' @param x The The built in variable list
#' @export

builtinvar_unwrap <- function(x) {

    x1 <- lapply(x,as_tibble)
    x2 <- do.call('bind_rows',x1)

    x2 <- x2 %>% tidycols()

    return(x2)

}

#' containerver_unwrap
#'
#' Quickly unwrap a Container Version resource
#' @param x The The container version variable list
#' @export

containerver_unwrap <- function(x) {

  cver <- as_tibble(x) %>% tidycols()

  if (length(cver$domain_name) == 1) {

      cver <- cver %>%
        unnest(domain_name)

    } else if (is_empty(cver$domain_name) == TRUE | length(cver$domain_name) < 1) {

      cver$domain_name <- NA

    } else {

      cver$domain_name <- str_c(cver$domain_name,collapse=', ')
    }

    if (length(cver$usage_context) == 1) {

        cver <- cver %>%
          unnest(usage_context)

      } else if (is_empty(cver$usage_context) == TRUE | length(cver$usage_context) < 1) {

        cver$usage_context <- NA

      } else {

        cver$usage_context <- str_c(cver$usage_context,collapse=', ')
      }

  return(cver)

}

#' wspace_picker
#'
#' Pick the default workspace or a user-specified one
#' @param aid The account ID
#' @param cid The container ID
#' @param wid The workspace ID
#' @param token Your GTM access token
#' @export

wspace_picker <- function(aid,cid,wid,token) {

  require(purrr)

  if (is_empty(wid)==FALSE) {

  wid <- wid

  } else {

  wid <- gtm_workspaces_list(aid,cid,token) %>%
    filter(name == 'Default Workspace') %>%
    pull(workspace_id)

  }

  return(wid)
}

#' variable_type_fix
#'
#' Create a new column with a readable value for the type of each variable
#' @param df Your data frame
#' @export

variable_type_fix <- function(df) {

  z <- df %>%
    mutate(type_name = ifelse(type == 'smm','lookup_table',
                  ifelse(type == 'gas','google_analytics_settings',
                  ifelse(type == 'fup','firebase_user_property',
                  ifelse(type == 'md','event_parameter','other')))))

  return(z)

}

#' token_status
#'
#' Check if the OAuth token has the right scope and if it is still valid and refresh it if not
#' @param token Your token
#' @export

token_status <- function(token) {

  require(httr)

status <- token$validate()

if (status == FALSE) {
  token$refresh()
}

}

#' trigger_id_url
#'
#' Create a URL for a trigger function
#' @param account_id The account ID
#' @param container_id The container ID
#' @param workspace_id The workspace ID
#' @param trigger_id The trigger ID
#' @param token The token
#' @export

trigger_id_url <- function(account_id,container_id,workspace_id,trigger_id,token) {

  path <- paste('https://www.googleapis.com/tagmanager/v2/accounts',account_id,'containers',container_id,'workspaces',sep='/')

  wid <- wspace_picker(account_id,container_id,workspace_id,token)

    if (is.numeric(trigger_id) == TRUE) {

          api_url <- paste(path,wid,'triggers',trigger_id,sep='/')

    } else {

      tid <- trigger_id

      trig <- gtm_triggers_list(account_id,container_id,wid,token) %>%
        filter(name == tid) %>%
        distinct(trigger_id) %>%
        pull(trigger_id)

        if (length(trig) == 1) {

          api_url <- paste(path,wid,'triggers',trig,sep='/')

        } else {

        stop('Bad input for trigger_id')

        }

    }

    return(api_url)

}

#' tag_id_url
#'
#' Create a URL for a tag function
#' @param account_id The account ID
#' @param container_id The container ID
#' @param workspace_id The workspace ID
#' @param tag_id The tag ID
#' @param token The token
#' @export

tag_id_url <- function(account_id,container_id,workspace_id,tag_id,token) {

  require(tidyverse)

  path <- paste('https://www.googleapis.com/tagmanager/v2/accounts',account_id,'containers',container_id,'workspaces',sep='/')

  wid <- wspace_picker(account_id,container_id,workspace_id,token)

    if (is.numeric(tag_id) == TRUE) {

          api_url <- paste(path,wid,'tags',tag_id,sep='/')

    } else {

      tid <- tag_id

      tags <- gtm_tags_list(account_id,container_id,wid,token)

      tags2 <- gtm_tags_summary(tags) %>%
        filter(tag_name == tid) %>%
        distinct(tag_id) %>%
        pull(tag_id)

        if (length(tags2) == 1) {

          api_url <- paste(path,wid,'tags',tags2,sep='/')

        } else {

        stop('Bad input for tag_id')

        }

    }

    return(api_url)

}
neugelb/gtmr documentation built on June 25, 2020, 10:06 a.m.