From 173997c44bb3c5143865144df17cb0225accf62c Mon Sep 17 00:00:00 2001 From: link Date: Mon, 6 Feb 2023 15:47:29 +0800 Subject: [PATCH] Send notification changes to message bus (#861) --- cmd/migration-tool/main.go | 6 +- codegen/message_bus/api.go | 2254 ++++++++++++++++++++++++++++++++++ common/constants.go | 7 + common/message.go | 23 + go.mod | 3 + go.sum | 10 + main.go | 31 +- pkg/utils/version/version.go | 4 +- route/init.go | 4 +- route/periodical.go | 2 +- route/socket.go | 62 - route/v1.go | 8 +- route/v1/notify.go | 8 +- route/v1/recover.go | 20 +- route/v1/system.go | 5 +- service/notify.go | 88 +- service/service.go | 35 +- types/system.go | 24 - 18 files changed, 2436 insertions(+), 158 deletions(-) create mode 100644 codegen/message_bus/api.go create mode 100644 common/constants.go create mode 100644 common/message.go delete mode 100644 route/socket.go delete mode 100644 types/system.go diff --git a/cmd/migration-tool/main.go b/cmd/migration-tool/main.go index f33b349..91a68a4 100644 --- a/cmd/migration-tool/main.go +++ b/cmd/migration-tool/main.go @@ -17,10 +17,10 @@ import ( interfaces "github.com/IceWhaleTech/CasaOS-Common" "github.com/IceWhaleTech/CasaOS-Common/utils/systemctl" + "github.com/IceWhaleTech/CasaOS/common" "github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/sqlite" "github.com/IceWhaleTech/CasaOS/service" - "github.com/IceWhaleTech/CasaOS/types" "gorm.io/gorm" ) @@ -47,7 +47,7 @@ func init() { flag.Parse() if *versionFlag { - fmt.Println("v" + types.CURRENTVERSION) + fmt.Println("v" + common.VERSION) os.Exit(0) } @@ -86,7 +86,7 @@ func init() { sqliteDB = sqlite.GetDb(dbFlag) // gredis.GetRedisConn(config.RedisInfo), - service.MyService = service.NewService(sqliteDB, "", nil) + service.MyService = service.NewService(sqliteDB, "") } func main() { diff --git a/codegen/message_bus/api.go b/codegen/message_bus/api.go new file mode 100644 index 0000000..a115aab --- /dev/null +++ b/codegen/message_bus/api.go @@ -0,0 +1,2254 @@ +// Package message_bus provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/deepmap/oapi-codegen version v1.12.4 DO NOT EDIT. +package message_bus + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/deepmap/oapi-codegen/pkg/runtime" +) + +const ( + Access_tokenScopes = "access_token.Scopes" +) + +// Action defines model for Action. +type Action struct { + // Name action name + Name string `json:"name"` + + // Properties event properties + Properties map[string]string `json:"properties"` + + // SourceID associated source id + SourceID string `json:"sourceID"` + + // Timestamp timestamp this action took place + Timestamp *time.Time `json:"timestamp,omitempty"` +} + +// ActionType defines model for ActionType. +type ActionType struct { + // Name action name + // + // (there is no naming convention for action names, but it is recommended to name each as structural and descriptive as possible) + Name string `json:"name"` + PropertyTypeList []PropertyType `json:"propertyTypeList"` + + // SourceID action source id to identify where the action will take + SourceID string `json:"sourceID"` +} + +// BaseResponse defines model for BaseResponse. +type BaseResponse struct { + // Message message returned by server side if there is any + Message *string `json:"message,omitempty"` +} + +// Event defines model for Event. +type Event struct { + // Name event name + Name string `json:"name"` + + // Properties event properties + Properties map[string]string `json:"properties"` + + // SourceID associated source id + SourceID string `json:"sourceID"` + + // Timestamp timestamp this event took place + Timestamp *time.Time `json:"timestamp,omitempty"` + + // Uuid event uuid + Uuid *string `json:"uuid,omitempty"` +} + +// EventType defines model for EventType. +type EventType struct { + // Name event name + // + // (there is no naming convention for event names, but it is recommended to name each as structural and descriptive as possible) + Name string `json:"name"` + PropertyTypeList []PropertyType `json:"propertyTypeList"` + + // SourceID event source id to identify where the event comes from + SourceID string `json:"sourceID"` +} + +// PropertyType defines model for PropertyType. +type PropertyType struct { + Description *string `json:"description,omitempty"` + Example *string `json:"example,omitempty"` + + // Name property name + // + // > It is recommended for a property name to be as descriptive as possible. One option is to prefix with a namespace. + // > - If the property is source specific, prefix with source ID. For example, `local-storage:vendor` + // > - Otherwise, prefix with `common:`. For example, `common:email` + // > + // > Some bad examples are `id`, `avail`, `blk`...which can be ambiguous and confusing. + Name string `json:"name"` +} + +// ActionName defines model for ActionName. +type ActionName = string + +// ActionNames defines model for ActionNames. +type ActionNames = []string + +// EventName defines model for EventName. +type EventName = string + +// EventNames defines model for EventNames. +type EventNames = []string + +// SourceID defines model for SourceID. +type SourceID = string + +// GetActionTypeOK defines model for GetActionTypeOK. +type GetActionTypeOK = ActionType + +// GetActionTypesOK defines model for GetActionTypesOK. +type GetActionTypesOK = []ActionType + +// GetEventTypeOK defines model for GetEventTypeOK. +type GetEventTypeOK = EventType + +// GetEventTypesOK defines model for GetEventTypesOK. +type GetEventTypesOK = []EventType + +// PublishEventOK defines model for PublishEventOK. +type PublishEventOK = Event + +// ResponseBadRequest defines model for ResponseBadRequest. +type ResponseBadRequest = BaseResponse + +// ResponseConflict defines model for ResponseConflict. +type ResponseConflict = BaseResponse + +// ResponseInternalServerError defines model for ResponseInternalServerError. +type ResponseInternalServerError = BaseResponse + +// ResponseNotFound defines model for ResponseNotFound. +type ResponseNotFound = BaseResponse + +// ResponseOK defines model for ResponseOK. +type ResponseOK = BaseResponse + +// TriggerActionOK defines model for TriggerActionOK. +type TriggerActionOK = Action + +// PublishEvent event properties +type PublishEvent map[string]string + +// RegisterActionTypes defines model for RegisterActionTypes. +type RegisterActionTypes = []ActionType + +// RegisterEventTypes defines model for RegisterEventTypes. +type RegisterEventTypes = []EventType + +// TriggerAction action properties +type TriggerAction map[string]string + +// SubscribeActionWSParams defines parameters for SubscribeActionWS. +type SubscribeActionWSParams struct { + Names *ActionNames `form:"names,omitempty" json:"names,omitempty"` +} + +// TriggerActionJSONBody defines parameters for TriggerAction. +type TriggerActionJSONBody map[string]string + +// RegisterActionTypesJSONBody defines parameters for RegisterActionTypes. +type RegisterActionTypesJSONBody = []ActionType + +// SubscribeEventWSParams defines parameters for SubscribeEventWS. +type SubscribeEventWSParams struct { + Names *EventNames `form:"names,omitempty" json:"names,omitempty"` +} + +// PublishEventJSONBody defines parameters for PublishEvent. +type PublishEventJSONBody map[string]string + +// RegisterEventTypesJSONBody defines parameters for RegisterEventTypes. +type RegisterEventTypesJSONBody = []EventType + +// TriggerActionJSONRequestBody defines body for TriggerAction for application/json ContentType. +type TriggerActionJSONRequestBody TriggerActionJSONBody + +// RegisterActionTypesJSONRequestBody defines body for RegisterActionTypes for application/json ContentType. +type RegisterActionTypesJSONRequestBody = RegisterActionTypesJSONBody + +// PublishEventJSONRequestBody defines body for PublishEvent for application/json ContentType. +type PublishEventJSONRequestBody PublishEventJSONBody + +// RegisterEventTypesJSONRequestBody defines body for RegisterEventTypes for application/json ContentType. +type RegisterEventTypesJSONRequestBody = RegisterEventTypesJSONBody + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // SubscribeActionWS request + SubscribeActionWS(ctx context.Context, sourceId SourceID, params *SubscribeActionWSParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // TriggerAction request with any body + TriggerActionWithBody(ctx context.Context, sourceId SourceID, name ActionName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + TriggerAction(ctx context.Context, sourceId SourceID, name ActionName, body TriggerActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetActionTypes request + GetActionTypes(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RegisterActionTypes request with any body + RegisterActionTypesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + RegisterActionTypes(ctx context.Context, body RegisterActionTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetActionTypesBySourceID request + GetActionTypesBySourceID(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetActionType request + GetActionType(ctx context.Context, sourceId SourceID, name ActionName, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SubscribeEventWS request + SubscribeEventWS(ctx context.Context, sourceId SourceID, params *SubscribeEventWSParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PublishEvent request with any body + PublishEventWithBody(ctx context.Context, sourceId SourceID, name EventName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + PublishEvent(ctx context.Context, sourceId SourceID, name EventName, body PublishEventJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEventTypes request + GetEventTypes(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RegisterEventTypes request with any body + RegisterEventTypesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + RegisterEventTypes(ctx context.Context, body RegisterEventTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEventTypesBySourceID request + GetEventTypesBySourceID(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEventType request + GetEventType(ctx context.Context, sourceId SourceID, name EventName, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SubscribeSIO request + SubscribeSIO(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PollSIO request + PollSIO(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SubscribeSIO2 request + SubscribeSIO2(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PollSIO2 request + PollSIO2(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) SubscribeActionWS(ctx context.Context, sourceId SourceID, params *SubscribeActionWSParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSubscribeActionWSRequest(c.Server, sourceId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) TriggerActionWithBody(ctx context.Context, sourceId SourceID, name ActionName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewTriggerActionRequestWithBody(c.Server, sourceId, name, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) TriggerAction(ctx context.Context, sourceId SourceID, name ActionName, body TriggerActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewTriggerActionRequest(c.Server, sourceId, name, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetActionTypes(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetActionTypesRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RegisterActionTypesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRegisterActionTypesRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RegisterActionTypes(ctx context.Context, body RegisterActionTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRegisterActionTypesRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetActionTypesBySourceID(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetActionTypesBySourceIDRequest(c.Server, sourceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetActionType(ctx context.Context, sourceId SourceID, name ActionName, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetActionTypeRequest(c.Server, sourceId, name) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SubscribeEventWS(ctx context.Context, sourceId SourceID, params *SubscribeEventWSParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSubscribeEventWSRequest(c.Server, sourceId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PublishEventWithBody(ctx context.Context, sourceId SourceID, name EventName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPublishEventRequestWithBody(c.Server, sourceId, name, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PublishEvent(ctx context.Context, sourceId SourceID, name EventName, body PublishEventJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPublishEventRequest(c.Server, sourceId, name, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEventTypes(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEventTypesRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RegisterEventTypesWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRegisterEventTypesRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RegisterEventTypes(ctx context.Context, body RegisterEventTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRegisterEventTypesRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEventTypesBySourceID(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEventTypesBySourceIDRequest(c.Server, sourceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEventType(ctx context.Context, sourceId SourceID, name EventName, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEventTypeRequest(c.Server, sourceId, name) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SubscribeSIO(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSubscribeSIORequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PollSIO(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPollSIORequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SubscribeSIO2(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSubscribeSIO2Request(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PollSIO2(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPollSIO2Request(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewSubscribeActionWSRequest generates requests for SubscribeActionWS +func NewSubscribeActionWSRequest(server string, sourceId SourceID, params *SubscribeActionWSParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/action/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + queryValues := queryURL.Query() + + if params.Names != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "names", runtime.ParamLocationQuery, *params.Names); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewTriggerActionRequest calls the generic TriggerAction builder with application/json body +func NewTriggerActionRequest(server string, sourceId SourceID, name ActionName, body TriggerActionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewTriggerActionRequestWithBody(server, sourceId, name, "application/json", bodyReader) +} + +// NewTriggerActionRequestWithBody generates requests for TriggerAction with any type of body +func NewTriggerActionRequestWithBody(server string, sourceId SourceID, name ActionName, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/action/%s/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetActionTypesRequest generates requests for GetActionTypes +func NewGetActionTypesRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/action_type") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRegisterActionTypesRequest calls the generic RegisterActionTypes builder with application/json body +func NewRegisterActionTypesRequest(server string, body RegisterActionTypesJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewRegisterActionTypesRequestWithBody(server, "application/json", bodyReader) +} + +// NewRegisterActionTypesRequestWithBody generates requests for RegisterActionTypes with any type of body +func NewRegisterActionTypesRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/action_type") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetActionTypesBySourceIDRequest generates requests for GetActionTypesBySourceID +func NewGetActionTypesBySourceIDRequest(server string, sourceId SourceID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/action_type/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetActionTypeRequest generates requests for GetActionType +func NewGetActionTypeRequest(server string, sourceId SourceID, name ActionName) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/action_type/%s/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSubscribeEventWSRequest generates requests for SubscribeEventWS +func NewSubscribeEventWSRequest(server string, sourceId SourceID, params *SubscribeEventWSParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/event/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + queryValues := queryURL.Query() + + if params.Names != nil { + + if queryFrag, err := runtime.StyleParamWithLocation("form", true, "names", runtime.ParamLocationQuery, *params.Names); err != nil { + return nil, err + } else if parsed, err := url.ParseQuery(queryFrag); err != nil { + return nil, err + } else { + for k, v := range parsed { + for _, v2 := range v { + queryValues.Add(k, v2) + } + } + } + + } + + queryURL.RawQuery = queryValues.Encode() + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewPublishEventRequest calls the generic PublishEvent builder with application/json body +func NewPublishEventRequest(server string, sourceId SourceID, name EventName, body PublishEventJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewPublishEventRequestWithBody(server, sourceId, name, "application/json", bodyReader) +} + +// NewPublishEventRequestWithBody generates requests for PublishEvent with any type of body +func NewPublishEventRequestWithBody(server string, sourceId SourceID, name EventName, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/event/%s/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetEventTypesRequest generates requests for GetEventTypes +func NewGetEventTypesRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/event_type") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRegisterEventTypesRequest calls the generic RegisterEventTypes builder with application/json body +func NewRegisterEventTypesRequest(server string, body RegisterEventTypesJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewRegisterEventTypesRequestWithBody(server, "application/json", bodyReader) +} + +// NewRegisterEventTypesRequestWithBody generates requests for RegisterEventTypes with any type of body +func NewRegisterEventTypesRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/event_type") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetEventTypesBySourceIDRequest generates requests for GetEventTypesBySourceID +func NewGetEventTypesBySourceIDRequest(server string, sourceId SourceID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/event_type/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetEventTypeRequest generates requests for GetEventType +func NewGetEventTypeRequest(server string, sourceId SourceID, name EventName) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithLocation("simple", false, "source_id", runtime.ParamLocationPath, sourceId) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithLocation("simple", false, "name", runtime.ParamLocationPath, name) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/event_type/%s/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSubscribeSIORequest generates requests for SubscribeSIO +func NewSubscribeSIORequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/socket.io") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewPollSIORequest generates requests for PollSIO +func NewPollSIORequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/socket.io") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSubscribeSIO2Request generates requests for SubscribeSIO2 +func NewSubscribeSIO2Request(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/socket.io/") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("GET", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewPollSIO2Request generates requests for PollSIO2 +func NewPollSIO2Request(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/socket.io/") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // SubscribeActionWS request + SubscribeActionWSWithResponse(ctx context.Context, sourceId SourceID, params *SubscribeActionWSParams, reqEditors ...RequestEditorFn) (*SubscribeActionWSResponse, error) + + // TriggerAction request with any body + TriggerActionWithBodyWithResponse(ctx context.Context, sourceId SourceID, name ActionName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TriggerActionResponse, error) + + TriggerActionWithResponse(ctx context.Context, sourceId SourceID, name ActionName, body TriggerActionJSONRequestBody, reqEditors ...RequestEditorFn) (*TriggerActionResponse, error) + + // GetActionTypes request + GetActionTypesWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetActionTypesResponse, error) + + // RegisterActionTypes request with any body + RegisterActionTypesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RegisterActionTypesResponse, error) + + RegisterActionTypesWithResponse(ctx context.Context, body RegisterActionTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*RegisterActionTypesResponse, error) + + // GetActionTypesBySourceID request + GetActionTypesBySourceIDWithResponse(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*GetActionTypesBySourceIDResponse, error) + + // GetActionType request + GetActionTypeWithResponse(ctx context.Context, sourceId SourceID, name ActionName, reqEditors ...RequestEditorFn) (*GetActionTypeResponse, error) + + // SubscribeEventWS request + SubscribeEventWSWithResponse(ctx context.Context, sourceId SourceID, params *SubscribeEventWSParams, reqEditors ...RequestEditorFn) (*SubscribeEventWSResponse, error) + + // PublishEvent request with any body + PublishEventWithBodyWithResponse(ctx context.Context, sourceId SourceID, name EventName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PublishEventResponse, error) + + PublishEventWithResponse(ctx context.Context, sourceId SourceID, name EventName, body PublishEventJSONRequestBody, reqEditors ...RequestEditorFn) (*PublishEventResponse, error) + + // GetEventTypes request + GetEventTypesWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetEventTypesResponse, error) + + // RegisterEventTypes request with any body + RegisterEventTypesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RegisterEventTypesResponse, error) + + RegisterEventTypesWithResponse(ctx context.Context, body RegisterEventTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*RegisterEventTypesResponse, error) + + // GetEventTypesBySourceID request + GetEventTypesBySourceIDWithResponse(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*GetEventTypesBySourceIDResponse, error) + + // GetEventType request + GetEventTypeWithResponse(ctx context.Context, sourceId SourceID, name EventName, reqEditors ...RequestEditorFn) (*GetEventTypeResponse, error) + + // SubscribeSIO request + SubscribeSIOWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SubscribeSIOResponse, error) + + // PollSIO request + PollSIOWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*PollSIOResponse, error) + + // SubscribeSIO2 request + SubscribeSIO2WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SubscribeSIO2Response, error) + + // PollSIO2 request + PollSIO2WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*PollSIO2Response, error) +} + +type SubscribeActionWSResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r SubscribeActionWSResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SubscribeActionWSResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type TriggerActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Action + JSON400 *BaseResponse + JSON404 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r TriggerActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r TriggerActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetActionTypesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]ActionType +} + +// Status returns HTTPResponse.Status +func (r GetActionTypesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetActionTypesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type RegisterActionTypesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BaseResponse + JSON400 *BaseResponse + JSON409 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r RegisterActionTypesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RegisterActionTypesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetActionTypesBySourceIDResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]ActionType + JSON404 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r GetActionTypesBySourceIDResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetActionTypesBySourceIDResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetActionTypeResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *ActionType + JSON404 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r GetActionTypeResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetActionTypeResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type SubscribeEventWSResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r SubscribeEventWSResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SubscribeEventWSResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PublishEventResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Event + JSON400 *BaseResponse + JSON404 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r PublishEventResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PublishEventResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEventTypesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]EventType + JSON500 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r GetEventTypesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEventTypesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type RegisterEventTypesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BaseResponse + JSON400 *BaseResponse + JSON409 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r RegisterEventTypesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RegisterEventTypesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEventTypesBySourceIDResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]EventType + JSON404 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r GetEventTypesBySourceIDResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEventTypesBySourceIDResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEventTypeResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EventType + JSON404 *BaseResponse +} + +// Status returns HTTPResponse.Status +func (r GetEventTypeResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEventTypeResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type SubscribeSIOResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r SubscribeSIOResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SubscribeSIOResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PollSIOResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r PollSIOResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PollSIOResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type SubscribeSIO2Response struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r SubscribeSIO2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SubscribeSIO2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PollSIO2Response struct { + Body []byte + HTTPResponse *http.Response +} + +// Status returns HTTPResponse.Status +func (r PollSIO2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PollSIO2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// SubscribeActionWSWithResponse request returning *SubscribeActionWSResponse +func (c *ClientWithResponses) SubscribeActionWSWithResponse(ctx context.Context, sourceId SourceID, params *SubscribeActionWSParams, reqEditors ...RequestEditorFn) (*SubscribeActionWSResponse, error) { + rsp, err := c.SubscribeActionWS(ctx, sourceId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseSubscribeActionWSResponse(rsp) +} + +// TriggerActionWithBodyWithResponse request with arbitrary body returning *TriggerActionResponse +func (c *ClientWithResponses) TriggerActionWithBodyWithResponse(ctx context.Context, sourceId SourceID, name ActionName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TriggerActionResponse, error) { + rsp, err := c.TriggerActionWithBody(ctx, sourceId, name, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseTriggerActionResponse(rsp) +} + +func (c *ClientWithResponses) TriggerActionWithResponse(ctx context.Context, sourceId SourceID, name ActionName, body TriggerActionJSONRequestBody, reqEditors ...RequestEditorFn) (*TriggerActionResponse, error) { + rsp, err := c.TriggerAction(ctx, sourceId, name, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseTriggerActionResponse(rsp) +} + +// GetActionTypesWithResponse request returning *GetActionTypesResponse +func (c *ClientWithResponses) GetActionTypesWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetActionTypesResponse, error) { + rsp, err := c.GetActionTypes(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetActionTypesResponse(rsp) +} + +// RegisterActionTypesWithBodyWithResponse request with arbitrary body returning *RegisterActionTypesResponse +func (c *ClientWithResponses) RegisterActionTypesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RegisterActionTypesResponse, error) { + rsp, err := c.RegisterActionTypesWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseRegisterActionTypesResponse(rsp) +} + +func (c *ClientWithResponses) RegisterActionTypesWithResponse(ctx context.Context, body RegisterActionTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*RegisterActionTypesResponse, error) { + rsp, err := c.RegisterActionTypes(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseRegisterActionTypesResponse(rsp) +} + +// GetActionTypesBySourceIDWithResponse request returning *GetActionTypesBySourceIDResponse +func (c *ClientWithResponses) GetActionTypesBySourceIDWithResponse(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*GetActionTypesBySourceIDResponse, error) { + rsp, err := c.GetActionTypesBySourceID(ctx, sourceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetActionTypesBySourceIDResponse(rsp) +} + +// GetActionTypeWithResponse request returning *GetActionTypeResponse +func (c *ClientWithResponses) GetActionTypeWithResponse(ctx context.Context, sourceId SourceID, name ActionName, reqEditors ...RequestEditorFn) (*GetActionTypeResponse, error) { + rsp, err := c.GetActionType(ctx, sourceId, name, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetActionTypeResponse(rsp) +} + +// SubscribeEventWSWithResponse request returning *SubscribeEventWSResponse +func (c *ClientWithResponses) SubscribeEventWSWithResponse(ctx context.Context, sourceId SourceID, params *SubscribeEventWSParams, reqEditors ...RequestEditorFn) (*SubscribeEventWSResponse, error) { + rsp, err := c.SubscribeEventWS(ctx, sourceId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseSubscribeEventWSResponse(rsp) +} + +// PublishEventWithBodyWithResponse request with arbitrary body returning *PublishEventResponse +func (c *ClientWithResponses) PublishEventWithBodyWithResponse(ctx context.Context, sourceId SourceID, name EventName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PublishEventResponse, error) { + rsp, err := c.PublishEventWithBody(ctx, sourceId, name, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePublishEventResponse(rsp) +} + +func (c *ClientWithResponses) PublishEventWithResponse(ctx context.Context, sourceId SourceID, name EventName, body PublishEventJSONRequestBody, reqEditors ...RequestEditorFn) (*PublishEventResponse, error) { + rsp, err := c.PublishEvent(ctx, sourceId, name, body, reqEditors...) + if err != nil { + return nil, err + } + return ParsePublishEventResponse(rsp) +} + +// GetEventTypesWithResponse request returning *GetEventTypesResponse +func (c *ClientWithResponses) GetEventTypesWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetEventTypesResponse, error) { + rsp, err := c.GetEventTypes(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEventTypesResponse(rsp) +} + +// RegisterEventTypesWithBodyWithResponse request with arbitrary body returning *RegisterEventTypesResponse +func (c *ClientWithResponses) RegisterEventTypesWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*RegisterEventTypesResponse, error) { + rsp, err := c.RegisterEventTypesWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseRegisterEventTypesResponse(rsp) +} + +func (c *ClientWithResponses) RegisterEventTypesWithResponse(ctx context.Context, body RegisterEventTypesJSONRequestBody, reqEditors ...RequestEditorFn) (*RegisterEventTypesResponse, error) { + rsp, err := c.RegisterEventTypes(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseRegisterEventTypesResponse(rsp) +} + +// GetEventTypesBySourceIDWithResponse request returning *GetEventTypesBySourceIDResponse +func (c *ClientWithResponses) GetEventTypesBySourceIDWithResponse(ctx context.Context, sourceId SourceID, reqEditors ...RequestEditorFn) (*GetEventTypesBySourceIDResponse, error) { + rsp, err := c.GetEventTypesBySourceID(ctx, sourceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEventTypesBySourceIDResponse(rsp) +} + +// GetEventTypeWithResponse request returning *GetEventTypeResponse +func (c *ClientWithResponses) GetEventTypeWithResponse(ctx context.Context, sourceId SourceID, name EventName, reqEditors ...RequestEditorFn) (*GetEventTypeResponse, error) { + rsp, err := c.GetEventType(ctx, sourceId, name, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEventTypeResponse(rsp) +} + +// SubscribeSIOWithResponse request returning *SubscribeSIOResponse +func (c *ClientWithResponses) SubscribeSIOWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SubscribeSIOResponse, error) { + rsp, err := c.SubscribeSIO(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseSubscribeSIOResponse(rsp) +} + +// PollSIOWithResponse request returning *PollSIOResponse +func (c *ClientWithResponses) PollSIOWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*PollSIOResponse, error) { + rsp, err := c.PollSIO(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParsePollSIOResponse(rsp) +} + +// SubscribeSIO2WithResponse request returning *SubscribeSIO2Response +func (c *ClientWithResponses) SubscribeSIO2WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*SubscribeSIO2Response, error) { + rsp, err := c.SubscribeSIO2(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseSubscribeSIO2Response(rsp) +} + +// PollSIO2WithResponse request returning *PollSIO2Response +func (c *ClientWithResponses) PollSIO2WithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*PollSIO2Response, error) { + rsp, err := c.PollSIO2(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParsePollSIO2Response(rsp) +} + +// ParseSubscribeActionWSResponse parses an HTTP response from a SubscribeActionWSWithResponse call +func ParseSubscribeActionWSResponse(rsp *http.Response) (*SubscribeActionWSResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SubscribeActionWSResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseTriggerActionResponse parses an HTTP response from a TriggerActionWithResponse call +func ParseTriggerActionResponse(rsp *http.Response) (*TriggerActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &TriggerActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Action + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetActionTypesResponse parses an HTTP response from a GetActionTypesWithResponse call +func ParseGetActionTypesResponse(rsp *http.Response) (*GetActionTypesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetActionTypesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []ActionType + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseRegisterActionTypesResponse parses an HTTP response from a RegisterActionTypesWithResponse call +func ParseRegisterActionTypesResponse(rsp *http.Response) (*RegisterActionTypesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &RegisterActionTypesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + } + + return response, nil +} + +// ParseGetActionTypesBySourceIDResponse parses an HTTP response from a GetActionTypesBySourceIDWithResponse call +func ParseGetActionTypesBySourceIDResponse(rsp *http.Response) (*GetActionTypesBySourceIDResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetActionTypesBySourceIDResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []ActionType + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetActionTypeResponse parses an HTTP response from a GetActionTypeWithResponse call +func ParseGetActionTypeResponse(rsp *http.Response) (*GetActionTypeResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetActionTypeResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ActionType + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseSubscribeEventWSResponse parses an HTTP response from a SubscribeEventWSWithResponse call +func ParseSubscribeEventWSResponse(rsp *http.Response) (*SubscribeEventWSResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SubscribeEventWSResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParsePublishEventResponse parses an HTTP response from a PublishEventWithResponse call +func ParsePublishEventResponse(rsp *http.Response) (*PublishEventResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PublishEventResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Event + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetEventTypesResponse parses an HTTP response from a GetEventTypesWithResponse call +func ParseGetEventTypesResponse(rsp *http.Response) (*GetEventTypesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEventTypesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []EventType + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseRegisterEventTypesResponse parses an HTTP response from a RegisterEventTypesWithResponse call +func ParseRegisterEventTypesResponse(rsp *http.Response) (*RegisterEventTypesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &RegisterEventTypesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + + } + + return response, nil +} + +// ParseGetEventTypesBySourceIDResponse parses an HTTP response from a GetEventTypesBySourceIDWithResponse call +func ParseGetEventTypesBySourceIDResponse(rsp *http.Response) (*GetEventTypesBySourceIDResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEventTypesBySourceIDResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []EventType + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetEventTypeResponse parses an HTTP response from a GetEventTypeWithResponse call +func ParseGetEventTypeResponse(rsp *http.Response) (*GetEventTypeResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEventTypeResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EventType + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest BaseResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseSubscribeSIOResponse parses an HTTP response from a SubscribeSIOWithResponse call +func ParseSubscribeSIOResponse(rsp *http.Response) (*SubscribeSIOResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SubscribeSIOResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParsePollSIOResponse parses an HTTP response from a PollSIOWithResponse call +func ParsePollSIOResponse(rsp *http.Response) (*PollSIOResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PollSIOResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseSubscribeSIO2Response parses an HTTP response from a SubscribeSIO2WithResponse call +func ParseSubscribeSIO2Response(rsp *http.Response) (*SubscribeSIO2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SubscribeSIO2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParsePollSIO2Response parses an HTTP response from a PollSIO2WithResponse call +func ParsePollSIO2Response(rsp *http.Response) (*PollSIO2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PollSIO2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} diff --git a/common/constants.go b/common/constants.go new file mode 100644 index 0000000..0fadade --- /dev/null +++ b/common/constants.go @@ -0,0 +1,7 @@ +package common + +const ( + SERVICENAME = "casaos" + VERSION = "0.4.2" + BODY = " " +) diff --git a/common/message.go b/common/message.go new file mode 100644 index 0000000..5e41a25 --- /dev/null +++ b/common/message.go @@ -0,0 +1,23 @@ +package common + +import ( + "fmt" + + "github.com/IceWhaleTech/CasaOS/codegen/message_bus" +) + +var ( + // devtype -> action -> event + EventTypes map[string]map[string]message_bus.EventType + + PropertyNameLookupMaps = map[string]map[string]string{ + "system": { + fmt.Sprintf("%s:%s", SERVICENAME, "utilization"): "ID_BUS", + }, + } + + ActionPastTense = map[string]string{ + "add": "added", + "remove": "removed", + } +) diff --git a/go.mod b/go.mod index 3b08af6..81e48bb 100644 --- a/go.mod +++ b/go.mod @@ -31,6 +31,7 @@ require ( github.com/patrickmn/go-cache v2.1.0+incompatible github.com/pkg/errors v0.9.1 github.com/robfig/cron v1.2.0 + github.com/samber/lo v1.37.0 github.com/satori/go.uuid v1.2.0 github.com/shirou/gopsutil/v3 v3.22.11 github.com/sirupsen/logrus v1.9.0 @@ -45,6 +46,7 @@ require ( require ( github.com/andybalholm/brotli v1.0.1 // indirect + github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/benbjohnson/clock v1.3.0 // indirect github.com/coreos/go-systemd/v22 v22.3.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect @@ -107,6 +109,7 @@ require ( github.com/yusufpapurcu/wmi v1.2.2 // indirect go.uber.org/atomic v1.7.0 // indirect go.uber.org/multierr v1.6.0 // indirect + golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 // indirect golang.org/x/net v0.5.0 // indirect golang.org/x/sys v0.4.0 // indirect diff --git a/go.sum b/go.sum index 7b51bff..a9e17e2 100644 --- a/go.sum +++ b/go.sum @@ -3,12 +3,16 @@ github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d/go.mod h1:lW9x+yEjqKdPbE3+cf2fGPJXCw/hChX3Omi9QHTLFsQ= github.com/IceWhaleTech/CasaOS-Common v0.4.2-alpha1 h1:4Z61swpEC/OUGLlzww1v/D916j7yqYnfBevdVD/dgjI= github.com/IceWhaleTech/CasaOS-Common v0.4.2-alpha1/go.mod h1:xcemiRsXcs1zrmQxYMyExDjZ7UHYwkJqYE71IDIV0xA= +github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= github.com/Xhofe/go-cache v0.0.0-20220723083548-714439c8af9a h1:RenIAa2q4H8UcS/cqmwdT1WCWIAH5aumP8m8RpbqVsE= github.com/Xhofe/go-cache v0.0.0-20220723083548-714439c8af9a/go.mod h1:sSBbaOg90XwWKtpT56kVujF0bIeVITnPlssLclogS04= github.com/andybalholm/brotli v1.0.1 h1:KqhlKozYbRtJvsPrrEeXcO+N2l6NYT5A2QAFmSULpEc= github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= +github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= +github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= github.com/chzyer/logex v1.2.0/go.mod h1:9+9sk7u7pGNWYMkh0hdiL++6OeibzJccyQU4p4MedaY= github.com/chzyer/readline v1.5.0/go.mod h1:x22KAscuvRqlLoK9CsoYsmxoXZMMFVyOl86cAH8qUic= github.com/chzyer/test v0.0.0-20210722231415-061457976a23/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -153,6 +157,7 @@ github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8Hm github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.11.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= @@ -227,12 +232,15 @@ github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfm github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/samber/lo v1.37.0 h1:XjVcB8g6tgUp8rsPsJ2CvhClfImrpL04YpQHXeHPhRw= +github.com/samber/lo v1.37.0/go.mod h1:9vaz2O4o8oOnK23pd2TrXufcbdbJIa3b6cstBWKpopA= github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/shirou/gopsutil/v3 v3.22.11 h1:kxsPKS+Eeo+VnEQ2XCaGJepeP6KY53QoRTETx3+1ndM= github.com/shirou/gopsutil/v3 v3.22.11/go.mod h1:xl0EeL4vXJ+hQMAGN8B9VFpxukEMA0XdevQOe5MZ1oY= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -286,6 +294,8 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= +golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM= +golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= diff --git a/main.go b/main.go index 8ef231b..ed1a83c 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,9 @@ //go:generate bash -c "mkdir -p codegen && go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen@v1.12.4 -generate types,server,spec -package codegen api/casaos/openapi.yaml > codegen/casaos_api.go" - +//go:generate bash -c "mkdir -p codegen/message_bus && go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen@v1.12.4 -generate types,client -package message_bus https://raw.githubusercontent.com/IceWhaleTech/CasaOS-MessageBus/main/api/message_bus/openapi.yaml > codegen/message_bus/api.go" package main import ( + "context" _ "embed" "flag" "fmt" @@ -14,10 +15,11 @@ import ( "github.com/IceWhaleTech/CasaOS-Common/model" "github.com/IceWhaleTech/CasaOS-Common/utils/constants" "github.com/IceWhaleTech/CasaOS-Common/utils/logger" - "github.com/gin-gonic/gin" util_http "github.com/IceWhaleTech/CasaOS-Common/utils/http" + "github.com/IceWhaleTech/CasaOS/codegen/message_bus" + "github.com/IceWhaleTech/CasaOS/common" "github.com/IceWhaleTech/CasaOS/pkg/cache" "github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/sqlite" @@ -25,7 +27,6 @@ import ( "github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/route" "github.com/IceWhaleTech/CasaOS/service" - "github.com/IceWhaleTech/CasaOS/types" "github.com/coreos/go-systemd/daemon" "go.uber.org/zap" @@ -56,7 +57,7 @@ var ( func init() { flag.Parse() if *versionFlag { - fmt.Println("v" + types.CURRENTVERSION) + fmt.Println("v" + common.VERSION) return } @@ -73,7 +74,7 @@ func init() { sqliteDB = sqlite.GetDb(*dbFlag) // gredis.GetRedisConn(config.RedisInfo), - service.MyService = service.NewService(sqliteDB, config.CommonInfo.RuntimePath, route.SocketIo()) + service.MyService = service.NewService(sqliteDB, config.CommonInfo.RuntimePath) service.Cache = cache.Init() @@ -99,10 +100,6 @@ func main() { } v1Router := route.InitV1Router() - defer service.SocketServer.Close() - - v1Router.GET("/v1/socketio/*any", gin.WrapH(service.SocketServer)) - v1Router.POST("/v1/socketio/*any", gin.WrapH(service.SocketServer)) v2Router := route.InitV2Router() v2DocRouter := route.InitV2DocRouter(_docHTML, _docYAML) @@ -148,7 +145,6 @@ func main() { "/v1/image", "/v1/samba", "/v1/notify", - "/v1/socketio", "/v1/driver", "/v1/cloud", "/v1/recover", @@ -166,6 +162,21 @@ func main() { panic(err) } } + var events []message_bus.EventType + events = append(events, message_bus.EventType{Name: "casaos:system:utilization", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}}) + events = append(events, message_bus.EventType{Name: "casaos:file:recover", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}}) + events = append(events, message_bus.EventType{Name: "casaos:file:operate", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}}) + // register at message bus + + response, err := service.MyService.MessageBus().RegisterEventTypesWithResponse(context.Background(), events) + if err != nil { + logger.Error("error when trying to register one or more event types - some event type will not be discoverable", zap.Error(err)) + } + + if response != nil && response.StatusCode() != http.StatusOK { + logger.Error("error when trying to register one or more event types - some event type will not be discoverable", zap.String("status", response.Status()), zap.String("body", string(response.Body))) + } + go func() { time.Sleep(time.Second * 2) // v0.3.6 diff --git a/pkg/utils/version/version.go b/pkg/utils/version/version.go index 8752f4a..d69d969 100644 --- a/pkg/utils/version/version.go +++ b/pkg/utils/version/version.go @@ -14,15 +14,15 @@ import ( "strconv" "strings" + "github.com/IceWhaleTech/CasaOS/common" "github.com/IceWhaleTech/CasaOS/model" - "github.com/IceWhaleTech/CasaOS/types" ) func IsNeedUpdate(version model.Version) (bool, model.Version) { v1 := strings.Split(version.Version, ".") - v2 := strings.Split(types.CURRENTVERSION, ".") + v2 := strings.Split(common.VERSION, ".") for len(v1) < len(v2) { v1 = append(v1, "0") diff --git a/route/init.go b/route/init.go index 0baa719..cb8f8c3 100644 --- a/route/init.go +++ b/route/init.go @@ -18,13 +18,13 @@ import ( "time" "github.com/IceWhaleTech/CasaOS-Common/utils/logger" + "github.com/IceWhaleTech/CasaOS/common" "github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/samba" "github.com/IceWhaleTech/CasaOS/pkg/utils/encryption" "github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/service" - "github.com/IceWhaleTech/CasaOS/types" "go.uber.org/zap" ) @@ -50,7 +50,7 @@ func InitInfo() { logger.Error("GetMacAddress", zap.String("error", err.Error())) } mb.Hash = encryption.GetMD5ByStr(mac) - mb.Version = types.CURRENTVERSION + mb.Version = common.VERSION os.Remove(config.AppInfo.DBPath + "/baseinfo.conf") by, err := json.Marshal(mb) if err != nil { diff --git a/route/periodical.go b/route/periodical.go index 588660b..2883acb 100644 --- a/route/periodical.go +++ b/route/periodical.go @@ -69,7 +69,7 @@ func SendAllHardwareStatusBySocket() { for k, v := range systemTempMap { body[k] = v } - service.MyService.Notify().SendNotify("sys_hardware_status", body) + service.MyService.Notify().SendNotify("casaos:system:utilization", body) } // func MonitoryUSB() { diff --git a/route/socket.go b/route/socket.go deleted file mode 100644 index 4d9e637..0000000 --- a/route/socket.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * @Author: LinkLeong link@icewhale.com - * @Date: 2022-05-23 17:18:56 - * @LastEditors: LinkLeong - * @LastEditTime: 2022-06-09 21:48:10 - * @FilePath: /CasaOS/route/socket.go - * @Description: - * @Website: https://www.casaos.io - * Copyright (c) 2022 by icewhale, All Rights Reserved. - */ -package route - -import ( - "github.com/IceWhaleTech/CasaOS-Common/utils/logger" - "github.com/IceWhaleTech/CasaOS/service" - socketio "github.com/googollee/go-socket.io" - "go.uber.org/zap" -) - -func SocketIo() *socketio.Server { - server := socketio.NewServer(nil) - server.OnConnect("/", func(s socketio.Conn) error { - s.SetContext("") - logger.Info("connected", zap.Any("id", s.ID())) - s.Join("public") - service.ClientCount += 1 - return nil - }) - - server.OnEvent("/", "notice", func(s socketio.Conn, msg string) { - logger.Info("notice", zap.Any("msg", msg)) - s.Emit("reply", "have "+msg) - }) - - // server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string { - // s.SetContext(msg) - // return "recv " + msg - // }) - - // server.OnEvent("/", "bye", func(s socketio.Conn) string { - // last := s.Context().(string) - // s.Emit("bye", last) - // s.Close() - // return last - // }) - - server.OnError("/", func(s socketio.Conn, e error) { - logger.Error("meet error", zap.Any("error", e)) - }) - - server.OnDisconnect("/", func(s socketio.Conn, reason string) { - service.ClientCount -= 1 - logger.Info("closed", zap.Any("reason", reason)) - }) - - go func() { - if err := server.Serve(); err != nil { - logger.Error("error when trying to listen socketio ", zap.Any("error", err)) - } - }() - return server -} diff --git a/route/v1.go b/route/v1.go index a818d35..3fce100 100644 --- a/route/v1.go +++ b/route/v1.go @@ -155,14 +155,10 @@ func InitV1Router() *gin.Engine { v1NotifyGroup.POST("/:path", v1.PostNotifyMessage) // merge to system v1NotifyGroup.POST("/system_status", v1.PostSystemStatusNotify) - v1NotifyGroup.POST("/install_app", v1.PostInstallAppNotify) - v1NotifyGroup.POST("/uninstall_app", v1.PostUninstallAppNotify) + //v1NotifyGroup.POST("/install_app", v1.PostInstallAppNotify) + //v1NotifyGroup.POST("/uninstall_app", v1.PostUninstallAppNotify) } } - // socketio - // v1Group.GET("/socketio/*any", gin.WrapH(service.SocketServer)) - // v1Group.POST("/socketio/*any", gin.WrapH(service.SocketServer)) - return r } diff --git a/route/v1/notify.go b/route/v1/notify.go index 100a49e..0f7de77 100644 --- a/route/v1/notify.go +++ b/route/v1/notify.go @@ -11,14 +11,14 @@ import ( ) func PostNotifyMessage(c *gin.Context) { - path := c.Param("path") + name := c.Param("name") message := make(map[string]interface{}) if err := c.ShouldBind(&message); err != nil { c.JSON(http.StatusBadRequest, model.Result{Success: common_err.INVALID_PARAMS, Message: err.Error()}) return } - service.MyService.Notify().SendNotify(path, message) + service.MyService.Notify().SendNotify(name, message) c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } @@ -40,7 +40,7 @@ func PostInstallAppNotify(c *gin.Context) { return } - service.MyService.Notify().SendInstallAppBySocket(app) + //service.MyService.Notify().SendInstallAppBySocket(app) c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } @@ -51,6 +51,6 @@ func PostUninstallAppNotify(c *gin.Context) { return } - service.MyService.Notify().SendUninstallAppBySocket(app) + //service.MyService.Notify().SendUninstallAppBySocket(app) c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } diff --git a/route/v1/recover.go b/route/v1/recover.go index 2cec3b4..5d4de60 100644 --- a/route/v1/recover.go +++ b/route/v1/recover.go @@ -23,7 +23,7 @@ func GetRecoverStorage(c *gin.Context) { c.String(200, `

Code cannot be empty

`) notify["status"] = "fail" notify["message"] = "Code cannot be empty" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } @@ -38,7 +38,7 @@ func GetRecoverStorage(c *gin.Context) { c.String(200, `

Initialization failure:`+err.Error()+`

`) notify["status"] = "fail" notify["message"] = "Initialization failure" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } @@ -47,7 +47,7 @@ func GetRecoverStorage(c *gin.Context) { c.String(200, `

Failed to get user information:`+err.Error()+`

`) notify["status"] = "fail" notify["message"] = "Failed to get user information" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } if len(username) > 0 { @@ -61,7 +61,7 @@ func GetRecoverStorage(c *gin.Context) { service.MyService.Storage().CheckAndMountByName(username) notify["status"] = "warn" notify["message"] = "The same configuration has been added" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } dmap := make(map[string]string) @@ -75,7 +75,7 @@ func GetRecoverStorage(c *gin.Context) { notify := make(map[string]interface{}) notify["status"] = "success" notify["message"] = "Success" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) } else if t == "Dropbox" { add := dropbox.Addition{} add.Code = c.Query("code") @@ -83,7 +83,7 @@ func GetRecoverStorage(c *gin.Context) { c.String(200, `

Code cannot be empty

`) notify["status"] = "fail" notify["message"] = "Code cannot be empty" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } add.RootFolderID = "" @@ -96,7 +96,7 @@ func GetRecoverStorage(c *gin.Context) { c.String(200, `

Initialization failure:`+err.Error()+`

`) notify["status"] = "fail" notify["message"] = "Initialization failure" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } username, err := dropbox.GetUserInfo(c) @@ -104,7 +104,7 @@ func GetRecoverStorage(c *gin.Context) { c.String(200, `

Failed to get user information:`+err.Error()+`

`) notify["status"] = "fail" notify["message"] = "Failed to get user information" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } if len(username) > 0 { @@ -118,7 +118,7 @@ func GetRecoverStorage(c *gin.Context) { service.MyService.Storage().CheckAndMountByName(username) notify["status"] = "warn" notify["message"] = "The same configuration has been added" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) return } dmap := make(map[string]string) @@ -143,7 +143,7 @@ func GetRecoverStorage(c *gin.Context) { notify["status"] = "success" notify["message"] = "Success" - service.MyService.Notify().SendNotify("recover_status", notify) + service.MyService.Notify().SendNotify("casaos:file:recover", notify) } c.String(200, `

Just close the page

`) diff --git a/route/v1/system.go b/route/v1/system.go index 8ee6f07..c2344af 100644 --- a/route/v1/system.go +++ b/route/v1/system.go @@ -14,6 +14,7 @@ import ( http2 "github.com/IceWhaleTech/CasaOS-Common/utils/http" "github.com/IceWhaleTech/CasaOS-Common/utils/port" + "github.com/IceWhaleTech/CasaOS/common" "github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err" @@ -46,7 +47,7 @@ func GetSystemCheckVersion(c *gin.Context) { data := make(map[string]interface{}, 3) data["need_update"] = need data["version"] = version - data["current_version"] = types.CURRENTVERSION + data["current_version"] = common.VERSION c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } @@ -92,7 +93,7 @@ func GetSystemConfigDebug(c *gin.Context) { - Remote Version: %s - Browser: $Browser$ - Version: $Version$ -`, sys.OS, types.CURRENTVERSION, disk.Total>>20, disk.Used>>20, array, version.Version) +`, sys.OS, common.VERSION, disk.Total>>20, disk.Used>>20, array, version.Version) // array = append(array, fmt.Sprintf("disk,total:%v,used:%v,UsedPercent:%v", disk.Total>>20, disk.Used>>20, disk.UsedPercent)) diff --git a/service/notify.go b/service/notify.go index 70d5440..7276c45 100644 --- a/service/notify.go +++ b/service/notify.go @@ -1,15 +1,20 @@ package service import ( + "context" + "encoding/json" json2 "encoding/json" "fmt" + "net/http" "time" - notifyCommon "github.com/IceWhaleTech/CasaOS-Common/model/notify" + "github.com/IceWhaleTech/CasaOS-Common/utils/logger" + "github.com/IceWhaleTech/CasaOS/common" model2 "github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model/notify" "github.com/IceWhaleTech/CasaOS/service/model" "github.com/IceWhaleTech/CasaOS/types" + "go.uber.org/zap" socketio "github.com/googollee/go-socket.io" "github.com/gorilla/websocket" @@ -30,12 +35,11 @@ type NotifyServer interface { GetList(c int) (list []model.AppNotify) MarkRead(id string, state int) // SendText(m model.AppNotify) - SendUninstallAppBySocket(app notifyCommon.Application) + // SendUninstallAppBySocket(app notifyCommon.Application) SendFileOperateNotify(nowSend bool) - SendInstallAppBySocket(app notifyCommon.Application) - SendStorageBySocket(message notify.StorageMessage) - SendNotify(path string, message map[string]interface{}) + //SendInstallAppBySocket(app notifyCommon.Application) + SendNotify(name string, message map[string]interface{}) SettingSystemTempData(message map[string]interface{}) GetSystemTempMap() map[string]interface{} } @@ -51,18 +55,25 @@ func (i *notifyServer) SettingSystemTempData(message map[string]interface{}) { } } -func (i *notifyServer) SendNotify(path string, message map[string]interface{}) { - SocketServer.BroadcastToRoom("/", "public", path, message) -} - -func (i *notifyServer) SendStorageBySocket(message notify.StorageMessage) { - SocketServer.BroadcastToRoom("/", "public", "storage_status", message) +func (i *notifyServer) SendNotify(name string, message map[string]interface{}) { + msg := make(map[string]string) + for k, v := range message { + bt, _ := json.Marshal(v) + msg[k] = string(bt) + } + response, err := MyService.MessageBus().PublishEventWithResponse(context.Background(), common.SERVICENAME, name, msg) + if err != nil { + logger.Error("failed to publish event to message bus", zap.Error(err), zap.Any("event", msg)) + } + if response.StatusCode() != http.StatusOK { + logger.Error("failed to publish event to message bus", zap.String("status", response.Status()), zap.Any("response", response)) + } + // SocketServer.BroadcastToRoom("/", "public", path, message) } // Send periodic broadcast messages func (i *notifyServer) SendFileOperateNotify(nowSend bool) { if nowSend { - len := 0 FileQueue.Range(func(k, v interface{}) bool { len++ @@ -74,7 +85,18 @@ func (i *notifyServer) SendFileOperateNotify(nowSend bool) { if len == 0 { model.Data = []string{} listMsg["file_operate"] = model - SocketServer.BroadcastToRoom("/", "public", "file_operate", listMsg) + msg := make(map[string]string) + for k, v := range listMsg { + bt, _ := json.Marshal(v) + msg[k] = string(bt) + } + response, err := MyService.MessageBus().PublishEventWithResponse(context.Background(), common.SERVICENAME, "casaos:file:operate", msg) + if err != nil { + logger.Error("failed to publish event to message bus", zap.Error(err), zap.Any("event", msg)) + } + if response.StatusCode() != http.StatusOK { + logger.Error("failed to publish event to message bus", zap.String("status", response.Status()), zap.Any("response", response)) + } return } @@ -122,7 +144,19 @@ func (i *notifyServer) SendFileOperateNotify(nowSend bool) { model.Data = list listMsg["file_operate"] = model - SocketServer.BroadcastToRoom("/", "public", "file_operate", listMsg) + msg := make(map[string]string) + for k, v := range listMsg { + bt, _ := json.Marshal(v) + msg[k] = string(bt) + } + response, err := MyService.MessageBus().PublishEventWithResponse(context.Background(), common.SERVICENAME, "casaos:file:operate", msg) + if err != nil { + logger.Error("failed to publish event to message bus", zap.Error(err), zap.Any("event", msg)) + } + if response.StatusCode() != http.StatusOK { + logger.Error("failed to publish event to message bus", zap.String("status", response.Status()), zap.Any("response", response)) + } + } else { for { @@ -179,20 +213,30 @@ func (i *notifyServer) SendFileOperateNotify(nowSend bool) { model.Data = list listMsg["file_operate"] = model - SocketServer.BroadcastToRoom("/", "public", "file_operate", listMsg) + msg := make(map[string]string) + for k, v := range listMsg { + bt, _ := json.Marshal(v) + msg[k] = string(bt) + } + response, err := MyService.MessageBus().PublishEventWithResponse(context.Background(), common.SERVICENAME, "casaos:file:operate", msg) + if err != nil { + logger.Error("failed to publish event to message bus", zap.Error(err), zap.Any("event", msg)) + } + if response.StatusCode() != http.StatusOK { + logger.Error("failed to publish event to message bus", zap.String("status", response.Status()), zap.Any("response", response)) + } time.Sleep(time.Second * 3) } } } -func (i *notifyServer) SendInstallAppBySocket(app notifyCommon.Application) { - SocketServer.BroadcastToRoom("/", "public", "app_install", app) +// func (i *notifyServer) SendInstallAppBySocket(app notifyCommon.Application) { +// SocketServer.BroadcastToRoom("/", "public", "app_install", app) +// } -} - -func (i *notifyServer) SendUninstallAppBySocket(app notifyCommon.Application) { - SocketServer.BroadcastToRoom("/", "public", "app_uninstall", app) -} +// func (i *notifyServer) SendUninstallAppBySocket(app notifyCommon.Application) { +// SocketServer.BroadcastToRoom("/", "public", "app_uninstall", app) +// } func (i *notifyServer) SSR() { server := socketio.NewServer(nil) diff --git a/service/service.go b/service/service.go index 3f69e63..db9f51c 100644 --- a/service/service.go +++ b/service/service.go @@ -12,19 +12,17 @@ package service import ( "github.com/IceWhaleTech/CasaOS-Common/external" - "github.com/IceWhaleTech/CasaOS-Common/utils/logger" - socketio "github.com/googollee/go-socket.io" + "github.com/IceWhaleTech/CasaOS/codegen/message_bus" + "github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/gorilla/websocket" "github.com/patrickmn/go-cache" - "go.uber.org/zap" "gorm.io/gorm" ) var Cache *cache.Cache var ( - MyService Repository - SocketServer *socketio.Server + MyService Repository ) var ( @@ -47,13 +45,10 @@ type Repository interface { FsListService() FsListService FsLinkService() FsLinkService FsService() FsService + MessageBus() *message_bus.ClientWithResponses } -func NewService(db *gorm.DB, RuntimePath string, socket *socketio.Server) Repository { - if socket == nil { - logger.Error("socket is nil", zap.Any("error", "socket is nil")) - } - SocketServer = socket +func NewService(db *gorm.DB, RuntimePath string) Repository { gatewayManagement, err := external.NewManagementService(RuntimePath) if err != nil && len(RuntimePath) > 0 { panic(err) @@ -149,3 +144,23 @@ func (c *store) Casa() CasaService { func (c *store) Health() HealthService { return c.health } + +func (c *store) MessageBus() *message_bus.ClientWithResponses { + client, _ := message_bus.NewClientWithResponses("", func(c *message_bus.Client) error { + // error will never be returned, as we always want to return a client, even with wrong address, + // in order to avoid panic. + // + // If we don't avoid panic, message bus becomes a hard dependency, which is not what we want. + + messageBusAddress, err := external.GetMessageBusAddress(config.CommonInfo.RuntimePath) + if err != nil { + c.Server = "message bus address not found" + return nil + } + + c.Server = messageBusAddress + return nil + }) + + return client +} diff --git a/types/system.go b/types/system.go deleted file mode 100644 index da9ad10..0000000 --- a/types/system.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - * @Author: LinkLeong link@icewhale.org - * @Date: 2022-11-15 15:51:44 - * @LastEditors: LinkLeong - * @LastEditTime: 2022-11-15 15:56:03 - * @FilePath: /CasaOS/types/system.go - * @Description: - * @Website: https://www.casaos.io - * Copyright (c) 2022 by icewhale, All Rights Reserved. - */ -/*@Author: LinkLeong link@icewhale.com - *@Date: 2022-02-17 18:53:22 - *@LastEditors: LinkLeong - *@LastEditTime: 2022-09-06 14:27:42 - *@FilePath: /CasaOS/types/system.go - *@Description: - *@Website: https://www.casaos.io - *Copyright (c) 2022 by icewhale, All Rights Reserved. - */ -package types - -const CURRENTVERSION = "0.4.2" - -const BODY = " "