-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
234 lines (197 loc) · 6.17 KB
/
main.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
// main.go
package main
import (
"context"
"embed"
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"time"
"github.com/DblK/tinshop/api"
"github.com/DblK/tinshop/config"
collection "github.com/DblK/tinshop/gamescollection"
"github.com/DblK/tinshop/repository"
"github.com/DblK/tinshop/sources"
"github.com/DblK/tinshop/stats"
"github.com/DblK/tinshop/utils"
"github.com/gorilla/mux"
)
//go:embed assets/*
var assetData embed.FS //nolint:gochecknoglobals
// TinShop holds all information about the Shop
type TinShop struct {
Shop repository.Shop
Server *http.Server
}
func main() {
shop := createShop()
// Run our server in a goroutine so that it doesn't block.
go func() {
if err := shop.Server.ListenAndServe(); err != nil {
log.Println(err)
}
}()
log.Printf("Total of %d files in your library (%d in titledb section)\n", len(shop.Shop.Collection.Games().Files), len(shop.Shop.Collection.Games().Titledb))
var uniqueGames = shop.Shop.Collection.CountGames()
log.Printf("Total of %d unique games in your library\n", uniqueGames)
log.Printf("Tinshop available at %s !\n", shop.Shop.Config.RootShop())
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15) //nolint:gomnd
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
_ = shop.Server.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
log.Println("shutting down")
os.Exit(0) //nolint:gocritic
}
func createShop() TinShop {
var shop = &TinShop{}
shop.Shop = initShop()
r := mux.NewRouter()
r.HandleFunc("/", shop.HomeHandler)
r.HandleFunc("/games/{game}", shop.GamesHandler)
r.HandleFunc("/{filter}", shop.FilteringHandler)
r.HandleFunc("/{filter}/", shop.FilteringHandler)
r.HandleFunc("/api/{endpoint}", shop.APIHandler)
r.NotFoundHandler = http.HandlerFunc(notFound)
r.MethodNotAllowedHandler = http.HandlerFunc(notAllowed)
r.Use(shop.StatsMiddleware)
r.Use(shop.TinfoilMiddleware)
r.Use(shop.CORSMiddleware)
http.Handle("/", r)
var port = 3000
if shop.Shop.Config.Port() != 0 {
port = shop.Shop.Config.Port()
}
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:" + strconv.Itoa(port),
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: 0, // Installing large game can take a lot of time
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
}
shop.Server = srv
return *shop
}
// ResetTinshop reset the storage for all information
// func ResetTinshop(myShop repository.Shop) {
// shopData = myShop
// }
func initShop() repository.Shop {
// Init shop data
myShop := repository.Shop{}
myShop.Config = config.New()
myShop.Collection = collection.New(myShop.Config)
myShop.Sources = sources.New(myShop.Collection)
myShop.Stats = stats.New()
myShop.API = api.New()
// Load collection
myShop.Collection.Load()
// Loading config
myShop.Config.AddHook(myShop.Collection.OnConfigUpdate)
myShop.Config.AddHook(myShop.Sources.OnConfigUpdate)
myShop.Config.AddBeforeHook(myShop.Sources.BeforeConfigUpdate)
myShop.Config.LoadConfig()
// Loading stats
myShop.Stats.Load()
return myShop
}
func notFound(w http.ResponseWriter, r *http.Request) {
log.Println("notFound")
log.Println(r.Header)
log.Println(r.RequestURI)
w.WriteHeader(http.StatusNotFound)
}
func notAllowed(w http.ResponseWriter, r *http.Request) {
log.Println("notAllowed")
log.Println(r.Header)
log.Println(r.RequestURI)
w.WriteHeader(http.StatusMethodNotAllowed)
}
func serveCollection(w http.ResponseWriter, tinfoilCollection interface{}) {
jsonResponse, jsonError := json.Marshal(tinfoilCollection)
if jsonError != nil {
log.Println("Unable to encode JSON")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write(jsonResponse)
}
// HomeHandler handles list of games
func (s *TinShop) HomeHandler(w http.ResponseWriter, _ *http.Request) {
if s.Shop.Collection == nil {
w.WriteHeader(http.StatusNotFound)
return
}
serveCollection(w, s.Shop.Collection.Games())
}
// GamesHandler handles downloading games
func (s *TinShop) GamesHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println("Requesting game", vars["game"])
s.Shop.Sources.DownloadGame(vars["game"], w, r)
}
// FilteringHandler handles filtering games collection
func (s *TinShop) FilteringHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if !utils.IsValidFilter(vars["filter"]) {
w.WriteHeader(http.StatusNotAcceptable)
return
}
if s.Shop.Collection == nil {
w.WriteHeader(http.StatusNotFound)
return
}
serveCollection(w, s.Shop.Collection.Filter(vars["filter"]))
}
// APIHandler handles api calls
func (s *TinShop) APIHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if vars["endpoint"] == "stats" {
summary, err := s.Shop.Stats.Summary()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
s.Shop.API.Stats(w, summary)
return
}
// Everything not existing
w.WriteHeader(http.StatusBadRequest)
}
// StatsMiddleware is a middleware to collect statistics
func (s *TinShop) StatsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/" || utils.IsValidFilter(cleanPath(r.RequestURI)) {
console := &repository.Switch{
IP: utils.GetIPFromRequest(r),
UID: r.Header.Get("Uid"),
Theme: r.Header.Get("Theme"),
Version: r.Header.Get("Version"),
Language: r.Header.Get("Language"),
}
_ = s.Shop.Stats.ListVisit(console)
} else if r.RequestURI[0:7] == "/games/" {
vars := mux.Vars(r)
if s.Shop.Sources.HasGame(vars["game"]) {
_ = s.Shop.Stats.DownloadAsked(utils.GetIPFromRequest(r), vars["game"])
}
}
next.ServeHTTP(w, r)
})
}