-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
257 lines (226 loc) · 6.55 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
"math"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
_ "github.com/mattn/go-sqlite3"
)
var (
sqlitePath = flag.String("dbPath", "conferencemapper.db", "Path to SQLite Database")
xDigitIDs = flag.Int("xDigitIDs", 7, "Number of digits for new random conference IDs")
)
// var sqlDb *sql.DB
type ConferenceMapperResult struct {
ConferenceID int `json:"id"` // PIN with potentially leading zeroes
ConferenceName string `json:"conference"`
}
func mapper(w http.ResponseWriter, r *http.Request) {
result := ConferenceMapperResult{}
defer sendResponse(w, &result)
conference := r.URL.Query().Get("conference")
// for log only
conferenceEscaped := url.QueryEscape(conference)
paramID := r.URL.Query().Get("id")
if paramID != "" {
confId, err := strconv.Atoi(paramID)
if err != nil {
log.WithFields(log.Fields{
"paramID": paramID,
"confID": confId,
}).Error("Parsing of confID failed")
return
}
result.ConferenceID = confId
}
log.WithFields(log.Fields{
"conference": conferenceEscaped,
"ConferenceID": result.ConferenceID,
}).Info("mapper(conference, id)")
sqlDb, err := sql.Open("sqlite3", *sqlitePath)
if err != nil {
log.WithFields(log.Fields{
"err": err,
}).Error("mapper: Connect to database")
return
}
defer sqlDb.Close()
if result.ConferenceID != 0 {
result.ConferenceName = strings.ToLower(getConfName(sqlDb, result.ConferenceID))
log.WithFields(log.Fields{
"confID": result.ConferenceID,
"confName": result.ConferenceName,
}).Debug("Parsed Conf name")
}
// only set new conference name if not set via conf id
if conference != "" && result.ConferenceName == "" {
result.ConferenceName = sanitizeConferenceName(conference)
result.ConferenceID = getConfId(sqlDb, result.ConferenceName)
}
updateConferenceUsage(sqlDb, result.ConferenceID)
}
func sendResponse(w http.ResponseWriter, result *ConferenceMapperResult) {
if err := json.NewEncoder(w).Encode(&result); err != nil {
log.WithFields(log.Fields{
"result": result,
"error": err,
}).Error("Encoding of response failed")
}
log.WithFields(log.Fields{
"result": *result,
}).Info("sendResponse()")
}
func getConfId(db *sql.DB, confName string) int {
log.WithFields(log.Fields{
"confName": confName,
}).Debug("getConfId(confName)")
var result int
row := db.QueryRow("SELECT conferenceId FROM conferences WHERE conferenceName = ?", confName)
if err := row.Scan(&result); err != nil {
if err == sql.ErrNoRows {
// generate new ID and return that
for {
result = rand.Intn(int(math.Pow10(*xDigitIDs))-1-int(math.Pow10(*xDigitIDs-1))) + int(math.Pow10(*xDigitIDs-1))
log.WithFields(log.Fields{
"confName": confName,
"confId": result,
}).Debug("getConfId(confName) store random confID")
if insertConference(db, confName, result) {
// insertion worked; return it
return result
}
}
}
log.WithFields(log.Fields{
"confName": confName,
"err": err,
}).Error("Could not get data conf id from db")
return -1
}
return result
}
// sanitizeConferenceName takes roomName@domain and sanizites it to a format used by jitsi
func sanitizeConferenceName(conference string) string {
parts := strings.Split(conference, "@")
room := strings.ToLower(strings.Join(parts[0:len(parts)-1], "@"))
return url.QueryEscape(room) + "@" + parts[len(parts)-1]
}
func getConfName(db *sql.DB, confId int) string {
log.WithFields(log.Fields{
"confId": confId,
}).Debug("getConfName(confId)")
var result string
row := db.QueryRow("SELECT conferenceName FROM conferences WHERE conferenceId = ?", confId)
if err := row.Scan(&result); err != nil {
log.WithFields(log.Fields{
"confId": confId,
"err": err,
}).Error("Could not query conf name from db")
return "false"
}
return result
}
// returns true if insertion completed
func insertConference(db *sql.DB, confName string, confId int) bool {
log.WithFields(log.Fields{
"confName": confName,
"confId": confId,
}).Debug("insertConference(confName,confId)")
stmt, err := db.Prepare("INSERT INTO conferences(conferenceName, conferenceId) VALUES (?, ?)")
if err != nil {
log.WithFields(log.Fields{
"confName": confName,
"confId": confId,
"err": err,
}).Error("Could not insert conf to db")
return false
}
_, err = stmt.Exec(confName, confId)
if err != nil {
log.WithFields(log.Fields{
"confName": confName,
"confId": confId,
"err": err,
}).Error("Could not insert conf to db (exec stmt)")
return false
}
return true
}
func updateConferenceUsage(db *sql.DB, confId int) bool {
_, err := db.Exec("UPDATE conferences set lastUsed = (strftime('%s','now')) WHERE conferenceId = ?", confId)
log.WithFields(log.Fields{
"confId": confId,
"err": err,
}).Debug("updateConferenceUsage()")
return err == nil
}
func cleanupOldEntries() {
for {
time.Sleep(24 * time.Hour)
log.Info("Run cleanup of old entries")
sqlDb, err := sql.Open("sqlite3", *sqlitePath)
if err != nil {
log.WithFields(log.Fields{
"err": err,
}).Error("cleanupOldEntries: Connect to database")
return
}
oldTime := time.Now().Add(-24 * time.Hour * 365).Unix()
_, err = sqlDb.Exec("DELETE FROM conferences WHERE lastUsed < ?", oldTime)
if err != nil {
log.WithFields(log.Fields{
"err": err,
}).Error("cleanupOldEntries: Run Cleanup")
return
}
sqlDb.Close()
}
}
func initDatabase() error {
sqlDb, err := sql.Open("sqlite3", *sqlitePath)
if err != nil {
log.WithFields(log.Fields{
"err": err,
}).Fatal("main: Open sql db")
}
stmt, err := sqlDb.Prepare(`CREATE TABLE IF NOT EXISTS conferences (
"conferenceId" INTEGER(6) NOT NULL PRIMARY KEY,
"conferenceName" TEXT NOT NULL UNIQUE,
"created" INTEGER(4) NOT NULL DEFAULT (strftime('%s','now')),
"lastUsed" INTEGER(4) NOT NULL DEFAULT (strftime('%s','now'))
)`)
if err != nil {
log.WithFields(log.Fields{
"err": err,
}).Fatal("main: Create db statement (Prepare)")
}
_, err = stmt.Exec()
if err != nil {
log.WithFields(log.Fields{
"err": err,
}).Fatal("main: Create db statement (Execute)")
}
sqlDb.Close()
return err
}
func main() {
flag.Parse()
if err := initDatabase(); err != nil {
log.WithField("error", err).Fatal("cannot initialize database")
}
go cleanupOldEntries()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Conference Mapper (for jitsi) is running")
})
http.HandleFunc("/conferenceMapper", mapper)
log.Info("Listen on 8001")
log.Fatal(http.ListenAndServe(":8001", nil))
}