agi.go 4.8 KB

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