agi.http.go 5.9 KB

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