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 // 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.NewWorkerFromListProcessor[*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 pool.Wait()
139}
140
141func OpenDatabase(dbType string, dbConn string) (gorm.Dialector, error) {
142 switch dbType {
143 case "sqlite":
144 return sqlite.Open(dbConn), nil
145 case "psql":
146 return postgres.Open(dbConn), nil
147 case "mysql":
148 return mysql.Open(dbConn), nil
149 default:
150 return nil, errors.New("No valid db type given")
151 }
152}