Add NetworkDevices widget to display and manage network devices
This commit is contained in:
70
widgets/networkdevices.go
Normal file
70
widgets/networkdevices.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package widgets
|
||||
|
||||
import (
|
||||
"ArinDash/apis/networking"
|
||||
"ArinDash/util"
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mum4k/termdash/cell"
|
||||
"github.com/mum4k/termdash/terminal/terminalapi"
|
||||
"github.com/mum4k/termdash/widgetapi"
|
||||
"github.com/mum4k/termdash/widgets/text"
|
||||
)
|
||||
|
||||
type NetworkDevicesOptions struct {
|
||||
}
|
||||
|
||||
func NetworkDevices() NetworkDevicesOptions {
|
||||
widgetOptions["NetworkDevicesOptions"] = createNetworkDevicesList
|
||||
return NetworkDevicesOptions{}
|
||||
}
|
||||
|
||||
func createNetworkDevicesList(ctx context.Context, _ terminalapi.Terminal, _ interface{}) widgetapi.Widget {
|
||||
list := util.PanicOnErrorWithResult(text.New())
|
||||
go util.Periodic(ctx, 20*time.Second, func() error {
|
||||
interfaces := networking.GetDevices()
|
||||
list.Reset()
|
||||
for iface, devices := range interfaces {
|
||||
status := cell.ColorGreen
|
||||
if iface == "offline" {
|
||||
status = cell.ColorGray
|
||||
}
|
||||
if err := list.Write(fmt.Sprintf("=== %s ===\n", iface)); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, mac := range sortedKeys(devices) {
|
||||
if err := list.Write(fmt.Sprintf("|%-15s|", mac), text.WriteCellOpts(cell.FgColor(cell.ColorGray))); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := list.Write(fmt.Sprintf("%2s ", devices[mac].Icon), text.WriteCellOpts(cell.FgColor(status))); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := list.Write(fmt.Sprintf(" %s", devices[mac].Name), text.WriteCellOpts(cell.FgColor(cell.ColorWhite))); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := list.Write(fmt.Sprintf(" (%s)\n", devices[mac].IP), text.WriteCellOpts(cell.FgColor(cell.ColorGray))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
func sortedKeys(devices map[string]networking.Device) []string {
|
||||
macs := make([]string, 0, len(devices))
|
||||
for mac := range devices {
|
||||
macs = append(macs, mac)
|
||||
}
|
||||
sort.SliceStable(macs, func(i, j int) bool {
|
||||
return strings.Compare(devices[macs[i]].Name, devices[macs[j]].Name) < 0
|
||||
})
|
||||
return macs
|
||||
}
|
||||
Reference in New Issue
Block a user