forked from hzeller/stuff-org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
194 lines (166 loc) · 5.7 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
// stuff store. Backed by a database.
package main
import (
"database/sql"
"encoding/json"
"flag"
"log"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
_ "github.com/mattn/go-sqlite3"
)
type Component struct {
Id int `json:"id"`
Equiv_set int `json:"equiv_set,omitempty"`
Value string `json:"value"`
Category string `json:"category"`
Description string `json:"description"`
Quantity string `json:"quantity"` // at this point just a string.
Notes string `json:"notes,omitempty"`
Datasheet_url string `json:"datasheet_url,omitempty"`
Drawersize int `json:"drawersize,omitempty"`
Footprint string `json:"footprint,omitempty"`
}
// Modify a user pointer. Returns 'true' if the changes should be commited.
type ModifyFun func(comp *Component) bool
// SearchResult holds metadata about the search.
type SearchResult struct {
OrignialQuery string
RewrittenQuery string
Results []*Component
}
// Interface to our storage backend.
type StuffStore interface {
// Find a component by its ID. Returns nil if it does not exist. Don't
// modify the returned pointer.
FindById(id int) *Component
// Edit record of given ID. If ID is new, it is inserted and an empty
// record returned to be edited.
// Returns if record has been saved, possibly with message.
// This does _not_ influence the equivalence set settings, use
// the JoinSet()/LeaveSet() functions for that.
EditRecord(id int, updater ModifyFun) (bool, string)
// Have component with id join set with given ID.
JoinSet(id int, equiv_set int)
// Leave any set we are in and go back to the default set
// (which is equiv_set == id)
LeaveSet(id int)
// Get possible matching components of given component,
// including all the components that are in the sets the matches
// are in.
// Ordered by equivalence set, id.
MatchingEquivSetForComponent(component int) []*Component
// Given a search term, returns all the components that match, ordered
// by some internal scoring system. Don't modify the returned objects!
Search(search_term string) *SearchResult
// Iterate through all elements.
IterateAll(func(comp *Component) bool)
}
var wantTimings = flag.Bool("want-timings", false, "Print processing timings.")
func ElapsedPrint(msg string, start time.Time) {
if *wantTimings {
log.Printf("%s took %s", msg, time.Since(start))
}
}
func stuffStoreRoot(out http.ResponseWriter, r *http.Request) {
http.Redirect(out, r, "/search", 302)
}
func parseAllowedEditorCIDR(allowed string) []*net.IPNet {
all_allowed := strings.Split(allowed, ",")
allowed_nets := make([]*net.IPNet, 0, len(all_allowed))
for i := 0; i < len(all_allowed); i++ {
if all_allowed[i] == "" {
continue
}
_, net, err := net.ParseCIDR(all_allowed[i])
if err != nil {
log.Fatal("--edit-permission-nets: Need IP/Network format: ", err)
} else {
allowed_nets = append(allowed_nets, net)
}
}
return allowed_nets
}
func main() {
imageDir := flag.String("imagedir", "img-srv", "Directory with component images")
templateDir := flag.String("templatedir", "./template", "Base-Directory with templates")
cacheTemplates := flag.Bool("cache-templates", true,
"Cache templates. False for online editing while development.")
staticResource := flag.String("staticdir", "static",
"Directory with static resources")
bindAddress := flag.String("bind-address", ":2000", "Port to serve from")
dbFile := flag.String("dbfile", "stuff-database.db", "SQLite database file")
logfile := flag.String("logfile", "", "Logfile to write interesting events")
do_cleanup := flag.Bool("cleanup-db", false, "Cleanup run of database")
permitted_nets := flag.String("edit-permission-nets", "", "Comma separated list of networks (CIDR format IP-Addr/network) that are allowed to edit content")
site_name := flag.String("site-name", "", "Site-name, in particular needed for SSL")
ssl_key := flag.String("ssl-key", "", "Key file")
ssl_cert := flag.String("ssl-cert", "", "Cert file")
flag.Parse()
edit_nets := parseAllowedEditorCIDR(*permitted_nets)
if *logfile != "" {
f, err := os.OpenFile(*logfile,
os.O_RDWR|os.O_CREATE|os.O_APPEND,
0644)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
}
is_dbfilenew := true
if _, err := os.Stat(*dbFile); err == nil {
is_dbfilenew = false
} else {
log.Printf("Implicitly creating new database file from --dbfile=%s", *dbFile)
}
db, err := sql.Open("sqlite3", *dbFile)
if err != nil {
log.Fatal(err)
}
var store StuffStore
store, err = NewDBBackend(db, is_dbfilenew)
if err != nil {
log.Fatal(err)
}
// Very crude way to run all the cleanup routines if
// requested. This is the only thing we do.
if *do_cleanup {
for i := 0; i < 3000; i++ {
if c := store.FindById(i); c != nil {
store.EditRecord(i, func(c *Component) bool {
before := *c
cleanupComponent(c)
if *c == before {
return false
}
json, _ := json.Marshal(before)
log.Printf("----- %s", json)
return true
})
}
}
return
}
templates := NewTemplateRenderer(*templateDir, *cacheTemplates)
imagehandler := AddImageHandler(store, templates, *imageDir, *staticResource)
AddFormHandler(store, templates, *imageDir, edit_nets)
AddSearchHandler(store, templates, imagehandler)
AddStatusHandler(store, templates, *imageDir)
AddSitemapHandler(store, *site_name)
http.Handle("/metrics", promhttp.Handler())
log.Printf("Listening on %q", *bindAddress)
if *ssl_cert != "" && *ssl_key != "" {
log.Fatal(http.ListenAndServeTLS(*bindAddress,
*ssl_cert, *ssl_key,
nil))
} else {
log.Fatal(http.ListenAndServe(*bindAddress, nil))
}
var block_forever chan bool
<-block_forever
}