-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcli.go
More file actions
235 lines (202 loc) Β· 6.05 KB
/
cli.go
File metadata and controls
235 lines (202 loc) Β· 6.05 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
package main
import (
"encoding/json"
"fmt"
"io"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/shazow/wifitui/internal/helpers"
"github.com/shazow/wifitui/internal/tui"
"github.com/shazow/wifitui/wifi"
)
func runTUI(b wifi.Backend) error {
m, err := tui.NewModel(b)
if err != nil {
return fmt.Errorf("error initializing model: %w", err)
}
p := tea.NewProgram(m, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
return fmt.Errorf("error running program: %w", err)
}
return nil
}
func formatConnection(c wifi.Connection) string {
var parts []string
if c.IsVisible {
parts = append(parts, fmt.Sprintf("%d%%", c.Strength()))
parts = append(parts, "visible")
}
if c.IsSecure {
parts = append(parts, "secure")
}
if c.IsActive {
parts = append(parts, "active")
}
return strings.Join(parts, ", ")
}
// writeJSON encodes v as indented JSON and writes it to w.
func writeJSON(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(v)
}
// filterVisibleConnections returns only the connections that are currently visible.
func filterVisibleConnections(connections []wifi.Connection) []wifi.Connection {
var visible []wifi.Connection
for _, c := range connections {
if c.IsVisible {
visible = append(visible, c)
}
}
return visible
}
// findConnectionBySSID returns the first connection matching the given SSID and true,
// or the zero value and false if no match is found.
func findConnectionBySSID(connections []wifi.Connection, ssid string) (wifi.Connection, bool) {
for _, c := range connections {
if c.SSID == ssid {
return c, true
}
}
return wifi.Connection{}, false
}
// writeConnectionDetails writes human-readable details for a connection to w.
func writeConnectionDetails(w io.Writer, c wifi.Connection, secret string) error {
var writeErr error
write := func(format string, args ...any) {
if writeErr != nil {
return
}
_, writeErr = fmt.Fprintf(w, format, args...)
}
write("SSID: %s\n", c.SSID)
write("Passphrase: %s\n", secret)
write("Active: %t\n", c.IsActive)
write("Known: %t\n", c.IsKnown)
write("Secure: %t\n", c.IsSecure)
write("Visible: %t\n", c.IsVisible)
write("Hidden: %t\n", c.IsHidden)
write("Strength: %d%%\n", c.Strength())
if c.LastConnected != nil {
write("Last Connected: %s\n", helpers.FormatDuration(*c.LastConnected))
}
return writeErr
}
func runList(w io.Writer, jsonOut bool, all bool, scan bool, b wifi.Backend) error {
connections, err := b.BuildNetworkList(scan)
if err != nil {
return fmt.Errorf("failed to list networks: %w", err)
}
if !all {
connections = filterVisibleConnections(connections)
}
if jsonOut {
return writeJSON(w, connections)
}
for _, c := range connections {
fmt.Fprintf(w, "%s\t%s\n", c.SSID, formatConnection(c))
}
return nil
}
func runShow(w io.Writer, jsonOut bool, ssid string, b wifi.Backend) error {
connections, err := b.BuildNetworkList(true)
if err != nil {
return fmt.Errorf("failed to list networks: %w", err)
}
c, found := findConnectionBySSID(connections, ssid)
if !found {
return fmt.Errorf("network not found: %s: %w", ssid, wifi.ErrNotFound)
}
secret, err := b.GetSecrets(ssid)
if err != nil {
// If we can't get a secret for a known network, that's an error.
// But for a visible-only network, it's expected.
if c.IsKnown {
return fmt.Errorf("failed to get network secret: %w", err)
}
secret = "" // No secret available
}
if jsonOut {
// We need a custom struct to include the passphrase
type connectionWithSecret struct {
wifi.Connection
Passphrase string `json:"passphrase,omitempty"`
}
return writeJSON(w, connectionWithSecret{Connection: c, Passphrase: secret})
}
return writeConnectionDetails(w, c, secret)
}
func attemptConnect(ssid string, passphrase string, security wifi.SecurityType, isHidden bool, shouldScan bool, b wifi.Backend) error {
// Populate the backend's internal state (e.g. NetworkManager's Connections
// and AccessPoints maps).
// ActivateConnection and JoinNetwork rely on this state being present.
if _, err := b.BuildNetworkList(shouldScan); err != nil {
return fmt.Errorf("failed to load networks: %w", err)
}
if passphrase != "" || isHidden {
return b.JoinNetwork(ssid, passphrase, security, isHidden)
}
return b.ActivateConnection(ssid)
}
// RetryConfig defines the configuration for connection retries.
type RetryConfig struct {
// Total is the maximum duration to keep retrying the connection.
Total time.Duration
// Interval is the duration to wait between each retry attempt.
Interval time.Duration
}
func runConnect(w io.Writer, ssid string, passphrase string, security wifi.SecurityType, isHidden bool, retry RetryConfig, b wifi.Backend) error {
start := time.Now()
shouldScan := false
for {
fmt.Fprintf(w, "Connecting to network %q with scan=%v...\n", ssid, shouldScan)
err := attemptConnect(ssid, passphrase, security, isHidden, shouldScan, b)
if err == nil {
return nil
}
if !shouldScan {
shouldScan = true
if retry.Total > 0 && time.Since(start) < retry.Total {
fmt.Fprintf(w, "Quick connect failed: %q\n", err)
continue
}
}
if retry.Total == 0 || time.Since(start) >= retry.Total {
return err
}
fmt.Fprintf(w, "Connection failed: %q\nRetrying in %v...\n", err, retry.Interval)
time.Sleep(retry.Interval)
}
}
func runRadio(w io.Writer, action string, b wifi.Backend) error {
var enabled bool
switch action {
case "on":
enabled = true
case "off":
enabled = false
case "", "toggle":
current, err := b.IsWirelessEnabled()
if err != nil {
return fmt.Errorf("failed to get wireless state: %w", err)
}
enabled = !current
default:
return fmt.Errorf("invalid radio action: %q (expected on, off, or toggle)", action)
}
if enabled {
fmt.Fprintln(w, "Enabling WiFi radio...")
} else {
fmt.Fprintln(w, "Disabling WiFi radio...")
}
if err := b.SetWireless(enabled); err != nil {
return fmt.Errorf("failed to set wireless state: %w", err)
}
if enabled {
fmt.Fprintln(w, "WiFi radio is on")
} else {
fmt.Fprintln(w, "WiFi radio is off")
}
return nil
}