agi.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package main
  2. import (
  3. "net/http"
  4. "path/filepath"
  5. "strconv"
  6. "time"
  7. agi "imuslab.com/arozos/mod/agi"
  8. "imuslab.com/arozos/mod/email"
  9. "imuslab.com/arozos/mod/git"
  10. "imuslab.com/arozos/mod/notification"
  11. prout "imuslab.com/arozos/mod/prouter"
  12. "imuslab.com/arozos/mod/utils"
  13. )
  14. var (
  15. AGIGateway *agi.Gateway
  16. mailBackend *email.Manager //Mail client backend, closed on shutdown
  17. )
  18. func AGIInit() {
  19. //Create the version control backend used by the AGI git library and the
  20. //GitApp WebApp. A failure here only disables git support, so the rest of
  21. //the gateway still starts.
  22. gitManager, err := git.NewManager(git.Options{
  23. Database: sysdb,
  24. KeyStorePath: filepath.Join("./system", "git"),
  25. Logger: systemWideLogger,
  26. })
  27. if err != nil {
  28. systemWideLogger.PrintAndLog("AGI", "Git support disabled", err)
  29. gitManager = nil
  30. }
  31. //Create the mail client backend used by the AGI email library and the Mail
  32. //WebApp. It keeps its own database and key under ./system/mail, so the
  33. //shared AGI database helpers can never reach anyone's mail accounts.
  34. emailManager, err := email.NewManager(email.Options{
  35. DataDir: filepath.Join("./system", "mail"),
  36. Notify: func(username string, title string, message string) {
  37. sendUserNotification(&notification.NotificationPayload{
  38. ID: "mail-" + strconv.FormatInt(time.Now().UnixNano(), 10),
  39. Title: title,
  40. Message: message,
  41. Receiver: []string{username},
  42. Sender: "Mail",
  43. Priority: notification.PriorityHigh,
  44. Timestamp: time.Now().Unix(),
  45. })
  46. },
  47. })
  48. if err != nil {
  49. systemWideLogger.PrintAndLog("AGI", "Mail support disabled", err)
  50. emailManager = nil
  51. }
  52. mailBackend = emailManager
  53. //Create new AGI Gateway object
  54. gw, err := agi.NewGateway(agi.AgiSysInfo{
  55. BuildVersion: build_version,
  56. InternalVersion: internal_version,
  57. LoadedModule: moduleHandler.GetModuleNameList(),
  58. ReservedTables: []string{"auth", "permisson", "register", "desktop"},
  59. ModuleRegisterParser: moduleHandler.RegisterModuleFromAGI,
  60. ModuleFolderResolver: moduleHandler.GetModulesFromSourceFolder,
  61. ScriptFolderDisabled: moduleHandler.IsSourceFolderDisabled,
  62. ExtIconRegisterParser: moduleHandler.RegisterExtIcon,
  63. ModuleListProvider: moduleHandler.GetModuleListJSONForUser,
  64. PackageManager: packageManager,
  65. Logger: systemWideLogger,
  66. UserHandler: userHandler,
  67. StartupRoot: "./web",
  68. ActivateScope: []string{"./web", "./subservice"},
  69. FileSystemRender: thumbRenderHandler,
  70. ShareManager: shareManager,
  71. NightlyManager: nightlyManager,
  72. MeetRoomManager: meetRoomManager,
  73. SharedSpaceManager: sharedSpaceManager,
  74. GitManager: gitManager,
  75. EmailManager: emailManager,
  76. TempFolderPath: *tmp_directory,
  77. NotificationSender: sendUserNotification,
  78. })
  79. if err != nil {
  80. systemWideLogger.PrintAndLog("AGI", "AGI Gateway Initialization Failed", err)
  81. }
  82. //Register user request handler endpoint
  83. http.HandleFunc("/system/ajgi/interface", func(w http.ResponseWriter, r *http.Request) {
  84. //Require login check
  85. authAgent.HandleCheckAuth(w, r, func(w http.ResponseWriter, r *http.Request) {
  86. //API Call from actual human users
  87. thisuser, _ := gw.Option.UserHandler.GetUserInfoFromRequest(w, r)
  88. gw.InterfaceHandler(w, r, thisuser)
  89. })
  90. })
  91. //Register external API request handler endpoint
  92. http.HandleFunc("/api/ajgi/interface", func(w http.ResponseWriter, r *http.Request) {
  93. //Check if token exists
  94. token, err := utils.PostPara(r, "token")
  95. if err != nil {
  96. w.WriteHeader(http.StatusUnauthorized)
  97. w.Write([]byte("401 - Unauthorized (token is empty)"))
  98. return
  99. }
  100. //Validate Token
  101. if authAgent.TokenValid(token) {
  102. //Valid
  103. thisUsername, err := gw.Option.UserHandler.GetAuthAgent().GetTokenOwner(token)
  104. if err != nil {
  105. systemWideLogger.PrintAndLog("AGI", "Unable to validate token owner", err)
  106. w.WriteHeader(http.StatusInternalServerError)
  107. w.Write([]byte("500 - Internal Server Error"))
  108. return
  109. }
  110. thisuser, _ := gw.Option.UserHandler.GetUserInfoFromUsername(thisUsername)
  111. gw.APIHandler(w, r, thisuser)
  112. } else {
  113. w.WriteHeader(http.StatusUnauthorized)
  114. w.Write([]byte("401 - Unauthorized (Invalid / expired token)"))
  115. return
  116. }
  117. })
  118. http.HandleFunc("/api/ajgi/exec", gw.HandleAgiExecutionRequestWithToken)
  119. // external AGI related function
  120. externalAGIRouter := prout.NewModuleRouter(prout.RouterOption{
  121. ModuleName: "ARZ Serverless",
  122. AdminOnly: false,
  123. UserHandler: userHandler,
  124. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  125. errorHandlePermissionDenied(w, r)
  126. },
  127. })
  128. externalAGIRouter.HandleFunc("/api/ajgi/listExt", gw.ListExternalEndpoint)
  129. externalAGIRouter.HandleFunc("/api/ajgi/addExt", gw.AddExternalEndPoint)
  130. externalAGIRouter.HandleFunc("/api/ajgi/rmExt", gw.RemoveExternalEndPoint)
  131. externalAGIRouter.HandleFunc("/api/ajgi/stats", gw.GetEndpointStats)
  132. AGIGateway = gw
  133. }