agi.http.go 5.1 KB

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