-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.go
More file actions
330 lines (268 loc) · 8.27 KB
/
Copy pathapp.go
File metadata and controls
330 lines (268 loc) · 8.27 KB
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
package main
import (
"context"
"fmt"
"os"
"runtime"
"time"
"epos-proxy/internal/config"
"epos-proxy/internal/logger"
"epos-proxy/internal/printer"
"epos-proxy/internal/server"
"epos-proxy/internal/util"
autostart "github.com/emersion/go-autostart"
wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// dialoger abstracts the Wails runtime dialog calls. Production code uses
// runtimeDialogs; tests substitute a fake so the dialog-driven code paths can
// be exercised without a live Wails context.
type dialoger interface {
Message(ctx context.Context, opts wailsruntime.MessageDialogOptions) (string, error)
SaveFile(ctx context.Context, opts wailsruntime.SaveDialogOptions) (string, error)
}
// runtimeDialogs forwards to the real Wails runtime.
type runtimeDialogs struct{}
func (runtimeDialogs) Message(ctx context.Context, opts wailsruntime.MessageDialogOptions) (string, error) {
return wailsruntime.MessageDialog(ctx, opts)
}
func (runtimeDialogs) SaveFile(ctx context.Context, opts wailsruntime.SaveDialogOptions) (string, error) {
return wailsruntime.SaveFileDialog(ctx, opts)
}
// App struct
type App struct {
ctx context.Context
webserver *server.Server
config *config.Manager
printerManager *printer.Manager
autoStart *autostart.App
dialogs dialoger
}
// dlg returns the dialog backend, defaulting to the Wails runtime so an App
// built as a bare struct literal still behaves correctly.
func (a *App) dlg() dialoger {
if a.dialogs == nil {
return runtimeDialogs{}
}
return a.dialogs
}
// showError surfaces an error to the user and logs any failure to do so.
func (a *App) showError(title, message string) {
if _, err := a.dlg().Message(a.ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.ErrorDialog,
Title: title,
Message: message,
}); err != nil {
logger.Errorf("Failed to show error dialog %q: %v", title, err)
}
}
type Printer struct {
Name string `json:"name"`
Ip string `json:"ip"`
Id string `json:"id"`
IsLAN bool `json:"isLAN"`
LANIp string `json:"lanIp,omitempty"`
Online bool `json:"online"`
Type string `json:"type"`
}
type UnavailablePrinter struct {
Name string `json:"name"`
ErrorMsg string `json:"errorMsg"`
IsLAN bool `json:"isLAN"`
LANIp string `json:"lanIp,omitempty"`
}
type AppVariable struct {
ServerRunning bool `json:"serverRunning"`
DefaultIp string `json:"defaultIp"`
Os string `json:"os"`
}
type Printers struct {
ErrorMsg string `json:"errorMsg"`
Printers []Printer `json:"printers"`
UnavailablePrinters []UnavailablePrinter `json:"unavailablePrinters"`
}
func NewApp() *App {
a := &App{}
a.autoStart = &autostart.App{
Name: "epos-proxy",
DisplayName: "ePOS Proxy",
Exec: []string{os.Args[0]},
}
a.printerManager = printer.NewManager()
a.dialogs = runtimeDialogs{}
return a
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
logger.Debugf("Application startup")
cfg, err := config.NewManager()
if err != nil {
logger.Fatalf("Config initialization failed: %v", err)
}
if err := cfg.Load(); err != nil {
logger.Warnf("Config load warning: %v", err)
}
logger.Debugf("Config loaded from %s", cfg.Path())
a.config = cfg
port, err := cfg.ResolvePort()
if err != nil {
logger.Warn("Unable to resolve port, using default")
}
a.webserver = server.New(port, a.printerManager)
}
func (a *App) shutdown(ctx context.Context) {
logger.Infof("Stopping proxy server")
if err := a.webserver.Stop(); err != nil {
logger.Errorf("Server stop error: %v", err)
}
}
func (a *App) AppVariable() AppVariable {
return AppVariable{
Os: runtime.GOOS,
ServerRunning: a.webserver.Running(),
DefaultIp: fmt.Sprintf("127.0.0.1:%d", a.webserver.Port),
}
}
func (a *App) GetPrinterIp(id string) string {
ip := fmt.Sprintf("127.0.0.1:%d/p/%s", a.webserver.Port, id)
logger.Debugf("Generated printer endpoint: %s", ip)
return ip
}
func (a *App) Printers() Printers {
logger.Debug("Collecting printer status")
printers := make([]Printer, 0)
unavailablePrinters := make([]UnavailablePrinter, 0)
printerInfos, err := printer.ListUSBPrinters()
errorMsg := ""
if err == nil {
logger.Debugf("Detected %d available USB printers", len(printerInfos.Available))
for _, info := range printerInfos.Available {
printers = append(printers, Printer{
Id: info.Id,
Name: info.Name,
Ip: a.GetPrinterIp(info.Id),
Online: true,
Type: string(info.Type),
})
}
for _, info := range printerInfos.Unavailable {
unavailablePrinters = append(unavailablePrinters, UnavailablePrinter{
Name: info.Name,
ErrorMsg: info.Error,
})
logger.Warnf("USB printer unavailable: %s (%s)", info.Name, info.Error)
}
} else {
errorMsg = err.Error()
logger.Errorf("USB printer detection failed: %v", err)
}
lanPrinters := printer.ListLANPrinters(a.config)
for _, info := range lanPrinters {
printers = append(printers, Printer{
Id: info.Id,
Name: fmt.Sprintf("Network - %s", info.IP),
Ip: a.GetPrinterIp(info.Id),
IsLAN: true,
LANIp: info.IP,
Type: string(printer.TypeReceipt),
})
}
return Printers{
Printers: printers,
UnavailablePrinters: unavailablePrinters,
ErrorMsg: errorMsg,
}
}
func (a *App) AddLANPrinter(ip string) error {
logger.Debugf("Adding LAN printer: %s", ip)
ip, err := printer.ValidateIPAddress(ip)
if err != nil {
return fmt.Errorf("invalid IP address: %s, error: %v", ip, err)
}
if err := printer.CheckLANPrinter(ip); err != nil {
return fmt.Errorf("LAN printer unreachable: %s, error: %v", ip, err)
}
if err := a.config.AddLanEposPrinter(ip); err != nil {
return fmt.Errorf("failed to save LAN printer: %s, error: %v", ip, err)
}
logger.Debugf("LAN printer added successfully: %s", ip)
return nil
}
func (a *App) ConfirmRemoveLANPrinter(ip string) (bool, error) {
logger.Debugf("Remove LAN printer requested: %s", ip)
result, err := a.dlg().Message(a.ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.QuestionDialog,
Title: "Remove Printer",
Message: fmt.Sprintf("Are you sure you want to remove the printer at %s?", ip),
Buttons: []string{"Cancel", "Confirm"},
DefaultButton: "Cancel",
CancelButton: "Cancel",
})
if err != nil {
return false, fmt.Errorf("failed to show confirmation dialog: %w", err)
}
if result == "Confirm" || result == "Yes" {
if err := a.config.RemoveLANPrinter(ip); err != nil {
return false, fmt.Errorf("failed to remove LAN printer: %w", err)
}
return true, nil
}
logger.Infof("Remove LAN printer cancelled, Remove printer dialog result: %s", result)
return false, nil
}
func (a *App) CheckLANPrinterStatus(ip string) bool {
logger.Debugf("Checking LAN printer status: %s", ip)
return printer.CheckLANPrinter(ip) == nil
}
func (a *App) DownloadLogs() {
logger.Debugf("Download logs requested")
logDir := logger.LogDirectory()
zipName := fmt.Sprintf("epos-proxy-logs-%s.zip",
time.Now().Format("2006-01-02"))
logger.Debugf("Creating logs archive: %s", zipName)
savePath, err := a.dlg().SaveFile(a.ctx, wailsruntime.SaveDialogOptions{
Title: "Save Archive",
DefaultFilename: zipName,
Filters: []wailsruntime.FileFilter{
{
DisplayName: "Zip Archives (*.zip)",
Pattern: "*.zip",
},
},
})
if err != nil {
logger.Errorf("Save dialog failed: %v", err)
a.showError("Download Logs Failed", err.Error())
return
}
// An empty path means the user dismissed the save dialog.
if savePath == "" {
logger.Infof("Download logs cancelled by user")
return
}
if err := util.ZipLogs(logDir, savePath); err != nil {
logger.Errorf("Log export failed: %v", err)
a.showError("Download Logs Failed", err.Error())
return
}
logger.Infof("Logs successfully exported to: %s", savePath)
}
func (a *App) IsAutostartEnabled() bool {
return a.autoStart.IsEnabled()
}
func (a *App) EnableAutostart() error {
logger.Info("Enabling autostart")
if runtime.GOOS == "linux" {
return util.EnableLinuxAutostart()
}
if !a.autoStart.IsEnabled() {
return a.autoStart.Enable()
}
return nil
}
func (a *App) DisableAutostart() error {
logger.Info("Disabling autostart")
if a.autoStart.IsEnabled() {
return a.autoStart.Disable()
}
return nil
}