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 "git.sr.ht/~gabrielgio/img/pkg/worker/scanner"
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 cachePath = flag.String("cache-path", "", "Folder to store thumbnail image")
38 )
39
40 flag.Parse()
41
42 l, err := logrus.ParseLevel(*logLevel)
43 if err != nil {
44 panic("failed to parse log level" + err.Error())
45 }
46 logger := logrus.New()
47 logger.SetLevel(l)
48
49 d, err := OpenDatabase(*dbType, *dbCon)
50 if err != nil {
51 panic("failed to parse database strings" + err.Error())
52 }
53
54 db, err := gorm.Open(d, &gorm.Config{
55 Logger: ext.Wraplog(logger.WithField("context", "sql")),
56 })
57 if err != nil {
58 panic("failed to connect database: " + err.Error())
59 }
60
61 if err = sql.Migrate(db); err != nil {
62 panic("failed to migrate database: " + err.Error())
63 }
64
65 hexKey, err := hex.DecodeString(*key)
66 if err != nil {
67 panic("failed to decode key database: " + err.Error())
68 }
69
70 r := router.New()
71 r.GET("/static/{filepath:*}", ext.FileServer(img.StaticFS, "static/"))
72
73 // repository
74 var (
75 userRepository = sql.NewUserRepository(db)
76 settingsRepository = sql.NewSettingsRespository(db)
77 fileSystemRepository = localfs.NewFileSystemRepository()
78 mediaRepository = sql.NewMediaRepository(db)
79 )
80
81 // middleware
82 var (
83 authMiddleware = ext.NewAuthMiddleware(hexKey, logger.WithField("context", "auth"))
84 logMiddleware = ext.NewLogMiddleare(logger.WithField("context", "http"))
85 initialMiddleware = ext.NewInitialSetupMiddleware(userRepository)
86 )
87
88 extRouter := ext.NewRouter(r)
89 extRouter.AddMiddleware(ext.HTML)
90 extRouter.AddMiddleware(initialMiddleware.Check)
91 extRouter.AddMiddleware(authMiddleware.LoggedIn)
92 extRouter.AddMiddleware(logMiddleware.HTTP)
93
94 scheduler := worker.NewScheduler(*schedulerCount)
95
96 // controller
97 var (
98 userController = service.NewAuthController(userRepository, userRepository, hexKey)
99 fileSystemController = service.NewFileSystemController(fileSystemRepository, userRepository)
100 )
101
102 // view
103 for _, v := range []view.View{
104 view.NewAuthView(userController),
105 view.NewFileSystemView(*fileSystemController, settingsRepository),
106 view.NewSettingsView(settingsRepository, userRepository),
107 view.NewMediaView(mediaRepository),
108 } {
109 v.SetMyselfIn(extRouter)
110 }
111
112 // processors
113 var (
114 fileScanner = scanner.NewFileScanner(mediaRepository, userRepository)
115 exifScanner = scanner.NewEXIFScanner(mediaRepository)
116 thumbnailScanner = scanner.NewThumbnailScanner(*cachePath, mediaRepository)
117 )
118
119 // worker
120 var (
121 serverWorker = worker.NewServerWorker(&fasthttp.Server{Handler: r.Handler, NoDefaultContentType: true})
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 thumbnailWorker = worker.NewWorkerFromBatchProcessor[*repository.Media](
133 thumbnailScanner,
134 scheduler,
135 logrus.WithField("context", "thumbnail scanner"),
136 )
137 )
138
139 pool := worker.NewWorkerPool()
140 pool.AddWorker("http server", serverWorker)
141 pool.AddWorker("exif scanner", exifWorker)
142 pool.AddWorker("file scanner", fileWorker)
143 pool.AddWorker("thumbnail scanner", thumbnailWorker)
144
145 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
146 defer stop()
147
148 pool.Start(ctx)
149}
150
151func OpenDatabase(dbType string, dbConn string) (gorm.Dialector, error) {
152 switch dbType {
153 case "sqlite":
154 return sqlite.Open(dbConn), nil
155 case "psql":
156 return postgres.Open(dbConn), nil
157 case "mysql":
158 return mysql.Open(dbConn), nil
159 default:
160 return nil, errors.New("No valid db type given")
161 }
162}