agi.http.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. "imuslab.com/arozos/mod/filesystem"
  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, scriptFsh *filesystem.FileSystemHandler, scriptPath string) {
  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. 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. //Get target status code for response
  112. vm.Set("_http_code", func(call otto.FunctionCall) otto.Value {
  113. //Get URL from function paramter
  114. url, err := call.Argument(0).ToString()
  115. if err != nil {
  116. return otto.FalseValue()
  117. }
  118. req, err := http.NewRequest("GET", url, nil)
  119. if err != nil {
  120. g.raiseError(err)
  121. return otto.FalseValue()
  122. }
  123. payload := ""
  124. client := new(http.Client)
  125. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  126. //Redirection. Return the target location as well
  127. dest, _ := req.Response.Location()
  128. payload = dest.String()
  129. return errors.New("Redirect")
  130. }
  131. response, err := client.Do(req)
  132. if err != nil {
  133. return otto.FalseValue()
  134. }
  135. defer client.CloseIdleConnections()
  136. vm.Run(`var _location = "` + payload + `";`)
  137. value, _ := otto.ToValue(response.StatusCode)
  138. return value
  139. })
  140. vm.Set("_http_download", func(call otto.FunctionCall) otto.Value {
  141. //Get URL from function paramter
  142. downloadURL, err := call.Argument(0).ToString()
  143. if err != nil {
  144. return otto.FalseValue()
  145. }
  146. decodedURL, _ := url.QueryUnescape(downloadURL)
  147. //Get download desintation from paramter
  148. vpath, err := call.Argument(1).ToString()
  149. if err != nil {
  150. return otto.FalseValue()
  151. }
  152. //Optional: filename paramter
  153. filename, err := call.Argument(2).ToString()
  154. if err != nil || filename == "undefined" {
  155. //Extract the filename from the url instead
  156. filename = filepath.Base(decodedURL)
  157. }
  158. //Check user acess permission
  159. if !u.CanWrite(vpath) {
  160. g.raiseError(errors.New("Permission Denied"))
  161. return otto.FalseValue()
  162. }
  163. //Convert the vpath to realpath. Check if it exists
  164. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  165. if err != nil {
  166. return otto.FalseValue()
  167. }
  168. if !fsh.FileSystemAbstraction.FileExists(rpath) || !fsh.FileSystemAbstraction.IsDir(rpath) {
  169. g.raiseError(errors.New(vpath + " is a file not a directory."))
  170. return otto.FalseValue()
  171. }
  172. downloadDest := filepath.Join(rpath, filename)
  173. //Ok. Download the file
  174. resp, err := http.Get(decodedURL)
  175. if err != nil {
  176. return otto.FalseValue()
  177. }
  178. defer resp.Body.Close()
  179. // Create the file
  180. err = fsh.FileSystemAbstraction.WriteStream(downloadDest, resp.Body, 0775)
  181. if err != nil {
  182. return otto.FalseValue()
  183. }
  184. return otto.TrueValue()
  185. })
  186. vm.Set("_http_getb64", func(call otto.FunctionCall) otto.Value {
  187. //Get URL from function variable and return bytes as base64
  188. url, err := call.Argument(0).ToString()
  189. if err != nil {
  190. return otto.NullValue()
  191. }
  192. //Get respond of the url
  193. res, err := http.Get(url)
  194. if err != nil {
  195. return otto.NullValue()
  196. }
  197. bodyContent, err := ioutil.ReadAll(res.Body)
  198. if err != nil {
  199. return otto.NullValue()
  200. }
  201. sEnc := base64.StdEncoding.EncodeToString(bodyContent)
  202. r, err := otto.ToValue(string(sEnc))
  203. if err != nil {
  204. log.Println(err.Error())
  205. return otto.NullValue()
  206. }
  207. return r
  208. })
  209. //Wrap all the native code function into an imagelib class
  210. vm.Run(`
  211. var http = {};
  212. http.get = _http_get;
  213. http.post = _http_post;
  214. http.head = _http_head;
  215. http.download = _http_download;
  216. http.getb64 = _http_getb64;
  217. http.getCode = _http_code;
  218. `)
  219. }