agi.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. ExtIconRegisterParser: moduleHandler.RegisterExtIcon,
  62. ModuleListProvider: moduleHandler.GetModuleListJSONForUser,
  63. PackageManager: packageManager,
  64. Logger: systemWideLogger,
  65. UserHandler: userHandler,
  66. StartupRoot: "./web",
  67. ActivateScope: []string{"./web", "./subservice"},
  68. FileSystemRender: thumbRenderHandler,
  69. ShareManager: shareManager,
  70. NightlyManager: nightlyManager,
  71. MeetRoomManager: meetRoomManager,
  72. SharedSpaceManager: sharedSpaceManager,
  73. GitManager: gitManager,
  74. EmailManager: emailManager,
  75. TempFolderPath: *tmp_directory,
  76. NotificationSender: sendUserNotification,
  77. })
  78. if err != nil {
  79. systemWideLogger.PrintAndLog("AGI", "AGI Gateway Initialization Failed", err)
  80. }
  81. //Register user request handler endpoint
  82. http.HandleFunc("/system/ajgi/interface", func(w http.ResponseWriter, r *http.Request) {
  83. //Require login check
  84. authAgent.HandleCheckAuth(w, r, func(w http.ResponseWriter, r *http.Request) {
  85. //API Call from actual human users
  86. thisuser, _ := gw.Option.UserHandler.GetUserInfoFromRequest(w, r)
  87. gw.InterfaceHandler(w, r, thisuser)
  88. })
  89. })
  90. //Register external API request handler endpoint
  91. http.HandleFunc("/api/ajgi/interface", func(w http.ResponseWriter, r *http.Request) {
  92. //Check if token exists
  93. token, err := utils.PostPara(r, "token")
  94. if err != nil {
  95. w.WriteHeader(http.StatusUnauthorized)
  96. w.Write([]byte("401 - Unauthorized (token is empty)"))
  97. return
  98. }
  99. //Validate Token
  100. if authAgent.TokenValid(token) {
  101. //Valid
  102. thisUsername, err := gw.Option.UserHandler.GetAuthAgent().GetTokenOwner(token)
  103. if err != nil {
  104. systemWideLogger.PrintAndLog("AGI", "Unable to validate token owner", err)
  105. w.WriteHeader(http.StatusInternalServerError)
  106. w.Write([]byte("500 - Internal Server Error"))
  107. return
  108. }
  109. thisuser, _ := gw.Option.UserHandler.GetUserInfoFromUsername(thisUsername)
  110. gw.APIHandler(w, r, thisuser)
  111. } else {
  112. w.WriteHeader(http.StatusUnauthorized)
  113. w.Write([]byte("401 - Unauthorized (Invalid / expired token)"))
  114. return
  115. }
  116. })
  117. http.HandleFunc("/api/ajgi/exec", gw.HandleAgiExecutionRequestWithToken)
  118. // external AGI related function
  119. externalAGIRouter := prout.NewModuleRouter(prout.RouterOption{
  120. ModuleName: "ARZ Serverless",
  121. AdminOnly: false,
  122. UserHandler: userHandler,
  123. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  124. errorHandlePermissionDenied(w, r)
  125. },
  126. })
  127. externalAGIRouter.HandleFunc("/api/ajgi/listExt", gw.ListExternalEndpoint)
  128. externalAGIRouter.HandleFunc("/api/ajgi/addExt", gw.AddExternalEndPoint)
  129. externalAGIRouter.HandleFunc("/api/ajgi/rmExt", gw.RemoveExternalEndPoint)
  130. externalAGIRouter.HandleFunc("/api/ajgi/stats", gw.GetEndpointStats)
  131. AGIGateway = gw
  132. }