agi.http.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package agi
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path/filepath"
  13. "github.com/robertkrimen/otto"
  14. user "imuslab.com/arozos/mod/user"
  15. )
  16. /*
  17. AJGI HTTP Request Library
  18. This is a library for allowing AGI script to make HTTP Request from the VM
  19. Returning either the head or the body of the request
  20. Author: tobychui
  21. */
  22. func (g *Gateway) HTTPLibRegister() {
  23. err := g.RegisterLib("http", g.injectHTTPFunctions)
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. }
  28. func (g *Gateway) injectHTTPFunctions(vm *otto.Otto, u *user.User) {
  29. vm.Set("_http_get", func(call otto.FunctionCall) otto.Value {
  30. //Get URL from function variable
  31. url, err := call.Argument(0).ToString()
  32. if err != nil {
  33. return otto.NullValue()
  34. }
  35. //Get respond of the url
  36. res, err := http.Get(url)
  37. if err != nil {
  38. return otto.NullValue()
  39. }
  40. bodyContent, err := ioutil.ReadAll(res.Body)
  41. if err != nil {
  42. return otto.NullValue()
  43. }
  44. returnValue, err := vm.ToValue(string(bodyContent))
  45. if err != nil {
  46. return otto.NullValue()
  47. }
  48. return returnValue
  49. })
  50. vm.Set("_http_post", func(call otto.FunctionCall) otto.Value {
  51. //Get URL from function paramter
  52. url, err := call.Argument(0).ToString()
  53. if err != nil {
  54. return otto.NullValue()
  55. }
  56. //Get JSON content from 2nd paramter
  57. sendWithPayload := true
  58. jsonContent, err := call.Argument(1).ToString()
  59. if err != nil {
  60. //Disable the payload send
  61. sendWithPayload = false
  62. }
  63. //Create the request
  64. var req *http.Request
  65. if sendWithPayload {
  66. req, _ = http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonContent)))
  67. } else {
  68. req, _ = http.NewRequest("POST", url, bytes.NewBuffer([]byte("")))
  69. }
  70. req.Header.Set("Content-Type", "application/json")
  71. //Send the request
  72. client := &http.Client{}
  73. resp, err := client.Do(req)
  74. if err != nil {
  75. log.Println(err)
  76. return otto.NullValue()
  77. }
  78. defer resp.Body.Close()
  79. bodyContent, err := ioutil.ReadAll(resp.Body)
  80. if err != nil {
  81. return otto.NullValue()
  82. }
  83. returnValue, _ := vm.ToValue(string(bodyContent))
  84. return returnValue
  85. })
  86. vm.Set("_http_head", func(call otto.FunctionCall) otto.Value {
  87. //Get URL from function paramter
  88. url, err := call.Argument(0).ToString()
  89. if err != nil {
  90. return otto.NullValue()
  91. }
  92. //Request the url
  93. resp, err := http.Get(url)
  94. if err != nil {
  95. return otto.NullValue()
  96. }
  97. headerKey, err := call.Argument(1).ToString()
  98. if err != nil || headerKey == "undefined" {
  99. //No headkey set. Return the whole header as JSON
  100. js, _ := json.Marshal(resp.Header)
  101. log.Println(resp.Header)
  102. returnValue, _ := vm.ToValue(string(js))
  103. return returnValue
  104. } else {
  105. //headerkey is set. Return if exists
  106. possibleValue := resp.Header.Get(headerKey)
  107. js, _ := json.Marshal(possibleValue)
  108. returnValue, _ := vm.ToValue(string(js))
  109. return returnValue
  110. }
  111. })
  112. vm.Set("_http_download", func(call otto.FunctionCall) otto.Value {
  113. //Get URL from function paramter
  114. downloadURL, err := call.Argument(0).ToString()
  115. if err != nil {
  116. return otto.FalseValue()
  117. }
  118. decodedURL, _ := url.QueryUnescape(downloadURL)
  119. //Get download desintation from paramter
  120. vpath, err := call.Argument(1).ToString()
  121. if err != nil {
  122. return otto.FalseValue()
  123. }
  124. //Optional: filename paramter
  125. filename, err := call.Argument(2).ToString()
  126. if err != nil || filename == "undefined" {
  127. //Extract the filename from the url instead
  128. filename = filepath.Base(decodedURL)
  129. }
  130. //Check user acess permission
  131. if !u.CanWrite(vpath) {
  132. g.raiseError(errors.New("Permission Denied"))
  133. return otto.FalseValue()
  134. }
  135. //Convert the vpath to realpath. Check if it exists
  136. rpath, err := u.VirtualPathToRealPath(vpath)
  137. if err != nil {
  138. return otto.FalseValue()
  139. }
  140. if !fileExists(rpath) || !IsDir(rpath) {
  141. g.raiseError(errors.New(vpath + " is a file not a directory."))
  142. return otto.FalseValue()
  143. }
  144. downloadDest := filepath.Join(rpath, filename)
  145. //Ok. Download the file
  146. resp, err := http.Get(decodedURL)
  147. if err != nil {
  148. return otto.FalseValue()
  149. }
  150. defer resp.Body.Close()
  151. // Create the file
  152. out, err := os.Create(downloadDest)
  153. if err != nil {
  154. return otto.FalseValue()
  155. }
  156. defer out.Close()
  157. // Write the body to file
  158. _, err = io.Copy(out, resp.Body)
  159. return otto.TrueValue()
  160. })
  161. //Wrap all the native code function into an imagelib class
  162. vm.Run(`
  163. var http = {};
  164. http.get = _http_get;
  165. http.post = _http_post;
  166. http.head = _http_head;
  167. http.download = _http_download;
  168. `)
  169. }