-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpbxlog.go
358 lines (305 loc) · 7.79 KB
/
pbxlog.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package main
import (
"bufio"
"database/sql"
"fmt"
"github.com/kardianos/osext"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/viper"
"html/template"
"net"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
type DbContext struct {
Db *sql.DB
Insert *sql.Stmt
}
func (c *DbContext) Close() {
if c.Insert != nil {
c.Insert.Close()
}
if c.Db != nil {
c.Db.Close()
}
}
func loadConfig() {
viper.SetConfigName("pbxlog")
viper.SetConfigType("yaml")
viper.AddConfigPath("$HOME")
viper.AddConfigPath("$HOME/.pbxlog")
viper.AddConfigPath(".")
viper.SetDefault("pabx", "")
viper.SetDefault("webui", "")
viper.SetDefault("dump-file", "")
viper.SetDefault("error-file", "")
viper.SetDefault("calls-db", "")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
fmt.Printf("Using pabx = %s\n", viper.GetString("pabx"))
fmt.Printf("Using webui = %s\n", viper.GetString("webui"))
fmt.Printf("Using dump-file = %s\n", viper.GetString("dump-file"))
fmt.Printf("Using error-file = %s\n", viper.GetString("error-file"))
fmt.Printf("Using calls-db = %s\n", viper.GetString("calls-db"))
if viper.GetString("pabx") == "" || viper.GetString("calls-db") == "" {
panic("pabx and calls-db configuration values required")
}
}
func connectToPABX() net.Conn {
conn, err := net.Dial("tcp", viper.GetString("pabx"))
panicErr(err)
return conn
}
func openDumpFile(configItem string) *os.File {
filename := viper.GetString(configItem)
if filename == "" {
return nil
}
dumpfile, err := os.OpenFile(filename,
os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
panicErr(err)
return dumpfile
}
type CDR struct {
Callid int
Extension int
ExtName string
Auth string
AuthName string
Calltime string
Duration string
Code string
Dialed string
Account string
Cost string
Clid string
Clidname string
Gpno string
Ringtime string
}
func openCallsDatabase() *DbContext {
ctx := new(DbContext)
var err error
ctx.Db, err = sql.Open("sqlite3", viper.GetString("calls-db"))
panicErr(err)
_, err = ctx.Db.Exec("CREATE TABLE IF NOT EXISTS calls (" +
"callid INTEGER, extension INTEGER, auth TEXT, calltime TEXT, duration TEXT, " +
"code TEXT, dialed TEXT, account TEXT, cost REAL, clid TEXT, " +
"clidname TEXT, gpno TEXT, ringtime TEXT);")
panicErr(err)
_, err = ctx.Db.Exec("CREATE TABLE IF NOT EXISTS extensions (num INTEGER, name TEXT);")
panicErr(err)
ctx.Insert, err = ctx.Db.Prepare("INSERT INTO calls(callid, extension, auth, calltime, " +
"duration, code, dialed, account, cost, clid, clidname, gpno, ringtime) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
panicErr(err)
return ctx
}
func insertCDR(ctx *DbContext, cdr *CDR) {
_, err := ctx.Insert.Exec(cdr.Callid, cdr.Extension, cdr.Auth,
cdr.Calltime, cdr.Duration, cdr.Code, cdr.Dialed, cdr.Account,
cdr.Cost, cdr.Clid, cdr.Clidname, cdr.Gpno, cdr.Ringtime)
panicErr(err)
}
func splitData(str string) *CDR {
n := len(str)
if n != 154 && n != 122 {
return nil
}
t := time.Now()
var cdr CDR
cdr.Callid, _ = strconv.Atoi(strings.TrimSpace(str[2:8]))
cdr.Extension, _ = strconv.Atoi(strings.TrimSpace(str[9:15]))
cdr.Auth = strings.TrimSpace(str[16:25])
cdr.Calltime = strings.TrimSpace(fmt.Sprintf("%d-%s-%s", t.Year(), str[26:28], str[29:40]))
cdr.Duration = strings.TrimSpace(str[41:49])
cdr.Code = strings.TrimSpace(str[50:52])
cdr.Dialed = strings.TrimSpace(str[53:71])
cdr.Account = strings.TrimSpace(str[72:89])
cdr.Cost = strings.TrimSpace(str[90:100])
cdr.Clid = strings.TrimSpace(str[101:117])
if n == 154 {
cdr.Clidname = strings.TrimSpace(str[118:136])
cdr.Gpno = strings.TrimSpace(str[137:143])
cdr.Ringtime = strings.TrimSpace(str[143:151])
} else {
cdr.Clidname = ""
cdr.Gpno = ""
cdr.Ringtime = ""
}
return &cdr
}
func skipHeader(line string) string {
const tag = "===="
if line[0] == 0x0C {
n := strings.LastIndex(line, tag)
if n >= 0 {
fmt.Print(" HDR ")
return line[n+len(tag)+2:]
}
}
return line
}
func main() {
if time.Now().Year() < 2018 {
panic("System date incorrect")
}
loadConfig()
pabxConn := connectToPABX()
defer pabxConn.Close()
pabx := bufio.NewReader(pabxConn)
ctx := openCallsDatabase()
defer ctx.Close()
startWebServer(ctx)
dumpfile := openDumpFile("dump-file")
if dumpfile != nil {
defer dumpfile.Close()
}
for {
// every call record ends with a nul character
str, err := pabx.ReadString('\000')
panicErr(err)
if dumpfile != nil {
dumpfile.Write([]byte(str))
dumpfile.Sync()
}
fmt.Print(".")
// every now and then the PABX will preface the call
// record with a human readable header. Skip it.
str = skipHeader(str)
// process this single call record
cdr := splitData(str)
if cdr == nil {
dumpError(str)
} else {
insertCDR(ctx, cdr)
}
}
}
func dumpError(str string) {
fmt.Print(" INVALID ")
errorfile := openDumpFile("error-file")
if errorfile != nil {
defer errorfile.Close()
msg := fmt.Sprintf("\nError: len = %d\n--\n%s\n--\n", len(str), str)
errorfile.Write([]byte(msg))
errorfile.Sync()
}
}
func panicErr(err error, args ...string) {
if err != nil {
panic(fmt.Sprintf("Error: %q: %s\n", err, args))
}
}
/* ----- WEBUI ----- */
func startWebServer(ctx *DbContext) {
webui := viper.GetString("webui")
if webui == "" {
return
}
http.HandleFunc("/",
func(w http.ResponseWriter, r *http.Request) {
handler(ctx, w, r)
})
listener, err := net.Listen("tcp", webui)
panicErr(err)
go http.Serve(listener, nil)
}
type Row struct {
CDR
Group int
}
type Page struct {
List []Row
Prev int
Next int
}
func handler(ctx *DbContext, w http.ResponseWriter, r *http.Request) {
folder, err := osext.ExecutableFolder()
if err != nil {
fmt.Fprintf(w, "osext = %v", err)
return
}
templateFile := path.Join(folder, "pbxlog.html")
t := template.New("pbxlog.html")
t, err = t.ParseFiles(templateFile)
if err != nil {
fmt.Fprintf(w, "ParseFiles = %v", err)
return
}
count, err := strconv.Atoi(r.FormValue("count"))
if err != nil || count < 1 {
count = 200
}
page, err := strconv.Atoi(r.FormValue("page"))
if err != nil || page < 1 {
page = 1
}
/* not using limit/offset for pagination, see below */
rows, err := ctx.Db.Query("" +
"SELECT callid, extension, COALESCE(x.name, '') AS extname, " +
"auth, COALESCE(a.name, '') AS authname, calltime, duration, " +
"code, dialed, account, cost, clid, clidname, " +
"gpno, ringtime " +
"FROM calls c " +
"LEFT JOIN extensions x ON c.extension = x.num " +
"LEFT JOIN extensions a ON c.auth = a.num " +
"ORDER BY calltime DESC, callid DESC ")
if err != nil {
fmt.Fprintf(w, "Query = %v", err)
return
}
defer rows.Close()
var p Page
var cdr Row
var grp map[int]int
var next int
var ok bool
/* handle pagination manually as sqlite3 limit/offset seems to skip
records for some reason. Since most people will not be looking too
far back in the database manually, although inefficient, this is
plenty fast enough */
skip := (page - 1) * count
for i := 0; i < skip; i++ {
rows.Next()
}
grp = make(map[int]int)
for i := 0; i < count; i++ {
if !rows.Next() {
break
}
err = rows.Scan(&cdr.Callid, &cdr.Extension, &cdr.ExtName, &cdr.Auth, &cdr.AuthName,
&cdr.Calltime, &cdr.Duration, &cdr.Code, &cdr.Dialed, &cdr.Account, &cdr.Cost,
&cdr.Clid, &cdr.Clidname, &cdr.Gpno, &cdr.Ringtime)
cdr.Group, ok = grp[cdr.Callid]
if !ok {
next = (next % 5) + 1
cdr.Group = next
grp[cdr.Callid] = cdr.Group
}
if err != nil {
fmt.Fprintf(w, "rows.Scan() = %v", err)
}
p.List = append(p.List, cdr)
}
err = rows.Err()
if err != nil {
fmt.Fprintf(w, "rows.Err() = %v", err)
}
p.Prev = page - 1
if p.Prev < 1 {
p.Prev = 1
}
p.Next = page + 1
err = t.Execute(w, p)
if err != nil {
fmt.Fprintf(w, "%v", err)
return
}
}