From a810ada66224c4634e551dc189b18a1c35ccf724 Mon Sep 17 00:00:00 2001
From: prashantsinalkar
Date: Mon, 8 Jul 2019 17:38:51 +0530
Subject: added plot/graph feature

---
 plumber.R | 37 ++++++++++++++++++++++---------------
 1 file changed, 22 insertions(+), 15 deletions(-)

diff --git a/plumber.R b/plumber.R
index 39c6ca4..0f091c8 100644
--- a/plumber.R
+++ b/plumber.R
@@ -6,6 +6,9 @@ library(futile.logger)
 library(tryCatchLog)
 library(ggplot2)
 
+# creare R directory
+dir.create(file.path("/tmp/R"), showWarnings = FALSE)
+
 #* Echo back the input
 #* @param msg The message to echo
 #* @get /echo
@@ -14,25 +17,17 @@ function(msg="")
     list(msg = paste0("The message is: '", msg, "'"))
 }
 
-#* Plot a histogram
-#* @png
-#* @get /plot
-function()
-{
-    rand <- rnorm(100)
-    hist(rand)
-}
-
 #* @serializer unboxedJSON
 #* @post /rscript
-function(code="", session_id="")
+function(code="", session_id="", R_file_id="")
 {
-    dir.create(file.path("/tmp/", session_id), showWarnings = FALSE)
-    InputFile <- paste("/tmp/",session_id,"/",session_id,".R", sep="")
-    OutputFile <- paste("/tmp/",session_id,"/",session_id,".txt", sep="")
+    # create session directory for user
+    dir.create(file.path("/tmp/R/", session_id), showWarnings = FALSE)
+    InputFile <- paste("/tmp/R/",session_id,"/", R_file_id,".R", sep="")
+    OutputFile <- paste("/tmp/R/",session_id,"/", R_file_id,".txt", sep="")
     RunInputFile <- paste("Rscript", InputFile, sep=" ")
     fileConn<-file(InputFile)
-    Line1 = paste("png('/tmp/",session_id,".png')\n", sep="")
+    Line1 = paste("png('/tmp/R/",session_id,"/", R_file_id,".png')\n", sep="")
     Line2 = code
     Line3 = "while (!is.null(dev.list()))  dev.off()"
     writeLines(c(Line1, Line2, Line3), fileConn)
@@ -44,11 +39,23 @@ function(code="", session_id="")
     writeLines(paste0(ro), fileConn)
     close(fileConn)
     ro <- read_file(OutputFile)
-    r<- list(status = "SUCCESS", code = "200", output = ro)
+    if (file.exists(paste("/tmp/R/",session_id,"/",R_file_id,".png", sep="")) == TRUE) {
+        graph_exist <- TRUE
+    } else {
+        graph_exist <- FALSE
+    }
+    r<- list(status = "SUCCESS", code = "200", output = ro, graph_exist = graph_exist)
     return (r)
 }
 
+#* @serializer contentType list(type='image/png')
+#* @get /file
+function(req, res, session_id="", R_file_id=""){
+  file = paste("/tmp/R/",session_id,"/",R_file_id,".png", sep="")
+  readBin(file,'raw',n = file.info(file)$size)
+}
 
+# function to run R script on system
 robust.system <- function (cmd) {
     stderrFile = tempfile(pattern="R_robust.system_stderr", fileext=as.character(Sys.getpid()))
     stdoutFile = tempfile(pattern="R_robust.system_stdout", fileext=as.character(Sys.getpid()))
-- 
cgit