-
Notifications
You must be signed in to change notification settings - Fork 10
/
webserver.go
300 lines (263 loc) · 6.82 KB
/
webserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package webserver
import (
"embed"
"encoding/json"
"fmt"
"github.com/aetaric/checkrr/logging"
"io/fs"
"net/http"
"strings"
"sync"
"time"
"github.com/aetaric/checkrr/check"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/robfig/cron/v3"
"github.com/spf13/viper"
bolt "go.etcd.io/bbolt"
)
//go:embed build
var staticFS embed.FS
var fileInfo [][]string
var baseurl BaseURL
var db *bolt.DB
var scheduler *cron.Cron
var cronEntry cron.EntryID
var checkrrInstance *check.Checkrr
var checkrrLogger *logging.Log
type Webserver struct {
Port int
BaseURL BaseURL
tls bool
cert string
key string
data chan []string
trustedProxies []string
DB *bolt.DB
}
type BaseURL string
// EnforceTrailingSlash ensures that the base URL has a trailing slash.
func (b BaseURL) EnforceTrailingSlash() BaseURL {
if !strings.HasSuffix(string(b), "/") {
return BaseURL(string(b) + "/")
}
return b
}
// String returns the base URL as a string.
func (b BaseURL) String() string {
return string(b)
}
func (w *Webserver) FromConfig(conf *viper.Viper, c chan []string, checkrr *check.Checkrr) {
w.Port = conf.GetInt("port")
w.tls = conf.GetBool("tls")
if w.tls {
w.key = conf.Sub("certs").GetString("key")
w.cert = conf.Sub("certs").GetString("cert")
}
w.BaseURL = BaseURL(conf.GetString("baseurl")).EnforceTrailingSlash()
baseurl = w.BaseURL
if conf.GetStringSlice("trustedproxies") != nil {
w.trustedProxies = conf.GetStringSlice("trustedproxies")
} else {
w.trustedProxies = nil
}
w.data = c
db = w.DB
checkrrInstance = checkrr
checkrrLogger = checkrr.Logger
}
func (w *Webserver) AddScehduler(cron *cron.Cron, entryid cron.EntryID) {
scheduler = cron
cronEntry = entryid
}
func (w *Webserver) Run() {
// Build a waitgroup so we can have a webserver and a chan processor
wg := new(sync.WaitGroup)
wg.Add(2)
// Webserver
go func() {
createServer(w)
wg.Done()
}()
// chan processor
go func() {
for data := range w.data {
fileInfo = append(fileInfo, data)
}
wg.Done()
}()
wg.Wait()
}
func createServer(w *Webserver) *gin.Engine {
embeddedBuildFolder := newStaticFileSystem()
// use debug mode if chekrr.debug is true
if viper.Sub("checkrr").GetBool("debug") {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
router := gin.Default()
router.SetTrustedProxies(w.trustedProxies)
router.Use(static.Serve(w.BaseURL.String(), embeddedBuildFolder))
api := router.Group(w.BaseURL.String() + "api")
api.GET("/files/bad", getBadFiles)
api.POST("/files/bad", deleteBadFiles)
api.GET("/stats/current", getCurrentStats)
api.GET("/stats/historical", getHistoricalStats)
api.GET("/schedule", getSchedule)
api.POST("/run", runCheckrr)
if w.tls {
router.RunTLS(fmt.Sprintf(":%v", w.Port), w.cert, w.key)
} else {
router.Run(fmt.Sprintf(":%v", w.Port))
}
return router
}
func getBadFiles(ctx *gin.Context) {
var files []badFileData
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Checkrr-files"))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
bad := check.BadFile{}
json.Unmarshal(v, &bad)
badfiledata := badFileData{Path: string(k), Data: &bad}
files = append(files, badfiledata)
}
return nil
})
if err != nil {
checkrrLogger.Fatalf("Error accessing database: %v", err.Error())
}
ctx.JSON(200, files)
}
func deleteBadFiles(ctx *gin.Context) {
var files []badFileData
var postData []int
ctx.BindJSON(&postData)
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Checkrr-files"))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
bad := check.BadFile{}
json.Unmarshal(v, &bad)
badfiledata := badFileData{Path: string(k), Data: &bad}
files = append(files, badfiledata)
}
return nil
})
if err != nil {
checkrrLogger.Fatalf("Error accessing database: %v", err.Error())
}
for _, v := range postData {
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Checkrr-files"))
b.Delete([]byte(files[v-1].Path))
return nil
})
}
ctx.JSON(200, files)
}
func getCurrentStats(ctx *gin.Context) {
var stats *Stats
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Checkrr-stats"))
statdata := b.Get([]byte("current-stats"))
s := Stats{}
json.Unmarshal(statdata, &s)
stats = &s
return nil
})
if err != nil {
checkrrLogger.Fatalf("Error accessing database: %v", err.Error())
}
ctx.JSON(200, stats)
}
func getHistoricalStats(ctx *gin.Context) {
var stats []statData
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Checkrr-stats"))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
s := Stats{}
json.Unmarshal(v, &s)
stat := statData{Timestamp: string(k), Data: &s}
stats = append(stats, stat)
}
return nil
})
for len(stats) > 30 {
_, stats = stats[0], stats[1:]
}
if err != nil {
checkrrLogger.Fatalf("Error accessing database: %v", err.Error())
}
ctx.JSON(200, stats)
}
func getSchedule(ctx *gin.Context) {
if scheduler != nil {
nextRun := scheduler.Entry(cronEntry).Next.UTC().String()
ctx.JSON(200, nextRun)
} else {
ctx.JSON(200, nil)
}
}
func runCheckrr(ctx *gin.Context) {
go checkrrInstance.Run()
ctx.JSON(200, nil)
}
// file system code
type staticFileSystem struct {
http.FileSystem
}
var _ static.ServeFileSystem = (*staticFileSystem)(nil)
func newStaticFileSystem() *staticFileSystem {
sub, err := fs.Sub(staticFS, "build")
if err != nil {
panic(err)
}
return &staticFileSystem{
FileSystem: http.FS(sub),
}
}
func (s *staticFileSystem) Exists(prefix string, path string) bool {
buildpath := ""
if baseurl == "/" {
buildpath = fmt.Sprintf("build%s", path)
} else {
buildpath = fmt.Sprintf("build/%s", strings.TrimPrefix(path, baseurl.String()))
}
// support for folders
if strings.HasSuffix(path, "/") {
_, err := staticFS.ReadDir(strings.TrimSuffix(buildpath, "/"))
return err == nil
}
// support for files
f, err := staticFS.Open(buildpath)
if f != nil {
_ = f.Close()
}
return err == nil
}
type statData struct {
Timestamp string
Data *Stats
}
type badFileData struct {
Path string
Data *check.BadFile
}
type Stats struct {
SonarrSubmissions uint64 `json:"sonarrSubmissions"`
RadarrSubmissions uint64 `json:"radarrSubmissions"`
LidarrSubmissions uint64 `json:"lidarrSubmissions"`
FilesChecked uint64 `json:"filesChecked"`
HashMatches uint64 `json:"hashMatches"`
HashMismatches uint64 `json:"hashMismatches"`
VideoFiles uint64 `json:"videoFiles"`
AudioFiles uint64 `json:"audioFiles"`
UnknownFileCount uint64 `json:"unknownFileCount"`
NonVideo uint64 `json:"nonVideo"`
Running bool `json:"running"`
Diff time.Duration `json:"timeDiff"`
}