agi.http.go 5.1 KB

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