84 lines
2.3 KiB
Go
84 lines
2.3 KiB
Go
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 := range sortedInterfaces(interfaces) {
|
|
if err := list.Write(fmt.Sprintf("=== %s ===\n", iface)); err != nil {
|
|
return err
|
|
}
|
|
for _, mac := range sortedKeys(interfaces[iface]) {
|
|
status := cell.ColorGray
|
|
if interfaces[iface][mac].Online {
|
|
status = cell.ColorGreen
|
|
}
|
|
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 ", interfaces[iface][mac].Icon), text.WriteCellOpts(cell.BgColor(status), cell.FgColor(cell.ColorBlack))); err != nil {
|
|
return err
|
|
}
|
|
if err := list.Write(fmt.Sprint("|"), text.WriteCellOpts(cell.FgColor(cell.ColorGray))); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := list.Write(fmt.Sprintf(" %s", interfaces[iface][mac].Name), text.WriteCellOpts(cell.FgColor(cell.ColorWhite))); err != nil {
|
|
return err
|
|
}
|
|
if err := list.Write(fmt.Sprintf(" (%s)\n", interfaces[iface][mac].IP), text.WriteCellOpts(cell.FgColor(cell.ColorGray))); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
})
|
|
|
|
return list
|
|
}
|
|
|
|
func sortedInterfaces(interfaces map[string]map[string]networking.Device) []string {
|
|
keys := make([]string, 0, len(interfaces))
|
|
for key := range interfaces {
|
|
keys = append(keys, key)
|
|
}
|
|
sort.Strings(keys)
|
|
return keys
|
|
}
|
|
|
|
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
|
|
}
|