lens @ 1d6fa60b3c60d068d12b19f10f5ad73e836b5a70

  1package main
  2
  3import (
  4	"context"
  5	"encoding/hex"
  6	"errors"
  7	"os"
  8	"os/signal"
  9
 10	"github.com/fasthttp/router"
 11	"github.com/sirupsen/logrus"
 12	flag "github.com/spf13/pflag"
 13	"github.com/valyala/fasthttp"
 14	"gorm.io/driver/mysql"
 15	"gorm.io/driver/postgres"
 16	"gorm.io/driver/sqlite"
 17	"gorm.io/gorm"
 18
 19	"git.sr.ht/~gabrielgio/img/pkg/components/auth"
 20	"git.sr.ht/~gabrielgio/img/pkg/components/filesystem"
 21	"git.sr.ht/~gabrielgio/img/pkg/components/media"
 22	"git.sr.ht/~gabrielgio/img/pkg/database/localfs"
 23	"git.sr.ht/~gabrielgio/img/pkg/database/sql"
 24	"git.sr.ht/~gabrielgio/img/pkg/ext"
 25	"git.sr.ht/~gabrielgio/img/pkg/view"
 26	"git.sr.ht/~gabrielgio/img/pkg/worker"
 27)
 28
 29func main() {
 30	var (
 31		key            = flag.String("aes-key", "", "AES key, either 16, 24, or 32 bytes string to select AES-128, AES-192, or AES-256")
 32		dbType         = flag.String("db-type", "sqlite", "Database to be used. Choose either mysql, psql or sqlite")
 33		dbCon          = flag.String("db-con", "main.db", "Database string connection for given database type. Ref: https://gorm.io/docs/connecting_to_the_database.html")
 34		logLevel       = flag.String("log-level", "error", "Log level: Choose either trace, debug, info, warning, error, fatal or panic")
 35		schedulerCount = flag.Uint("scheduler-count", 10, "How many workers are created to process media files")
 36
 37		// TODO: this will later be replaced by user specific root folder
 38		root = flag.String("root", "", "root folder for the whole application. All the workers will use it as working directory")
 39	)
 40
 41	flag.Parse()
 42
 43	l, err := logrus.ParseLevel(*logLevel)
 44	if err != nil {
 45		panic("failed to parse log level" + err.Error())
 46	}
 47	logger := logrus.New()
 48	logger.SetLevel(l)
 49
 50	d, err := OpenDatabase(*dbType, *dbCon)
 51	if err != nil {
 52		panic("failed to parse database strings" + err.Error())
 53	}
 54
 55	db, err := gorm.Open(d, &gorm.Config{
 56		Logger: ext.Wraplog(logger.WithField("context", "sql")),
 57	})
 58	if err != nil {
 59		panic("failed to connect database: " + err.Error())
 60	}
 61
 62	if err = sql.Migrate(db); err != nil {
 63		panic("failed to migrate database: " + err.Error())
 64	}
 65
 66	hexKey, err := hex.DecodeString(*key)
 67	if err != nil {
 68		panic("failed to decode key database: " + err.Error())
 69	}
 70
 71	r := router.New()
 72	r.ServeFiles("/static/{filepath:*}", "./static")
 73	r.NotFound = ext.NotFoundHTML
 74
 75	authMiddleware := ext.NewAuthMiddleware(hexKey, logger.WithField("context", "auth"))
 76	logMiddleware := ext.NewLogMiddleare(logger.WithField("context", "http"))
 77
 78	extRouter := ext.NewRouter(r)
 79	extRouter.AddMiddleware(logMiddleware.HTTP)
 80	extRouter.AddMiddleware(authMiddleware.LoggedIn)
 81	extRouter.AddMiddleware(ext.HTML)
 82
 83	scheduler := worker.NewScheduler(*schedulerCount)
 84
 85	// repository
 86	var (
 87		userRepository       = sql.NewUserRepository(db)
 88		settingsRepository   = sql.NewSettingsRespository(db)
 89		fileSystemRepository = localfs.NewFileSystemRepository(*root)
 90		mediaRepository      = sql.NewMediaRepository(db)
 91	)
 92
 93	//TODO: remove later
 94	userRepository.EnsureAdmin(context.Background())
 95
 96	// controller
 97	var (
 98		userController       = auth.NewController(userRepository, hexKey)
 99		fileSystemController = filesystem.NewController(fileSystemRepository)
100	)
101
102	// view
103	for _, v := range []view.View{
104		view.NewAuthView(userController),
105		view.NewFileSystemView(*fileSystemController, settingsRepository),
106		view.NewSettingsView(settingsRepository),
107		view.NewMediaView(mediaRepository),
108	} {
109		v.SetMyselfIn(extRouter)
110	}
111
112	// worker
113	var (
114		serverWorker = worker.NewServerWorker(&fasthttp.Server{Handler: r.Handler})
115		fileScanner  = worker.NewFileScanner(*root, mediaRepository)
116		exifScanner  = worker.NewEXIFScanner(mediaRepository)
117	)
118
119	pool := worker.NewWorkerPool()
120	pool.AddWorker("http server", serverWorker)
121	pool.AddWorker("exif scanner", worker.NewWorkerFromListProcessor[*media.Media](exifScanner, scheduler))
122	pool.AddWorker("file scanner", worker.NewWorkerFromChanProcessor[string](fileScanner, scheduler))
123
124	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
125	defer stop()
126
127	pool.Start(ctx)
128	pool.Wait()
129}
130
131func OpenDatabase(dbType string, dbConn string) (gorm.Dialector, error) {
132	switch dbType {
133	case "sqlite":
134		return sqlite.Open(dbConn), nil
135	case "psql":
136		return postgres.Open(dbConn), nil
137	case "mysql":
138		return mysql.Open(dbConn), nil
139	default:
140		return nil, errors.New("No valid db type given")
141	}
142}