lens @ ead855b7991b14554eb098616cfac29d91e796eb

  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"
 20	"git.sr.ht/~gabrielgio/img/pkg/components/auth"
 21	"git.sr.ht/~gabrielgio/img/pkg/components/filesystem"
 22	"git.sr.ht/~gabrielgio/img/pkg/components/media"
 23	"git.sr.ht/~gabrielgio/img/pkg/database/localfs"
 24	"git.sr.ht/~gabrielgio/img/pkg/database/sql"
 25	"git.sr.ht/~gabrielgio/img/pkg/ext"
 26	"git.sr.ht/~gabrielgio/img/pkg/view"
 27	"git.sr.ht/~gabrielgio/img/pkg/worker"
 28)
 29
 30func main() {
 31	var (
 32		key            = flag.String("aes-key", "", "AES key, either 16, 24, or 32 bytes string to select AES-128, AES-192, or AES-256")
 33		dbType         = flag.String("db-type", "sqlite", "Database to be used. Choose either mysql, psql or sqlite")
 34		dbCon          = flag.String("db-con", "main.db", "Database string connection for given database type. Ref: https://gorm.io/docs/connecting_to_the_database.html")
 35		logLevel       = flag.String("log-level", "error", "Log level: Choose either trace, debug, info, warning, error, fatal or panic")
 36		schedulerCount = flag.Uint("scheduler-count", 10, "How many workers are created to process media files")
 37
 38		// TODO: this will later be replaced by user specific root folder
 39		root = flag.String("root", "", "root folder for the whole application. All the workers will use it as working directory")
 40	)
 41
 42	flag.Parse()
 43
 44	l, err := logrus.ParseLevel(*logLevel)
 45	if err != nil {
 46		panic("failed to parse log level" + err.Error())
 47	}
 48	logger := logrus.New()
 49	logger.SetLevel(l)
 50
 51	d, err := OpenDatabase(*dbType, *dbCon)
 52	if err != nil {
 53		panic("failed to parse database strings" + err.Error())
 54	}
 55
 56	db, err := gorm.Open(d, &gorm.Config{
 57		Logger: ext.Wraplog(logger.WithField("context", "sql")),
 58	})
 59	if err != nil {
 60		panic("failed to connect database: " + err.Error())
 61	}
 62
 63	if err = sql.Migrate(db); err != nil {
 64		panic("failed to migrate database: " + err.Error())
 65	}
 66
 67	hexKey, err := hex.DecodeString(*key)
 68	if err != nil {
 69		panic("failed to decode key database: " + err.Error())
 70	}
 71
 72	r := router.New()
 73	r.GET("/static/{filepath:*}", ext.FileServer(img.StaticFS, "static/"))
 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	// processors
113	var (
114		fileScanner = worker.NewFileScanner(*root, mediaRepository)
115		exifScanner = worker.NewEXIFScanner(mediaRepository)
116	)
117
118	// worker
119	var (
120		serverWorker = worker.NewServerWorker(&fasthttp.Server{Handler: r.Handler})
121		fileWorker   = worker.NewWorkerFromChanProcessor[string](fileScanner, scheduler)
122		exifWorker   = worker.NewWorkerFromBatchProcessor[*media.Media](
123			exifScanner,
124			scheduler,
125			logrus.WithField("context", "exif scanner"),
126		)
127	)
128
129	pool := worker.NewWorkerPool()
130	pool.AddWorker("http server", serverWorker)
131	pool.AddWorker("exif scanner", exifWorker)
132	pool.AddWorker("file scanner", fileWorker)
133
134	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
135	defer stop()
136
137	pool.Start(ctx)
138}
139
140func OpenDatabase(dbType string, dbConn string) (gorm.Dialector, error) {
141	switch dbType {
142	case "sqlite":
143		return sqlite.Open(dbConn), nil
144	case "psql":
145		return postgres.Open(dbConn), nil
146	case "mysql":
147		return mysql.Open(dbConn), nil
148	default:
149		return nil, errors.New("No valid db type given")
150	}
151}