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/database/localfs"
21 "git.sr.ht/~gabrielgio/img/pkg/database/repository"
22 "git.sr.ht/~gabrielgio/img/pkg/database/sql"
23 "git.sr.ht/~gabrielgio/img/pkg/ext"
24 "git.sr.ht/~gabrielgio/img/pkg/service"
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.GET("/static/{filepath:*}", ext.FileServer(img.StaticFS, "static/"))
73
74 // repository
75 var (
76 userRepository = sql.NewUserRepository(db)
77 settingsRepository = sql.NewSettingsRespository(db)
78 fileSystemRepository = localfs.NewFileSystemRepository(*root)
79 mediaRepository = sql.NewMediaRepository(db)
80 )
81
82 // middleware
83 var (
84 authMiddleware = ext.NewAuthMiddleware(hexKey, logger.WithField("context", "auth"))
85 logMiddleware = ext.NewLogMiddleare(logger.WithField("context", "http"))
86 initialMiddleware = ext.NewInitialSetupMiddleware(userRepository)
87 )
88
89 extRouter := ext.NewRouter(r)
90 extRouter.AddMiddleware(ext.HTML)
91 extRouter.AddMiddleware(initialMiddleware.Check)
92 extRouter.AddMiddleware(authMiddleware.LoggedIn)
93 extRouter.AddMiddleware(logMiddleware.HTTP)
94
95 scheduler := worker.NewScheduler(*schedulerCount)
96
97 // controller
98 var (
99 userController = service.NewAuthController(userRepository, userRepository, hexKey)
100 fileSystemController = service.NewFileSystemController(fileSystemRepository)
101 )
102
103 // view
104 for _, v := range []view.View{
105 view.NewAuthView(userController),
106 view.NewFileSystemView(*fileSystemController, settingsRepository),
107 view.NewSettingsView(settingsRepository, userRepository),
108 view.NewMediaView(mediaRepository),
109 } {
110 v.SetMyselfIn(extRouter)
111 }
112
113 // processors
114 var (
115 fileScanner = worker.NewFileScanner(*root, mediaRepository)
116 exifScanner = worker.NewEXIFScanner(mediaRepository)
117 )
118
119 // worker
120 var (
121 serverWorker = worker.NewServerWorker(&fasthttp.Server{Handler: r.Handler})
122 fileWorker = worker.NewWorkerFromChanProcessor[string](
123 fileScanner,
124 scheduler,
125 logrus.WithField("context", "file scanner"),
126 )
127 exifWorker = worker.NewWorkerFromBatchProcessor[*repository.Media](
128 exifScanner,
129 scheduler,
130 logrus.WithField("context", "exif scanner"),
131 )
132 )
133
134 pool := worker.NewWorkerPool()
135 pool.AddWorker("http server", serverWorker)
136 pool.AddWorker("exif scanner", exifWorker)
137 pool.AddWorker("file scanner", fileWorker)
138
139 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
140 defer stop()
141
142 pool.Start(ctx)
143}
144
145func OpenDatabase(dbType string, dbConn string) (gorm.Dialector, error) {
146 switch dbType {
147 case "sqlite":
148 return sqlite.Open(dbConn), nil
149 case "psql":
150 return postgres.Open(dbConn), nil
151 case "mysql":
152 return mysql.Open(dbConn), nil
153 default:
154 return nil, errors.New("No valid db type given")
155 }
156}