2023-11-18 12:36:17 +03:00
|
|
|
package plugin
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
"runtime"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/Neur0toxine/sshpoke/pkg/convert"
|
|
|
|
"github.com/Neur0toxine/sshpoke/pkg/dto"
|
2023-11-18 17:51:04 +03:00
|
|
|
"github.com/Neur0toxine/sshpoke/pkg/errtools"
|
2023-11-18 12:36:17 +03:00
|
|
|
"github.com/Neur0toxine/sshpoke/pkg/plugin/pb"
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
parent pb.PluginServiceClient
|
|
|
|
token string
|
|
|
|
close func() error
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewClient(addr, token string) (*Client, error) {
|
|
|
|
conn, err := grpc.Dial(normalizeAddr(addr), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
c := &Client{
|
|
|
|
parent: pb.NewPluginServiceClient(conn),
|
|
|
|
token: token,
|
|
|
|
close: conn.Close,
|
|
|
|
}
|
|
|
|
runtime.SetFinalizer(c, connCloser)
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Event(ctx context.Context) (*Stream, error) {
|
|
|
|
stream, err := c.parent.Event(ctx, &emptypb.Empty{})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &Stream{stream: stream}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) EventStatus(ctx context.Context, status dto.EventStatus) error {
|
|
|
|
_, err := c.parent.EventStatus(ctx, convert.AppEventStatusToMessage(status))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func connCloser(c *Client) {
|
|
|
|
_ = c.close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func normalizeAddr(addr string) string {
|
|
|
|
addr = strings.TrimSpace(addr)
|
|
|
|
if strings.HasPrefix(addr, "grpc://") {
|
|
|
|
addr = addr[7:]
|
|
|
|
}
|
2023-11-18 17:51:04 +03:00
|
|
|
_, _, err := net.SplitHostPort(addr)
|
|
|
|
if err != nil && errtools.IsPortMissingErr(err) {
|
|
|
|
addr = net.JoinHostPort(addr, strconv.Itoa(DefaultPort))
|
2023-11-18 12:36:17 +03:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
2023-11-18 17:51:04 +03:00
|
|
|
return addr
|
2023-11-18 12:36:17 +03:00
|
|
|
}
|