memos/server/server.go

187 lines
4.9 KiB
Go
Raw Normal View History

2022-02-03 15:32:03 +08:00
package server
import (
2023-01-02 23:18:12 +08:00
"context"
2022-02-03 15:32:03 +08:00
"fmt"
"net/http"
2023-09-17 19:20:03 +08:00
"strings"
2022-02-04 18:54:24 +08:00
"time"
2022-02-03 15:32:03 +08:00
"github.com/google/uuid"
"github.com/labstack/echo/v4"
2023-01-02 23:18:12 +08:00
"github.com/pkg/errors"
2023-09-17 22:55:13 +08:00
"github.com/usememos/memos/plugin/telegram"
"github.com/usememos/memos/server/integration"
2022-06-27 22:09:06 +08:00
"github.com/usememos/memos/server/profile"
2024-02-29 01:32:59 +08:00
apiv1 "github.com/usememos/memos/server/route/api/v1"
apiv2 "github.com/usememos/memos/server/route/api/v2"
"github.com/usememos/memos/server/route/frontend"
2023-11-06 20:49:02 +08:00
versionchecker "github.com/usememos/memos/server/service/version_checker"
2022-06-27 22:09:06 +08:00
"github.com/usememos/memos/store"
2022-02-03 15:32:03 +08:00
)
type Server struct {
e *echo.Echo
2022-02-03 15:32:03 +08:00
ID string
Secret string
Profile *profile.Profile
Store *store.Store
2023-07-30 09:53:24 +08:00
// Asynchronous runners.
2023-12-19 22:34:06 +08:00
telegramBot *telegram.Bot
2022-02-03 15:32:03 +08:00
}
func NewServer(ctx context.Context, profile *profile.Profile, store *store.Store) (*Server, error) {
2022-02-03 15:32:03 +08:00
e := echo.New()
e.Debug = true
e.HideBanner = true
2022-05-20 22:48:36 +08:00
e.HidePort = true
2022-02-03 15:32:03 +08:00
2023-02-03 10:30:18 +08:00
s := &Server{
e: e,
Store: store,
2023-02-03 10:30:18 +08:00
Profile: profile,
2023-07-30 09:53:24 +08:00
// Asynchronous runners.
telegramBot: telegram.NewBotWithHandler(integration.NewTelegramHandler(store)),
}
2024-02-29 23:54:43 +08:00
// Register CORS middleware.
2024-02-04 23:48:26 +08:00
e.Use(CORSMiddleware())
serverID, err := s.getSystemServerID(ctx)
if err != nil {
2023-09-17 22:55:13 +08:00
return nil, errors.Wrap(err, "failed to retrieve system server ID")
}
s.ID = serverID
2022-02-03 15:32:03 +08:00
secret := "usememos"
2022-05-02 09:40:25 +08:00
if profile.Mode == "prod" {
secret, err = s.getSystemSecretSessionName(ctx)
if err != nil {
2023-09-17 22:55:13 +08:00
return nil, errors.Wrap(err, "failed to retrieve system secret session name")
}
2022-03-29 07:30:29 +08:00
}
s.Secret = secret
2023-11-26 23:06:50 +08:00
// Register healthz endpoint.
e.GET("/healthz", func(c echo.Context) error {
2023-11-26 23:33:34 +08:00
return c.String(http.StatusOK, "Service ready.")
2023-11-26 23:06:50 +08:00
})
2024-02-29 23:54:43 +08:00
// Only serve frontend when it's enabled.
if profile.Frontend {
frontendService := frontend.NewFrontendService(profile, store)
frontendService.Serve(ctx, e)
}
2023-11-26 23:06:50 +08:00
// Register API v1 endpoints.
rootGroup := e.Group("")
apiV1Service := apiv1.NewAPIV1Service(s.Secret, profile, store, s.telegramBot)
apiV1Service.Register(rootGroup)
2023-12-15 07:32:49 +08:00
apiV2Service := apiv2.NewAPIV2Service(s.Secret, profile, store, s.Profile.Port+1)
// Register gRPC gateway as api v2.
2023-12-15 07:32:49 +08:00
if err := apiV2Service.RegisterGateway(ctx, e); err != nil {
2023-09-17 22:55:13 +08:00
return nil, errors.Wrap(err, "failed to register gRPC gateway")
}
return s, nil
2022-02-03 15:32:03 +08:00
}
func (s *Server) Start(ctx context.Context) error {
2023-11-06 22:33:12 +08:00
go versionchecker.NewVersionChecker(s.Store, s.Profile).Start(ctx)
go s.telegramBot.Start(ctx)
return s.e.Start(fmt.Sprintf("%s:%d", s.Profile.Addr, s.Profile.Port))
2023-01-01 21:32:17 +08:00
}
2023-01-02 23:18:12 +08:00
2023-02-03 10:30:18 +08:00
func (s *Server) Shutdown(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
// Shutdown echo server
if err := s.e.Shutdown(ctx); err != nil {
fmt.Printf("failed to shutdown server, error: %v\n", err)
}
// Close database connection
if err := s.Store.Close(); err != nil {
2023-02-03 10:30:18 +08:00
fmt.Printf("failed to close database, error: %v\n", err)
}
fmt.Printf("memos stopped properly\n")
}
func (s *Server) GetEcho() *echo.Echo {
return s.e
}
func (s *Server) getSystemServerID(ctx context.Context) (string, error) {
serverIDSetting, err := s.Store.GetWorkspaceSetting(ctx, &store.FindWorkspaceSetting{
Name: apiv1.SystemSettingServerIDName.String(),
})
2023-07-06 22:53:38 +08:00
if err != nil {
return "", err
}
if serverIDSetting == nil || serverIDSetting.Value == "" {
serverIDSetting, err = s.Store.UpsertWorkspaceSetting(ctx, &store.WorkspaceSetting{
Name: apiv1.SystemSettingServerIDName.String(),
Value: uuid.NewString(),
})
if err != nil {
return "", err
}
}
return serverIDSetting.Value, nil
}
func (s *Server) getSystemSecretSessionName(ctx context.Context) (string, error) {
secretSessionNameValue, err := s.Store.GetWorkspaceSetting(ctx, &store.FindWorkspaceSetting{
Name: apiv1.SystemSettingSecretSessionName.String(),
})
2023-07-06 22:53:38 +08:00
if err != nil {
return "", err
}
if secretSessionNameValue == nil || secretSessionNameValue.Value == "" {
secretSessionNameValue, err = s.Store.UpsertWorkspaceSetting(ctx, &store.WorkspaceSetting{
Name: apiv1.SystemSettingSecretSessionName.String(),
Value: uuid.NewString(),
})
if err != nil {
return "", err
}
}
return secretSessionNameValue.Value, nil
}
2023-09-17 19:20:03 +08:00
func grpcRequestSkipper(c echo.Context) bool {
return strings.HasPrefix(c.Request().URL.Path, "/memos.api.v2.")
}
2024-02-04 23:48:26 +08:00
func CORSMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if grpcRequestSkipper(c) {
return next(c)
}
r := c.Request()
w := c.Response().Writer
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
2024-02-05 06:10:10 +08:00
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
2024-02-04 23:48:26 +08:00
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
// If it's preflight request, return immediately.
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return nil
}
2024-02-05 06:10:10 +08:00
return next(c)
2024-02-04 23:48:26 +08:00
}
}
}