Unzipping a file in R Shiny using unzip() fails when deployed - r

I'd like to unzip a compressed .mdb file in the www folder of my shiny app, query it for data, and then remove it. Unzip() works on my local machine, but when I deploy the app at shinyapps.io, it has issues unzipping the file. Because I'm not able to read.table() the resulting file (it's an .mdb) I don't think unz() will work.
This code works when run on my local machine
Server:
require(shiny)
shinyServer(function(input, output) {
observeEvent(input$run,{ #Run Button
dbName=unzip('www/test.zip', list=T)
output$name=renderText({
paste(dbName[1])
})
db=unzip('www/ttt.zip', exdir='www', unzip=getOption("unzip"))
test1=read.csv(db) #.csv for simplicity, but my problem uses a .mdb
file.remove(db)
output$testcount=renderText({
paste(sum(test1))
})
})#/Run Button
})#/SS
ui:
shinyUI(
sidebarLayout(
sidebarPanel(width=3,
h5('ZIP test'),
p(align="left",
shiny::actionButton("run", label = "Run!")
),
textOutput(outputId = "name"),
textOutput(outputId = "testcount")
),
mainPanel(width=9,
plotOutput(outputId = "probs",height = "550px")
)
)
)
But fails when uploaded to Shinyapps.io.
Any idea of what I'm doing wrong here? I've tried passing the file path directly, and messing with the unzip= options, but to no avail. If I remove the second call, It will tell me the name just fine, but if I try to unzip the file, it breaks.
Any help is appreciated!
EDIT
I was able to get it to work by removing exdir='www', unzip=getOption("unzip") and just looking for the file in the root directory: test1=read.csv('file1.csv')

I'm using unzip() on shiny-server and everytime the function is called the content of the .zip is saved in the root directory of the app. I asume thats a problem for shinyapps.io.
In the documentation you can only specify the location where the file is with 'exdir' from what I read.

Related

How would you get the file server's path for images from a call to the shinyApp(ui = ui, server = server) function? [duplicate]

I'm trying to put a static image into a Shiny app. I have created a folder called www in the working directory of my Shiny app and put a PNG file there. Using the following code should show the image:
library(shiny)
ui <- fluidPage(
tags$img(src='photo.png')
)
server <- function(input, output) {}
shinyApp(ui=ui, server=server)
But instead I have this:
Querying the image URL (http://127.0.0.1:7122/photo.png) directly shows a 404 status code.
The outcome is the same regardless of whether I start the Shiny app by running the code manually, clicking the "Run App" button in RStudio, or executing the file via Rscript app.R on the command line.
Here is the folder structure:
.
├── app.R
└── www
└── photo.png
Am I missing something?
I don't think this is a bug - there is some documentation missing.
The issue here is, that the default resource publishing via the www folder using the / prefix is implemented only for two-file (server.R and ui.R) and single-file (app.R) shiny apps - not for shiny app objects (the object returned by shinyApp()). This makes sense, as in contrast to e.g. the app.R file a shiny app object doesn't reside in a fixed directory.
The www folder to / prefix mapping only takes place if runApp's appDir parameter is provided with a directory or file path (string object). The character method can be seen here. Another relevant function (downstream) can be found here.
Once a shiny app object is passed to runApp's appDir argument we need to use addResourcePath, which is the case when running runApp(shinyApp(ui, server)).
Accordingly the following works:
library(shiny)
addResourcePath("prefix", "www")
ui <- fluidPage(
tags$img(src='prefix/photo.png')
)
server <- function(input, output) {}
appObj <- shinyApp(ui=ui, server=server)
runApp(appObj)
# print(appObj) # also works
It seems that this is a bug in Shiny.
Until this is fixed, there are two rough workaround strategies:
Convince Shiny that www should be mapped in a shinyApp object. To do this, we need to modify the shinyApp object:
library(shiny)
ui <- fluidPage(
tags$img(src = 'photo.png')
)
server <- function(input, output) {}
app <- shinyApp(ui = ui, server = server)
app$staticPaths <- list(
`/` = httpuv::staticPath(
file.path(getwd(), "www"), indexhtml = FALSE, fallthrough = TRUE
)
)
app
(Solution based on a RStudio Community discussion.)
Launch Shiny without using the shinyApp object directly:
by pressing the “Run App” button in RStudio, or
by executing runApp('.') or runApp('app.R').
Other ways of launching the app do not work! Notably, this also includes replacing the last line in the script with runApp(shinyApp(ui, server)).

Error when using file.choose() in Shiny Web App (deployed online)

I am developing this shiny app that needs to push a local file to a FTP. I am having trouble with this.
I am using ftpUpload() to upload, and file.choose() to grab the file path:
ftpUpload(file.choose(new = FALSE), "ftp.com/Abc", userpwd)
This worked fine when I run the app in my local machine. However after I deploy it on the web, it doesn't work. It disconnects the serve.
I am thinking the issues are on file.choose() since the interactive file selection dialog wouldn't show up.
Does anyone know how to get the file.choose() working, or any other solutions?
Again I am trying to push a local file to an FTP server through an online Shiny App.
Update:
I have checked the log and I get this error:
Warning in file(what, "rb") : cannot open file 'xt': No such file or directory
Warning: Error in file: cannot open the connection
I am using a windows. and this error won't appear when I run the app locally from my RStudio
A minimal working solution with fileInput.
# ui.R
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("myFile", "Choose your File")
)
),
mainPanel(
)
)
)
# server.R
server <- function(input, output, session) {
observeEvent(input$myFile,{
selectedFile <- input$myFile
if (is.null(selectedFile))
return(NULL)
# Your code
ftpUpload(selectedFile$datapath, "ftp.com/Abc", userpwd)
})
}
Hope this helps.

Shiny App Google Analytics API connection does not work: no JSON file found

I want to access data in a Shiny App directly via Google Analytics API and now have an google OAuth 2.0 authentication issue.
My approach was the following one:
1) Created a web aplication project in my Google project and downloaded the json File.
2) I added the json file to my app folder. So the structure of my app folder is the following:
app.r
test.json
3) Then I created a .Renviron file in the same app folder. My assumption for the error lays here, since I am not sure if I created it correctly. I created a txt file and named it .Renviron. And I inserted the following line: GAR_CLIENT_WEB_JSON = "test.json"
So now in my app folder are: app.r, test.json, and .Renviron
4) in app.R I have the following code:
library(shiny)
library(googleAuthR)
gar_set_client(scopes = c("https://www.googleapis.com/auth/analytics.readonly"))
# Define UI
ui <- fluidPage(
gar_auth_jsUI("auth")
)
# Define server logic
server <- function(input, output) {
}
# Run the application
shinyApp(ui = ui, server = server)
When testing with Sys.getenv("GAR_CLIENT_WEB_JSON") it always tells me, that it is empty.
And when running the app, I get the following error:
Error in gar_set_client(scopes = c("https://www.googleapis.com/auth/analytics.readonly")) :
No client JSON files found
Does anybody has an idea what I am doing wrong?
Just to confirm if the environment file is created properly, can you try creating your environment file this way:
Open up Notepad, paste in your environment variables
File > Save As...and find your local project folder, then under "Save as type" select "All Files", THEN type the File name ".Renviron"
Try again to see if the environment variable is being read.
Try stating the full/explicit filepath in the the .Renviron file when assigning both "GAR_CLIENT_WEB_JSON" and "GL_AUTH"
Eg:
GL_AUTH="/Users/yourUser/Desktop/yourFoldername/yourFilename.json"
GAR_CLIENT_WEB_JSON="/Users/yourUser/Desktop/yourFoldername/yourFilename.json"
Solved the error in my case.

Static image in Shiny app not found (HTTP status 404)

I'm trying to put a static image into a Shiny app. I have created a folder called www in the working directory of my Shiny app and put a PNG file there. Using the following code should show the image:
library(shiny)
ui <- fluidPage(
tags$img(src='photo.png')
)
server <- function(input, output) {}
shinyApp(ui=ui, server=server)
But instead I have this:
Querying the image URL (http://127.0.0.1:7122/photo.png) directly shows a 404 status code.
The outcome is the same regardless of whether I start the Shiny app by running the code manually, clicking the "Run App" button in RStudio, or executing the file via Rscript app.R on the command line.
Here is the folder structure:
.
├── app.R
└── www
└── photo.png
Am I missing something?
I don't think this is a bug - there is some documentation missing.
The issue here is, that the default resource publishing via the www folder using the / prefix is implemented only for two-file (server.R and ui.R) and single-file (app.R) shiny apps - not for shiny app objects (the object returned by shinyApp()). This makes sense, as in contrast to e.g. the app.R file a shiny app object doesn't reside in a fixed directory.
The www folder to / prefix mapping only takes place if runApp's appDir parameter is provided with a directory or file path (string object). The character method can be seen here. Another relevant function (downstream) can be found here.
Once a shiny app object is passed to runApp's appDir argument we need to use addResourcePath, which is the case when running runApp(shinyApp(ui, server)).
Accordingly the following works:
library(shiny)
addResourcePath("prefix", "www")
ui <- fluidPage(
tags$img(src='prefix/photo.png')
)
server <- function(input, output) {}
appObj <- shinyApp(ui=ui, server=server)
runApp(appObj)
# print(appObj) # also works
It seems that this is a bug in Shiny.
Until this is fixed, there are two rough workaround strategies:
Convince Shiny that www should be mapped in a shinyApp object. To do this, we need to modify the shinyApp object:
library(shiny)
ui <- fluidPage(
tags$img(src = 'photo.png')
)
server <- function(input, output) {}
app <- shinyApp(ui = ui, server = server)
app$staticPaths <- list(
`/` = httpuv::staticPath(
file.path(getwd(), "www"), indexhtml = FALSE, fallthrough = TRUE
)
)
app
(Solution based on a RStudio Community discussion.)
Launch Shiny without using the shinyApp object directly:
by pressing the “Run App” button in RStudio, or
by executing runApp('.') or runApp('app.R').
Other ways of launching the app do not work! Notably, this also includes replacing the last line in the script with runApp(shinyApp(ui, server)).

ERROR: cannot open the connection in R Shiny

I went through all of the steps found here, and even got the following message without error:
Application successfully deployed to https://user-name.shinyapps.io/projectFolder/
However, I get the ERROR: cannot open the connection message when trying to run the program. Here are the contents of the folder (projectFolder) to which I directed R Studio:
ui.R # contains only ui code
server.R # contains only server code
script.R # my full script, which contains global, ui, and server code
gomap.js # used for mapping app
styles.css # used for Shiny App
data.csv # my global data to be hosted on shinyapps.io
Here's a sample of the different scripts:
ui.R
ui <- shinyUI(navbarPage("Tab title", id="nav",
tabPanel("Interactive map",
div(class="outer",
tags$head(
includeCSS("/Users/user/Documents/R/projects/styles.css"),
includeScript("/Users/user/Documents/R/projects/gomap.js")
),
#### more UI code ####
))
))
Might the issue be because of the filepaths above? Do I need to setwd at the top of both the ui.R and server.R files? Or is it because within script.R you can find the full code for ui.R and server.R (perhaps this is redundant and I need to create a global.R file with just the data loading and manipulation?
The overarching question is, how do you break up your files to load onto shinyapps.io?
GBR24, some things you can try:
Relative Paths
Set up your wording directory as to where your ui.R files and server.r files are and then use relative lowercase paths to your subdirectories like css when deploying, not full ones with \user\Me\MyR\Project1\ ...etc.
Path layout example:
directory with ui.r file which will be
--css subdirectory
--data
--www
so when you call your data that you have placed in data subdirectory use:
myfile <- file.path("data", "data.csv")
dat <- read.csv(myfile, header=T)
NO CAPS
This could be a problem with capitalisation of file names and paths. This has just started to happen to me. On deploying in RStudio I get a review issues dialogue when publishing content with a "filepaths are case-sensitive on deployment server warning".
So, for example, Shiny server wants serverhead.R not serverHead.R. Solution is to change your file names to lowercase. It seems to be okay with .R extension capitalised for now.
github windows users: You need to remind Github that you want lowercase so it does not push files back with CaseNotLowered.R
In Gitshell, you force the file name:
git mv -f OldName newname
Thanks to Github Support and answers here.
Look at logs
You can check on your deployment from RStudio using this command for clues. From console command line, with your account and app name:
rsconnect::showLogs(account = "myshinyioaccount", appName = "myapp")
EDIT it was formerly shinyapps::showLogs (thanks conrad-mac)
For example I could see a filename problem before the connection error message:
... 2016-07-12T13:13:26.061123+00:00 shinyapps[555]: Error in file(filename, "r", encoding = encoding) :
2016-07-12T13:13:26.060971+00:00 shinyapps[555]: 2: eval.parent
2016-07-12T13:13:26.061126+00:00 shinyapps[555]: cannot open the connection
Hope this helps!

Resources