From 82652060a7ee0bf955a03145fbbcac4088632fe1 Mon Sep 17 00:00:00 2001 From: milarin Date: Wed, 10 Jan 2024 21:56:00 +0100 Subject: [PATCH] ObserveEndOfFile implemented --- props_observe.go | 12 ++++++++++++ send_command.go | 24 ++++++++++++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/props_observe.go b/props_observe.go index 4da9444..a62cf1e 100644 --- a/props_observe.go +++ b/props_observe.go @@ -7,6 +7,18 @@ import ( "git.milar.in/milarin/channel" ) +func ObserveEndOfFile(ctx context.Context, socket string) (<-chan string, error) { + ch, err := ObserveEvent[any](ctx, socket, "end-file") + if err != nil { + return nil, err + } + + getReason := func(e Event[any]) string { return e.Reason } + notEmpty := func(str string) bool { return str != "" } + reasons := channel.Filter(channel.MapSuccessive(ch, getReason), notEmpty) + return reasons, nil +} + func ObserveDisplayNames(ctx context.Context, socket string) (<-chan []string, error) { return ObserveProperty[[]string](ctx, socket, "display-names") } diff --git a/send_command.go b/send_command.go index 51b1b80..27455aa 100644 --- a/send_command.go +++ b/send_command.go @@ -5,6 +5,8 @@ import ( "encoding/json" "errors" "net" + + "git.milar.in/milarin/channel" ) type Command struct { @@ -18,10 +20,11 @@ type Response[T any] struct { } type Event[T any] struct { - Data T `json:"data"` - ID int `json:"id"` - Name string `json:"name"` - Error string `json:"error"` + Data T `json:"data"` + ID int `json:"id"` + Name string `json:"name"` + Error string `json:"error"` + Reason string `json:"reason"` } func SendCommand[T any](socket string, cmd *Command) (*Response[T], error) { @@ -72,7 +75,16 @@ func SetProperty[T any](socket string, propertyName string, propertyValue T) err } func ObserveProperty[T any](ctx context.Context, socket string, propertyName string) (<-chan T, error) { - out := make(chan T, 10) + ch, err := ObserveEvent[T](ctx, socket, propertyName) + if err != nil { + return nil, err + } + + return channel.MapSuccessive(ch, func(e Event[T]) T { return e.Data }), nil +} + +func ObserveEvent[T any](ctx context.Context, socket string, propertyName string) (<-chan Event[T], error) { + out := make(chan Event[T], 10) conn, err := net.Dial("unix", socket) if err != nil { @@ -113,7 +125,7 @@ func ObserveProperty[T any](ctx context.Context, socket string, propertyName str if err := dec.Decode(&event); err != nil { break } - out <- event.Data + out <- event } }()